1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183 |
x6
x6
x6
x6
x6
x6
x22
x22
x2
x2
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x22
x21
x22
x20
x20
x22
x1
x22
x22
x22
x22
x22
x19
x19
x22
x2
x1
x1
x1
x1
x2
x2
x22
x20
x20
x21
x22
x6
x2
x2
x2
x2
x6
x4
x4
x2
x6
x1
x1
x1
x1
x1
x2
x2
x2
x2 |
I
|
import type { Nullable } from "@libs/typing"
import { denoLoaderPlugin, denoResolverPlugin } from "@luca/esbuild-deno-loader"
import { encodeBase64 } from "@std/encoding/base64"
import { minify as terser } from "terser"
import { fromFileUrl } from "@std/path/from-file-url"
import { delay } from "@std/async/delay"
export async function bundle(input: URL | string, { builder = "binary", minify = "terser", format = "esm", debug = false, banner = "", shadow = true, config, lockfile, exports, raw, overrides } = {} as options): Promise<string> {
const esbuild = builder === "wasm" ? await import("../vendored/esbuild/wasm.js") : await import("esbuild")
if (builder === "wasm") {
await esbuild.initialize({ worker: false })
}
const url = input instanceof URL ? input : new URL(`data:application/typescript;base64,${encodeBase64(input)}`)
let code = ""
try {
const { outputFiles: [{ text: output }] } = await esbuild.build({
plugins: [
overrides?.imports ? overridesImports({ imports: overrides.imports }) : null,
denoResolverPlugin({ configPath: config ? fromFileUrl(config) : undefined }),
denoLoaderPlugin({ configPath: config ? fromFileUrl(config) : undefined, lockPath: lockfile ? fromFileUrl(lockfile) : undefined }),
].filter((plugin): plugin is Plugin => Boolean(plugin)),
entryPoints: [url.href],
format,
globalName: exports,
write: false,
minify: minify === "basic",
target: "esnext",
treeShaking: true,
sourcemap: debug ? "inline" : false,
sourcesContent: debug,
bundle: true,
logLevel: "silent",
...raw,
})
code = output
if (minify) {
code = code.trim()
}
} catch (error) {
throw new TypeError(`Failed to bundle ts:\n${(error as Error).message}`)
} finally {
await esbuild.stop()
await delay(500)
}
if (minify === "terser") {
code = await terser(code, { format: { comments: false }, module: true, sourceMap: debug ? { url: "inline" } : false }).then((response) => response.code!)
}
if (banner) {
if (banner.includes("\n")) {
banner = `/**\n${banner.split("\n").map((line) => ` * ${line}`).join("\n")}\n */`
} else {
banner = `// ${banner}`
}
code = `${banner}\n${code}`
}
if (shadow) {
code = code.replaceAll(/(["'])(?<scheme>file:\/\/).*?\/(?<name>[A-Za-z0-9_]+\.(?:ts|js|mjs))\1/g, "'$<scheme>/shadow/$<name>'")
}
return code
}
export type options = {
builder?: "binary" | "wasm"
minify?: false | "basic" | "terser"
format?: "esm" | "iife"
exports?: string
debug?: boolean
config?: URL
lockfile?: URL
banner?: string
shadow?: boolean
raw?: Record<PropertyKey, unknown>
overrides?: {
imports?: Record<string, string>
}
}
type Plugin = {
name: string
setup: (build: { onResolve: (options: { filter: RegExp }, callback: (args: { path: string }) => Nullable<{ path: string; namespace: string }>) => void }) => void
}
function overridesImports(options: { imports: NonNullable<NonNullable<options["overrides"]>["imports"]> }): Plugin {
return ({
name: "libs-bundler-overrides-imports",
setup(build) {
build.onResolve({ filter: /.*/ }, (args) => {
if (!(args.path in options.imports)) {
return null
}
const url = new URL(options.imports[args.path])
if (url.protocol === "file:") {
return { path: fromFileUrl(url), namespace: "file" }
}
const namespace = url.protocol.slice(0, -1)
const path = url.href.slice(namespace.length + 1)
return { path, namespace }
})
},
}) as Plugin
}
|