-
Notifications
You must be signed in to change notification settings - Fork 116
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: support bun
plugin
#333
Draft
Dunqing
wants to merge
4
commits into
unjs:main
Choose a base branch
from
Dunqing:feat/bun
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+415
β2
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,134 @@ | ||||||
import fs from 'fs' | ||||||
import type { SourceMap } from 'rollup' | ||||||
import type { RawSourceMap } from '@ampproject/remapping' | ||||||
import type { BunPlugin, UnpluginBuildContext, UnpluginContext, UnpluginContextMeta, UnpluginFactory, UnpluginInstance, UnpluginOptions } from '../types' | ||||||
import { combineSourcemaps, createBunContext, guessLoader, processCodeWithSourceMap, toArray } from './utils' | ||||||
|
||||||
let i = 0 | ||||||
|
||||||
export function getBunPlugin<UserOptions = Record<string, never>>( | ||||||
factory: UnpluginFactory<UserOptions>, | ||||||
): UnpluginInstance<UserOptions>['bun'] { | ||||||
return (userOptions?: UserOptions): BunPlugin => { | ||||||
const meta: UnpluginContextMeta = { | ||||||
framework: 'bun', | ||||||
} | ||||||
const plugins = toArray(factory(userOptions!, meta)) | ||||||
|
||||||
const setup = (plugin: UnpluginOptions): BunPlugin['setup'] => | ||||||
plugin.bun?.setup | ||||||
?? ((build) => { | ||||||
meta.build = build | ||||||
const { onResolve, onLoad, config: initialOptions } = build | ||||||
|
||||||
const onResolveFilter = plugin.esbuild?.onResolveFilter ?? /.*/ | ||||||
const onLoadFilter = plugin.esbuild?.onLoadFilter ?? /.*/ | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
||||||
const context: UnpluginBuildContext = createBunContext(initialOptions) | ||||||
|
||||||
if (plugin.resolveId) { | ||||||
onResolve({ filter: onResolveFilter }, async (args) => { | ||||||
if (initialOptions.external?.includes(args.path)) { | ||||||
// We don't want to call the `resolveId` hook for external modules, since rollup doesn't do | ||||||
// that and we want to have consistent behaviour across bundlers | ||||||
return undefined | ||||||
} | ||||||
|
||||||
const isEntry = args.kind === 'entry-point' | ||||||
const result = await plugin.resolveId!( | ||||||
args.path, | ||||||
// We explicitly have this if statement here for consistency with the integration of other bundelers. | ||||||
// Here, `args.importer` is just an empty string on entry files whereas the euqivalent on other bundlers is `undefined.` | ||||||
isEntry ? undefined : args.importer, | ||||||
{ isEntry }, | ||||||
) | ||||||
if (typeof result === 'string') | ||||||
return { path: result, namespace: plugin.name } | ||||||
else if (typeof result === 'object' && result !== null) | ||||||
return { path: result.id, external: result.external, namespace: plugin.name } | ||||||
}) | ||||||
} | ||||||
|
||||||
if (plugin.load || plugin.transform) { | ||||||
onLoad({ filter: onLoadFilter }, async (args) => { | ||||||
const id = args.path | ||||||
|
||||||
let code: string | undefined, map: SourceMap | null | undefined | ||||||
|
||||||
if (plugin.load && (!plugin.loadInclude || plugin.loadInclude(id))) { | ||||||
const result = await plugin.load.call(context as UnpluginBuildContext & UnpluginContext, id) | ||||||
if (typeof result === 'string') { | ||||||
code = result | ||||||
} | ||||||
else if (typeof result === 'object' && result !== null) { | ||||||
code = result.code | ||||||
map = result.map as any | ||||||
} | ||||||
} | ||||||
|
||||||
if (!plugin.transform) { | ||||||
if (code === undefined) { | ||||||
return { | ||||||
contents: '', | ||||||
} | ||||||
} | ||||||
|
||||||
if (map) | ||||||
code = processCodeWithSourceMap(map, code) | ||||||
|
||||||
return { contents: code, loader: guessLoader(args.path) } | ||||||
} | ||||||
|
||||||
if (!plugin.transformInclude || plugin.transformInclude(id)) { | ||||||
if (!code) { | ||||||
// caution: 'utf8' assumes the input file is not in binary. | ||||||
// if you want your plugin handle binary files, make sure to | ||||||
// `plugin.load()` them first. | ||||||
code = await fs.promises.readFile(args.path, 'utf8') | ||||||
} | ||||||
|
||||||
const result = await plugin.transform.call(context as UnpluginBuildContext & UnpluginContext, code, id) | ||||||
if (typeof result === 'string') { | ||||||
code = result | ||||||
} | ||||||
else if (typeof result === 'object' && result !== null) { | ||||||
code = result.code | ||||||
// if we already got sourcemap from `load()`, | ||||||
// combine the two sourcemaps | ||||||
if (map && result.map) { | ||||||
map = combineSourcemaps(args.path, [ | ||||||
result.map as RawSourceMap, | ||||||
map as RawSourceMap, | ||||||
]) as SourceMap | ||||||
} | ||||||
else { | ||||||
// otherwise, we always keep the last one, even if it's empty | ||||||
map = result.map as any | ||||||
} | ||||||
} | ||||||
} | ||||||
|
||||||
if (code) { | ||||||
if (map) | ||||||
code = processCodeWithSourceMap(map, code) | ||||||
return { contents: code, loader: guessLoader(args.path) } | ||||||
} | ||||||
|
||||||
return { | ||||||
contents: '', | ||||||
} | ||||||
}) | ||||||
} | ||||||
}) | ||||||
|
||||||
const setupMultiplePlugins = (): BunPlugin['setup'] => | ||||||
(build) => { | ||||||
for (const plugin of plugins) | ||||||
setup(plugin)(build) | ||||||
} | ||||||
|
||||||
return plugins.length === 1 | ||||||
? { name: plugins[0].name, setup: setup(plugins[0]) } | ||||||
: { name: meta.bunHostName ?? `unplugin-host-${i++}`, setup: setupMultiplePlugins() } | ||||||
} | ||||||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,135 @@ | ||||||
import fs from 'fs' | ||||||
import path from 'path' | ||||||
import { Buffer } from 'buffer' | ||||||
import remapping from '@ampproject/remapping' | ||||||
import { Parser } from 'acorn' | ||||||
import type { DecodedSourceMap, EncodedSourceMap } from '@ampproject/remapping' | ||||||
import type { Loader, PluginBuilder } from 'bun' | ||||||
import type { SourceMap } from 'rollup' | ||||||
import type { UnpluginBuildContext } from '../types' | ||||||
|
||||||
export * from '../utils' | ||||||
|
||||||
const ExtToLoader: Record<string, Loader> = { | ||||||
'.js': 'js', | ||||||
'.mjs': 'js', | ||||||
'.cjs': 'js', | ||||||
'.jsx': 'jsx', | ||||||
'.ts': 'ts', | ||||||
'.cts': 'ts', | ||||||
'.mts': 'ts', | ||||||
'.tsx': 'tsx', | ||||||
'.json': 'json', | ||||||
'.txt': 'text', | ||||||
'.toml': 'toml', | ||||||
'.node': 'napi', | ||||||
} | ||||||
|
||||||
export function guessLoader(id: string): Loader { | ||||||
return ExtToLoader[path.extname(id).toLowerCase()] || 'file' | ||||||
} | ||||||
|
||||||
// `load` and `transform` may return a sourcemap without toString and toUrl, | ||||||
// but esbuild needs them, we fix the two methods | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
export function fixSourceMap(map: EncodedSourceMap): SourceMap { | ||||||
if (!('toString' in map)) { | ||||||
Object.defineProperty(map, 'toString', { | ||||||
enumerable: false, | ||||||
value: function toString() { | ||||||
return JSON.stringify(this) | ||||||
}, | ||||||
}) | ||||||
} | ||||||
if (!('toUrl' in map)) { | ||||||
Object.defineProperty(map, 'toUrl', { | ||||||
enumerable: false, | ||||||
value: function toUrl() { | ||||||
return `data:application/json;charset=utf-8;base64,${Buffer.from(this.toString()).toString('base64')}` | ||||||
}, | ||||||
}) | ||||||
} | ||||||
return map as SourceMap | ||||||
} | ||||||
|
||||||
// taken from https://github.com/vitejs/vite/blob/71868579058512b51991718655e089a78b99d39c/packages/vite/src/node/utils.ts#L525 | ||||||
const nullSourceMap: EncodedSourceMap = { | ||||||
names: [], | ||||||
sources: [], | ||||||
mappings: '', | ||||||
version: 3, | ||||||
} | ||||||
export function combineSourcemaps( | ||||||
filename: string, | ||||||
sourcemapList: Array<DecodedSourceMap | EncodedSourceMap>, | ||||||
): EncodedSourceMap { | ||||||
sourcemapList = sourcemapList.filter(m => m.sources) | ||||||
|
||||||
if ( | ||||||
sourcemapList.length === 0 | ||||||
|| sourcemapList.every(m => m.sources.length === 0) | ||||||
) | ||||||
return { ...nullSourceMap } | ||||||
|
||||||
// We don't declare type here so we can convert/fake/map as EncodedSourceMap | ||||||
let map // : SourceMap | ||||||
let mapIndex = 1 | ||||||
const useArrayInterface | ||||||
= sourcemapList.slice(0, -1).find(m => m.sources.length !== 1) === undefined | ||||||
if (useArrayInterface) { | ||||||
map = remapping(sourcemapList, () => null, true) | ||||||
} | ||||||
else { | ||||||
map = remapping( | ||||||
sourcemapList[0], | ||||||
(sourcefile) => { | ||||||
if (sourcefile === filename && sourcemapList[mapIndex]) | ||||||
return sourcemapList[mapIndex++] | ||||||
else | ||||||
return { ...nullSourceMap } | ||||||
}, | ||||||
true, | ||||||
) | ||||||
} | ||||||
if (!map.file) | ||||||
delete map.file | ||||||
|
||||||
return map as EncodedSourceMap | ||||||
} | ||||||
|
||||||
export function createBunContext(initialOptions: PluginBuilder['config']): UnpluginBuildContext { | ||||||
return { | ||||||
parse(code: string, opts: any = {}) { | ||||||
return Parser.parse(code, { | ||||||
sourceType: 'module', | ||||||
ecmaVersion: 'latest', | ||||||
locations: true, | ||||||
...opts, | ||||||
}) | ||||||
}, | ||||||
addWatchFile() { | ||||||
}, | ||||||
emitFile(emittedFile) { | ||||||
// Ensure output directory exists for this.emitFile | ||||||
if (initialOptions.outdir && !fs.existsSync(initialOptions.outdir)) | ||||||
fs.mkdirSync(initialOptions.outdir, { recursive: true }) | ||||||
|
||||||
const outFileName = emittedFile.fileName || emittedFile.name | ||||||
if (initialOptions.outdir && emittedFile.source && outFileName) | ||||||
fs.writeFileSync(path.resolve(initialOptions.outdir, outFileName), emittedFile.source) | ||||||
}, | ||||||
getWatchFiles() { | ||||||
return [] | ||||||
}, | ||||||
} | ||||||
} | ||||||
|
||||||
export function processCodeWithSourceMap(map: SourceMap | null | undefined, code: string) { | ||||||
if (map) { | ||||||
if (!map.sourcesContent || map.sourcesContent.length === 0) | ||||||
map.sourcesContent = [code] | ||||||
|
||||||
map = fixSourceMap(map as EncodedSourceMap) | ||||||
code += `\n//# sourceMappingURL=${map.toUrl()}` | ||||||
} | ||||||
return code | ||||||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.