Skip to content
Open
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_core.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/bun-plugin/package.json": "Patch",
"packages/next-plugin/package.json": "Patch"
},
"note": "Compile `.mts`, `.cts` and `.cjs` modules in every plugin, Turbopack and the import graph, and resolve `./a.js`, `./a.mjs` and `./a.cjs` imports to their TypeScript sources. Resolve package `exports` in the package's own order with the conditions of the bundler: Vite's `resolve.conditions`, the ESM conditions of webpack and Rspack per environment, and the target and `conditions` of Bun. Atom hoisting in webpack and Rsbuild plans over the `src` and `app` directories of the working directory and of the bundler root, not `src` alone. Bun keeps the modules whose values a file inlines in its module graph, so changing one rebuilds the file, and bundles the project's own `.js` and `.cjs` modules. No new build errors.",
"date": "2026-11-15T00:00:00.000Z"
}
2 changes: 1 addition & 1 deletion apps/landing/src/app/(detail)/docs/limitations/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ A dynamic value such as `width` becomes a CSS variable set in `style`, so a comp
- An `.mdx` file is extracted after your MDX plugin compiles it to JavaScript, never as raw MDX. The Vite (`@mdx-js/rollup`), webpack and Rsbuild (`@mdx-js/loader`, `@rsbuild/plugin-mdx`) plugins and Next.js with webpack (`@next/mdx`) run their MDX step in a later phase: Vite in a `post` transform, webpack and Rsbuild in a `post` loader. Next.js with Turbopack and the Bun plugin do not extract MDX yet. The scan that reserves class names before a build reads JavaScript and TypeScript modules only, so a document's own classes are named when it compiles. Put components that need Devup UI styles in a `.tsx` module and use them from the document.
- The plugins read `jsxImportSource` from the `tsconfig.json` (or `jsconfig.json`) in the working directory. Opt out with `importAliases: { '@emotion/react/jsx-runtime': false }`.
- The outermost `ThemeProvider` also declares its theme on `:root`, in a `<style>` element rendered before its `<div>`, so `createGlobalStyle` and `<Global>` rules on `html`, `body` or `:root` read it; a nested provider changes only its own subtree. Several outermost providers side by side all write `:root`, and the last one in the document wins there. The `<style>` element also counts in the `textContent` of what holds the provider.
- The Bun plugin compiles `.ts`, `.tsx`, `.jsx` and `.mjs` files, but `.js` files only inside `@devup-ui` packages: Devup UI code in a `.js` file of your own project reaches the runtime placeholders. Use `.jsx`, `.tsx` or `.mjs` for it. A Bun runtime plugin must return the source of every file it matches, and Bun reads that source as an ES module, so matching `.js` files would break CommonJS ones.
- The Bun plugin compiles `.ts`, `.mts`, `.cts`, `.tsx`, `.jsx` and `.mjs` files, and `.js` files inside `@devup-ui` packages and the packages listed in `include`; `Bun.build` also compiles every `.js` and `.cjs` file outside `node_modules`. Under the Bun runtime, Devup UI code in a `.js` or `.cjs` file of your own project reaches the runtime placeholders. Use `.jsx`, `.tsx` or `.mjs` for it. A Bun runtime plugin must return the source of every file it matches, and Bun reads that source as an ES module, so matching `.js` files would break CommonJS ones. For the same reason, a `.cts` file loaded under the Bun runtime must use `import` and `export`, not `module.exports` or `export =`.
- Code that only the runtime can compute — other globals, `Date`, `Math.random`, `new`, classes, async code — is never run by the build; on an element it stays a CSS variable, elsewhere it is a build error.

## Build errors
Expand Down
2 changes: 1 addition & 1 deletion e2e/plugins/engine-parity.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ function nextSelectors(value, engine, kind) {
? ['engine']
: [
`${prefix}./df/devup-ui/*.css/0/options/engine`,
`${prefix}*.{tsx,ts,jsx,js,mjs}/loaders/0/options/engine`,
`${prefix}*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}/loaders/0/options/engine`,
].sort(),
)
return value
Expand Down
25 changes: 19 additions & 6 deletions packages/bun-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,17 +62,30 @@ Class names are short in `Bun.build` and readable under the runtime; pass

## Compiled Files

`.ts`, `.tsx`, `.jsx` and `.mjs` files are compiled wherever they are, and
`.js` files only inside `@devup-ui` packages and the packages you list in
`include`, as in the other plugins. Devup UI code in a `.js` file of your own
project is not compiled and reaches the runtime placeholders
`.ts`, `.mts`, `.cts`, `.tsx`, `.jsx` and `.mjs` files are compiled wherever
they are, `node_modules` included, and `.js` files inside `@devup-ui`
packages and the packages you list in `include`, as in the other plugins.
`.mts` and `.cts` files are read as TypeScript.

`Bun.build` also compiles every `.js` and `.cjs` file outside `node_modules`:
those of your own project, and those of a linked workspace package Bun resolves
to its real path. A `.js` or `.cjs` file inside `node_modules` is left to Bun,
except the `.js` files of `@devup-ui` packages and of the packages in
`include`.

Under the runtime, the `.js` and `.cjs` files of your own project are not
compiled: Devup UI code in one reaches the runtime placeholders
(`Cannot run on the runtime`). Give such files a `.jsx`, `.tsx` or `.mjs`
extension.

The runtime cannot take those files on. A Bun runtime plugin must return the
source of every file its filter matches, it cannot hand a file back to Bun, and
Bun reads returned source as an ES module, so a CommonJS `.js` file
(`require`, `module.exports`) it matched would stop loading.
Bun reads returned source as an ES module, so a CommonJS `.js` or `.cjs` file
(`require`, `module.exports`) it matched would stop loading. For the same
reason, a `.cts` file loaded under the runtime must be written with `import`
and `export`: one written with `module.exports` or `export =` loses its
exports. `Bun.build` reads returned CommonJS as CommonJS, so this applies to
the runtime only.

## Libraries

Expand Down
76 changes: 75 additions & 1 deletion packages/bun-plugin/src/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
} from 'bun:test'

import { bunRegistration } from '../../../../bun.setup'
import { DevupUI, register } from '../plugin'
import { bunConditions, DevupUI, register } from '../plugin'
import { captureBunHooks } from './captured-hooks.test-support'

const selectCompiler = pluginUtils.loadCompiler
Expand Down Expand Up @@ -117,6 +117,32 @@ async function load(path: string, namespace = 'file') {
})
}

describe('bunConditions', () => {
it('resolves with the conditions of the target and the configured ones', () => {
expect(bunConditions(undefined)).toEqual([
'import',
'module',
'bun',
'node',
])
expect(bunConditions({})).toEqual(['import', 'module', 'browser'])
expect(bunConditions({ target: 'node', conditions: 'worker' })).toEqual([
'import',
'module',
'node',
'worker',
])
expect(bunConditions({ target: 'bun', conditions: ['a', 'b'] })).toEqual([
'import',
'module',
'bun',
'node',
'a',
'b',
])
})
})

describe('registered Bun hooks', () => {
it('compiles default runtime input into native state without mutating WASM', async () => {
const native = pluginUtils.loadCompiler()
Expand Down Expand Up @@ -290,6 +316,52 @@ describe('registered Bun hooks', () => {
expect(writeSync).not.toHaveBeenCalled()
})

it('bundles the project .js and .cjs modules and leaves packages to Bun', async () => {
const dir = join(root, 'local-scripts')
await Bun.write(
join(dir, 'entry.ts'),
"import { view } from './view.js'; import { lib } from 'lib'; export { view, lib }",
)
await Bun.write(
join(dir, 'view.js'),
"import { css } from '@devup-ui/react'; export const view = css({ color: 'orange' })",
)
await Bun.write(
join(dir, 'node_modules/lib/package.json'),
JSON.stringify({ name: 'lib', main: 'index.js' }),
)
await Bun.write(
join(dir, 'node_modules/lib/index.js'),
'export const lib = 1',
)
const result = await Bun.build({
entrypoints: [join(dir, 'entry.ts')],
target: 'bun',
outdir: join(dir, 'out'),
plugins: [DevupUI({ engine: 'wasm' })],
})
expect(result.success).toBe(true)
const outputs = await Promise.all(
result.outputs.map((output) => output.text()),
)
expect(outputs.join('')).toMatch(/color:\s*orange/)
expect(outputs.join('')).not.toContain('css(')
})

it('keeps the build-time dependencies of a source in its module graph', async () => {
await Bun.write(join(root, 'dep-tokens.ts'), "export const color = 'red'")
const path = join(root, 'dep-source.ts')
await Bun.write(
path,
"import { css } from '@devup-ui/react'; import { color } from './dep-tokens'; export const c = css({ color })",
)
await register({ engine: 'wasm' })
const result = await load(path)
if (!result || !('contents' in result))
throw new Error('Expected transformed source contents')
expect(result.contents).toEndWith('\nimport "./dep-tokens.ts";')
})

it('creates cold directories before writing configuration and CSS', async () => {
await register({ engine: 'wasm' })
expect(mkdir).toHaveBeenCalledWith('df', { recursive: true })
Expand Down Expand Up @@ -409,6 +481,8 @@ describe('registered Bun hooks', () => {
for (const [extension, loader] of [
['tsx', 'tsx'],
['ts', 'ts'],
['mts', 'ts'],
['cts', 'ts'],
['jsx', 'jsx'],
['mjs', 'js'],
['js', 'js'],
Expand Down
104 changes: 82 additions & 22 deletions packages/bun-plugin/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,14 @@ type SourceLoader = 'tsx' | 'ts' | 'jsx' | 'js'
const SEPARATOR = '[\\/\\\\]'

/**
* The files the plugin loads: TypeScript and JSX sources anywhere, `.js` under
* Devup UI, and `.js` of the packages in `include`. An included package is the
* directory right under the innermost `node_modules` (pnpm and Bun stores
* included), matched the way `createNodeModulesExcludeRegex` matches it.
* The files the plugin loads: TypeScript (`.mts` and `.cts` included) and JSX
* sources anywhere, `.js` under Devup UI, and `.js` of the packages in
* `include`. An included package is the directory right under the innermost
* `node_modules` (pnpm and Bun stores included), matched the way
* `createNodeModulesExcludeRegex` matches it.
*/
function createSourceFilter(include: readonly string[]): RegExp {
const sources = `\\.(?:tsx?|jsx|mjs)$|${SEPARATOR}@devup-ui${SEPARATOR}.*\\.js$`
const sources = `\\.(?:[mc]?ts|tsx|jsx|mjs)$|${SEPARATOR}@devup-ui${SEPARATOR}.*\\.js$`
if (include.length === 0) return new RegExp(sources)
const names = include
.map((name) =>
Expand All @@ -111,6 +112,51 @@ function createSourceFilter(include: readonly string[]): RegExp {
)
}

/**
* The `exports` conditions Bun resolves an import with: those of its target
* (`browser` by default for `Bun.build`, `bun` under the runtime) and the
* configured `conditions`
*/
export function bunConditions(
config: Pick<Bun.BuildConfig, 'target' | 'conditions'> | undefined,
): string[] {
const target = config ? (config.target ?? 'browser') : 'bun'
return [
'import',
'module',
...{ browser: ['browser'], node: ['node'], bun: ['bun', 'node'] }[target],
...[config?.conditions ?? []].flat(),
]
}

/**
* `code` followed by a bare import of each build-time dependency, so that
* Bun's module graph, and with it its watcher, keeps the modules whose values
* the extractor inlined. Appended, the imports move no line or column of the
* extracted code.
*/
export function withDependencyImports(
code: string,
filePath: string,
dependencies: readonly string[],
): string {
return [
code,
...[...new Set(dependencies)].map((dependency) => {
const path = relative(dirname(filePath), dependency).replaceAll('\\', '/')
return `import ${JSON.stringify(path.startsWith('.') ? path : `./${path}`)};`
}),
].join('\n')
}

/** Bun's loader for a source file */
function sourceLoader(filePath: string): SourceLoader {
if (filePath.endsWith('.tsx')) return 'tsx'
if (/\.[mc]?ts$/.test(filePath)) return 'ts'
if (filePath.endsWith('.jsx')) return 'jsx'
return 'js'
}

/**
* 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
Expand Down Expand Up @@ -156,11 +202,12 @@ async function initialize(
shorthands: Record<string, readonly string[]>,
watchTailwindCss: ReturnType<typeof createTailwindWatcher>,
project: BunProject,
conditions: readonly string[],
) {
const { distDir } = project
compiler.registerShorthands(shorthands)
compiler.setPrefix(null)
compiler.setModuleResolver(createModuleResolver())
compiler.setModuleResolver(createModuleResolver({ conditions }))
if (!existsSync(distDir)) await mkdir(distDir, { recursive: true })
await writeFile(join(distDir, '.gitignore'), '*', 'utf-8')
await writeFile(
Expand Down Expand Up @@ -204,13 +251,7 @@ async function loadSourceFile(
bundling: boolean,
{ cssDir, importAliases, compiledPackages }: BunProject,
) {
const loader: SourceLoader = filePath.endsWith('.tsx')
? 'tsx'
: filePath.endsWith('.ts')
? 'ts'
: filePath.endsWith('.jsx')
? 'jsx'
: 'js'
const loader = sourceLoader(filePath)
const contents = await Bun.file(filePath).text()

if (
Expand All @@ -236,7 +277,10 @@ async function loadSourceFile(
const sheet = code.css
if (!bundling && sheet !== undefined)
writeFileSync(join(cssDir, 'devup-ui.css'), sheet, 'utf-8')
return { contents: code.code, loader }
return {
contents: withDependencyImports(code.code, filePath, code.dependencies),
loader,
}
}
return { contents, loader }
}
Expand Down Expand Up @@ -272,7 +316,13 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) {
// this process left in the engine
const endBuild = beginBuild(compiler)
build.onEnd?.(endBuild)
await initialize(compiler, shorthands, watchTailwindCss, project)
await initialize(
compiler,
shorthands,
watchTailwindCss,
project,
bunConditions(build.config),
)
const debug = options.debug ?? !bundling
compiler.setDebug(debug)
const slots = createSharedSlotReservation(compiler)
Expand Down Expand Up @@ -353,17 +403,27 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) {
},
)

const loadSource = ({ path }: { readonly path: string }) => {
if (reservationPending) {
reserveFiles()
reservationPending = false
}
return loadSourceFile(compiler, path, bundling, project)
}
// Load source files from packages directory (file namespace)
build.onLoad(
{ filter: createSourceFilter(options.include ?? []) },
({ path }) => {
if (reservationPending) {
reserveFiles()
reservationPending = false
}
return loadSourceFile(compiler, path, bundling, project)
},
loadSource,
)
// A bundle also takes the project's own `.js` and `.cjs` modules. Bun
// loads one itself when the hook returns nothing, which the runtime
// does not allow, so dependencies are left to Bun here.
if (bundling)
build.onLoad({ filter: /\.c?js$/ }, (args) =>
!/[\\/]node_modules[\\/]/.test(args.path)
? loadSource(args)
: undefined,
)
},
} satisfies BunPlugin
}
Expand Down
2 changes: 1 addition & 1 deletion packages/next-plugin/src/__tests__/atom-hoist.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const { default: loader } = await import(${builtPluginEntry('next-plugin', 'load
const { default: cssLoader } = await import(${builtPluginEntry('next-plugin', 'css-loader.mjs')});
const config = DevupUI({}, { atomHoist: 2, cssDir, distDir: join(root, 'df') });
const rules = config.turbopack.rules;
const jsOptions = rules['*.{tsx,ts,jsx,js,mjs}'].loaders[0].options;
const jsOptions = rules['*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}'].loaders[0].options;
const cssOptions = rules['./df/devup-ui/*.css'][0].options;
const invoke = (fn, options, request) => new Promise((resolve, reject) => {
fn.call({ resourcePath: request.resourcePath, getOptions: () => options, addDependency() {},
Expand Down
3 changes: 2 additions & 1 deletion packages/next-plugin/src/__tests__/availability-adapters.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ export async function openAdapter({ adapter, worktree, root, files }) {
assert.fail('must observe one real coordinator')
}
const rules = config.turbopack.rules
const jsOptions = rules['*.{tsx,ts,jsx,js,mjs}'].loaders[0].options
const jsOptions =
rules['*.{tsx,ts,mts,cts,jsx,js,mjs,cjs}'].loaders[0].options
const cssOptions = rules['./df/devup-ui/*.css'][0].options
const invoke = (fn, opts, input) =>
new Promise((resolve, reject) => {
Expand Down
Loading
Loading