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_plugin_project_root.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": "Resolve relative plugin options (devupFile, distDir, cssDir), the tsconfig and the webpack extraction ids against the bundler's project root (Vite root, webpack context, Rsbuild rootPath, Next's project directory for webpack builds, Bun.build root) instead of process.cwd(), so builds started from a parent directory as turbo or nx do read the project's devup.json and write its df. Builds started from the project root are unchanged. When devupFile is not set and only the working directory holds a devup.json, that file is still read and a one-time warning says to move it next to the project or set devupFile. Class names may change once for webpack and Next webpack builds run from a parent directory, because files are now numbered relative to the project root.",
"date": "2026-11-15T00:00:00.000Z"
}
10 changes: 9 additions & 1 deletion apps/landing/src/app/(detail)/docs/devup/devup-json/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,15 @@ your-project/

## Plugin Configuration

By default, plugins look for `devup.json` in the project root. You can customize this:
By default, plugins look for `devup.json` in the project root: Vite's `root`,
webpack's `context`, Rsbuild's root, the Next.js project directory (webpack
builds) or the `root` of `Bun.build`. Relative `devupFile`, `distDir` and
`cssDir` paths resolve against it, not against the directory a monorepo tool
(turbo, nx, ...) starts the build from. If `devupFile` is not set and only the
working directory holds a `devup.json`, that file is still used and a one-time
warning asks you to move it into the project root or set `devupFile`.

You can customize the path:

### Vite

Expand Down
6 changes: 6 additions & 0 deletions packages/bun-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,12 @@ Create a `devup.json` file in your project root:
```

The plugin will generate `df/theme.d.ts` with TypeScript types for your theme.

The project root is the `root` of `Bun.build` when it sets one, and the working
directory otherwise: `devup.json`, `df` and `tsconfig.json` are read and written
there. When the root has no `devup.json` but the working directory does, that
file is still read and a one-time warning is printed; move `devup.json` into the
root to resolve it.

## How It Works

Expand Down
63 changes: 62 additions & 1 deletion packages/bun-plugin/src/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,9 @@ describe('registered Bun hooks', () => {
)
exists.mockImplementation(realExists)
const resolve = spyOn(nodePath, 'resolve').mockImplementation((...paths) =>
paths.length === 1 && paths[0] === 'src' ? root : realResolve(...paths),
paths.length === 2 && paths[0] === process.cwd() && paths[1] === 'src'
? root
: realResolve(...paths),
)
try {
await register({ engine: 'wasm' })
Expand Down Expand Up @@ -558,3 +560,62 @@ describe('registered Bun hooks', () => {
await expect(load(path)).rejects.toThrow(/invalid\.ts:\d+:\d+:/)
})
})

describe('project root', () => {
/** Run setup as `Bun.build` does, with `root` in its config */
async function setupBuild(buildRoot: string | undefined) {
const ends: (() => void)[] = []
const builder = {
config: { entrypoints: [], root: buildRoot },
onStart: () => builder,
onEnd: (end: () => void) => {
ends.push(end)
return builder
},
onResolve: () => builder,
onLoad: () => builder,
}
try {
await DevupUI({ engine: 'wasm' }).setup(
builder as unknown as Parameters<
ReturnType<typeof DevupUI>['setup']
>[0],
)
} finally {
// End the build session setup began
for (const end of ends) end()
}
return write.mock.calls.map(([path]) => String(path))
}

it('writes df under the root of Bun.build', async () => {
const buildRoot = nodePath.resolve('apps', 'web')
const written = await setupBuild(buildRoot)
expect(written).toContain(join(buildRoot, 'df', '.gitignore'))
expect(written).toContain(join(buildRoot, 'df', 'devup-ui', 'devup-ui.css'))
})

it('keeps writing df in the cwd without a root', async () => {
const written = await setupBuild(undefined)
expect(written).toContain(join('df', '.gitignore'))
expect(written).toContain(
nodePath.resolve('df', 'devup-ui', 'devup-ui.css'),
)
})

it('falls back to the devup.json of the cwd with a warning', async () => {
const warn = spyOn(console, 'warn').mockReturnValue(undefined)
const cwdFile = nodePath.resolve('devup.json')
exists.mockImplementation((path) => String(path) === cwdFile)
try {
const buildRoot = nodePath.resolve('apps', 'bun-fallback')
const written = await setupBuild(buildRoot)
expect(readConfig).toHaveBeenCalledWith(cwdFile, 'utf-8')
expect(written).toContain(join(buildRoot, 'df', '.gitignore'))
expect(warn).toHaveBeenCalledTimes(1)
expect(String(warn.mock.calls[0]?.[0])).toContain('devupFile')
} finally {
warn.mockRestore()
}
})
})
97 changes: 72 additions & 25 deletions packages/bun-plugin/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@ import {
mergeImportAliases,
normalizeShorthands,
readJsxImportSource,
resolveDevupFile,
resolveProjectPath,
seedFileNumbers,
setupWarning,
tailwindCssFiles,
type WasmImportAliases,
withTailwindCss,
} from '@devup-ui/plugin-utils'
import { type BunPlugin, plugin, type PluginBuilder } from 'bun'
Expand All @@ -30,18 +33,42 @@ import { cssDirName, cssNamespace, resolveCssId } from './css-id'
import { createTailwindWatcher } from './tailwind-watch'

const libPackage = '@devup-ui/react'
const devupFile = 'devup.json'
const distDir = 'df'
const cssDir = resolve(distDir, cssDirName)
const distDirName = 'df'
const singleCss = true
const importAliases = mergeImportAliases(undefined, readJsxImportSource())
// The packages whose imports the extractor compiles: Devup UI, the packages it
// takes the place of, and StyleX
const compiledPackages = [
libPackage,
'@stylexjs/stylex',
...Object.keys(importAliases),
]

/** Where a project keeps its files, and what its tsconfig compiles */
interface BunProject {
readonly root: string
readonly devupFile: string
readonly distDir: string
readonly cssDir: string
readonly importAliases: WasmImportAliases
/**
* The packages whose imports the extractor compiles: Devup UI, the packages
* it takes the place of, and StyleX
*/
readonly compiledPackages: string[]
}

/**
* The project at `root`: the `root` of `Bun.build`, or the working directory
* of the runtime and of a build without one
*/
function locateProject(root: string): BunProject {
const importAliases = mergeImportAliases(undefined, readJsxImportSource(root))
return {
root,
devupFile: resolveDevupFile(root, undefined),
distDir: resolveProjectPath(root, distDirName),
cssDir: resolve(root, distDirName, cssDirName),
importAliases,
compiledPackages: [
libPackage,
'@stylexjs/stylex',
...Object.keys(importAliases),
],
}
}

export interface DevupUIBunPluginOptions {
/** Native by default. Select WASM explicitly without automatic fallback. */
Expand Down Expand Up @@ -92,6 +119,7 @@ function createSourceFilter(include: readonly string[]): RegExp {
*/
async function writeDataFiles(
compiler: DevupCompiler,
{ devupFile, distDir, cssDir }: BunProject,
reloading = false,
): Promise<string[]> {
let tailwindFiles: string[] = []
Expand Down Expand Up @@ -127,24 +155,30 @@ async function initialize(
compiler: DevupCompiler,
shorthands: Record<string, readonly string[]>,
watchTailwindCss: ReturnType<typeof createTailwindWatcher>,
project: BunProject,
) {
const { distDir } = project
compiler.registerShorthands(shorthands)
compiler.setPrefix(null)
compiler.setModuleResolver(createModuleResolver())
if (!existsSync(distDir)) await mkdir(distDir, { recursive: true })
await writeFile(join(distDir, '.gitignore'), '*', 'utf-8')
await writeFile(
join(distDir, 'compat.d.ts'),
createCompatTypes(importAliases),
createCompatTypes(project.importAliases),
'utf-8',
)
watchTailwindCss(await writeDataFiles(compiler))
watchTailwindCss(await writeDataFiles(compiler, project))
}

const scanners = new Map<SourceLoader, Bun.Transpiler>()

/** Whether `contents` imports a package the extractor compiles */
function importsCompiledPackage(contents: string, loader: SourceLoader) {
function importsCompiledPackage(
contents: string,
loader: SourceLoader,
compiledPackages: readonly string[],
) {
let scanner = scanners.get(loader)
if (!scanner) {
scanner = new Bun.Transpiler({ loader })
Expand All @@ -168,6 +202,7 @@ async function loadSourceFile(
compiler: DevupCompiler,
filePath: string,
bundling: boolean,
{ cssDir, importAliases, compiledPackages }: BunProject,
) {
const loader: SourceLoader = filePath.endsWith('.tsx')
? 'tsx'
Expand All @@ -180,7 +215,7 @@ async function loadSourceFile(

if (
isProjectJsx(filePath, importAliases) ||
importsCompiledPackage(contents, loader) ||
importsCompiledPackage(contents, loader, compiledPackages) ||
compiler.hasDevupUI(filePath, contents, libPackage, importAliases)
) {
using code = compiler.codeExtract(
Expand Down Expand Up @@ -213,20 +248,31 @@ async function loadSourceFile(
function DevupUI(options: DevupUIBunPluginOptions = {}) {
const shorthands = normalizeShorthands(options.shorthands ?? {})
const compiler = loadCompiler(options.engine)
// Each setup locates the project again; the watcher reads it then
const project = locateProject(process.cwd())
const watchTailwindCss = createTailwindWatcher(() =>
writeDataFiles(compiler, true),
writeDataFiles(compiler, project, true),
)
return {
name: 'devup-ui',

async setup(build: PluginBuilder) {
// `Bun.build` hands its config to plugins; the runtime has none
const bundling = build.config !== undefined
// The relative paths belong to the `root` of `Bun.build` when it sets
// one, not to the directory a monorepo tool starts the build from
Object.assign(
project,
locateProject(
resolve((bundling && build.config.root) || process.cwd()),
),
)
const { root, importAliases, cssDir } = project
// A build starts from its own options, not from what an earlier build in
// this process left in the engine
const endBuild = beginBuild(compiler)
build.onEnd?.(endBuild)
await initialize(compiler, shorthands, watchTailwindCss)
await initialize(compiler, shorthands, watchTailwindCss, project)
const debug = options.debug ?? !bundling
compiler.setDebug(debug)
const slots = createSharedSlotReservation(compiler)
Expand All @@ -235,14 +281,14 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) {
slots.invalidate()
slots.reserve(
{
roots: [resolve('src'), resolve('app')],
roots: [resolve(root, 'src'), resolve(root, 'app')],
entries: bundling
? build.config.entrypoints.map((entry) => ({
request: resolve(entry),
context: process.cwd(),
context: root,
}))
: [],
cwd: process.cwd(),
cwd: root,
package: libPackage,
importAliases,
toId: (path) => path,
Expand All @@ -266,15 +312,16 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) {
seedFileNumbers(
compiler,
collectNumberedFiles({
roots: [resolve('src')],
needles: compiledPackages,
roots: [resolve(root, 'src')],
cwd: root,
needles: project.compiledPackages,
importAliases,
toId: (path) => path,
}),
)
} catch (error) {
if (!(error instanceof Error)) throw error
if (!isMissingDirectory(error, resolve('src')))
if (!isMissingDirectory(error, resolve(root, 'src')))
console.warn(
setupWarning(
'Bun file numbering',
Expand All @@ -290,7 +337,7 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) {
// content-keyed transpiler cache. See ./css-id.
build.onResolve(
{ filter: /devup-ui(-\d+)?\.css$/ },
({ path, importer }) => resolveCssId(path, importer, distDir),
({ path, importer }) => resolveCssId(path, importer, distDirName),
)

// The bundler takes the stylesheet once every other module is loaded,
Expand All @@ -314,7 +361,7 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) {
reserveFiles()
reservationPending = false
}
return loadSourceFile(compiler, path, bundling)
return loadSourceFile(compiler, path, bundling, project)
},
)
},
Expand Down
17 changes: 17 additions & 0 deletions packages/next-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,23 @@ const box = <Box _hover={{ bg: ['red', 'blue'] }} />
const box = <Box _hover={[{ bg: 'red' }, { bg: 'blue' }]} />
```

## Project root

With webpack (`next build --webpack`), relative `devupFile`, `distDir` and
`cssDir` paths, the `tsconfig.json` the plugin reads and the file ids class names
are derived from resolve against the Next project directory, not against the
directory the build is started from. A build that a monorepo tool (turbo, nx,
...) runs from a parent directory (`next build apps/web`) reads
`apps/web/devup.json` and writes `apps/web/df`. Builds run from the project
directory are unchanged; builds run from a parent directory may get different
class names once. Turbopack does not tell its config the project directory, so
there the paths stay relative to the working directory.

When `devupFile` is not set and the project directory has no `devup.json` but
the working directory does, that file is still read and a one-time warning is
printed. Move `devup.json` into the project directory, or set `devupFile` to the
file you want, to resolve it.

## Custom Shorthands

Custom shorthands belong to the plugin options rather than `devup.json` because
Expand Down
Loading
Loading