From 0759b8d43ccb7637f4fc90586d75aecc24390c22 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Tue, 17 Nov 2026 12:32:46 +0900 Subject: [PATCH 1/3] fix(bun-plugin): run CommonJS under the Bun runtime and compile every source kind Bun reads the contents a runtime onLoad callback returns as an ES module. For CommonJS it builds the CommonJS wrapper but never calls it, so the module body does not run and require() and import see {} (Bun 1.4.4). Returning no contents is an error, and no loader (js, ts, object) or namespace keeps CommonJS semantics, so the runtime plugin now runs a CommonJS module itself: Devup UI compiles it, Bun's transpiler strips TypeScript, and the module runs in a CommonJS function with its own require, module, __filename and __dirname, registered in require.cache for cycles. Bun gets an ES module that exports module.exports as "module.exports" (what require() returns), as default (exports.default under __esModule) and by name, as Bun exports CommonJS. The filter now covers .mts and .cts everywhere, and .js and .cjs outside node_modules and in @devup-ui packages. Source loads are synchronous, since Bun cannot require() a module whose onLoad is async. Bun.build is unchanged: it bundles the CommonJS it is handed. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_bun_runtime_commonjs.json | 7 + .../app/(detail)/docs/limitations/page.mdx | 2 +- packages/bun-plugin/README.md | 28 ++- .../src/__tests__/commonjs-runtime.child.ts | 45 +++++ .../src/__tests__/commonjs-runtime.test.ts | 164 ++++++++++++++++ .../bun-plugin/src/__tests__/plugin.test.ts | 180 ++++++++++++++++++ packages/bun-plugin/src/commonjs.ts | 172 +++++++++++++++++ packages/bun-plugin/src/plugin.ts | 49 +++-- 8 files changed, 622 insertions(+), 25 deletions(-) create mode 100644 .changepacks/changepack_log_bun_runtime_commonjs.json create mode 100644 packages/bun-plugin/src/__tests__/commonjs-runtime.child.ts create mode 100644 packages/bun-plugin/src/__tests__/commonjs-runtime.test.ts create mode 100644 packages/bun-plugin/src/commonjs.ts diff --git a/.changepacks/changepack_log_bun_runtime_commonjs.json b/.changepacks/changepack_log_bun_runtime_commonjs.json new file mode 100644 index 000000000..554c25574 --- /dev/null +++ b/.changepacks/changepack_log_bun_runtime_commonjs.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/bun-plugin/package.json": "Patch" + }, + "note": "Compile every source kind under the Bun runtime: `.mts`, `.cts`, and `.js` and `.cjs` files outside `node_modules` join `.ts`, `.tsx`, `.jsx` and `.mjs`. CommonJS keeps its exports: Bun does not run CommonJS an `onLoad` callback returns, so the runtime plugin runs the module itself and hands Bun an ES module exporting its `module.exports` to `require()` and `import`. Source loads are synchronous, so `require()` works on compiled files too.", + "date": "2026-11-17T00:00:00.000Z" +} diff --git a/apps/landing/src/app/(detail)/docs/limitations/page.mdx b/apps/landing/src/app/(detail)/docs/limitations/page.mdx index 82152bae5..573d30103 100644 --- a/apps/landing/src/app/(detail)/docs/limitations/page.mdx +++ b/apps/landing/src/app/(detail)/docs/limitations/page.mdx @@ -100,7 +100,7 @@ A dynamic value such as `width` becomes a CSS variable set in `style`, so a comp - `withComponent` takes a tag name or a component written as a name or `a.b`. A target only the runtime knows, as `withComponent(make())`, is a build error: the styled component compiles to a plain function with no `withComponent`. Pass the target directly, or render with `as`. - 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 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`, `.mjs`, `.js` and `.cjs` files, ES modules and CommonJS alike, under the runtime as in `Bun.build`; `require()` and `import` keep the exports of a CommonJS module. Inside `node_modules` it compiles `.js` and `.cjs` files of `@devup-ui` packages only. A Bun runtime plugin must return the source of every file it matches, and Bun runs that source as an ES module, so under the runtime the plugin runs a CommonJS module itself and hands Bun an ES module that exports its `module.exports`. - 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 diff --git a/packages/bun-plugin/README.md b/packages/bun-plugin/README.md index 3fb45ddf9..98ec4e6f6 100644 --- a/packages/bun-plugin/README.md +++ b/packages/bun-plugin/README.md @@ -62,16 +62,24 @@ 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. Devup UI code in a `.js` file of -your own project is not compiled and 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. +`.ts`, `.mts`, `.cts`, `.tsx`, `.jsx` and `.mjs` files are compiled wherever +they are, and `.js` and `.cjs` files outside `node_modules` and inside +`@devup-ui` packages. The `.js` and `.cjs` files of other packages in +`node_modules` are left to Bun. + +ES modules and CommonJS are both supported, under the runtime as in +`Bun.build`. A `.cjs`, `.cts` or `.js` file written with `require`, +`module.exports`, `exports.name` or `export =` keeps its exports for +`require()` and `import`. + +A Bun runtime plugin must return the source of every file it matches, and Bun +runs returned source as an ES module: CommonJS returned as is would not run +and would export nothing. So under the runtime the plugin runs a CommonJS +module itself, when it is loaded, as Bun does, and hands Bun an ES module that +exports its `module.exports`. `require()` returns `module.exports`, and +`import` gets it as `default` (`exports.default` when `__esModule` is set) +along with its named exports. `.jsx` and `.tsx` files are ES modules, as Bun +reads them. ## Compiler Engine diff --git a/packages/bun-plugin/src/__tests__/commonjs-runtime.child.ts b/packages/bun-plugin/src/__tests__/commonjs-runtime.child.ts new file mode 100644 index 000000000..963cdc197 --- /dev/null +++ b/packages/bun-plugin/src/__tests__/commonjs-runtime.child.ts @@ -0,0 +1,45 @@ +// Loads every source kind through the registered runtime plugin, in a fresh +// Bun process without the repository's test preload. Prints what `require()` +// and `import` return, and the stylesheet the plugin wrote. +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { join } from 'node:path' + +import { register } from '../plugin' + +const [root, order, ...files] = process.argv.slice(2) +if (!root) throw new Error('Expected a fixture root') +const importFirst = order === 'import-first' +process.chdir(root) +await register({ engine: 'wasm' }) + +function describe(value: unknown): unknown { + if (typeof value === 'function') return { function: value() } + if (typeof value !== 'object' || value === null) return value + return Object.fromEntries( + Object.keys(value) + .sort() + .map((key) => [key, describe(Reflect.get(value, key))]), + ) +} + +const require = createRequire(join(root, 'entry.js')) +const results: Record = {} +for (const file of files) { + const path = join(root, file) + let imported: Record = {} + if (importFirst) imported = await import(path) + const required: unknown = require(path) + if (!importFirst) imported = await import(path) + results[file] = { + required: describe(required), + imported: describe({ ...imported }), + same: 'default' in imported && imported.default === required, + } +} +process.stdout.write( + JSON.stringify({ + results, + css: readFileSync(join(root, 'df', 'devup-ui', 'devup-ui.css'), 'utf-8'), + }), +) diff --git a/packages/bun-plugin/src/__tests__/commonjs-runtime.test.ts b/packages/bun-plugin/src/__tests__/commonjs-runtime.test.ts new file mode 100644 index 000000000..455d620a4 --- /dev/null +++ b/packages/bun-plugin/src/__tests__/commonjs-runtime.test.ts @@ -0,0 +1,164 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { afterAll, describe, expect, it } from 'bun:test' + +// Every source kind, loaded through the runtime plugin in a fresh Bun process +const sources: Record = { + 'commonjs.cjs': `const { css } = require('@devup-ui/react') +module.exports = { cls: css({ color: '#010203' }), self: this === module.exports, file: require('node:path').basename(__filename) } +`, + 'export-equals.cts': `import { css } from '@devup-ui/react' +const kind: string = 'export =' +export = { cls: css({ color: '#040506' }), kind } +`, + 'module-exports.cts': `const { css } = require('@devup-ui/react') +module.exports = { cls: css({ color: '#070809' }) as string } +`, + 'commonjs.js': `const react = require('@devup-ui/react') +exports.cls = react.css({ color: '#0A0B0C' }) +exports.run = function () { return 'run' } +`, + 'module.js': `import { css } from '@devup-ui/react' +export const cls = css({ color: '#0D0E0F' }) +`, + 'module.mts': `import { css } from '@devup-ui/react' +export const cls: string = css({ color: '#101112' }) +`, + 'function.cjs': `module.exports = function plain() { return 'plain' } +module.exports.extra = 1 +`, + 'interop.cjs': `Object.defineProperty(exports, '__esModule', { value: true }) +exports.default = 'main' +exports.named = 'named' +`, + 'cycle-a.cjs': `exports.early = 'early' +exports.seen = require('./cycle-b.cjs').seen +`, + 'cycle-b.cjs': `exports.seen = require('./cycle-a.cjs').early +`, + 'syntax.cjs': `export const kind = 'module syntax' +`, +} +const files = Object.keys(sources).filter((file) => file !== 'cycle-b.cjs') +const colors = ['010203', '040506', '070809', '0A0B0C', '0D0E0F', '101112'] + +const roots: string[] = [] +afterAll(() => { + for (const root of roots) rmSync(root, { recursive: true, force: true }) +}) + +function fixture() { + const root = mkdtempSync(join(tmpdir(), 'devup-bun-commonjs-')) + roots.push(root) + writeFileSync(join(root, 'bunfig.toml'), '') + writeFileSync(join(root, 'devup.json'), '{}') + for (const [file, source] of Object.entries(sources)) + writeFileSync(join(root, file), source) + // The runtime stub a `require()` the extractor keeps loads + const react = join(root, 'node_modules', '@devup-ui', 'react') + mkdirSync(react, { recursive: true }) + writeFileSync( + join(react, 'package.json'), + '{"name":"@devup-ui/react","main":"index.js"}', + ) + writeFileSync( + join(react, 'index.js'), + "exports.css = () => { throw new Error('Cannot run on the runtime') }\n", + ) + return root +} + +interface Loaded { + required: unknown + imported: unknown + same: boolean +} + +function run(root: string, order: string) { + const child = Bun.spawnSync( + [ + process.execPath, + join(import.meta.dir, 'commonjs-runtime.child.ts'), + root, + order, + ...files, + ], + { + cwd: root, + stdout: 'pipe', + stderr: 'pipe', + timeout: 30000, + env: { ...process.env, BUN_RUNTIME_TRANSPILER_CACHE_PATH: '0' }, + }, + ) + expect(child.stderr.toString()).toBe('') + expect(child.exitCode).toBe(0) + const output: { results: Record; css: string } = JSON.parse( + child.stdout.toString(), + ) + return output +} + +/** What Bun gives for a CommonJS module that exports `value` */ +function commonJs(value: Record): Loaded { + return { + required: value, + imported: { ...value, default: value, 'module.exports': value }, + same: true, + } +} + +const styled = { cls: expect.any(String) } + +describe.each(['require-first', 'import-first'])('Bun runtime, %s', (order) => { + it('keeps the exports of every source kind and compiles their styles', () => { + const { results, css } = run(fixture(), order) + expect(results).toEqual({ + 'commonjs.cjs': commonJs({ ...styled, self: true, file: 'commonjs.cjs' }), + 'export-equals.cts': commonJs({ ...styled, kind: 'export =' }), + 'module-exports.cts': commonJs(styled), + 'commonjs.js': commonJs({ ...styled, run: { function: 'run' } }), + 'module.js': { required: styled, imported: styled, same: false }, + 'module.mts': { required: styled, imported: styled, same: false }, + 'function.cjs': { + required: { function: 'plain' }, + imported: { + default: { function: 'plain' }, + 'module.exports': { function: 'plain' }, + extra: 1, + }, + same: true, + }, + 'interop.cjs': { + required: { default: 'main', named: 'named' }, + imported: { + default: 'main', + 'module.exports': { default: 'main', named: 'named' }, + named: 'named', + }, + same: false, + }, + 'cycle-a.cjs': commonJs({ early: 'early', seen: 'early' }), + 'syntax.cjs': { + required: { kind: 'module syntax' }, + imported: { kind: 'module syntax' }, + same: false, + }, + }) + // Every module's class is in the stylesheet, with its color + const classes = Object.values(results).flatMap(({ required }) => + typeof required === 'object' && + required !== null && + 'cls' in required && + typeof required.cls === 'string' + ? [required.cls] + : [], + ) + expect(classes).toHaveLength(colors.length) + classes.forEach((cls, index) => + expect(css).toContain(`.${cls}{color:#${colors[index]}}`), + ) + }, 60000) +}) diff --git a/packages/bun-plugin/src/__tests__/plugin.test.ts b/packages/bun-plugin/src/__tests__/plugin.test.ts index 9d656825a..2ed600bf4 100644 --- a/packages/bun-plugin/src/__tests__/plugin.test.ts +++ b/packages/bun-plugin/src/__tests__/plugin.test.ts @@ -81,6 +81,11 @@ describe('shorthand creation boundary', () => { const root = fs.mkdtempSync(join(tmpdir(), 'devup-ui-bun-hooks-')) const scopedRoot = join(root, '@devup-ui/fixture') fs.mkdirSync(scopedRoot, { recursive: true }) +// The runtime stub a `require()` the extractor keeps in CommonJS loads +const reactStub = join(root, 'node_modules/@devup-ui/react') +fs.mkdirSync(reactStub, { recursive: true }) +fs.writeFileSync(join(reactStub, 'package.json'), '{"main":"index.js"}') +fs.writeFileSync(join(reactStub, 'index.js'), 'exports.css = () => {}') const realPlugin = Bun.plugin const realExists = fs.existsSync const realResolve = nodePath.resolve @@ -410,6 +415,9 @@ describe('registered Bun hooks', () => { ['jsx', 'jsx'], ['mjs', 'js'], ['js', 'js'], + ['cjs', 'js'], + ['mts', 'ts'], + ['cts', 'ts'], ] as const) { it(`compiles a ${extension} source through the captured onLoad callback`, async () => { const source = @@ -486,3 +494,175 @@ describe('registered Bun hooks', () => { await expect(load(path)).rejects.toThrow(/invalid\.ts:\d+:\d+:/) }) }) + +describe('CommonJS under the runtime', () => { + async function loadSource(name: string, source: string) { + const path = join(root, name) + await Bun.write(path, source) + await register({ engine: 'wasm' }) + return { path, result: await load(path) } + } + + /** Imports the ES module the plugin hands Bun in place of CommonJS */ + async function importResult(name: string, result: unknown) { + if ( + typeof result !== 'object' || + result === null || + !('contents' in result) || + typeof result.contents !== 'string' + ) + throw new Error('Expected source contents') + expect(result).toEqual({ contents: result.contents, loader: 'js' }) + const path = join(root, `${name}.mjs`) + await Bun.write(path, result.contents) + const module: Record = await import(path) + return module + } + + it('runs CommonJS that uses Devup UI and exports what it assigns', async () => { + const { path, result } = await loadSource( + 'styled.cjs', + "const { css } = require('@devup-ui/react')\nmodule.exports = { cls: css({ color: 'navy' }), file: __filename }", + ) + const exported = require.cache[path]?.exports + expect(exported).toEqual({ cls: expect.any(String), file: path }) + expect({ ...(await importResult('styled', result)) }).toEqual({ + 'module.exports': exported, + default: exported, + cls: exported.cls, + file: path, + }) + expect(writeSync).toHaveBeenCalledWith( + expect.stringContaining('devup-ui.css'), + expect.stringContaining('navy'), + 'utf-8', + ) + }) + + it('strips TypeScript from CommonJS without fixing its path', async () => { + const { result } = await loadSource( + 'typed.cts', + 'const directory: string = __dirname\nexport = { directory, env: process.env.NODE_ENV, defined: typeof __filename }', + ) + expect({ ...(await importResult('typed', result)) }).toMatchObject({ + default: { + directory: root, + env: process.env.NODE_ENV, + defined: 'string', + }, + }) + }) + + it('exports functions, primitives and null as Bun does', async () => { + const callable = await loadSource( + 'callable.cjs', + "module.exports = function named() { return 'called' }\nmodule.exports.extra = 1", + ) + const module = await importResult('callable', callable.result) + expect(module.default).toBe(module['module.exports']) + expect(module.extra).toBe(1) + expect(Object.keys(module).sort()).toEqual([ + 'default', + 'extra', + 'module.exports', + ]) + for (const [name, value] of [ + ['text', 'text'], + ['nothing', null], + ] as const) { + const { result } = await loadSource( + `${name}.cjs`, + `module.exports = ${JSON.stringify(value)}`, + ) + expect({ ...(await importResult(name, result)) }).toEqual({ + 'module.exports': value, + default: value, + }) + } + }) + + it('takes the default export of a compiled ES module', async () => { + const { result } = await loadSource( + 'compiled.cjs', + "Object.defineProperty(exports, '__esModule', { value: true })\nexports.default = 'main'\nexports.named = 'named'", + ) + const module = await importResult('compiled', result) + expect(module.default).toBe('main') + expect(module.named).toBe('named') + }) + + it('runs a module again when it is loaded again', async () => { + const { path } = await loadSource('again.cjs', 'exports.at = Math.random()') + const first = require.cache[path] + await load(path) + expect(require.cache[path]).not.toBe(first) + expect(require.cache[path]?.loaded).toBe(true) + }) + + it('drops a module that throws from the require cache', async () => { + const path = join(root, 'throws.cjs') + await Bun.write(path, "exports.before = 1\nthrow new Error('boom')") + await register({ engine: 'wasm' }) + await expect(load(path)).rejects.toThrow('boom') + expect(require.cache[path]).toBeUndefined() + }) + + for (const [name, source, loader] of [ + ['module-syntax.cjs', "export const kind = 'module'", 'js'], + ['top-level-await.cjs', 'module.exports = await Promise.resolve(1)', 'js'], + ['broken.cts', 'module.exports = (', 'ts'], + ] as const) + it(`leaves ${name} to Bun`, async () => { + const { result } = await loadSource(name, source) + expect(result).toEqual({ contents: source, loader }) + }) + + it('hands CommonJS to Bun.build, which bundles it', async () => { + const entry = join(root, 'bundled-entry.mjs') + await Bun.write( + join(root, 'bundled.cjs'), + "const { css } = require('@devup-ui/react')\nmodule.exports = { cls: css({ color: 'teal' }) }", + ) + await Bun.write( + join(root, 'bundled.cts'), + "import { css } from '@devup-ui/react'\nexport = { cls: css({ color: 'olive' }) }", + ) + await Bun.write( + entry, + "export { default as cjs } from './bundled.cjs'\nexport { default as cts } from './bundled.cts'", + ) + const result = await Bun.build({ + entrypoints: [entry], + target: 'bun', + external: ['@devup-ui/react'], + outdir: join(root, 'bundled'), + plugins: [DevupUI({ engine: 'wasm' })], + }) + expect(result.success).toBe(true) + const css = await Promise.all( + result.outputs + .filter((output) => output.path.endsWith('.css')) + .map((output) => output.text()), + ) + expect(css.join('')).toMatch(/color:\s*teal/) + expect(css.join('')).toMatch(/color:\s*olive/) + const output = result.outputs.find(({ path }) => path.endsWith('.js')) + if (!output) throw new Error('Expected a bundle') + const bundle: Record = await import(output.path) + expect(bundle).toEqual({ + cjs: { cls: expect.any(String) }, + cts: { cls: expect.any(String) }, + }) + }) + + it('keeps exports through the registered runtime plugin', async () => { + const required = join(root, 'required.cjs') + const imported = join(root, 'imported.cts') + await Bun.write(required, "exports.kind = 'required'") + await Bun.write(imported, "export = { kind: 'imported' as string }") + expect(require(required)).toEqual({ kind: 'required' }) + const module: Record = await import(imported) + expect(module.default).toEqual({ kind: 'imported' }) + expect(module.kind).toBe('imported') + }) +}) diff --git a/packages/bun-plugin/src/commonjs.ts b/packages/bun-plugin/src/commonjs.ts new file mode 100644 index 000000000..7f2677f02 --- /dev/null +++ b/packages/bun-plugin/src/commonjs.ts @@ -0,0 +1,172 @@ +import { randomUUID } from 'node:crypto' +import Module, { createRequire } from 'node:module' +import { dirname } from 'node:path' +import { constants, runInThisContext } from 'node:vm' + +/** + * CommonJS under the Bun runtime. + * + * Bun reads the contents an `onLoad` callback returns as an ES module. When + * those contents are CommonJS, Bun wraps them in the CommonJS function wrapper + * but never calls it: the module body does not run, and `require()` and + * `import` see `{}` (Bun 1.4). `Bun.build` is not affected. + * + * So the runtime plugin runs a CommonJS module itself and hands Bun an ES + * module that exports the result the way Bun exports CommonJS: `require()` + * returns `module.exports` through the `"module.exports"` export, and `import` + * gets `default` and the named exports. As in Bun's own loader, the module + * runs when it is loaded, before the ES modules that import it. + */ + +type ModuleFunction = (this: unknown, ...args: unknown[]) => void + +/** Words CommonJS uses; a file without any is an ES module or a script */ +const commonJsWords = /\b(?:module|exports)\b|\bexport\s*=/ +/** Extensions Node runs as CommonJS unless they hold module syntax */ +const commonJsExtension = /\.c[jt]s$/ +const esModuleExtension = /\.m[jt]s$/ + +// Bun's transpiler replaces `__filename` and `__dirname` with constants for a +// file it has no path of, and inlines `process.env.NODE_ENV`. The module reads +// them when it runs instead. +const filenameAlias = '__devupUiFilename' +const dirnameAlias = '__devupUiDirname' +const typeScript = new Bun.Transpiler({ + loader: 'ts', + target: 'bun', + define: { + __filename: filenameAlias, + __dirname: dirnameAlias, + 'process.env.NODE_ENV': 'process.env.NODE_ENV', + }, +}) +const javaScript = new Bun.Transpiler({ loader: 'js', target: 'bun' }) + +/** The values the generated ES modules export, by load */ +const loaded = new Map() +// Unique to this copy of the plugin, so a second copy keeps its own values +const loadedKey = `devup-ui:commonjs:${randomUUID()}` +Object.defineProperty(globalThis, Symbol.for(loadedKey), { value: loaded }) +let loads = 0 + +/** + * `code` as a CommonJS script, or `undefined` for an ES module. Bun reports + * the syntax error of code that does not parse when it loads the source. + */ +function toScript(code: string, loader: 'ts' | 'js') { + try { + const script = loader === 'ts' ? typeScript.transformSync(code) : code + const { exports, imports } = javaScript.scan(script) + return exports.length > 0 || + imports.some(({ kind }) => kind === 'import-statement') + ? undefined + : script + } catch { + return undefined + } +} + +/** The module function of `script`, or `undefined` when it is no script */ +function compile(script: string, path: string): ModuleFunction | undefined { + try { + return runInThisContext( + `(function (exports, require, module, __filename, __dirname, ${filenameAlias}, ${dirnameAlias}) {${ + // A hashbang is only valid at the start of a file + script.replace(/^#!/, '//') + }\n})`, + { + filename: path, + importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER, + }, + ) + } catch { + // Syntax only an ES module holds, such as top-level await or + // `import.meta`: Bun loads the source as an ES module + return undefined + } +} + +/** Runs a CommonJS module and returns its `module.exports` */ +function evaluate(run: ModuleFunction, path: string): unknown { + const require = createRequire(path) + // `require()` registers the module before Bun calls `onLoad`; `import` + // does not, so the module is registered here. A cycle back to this file + // then gets the exports so far, as it does in Node. + let module = require.cache[path] + if (!module || module.loaded) { + module = new Module(path) + module.filename = path + require.cache[path] = module + } + const directory = dirname(path) + try { + run.call( + module.exports, + module.exports, + require, + module, + path, + directory, + path, + directory, + ) + } catch (error) { + delete require.cache[path] + throw error + } + module.loaded = true + return module.exports +} + +/** An ES module exporting `value` as Bun exports CommonJS */ +function exportingSource(value: unknown) { + const id = loads++ + loaded.set(id, value) + const names = + (typeof value === 'object' && value !== null) || typeof value === 'function' + ? Object.keys(value).filter( + (name) => name !== 'default' && name !== 'module.exports', + ) + : [] + return [ + `const loaded = globalThis[Symbol.for(${JSON.stringify(loadedKey)})]`, + `const value = loaded.get(${id})`, + `loaded.delete(${id})`, + // Babel and TypeScript mark an ES module compiled to CommonJS + 'const main = value?.__esModule ? value.default : value', + 'export { value as "module.exports", main as default }', + ...names.map( + (name, index) => + `const name${index} = value[${JSON.stringify(name)}]\nexport { name${index} as ${JSON.stringify(name)} }`, + ), + ].join('\n') +} + +/** + * Runs `code` when it is a CommonJS module, and returns the ES module Bun is + * to load in its place; `undefined` for an ES module. + * + * `stylesheet` is the stylesheet import the extractor added. Under the runtime + * it loads nothing, and CommonJS cannot hold an import. + */ +export function commonJsSource( + path: string, + code: string, + loader: string, + stylesheet?: string, +) { + if ( + (loader !== 'ts' && loader !== 'js') || + esModuleExtension.test(path) || + !(commonJsExtension.test(path) || commonJsWords.test(code)) + ) + return undefined + const script = toScript( + stylesheet === undefined + ? code + : code.replace(`import ${JSON.stringify(stylesheet)};\n`, ''), + loader, + ) + const run = script === undefined ? undefined : compile(script, path) + return run && exportingSource(evaluate(run, path)) +} diff --git a/packages/bun-plugin/src/plugin.ts b/packages/bun-plugin/src/plugin.ts index 0e2b55754..c22ab9ac3 100644 --- a/packages/bun-plugin/src/plugin.ts +++ b/packages/bun-plugin/src/plugin.ts @@ -1,4 +1,4 @@ -import { existsSync, writeFileSync } from 'node:fs' +import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { mkdir, writeFile } from 'node:fs/promises' import { dirname, join, relative, resolve } from 'node:path' @@ -26,6 +26,7 @@ import { } from '@devup-ui/plugin-utils' import { type BunPlugin, plugin, type PluginBuilder } from 'bun' +import { commonJsSource } from './commonjs' import { cssDirName, cssNamespace, resolveCssId } from './css-id' import { createTailwindWatcher } from './tailwind-watch' @@ -136,30 +137,41 @@ function importsCompiledPackage(contents: string, loader: SourceLoader) { } } -async function loadSourceFile( - compiler: DevupCompiler, - filePath: string, - bundling: boolean, -) { - const loader: SourceLoader = filePath.endsWith('.tsx') +/** Bun's loader for a source file */ +function sourceLoader(filePath: string): SourceLoader { + return filePath.endsWith('.tsx') ? 'tsx' - : filePath.endsWith('.ts') + : /\.[cm]?ts$/.test(filePath) ? 'ts' : filePath.endsWith('.jsx') ? 'jsx' : 'js' - const contents = await Bun.file(filePath).text() +} + +// Synchronous: Bun cannot `require()` a module whose `onLoad` is async +function loadSourceFile( + compiler: DevupCompiler, + filePath: string, + bundling: boolean, +) { + const loader = sourceLoader(filePath) + let contents = readFileSync(filePath, 'utf-8') + let stylesheet: string | undefined if ( isProjectJsx(filePath, importAliases) || importsCompiledPackage(contents, loader) || compiler.hasDevupUI(filePath, contents, libPackage, importAliases) ) { + const cssImportDir = relative(dirname(filePath), cssDir).replaceAll( + '\\', + '/', + ) using code = compiler.codeExtract( filePath, contents, libPackage, - relative(dirname(filePath), cssDir).replaceAll('\\', '/'), + cssImportDir, singleCss, true, false, @@ -173,9 +185,16 @@ 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 } + contents = code.code + stylesheet = `${cssImportDir}/devup-ui.css` } - return { contents, loader } + // `Bun.build` bundles the CommonJS it is handed; the runtime does not run it + const commonJs = bundling + ? undefined + : commonJsSource(filePath, contents, loader, stylesheet) + return commonJs === undefined + ? { contents, loader } + : { contents: commonJs, loader: 'js' as const } } /** @@ -278,10 +297,12 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) { }, ) - // Load source files from packages directory (file namespace) + // Load every TypeScript and JavaScript source, ES module or CommonJS. + // JavaScript in node_modules is left to Bun, except Devup UI's own. build.onLoad( { - filter: /\.(?:tsx?|jsx|mjs)$|[\\/]@devup-ui[\\/].*\.js$/, + filter: + /\.(?:[cm]?tsx?|jsx|mjs)$|^(?![^]*[\\/]node_modules[\\/])[^]*\.c?js$|[\\/]node_modules[\\/]@devup-ui[\\/](?![^]*[\\/]node_modules[\\/])[^]*\.c?js$/, }, ({ path }) => { if (reservationPending) { From b855c2f66144566811591fa3d3d3175c3d367a7d Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Tue, 17 Nov 2026 13:23:45 +0900 Subject: [PATCH 2/3] test(bun-plugin): require the runtime fixture through createRequire The lint forbids require() imports; createRequire goes through the same Bun loader and plugin, so the test still checks the CommonJS exports. Co-Authored-By: Claude Opus 5.5 --- packages/bun-plugin/src/__tests__/plugin.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/bun-plugin/src/__tests__/plugin.test.ts b/packages/bun-plugin/src/__tests__/plugin.test.ts index 2ed600bf4..822af400d 100644 --- a/packages/bun-plugin/src/__tests__/plugin.test.ts +++ b/packages/bun-plugin/src/__tests__/plugin.test.ts @@ -1,4 +1,5 @@ import * as fs from 'node:fs' +import { createRequire } from 'node:module' import { tmpdir } from 'node:os' import * as nodePath from 'node:path' import { join } from 'node:path' @@ -660,7 +661,9 @@ describe('CommonJS under the runtime', () => { const imported = join(root, 'imported.cts') await Bun.write(required, "exports.kind = 'required'") await Bun.write(imported, "export = { kind: 'imported' as string }") - expect(require(required)).toEqual({ kind: 'required' }) + expect(createRequire(import.meta.url)(required)).toEqual({ + kind: 'required', + }) const module: Record = await import(imported) expect(module.default).toEqual({ kind: 'imported' }) expect(module.kind).toBe('imported') From 9f3d68fb1e2771ed76ba3bedcc1e3dcfa8df89d9 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Tue, 17 Nov 2026 14:59:24 +0900 Subject: [PATCH 3/3] test(bun-plugin): run the Bun.build bundle in its own process The bundle the Bun.build CommonJS test imported in-process landed in the root coverage report at 82% lines (Bun's unused CommonJS interop helpers) and failed the 100% threshold. Import it in a child process instead. Co-Authored-By: Claude Opus 5.5 --- packages/bun-plugin/src/__tests__/plugin.test.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/bun-plugin/src/__tests__/plugin.test.ts b/packages/bun-plugin/src/__tests__/plugin.test.ts index 72c1a14a1..45d1b7fc8 100644 --- a/packages/bun-plugin/src/__tests__/plugin.test.ts +++ b/packages/bun-plugin/src/__tests__/plugin.test.ts @@ -751,8 +751,17 @@ describe('CommonJS under the runtime', () => { expect(css.join('')).toMatch(/color:\s*olive/) const output = result.outputs.find(({ path }) => path.endsWith('.js')) if (!output) throw new Error('Expected a bundle') - const bundle: Record = await import(output.path) - expect(bundle).toEqual({ + // Run the bundle in its own process, so its code stays out of coverage + const child = Bun.spawnSync( + [ + process.execPath, + '-e', + `console.log(JSON.stringify(await import(${JSON.stringify(output.path)})))`, + ], + { cwd: root, stdout: 'pipe', stderr: 'pipe' }, + ) + expect(child.stderr.toString()).toBe('') + expect(JSON.parse(child.stdout.toString())).toEqual({ cjs: { cls: expect.any(String) }, cts: { cls: expect.any(String) }, })