@statewalker/webrun-bundler 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +190 -2
- package/dist/index.d.mts +202 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +630 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +63 -3
- package/src/bundle.test.ts +459 -0
- package/src/bundle.ts +291 -0
- package/src/index.ts +17 -0
- package/src/input-maps.ts +90 -0
- package/src/packages.ts +126 -0
- package/src/paths.ts +62 -0
- package/src/resolve.ts +116 -0
- package/src/types.ts +154 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
import { normalizePath, readText, tryReadText } from "@statewalker/webrun-files";
|
|
2
|
+
import { exports, imports } from "resolve.exports";
|
|
3
|
+
//#region src/paths.ts
|
|
4
|
+
/** `path` joined to `dir`, with `.` and `..` resolved; `undefined` when it leaves `root`. */
|
|
5
|
+
function joinWithin(root, dir, path) {
|
|
6
|
+
const parts = (path.startsWith("/") ? path : `${dir}/${path}`).split("/");
|
|
7
|
+
const out = [];
|
|
8
|
+
for (const p of parts) {
|
|
9
|
+
if (!p || p === ".") continue;
|
|
10
|
+
if (p === "..") {
|
|
11
|
+
if (!out.length) return void 0;
|
|
12
|
+
out.pop();
|
|
13
|
+
} else out.push(p);
|
|
14
|
+
}
|
|
15
|
+
const joined = `/${out.join("/")}`;
|
|
16
|
+
const r = normalizePath(root);
|
|
17
|
+
return r === "/" || joined === r || joined.startsWith(`${r}/`) ? joined : void 0;
|
|
18
|
+
}
|
|
19
|
+
const dirOf = (path) => path.slice(0, path.lastIndexOf("/")) || "/";
|
|
20
|
+
/** The id of a mount's file: `<prefix>/<path below root>`. */
|
|
21
|
+
function idOf(mount, path) {
|
|
22
|
+
const r = normalizePath(mount.root);
|
|
23
|
+
const rel = r === "/" ? path : path.slice(r.length);
|
|
24
|
+
return `${mount.prefix}${rel || "/"}`;
|
|
25
|
+
}
|
|
26
|
+
/** A mount's file from its id; `undefined` when the id is not the mount's. */
|
|
27
|
+
function pathOf(mount, id) {
|
|
28
|
+
if (!id.startsWith(`${mount.prefix}/`)) return void 0;
|
|
29
|
+
const r = normalizePath(mount.root);
|
|
30
|
+
const rel = id.slice(mount.prefix.length);
|
|
31
|
+
return r === "/" ? rel : `${r}${rel}`;
|
|
32
|
+
}
|
|
33
|
+
async function isFile(mount, path) {
|
|
34
|
+
return (await mount.files.stats(path))?.kind === "file";
|
|
35
|
+
}
|
|
36
|
+
async function readManifest(files, dir) {
|
|
37
|
+
const text = await tryReadText(files, `${dir === "/" ? "" : dir}/package.json`);
|
|
38
|
+
if (text === void 0) return void 0;
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(text);
|
|
41
|
+
} catch {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** `react` → `{ name: "react" }`; `@a/b/c.js` → `{ name: "@a/b", subpath: "c.js" }`. */
|
|
46
|
+
function parsePackageSpecifier(spec) {
|
|
47
|
+
const parts = spec.split("/");
|
|
48
|
+
const n = spec.startsWith("@") ? 2 : 1;
|
|
49
|
+
const name = parts.slice(0, n).join("/");
|
|
50
|
+
const subpath = parts.slice(n).join("/");
|
|
51
|
+
return subpath ? {
|
|
52
|
+
name,
|
|
53
|
+
subpath
|
|
54
|
+
} : { name };
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/input-maps.ts
|
|
58
|
+
const MAP_COMMENT = /\/\/[#@]\s*sourceMappingURL=(\S+)\s*$/;
|
|
59
|
+
const toBase64$1 = (text) => {
|
|
60
|
+
const bytes = new TextEncoder().encode(text);
|
|
61
|
+
let bin = "";
|
|
62
|
+
for (let i = 0; i < bytes.length; i += 32768) bin += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
63
|
+
return btoa(bin);
|
|
64
|
+
};
|
|
65
|
+
const fromBase64 = (b64) => new TextDecoder().decode(Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)));
|
|
66
|
+
/**
|
|
67
|
+
* A file's own source map, made usable by esbuild, which reads only maps inlined in
|
|
68
|
+
* the file it loads (it cannot follow a linked `.map` through a FilesApi):
|
|
69
|
+
*
|
|
70
|
+
* - a linked map (`//# sourceMappingURL=index.js.map`) is read from the same tree and
|
|
71
|
+
* inlined; an inline `data:` map is kept;
|
|
72
|
+
* - its sources become ids of the same tree (`npm:pkg@1.0.0/src/index.ts`), so the
|
|
73
|
+
* bundle's map names the package's original files, not the published JavaScript;
|
|
74
|
+
* - missing `sourcesContent` is filled from the tree when the original file ships
|
|
75
|
+
* with the package.
|
|
76
|
+
*
|
|
77
|
+
* esbuild then composes it with its own: a bundled line traces to the original source.
|
|
78
|
+
* A map that is missing or unreadable is dropped (the file maps to itself).
|
|
79
|
+
*/
|
|
80
|
+
/**
|
|
81
|
+
* `code` without its trailing `sourceMappingURL` comment (and without reading the map): for
|
|
82
|
+
* bundles built with no source map, where an inlined input map would only add to what esbuild
|
|
83
|
+
* parses and holds (a package's maps, with their sources' text, can outweigh its code).
|
|
84
|
+
*/
|
|
85
|
+
function withoutInputMap(code) {
|
|
86
|
+
const end = code.trimEnd();
|
|
87
|
+
const nl = end.lastIndexOf("\n");
|
|
88
|
+
return MAP_COMMENT.test(end.slice(nl + 1)) ? end.slice(0, Math.max(0, nl)) : code;
|
|
89
|
+
}
|
|
90
|
+
async function inlineInputMap(mount, path, code) {
|
|
91
|
+
const lines = code.trimEnd().split("\n");
|
|
92
|
+
const last = lines[lines.length - 1] ?? "";
|
|
93
|
+
const match = MAP_COMMENT.exec(last);
|
|
94
|
+
if (!match) return code;
|
|
95
|
+
const url = match[1];
|
|
96
|
+
const body = lines.slice(0, -1).join("\n");
|
|
97
|
+
let text;
|
|
98
|
+
let mapDir = dirOf(path);
|
|
99
|
+
if (url.startsWith("data:")) {
|
|
100
|
+
const comma = url.indexOf(",");
|
|
101
|
+
const meta = url.slice(5, comma);
|
|
102
|
+
const payload = url.slice(comma + 1);
|
|
103
|
+
try {
|
|
104
|
+
text = meta.endsWith(";base64") ? fromBase64(payload) : decodeURIComponent(payload);
|
|
105
|
+
} catch {
|
|
106
|
+
text = void 0;
|
|
107
|
+
}
|
|
108
|
+
} else if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) {
|
|
109
|
+
const mapPath = joinWithin(mount.root, dirOf(path), decodeURIComponent(url));
|
|
110
|
+
if (mapPath) {
|
|
111
|
+
text = await tryReadText(mount.files, mapPath);
|
|
112
|
+
mapDir = dirOf(mapPath);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
let map;
|
|
116
|
+
try {
|
|
117
|
+
map = JSON.parse(text ?? "");
|
|
118
|
+
} catch {
|
|
119
|
+
return body;
|
|
120
|
+
}
|
|
121
|
+
const sourceDir = map.sourceRoot ? joinWithin("/", mapDir, map.sourceRoot.replace(/\/$/, "")) ?? mapDir : mapDir;
|
|
122
|
+
const contents = map.sourcesContent ? [...map.sourcesContent] : [];
|
|
123
|
+
const sources = [];
|
|
124
|
+
for (let i = 0; i < map.sources.length; i++) {
|
|
125
|
+
const src = map.sources[i];
|
|
126
|
+
const local = /^[a-z][a-z0-9+.-]*:/i.test(src) ? void 0 : joinWithin(mount.root, sourceDir, src);
|
|
127
|
+
sources.push(local ? idOf(mount, local) : src);
|
|
128
|
+
if (contents[i] == null && local) contents[i] = await tryReadText(mount.files, local) ?? null;
|
|
129
|
+
}
|
|
130
|
+
const fixed = {
|
|
131
|
+
...map,
|
|
132
|
+
sources,
|
|
133
|
+
sourcesContent: contents
|
|
134
|
+
};
|
|
135
|
+
delete fixed.sourceRoot;
|
|
136
|
+
return `${body}\n//# sourceMappingURL=data:application/json;base64,${toBase64$1(JSON.stringify(fixed))}\n`;
|
|
137
|
+
}
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/packages.ts
|
|
140
|
+
const mountPrefix = (name, version) => `npm:${name}@${version ?? "0.0.0"}`;
|
|
141
|
+
/**
|
|
142
|
+
* Packages from `node_modules` folders, found as Node finds them: in the importing
|
|
143
|
+
* file's directory and each parent, inside the importer's own FilesApi. A package
|
|
144
|
+
* installed in the project (or in another package's `node_modules`) is read where it is.
|
|
145
|
+
*
|
|
146
|
+
* pnpm layouts: a package's own dependencies sit next to its real directory in
|
|
147
|
+
* `node_modules/.pnpm`, which Node reaches through the symlink's real path and a FilesApi
|
|
148
|
+
* cannot see. When the walk finds nothing, each ancestor's `node_modules/.pnpm/node_modules`
|
|
149
|
+
* (pnpm's hoisted links to every installed package) is tried too.
|
|
150
|
+
*/
|
|
151
|
+
function nodeModulesPackages() {
|
|
152
|
+
const mounts = /* @__PURE__ */ new Map();
|
|
153
|
+
const at = async (files, root, name) => {
|
|
154
|
+
const known = mounts.get(root);
|
|
155
|
+
if (known && known.files === files) return known;
|
|
156
|
+
const manifest = await readManifest(files, root);
|
|
157
|
+
if (!manifest) return void 0;
|
|
158
|
+
const mount = {
|
|
159
|
+
prefix: mountPrefix(name, manifest.version),
|
|
160
|
+
files,
|
|
161
|
+
root,
|
|
162
|
+
manifest
|
|
163
|
+
};
|
|
164
|
+
mounts.set(root, mount);
|
|
165
|
+
return mount;
|
|
166
|
+
};
|
|
167
|
+
const ancestors = (path) => {
|
|
168
|
+
const dirs = [];
|
|
169
|
+
for (let dir = dirOf(path);; dir = dirOf(dir)) {
|
|
170
|
+
dirs.push(dir === "/" ? "" : dir);
|
|
171
|
+
if (dir === "/") return dirs;
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
return { async get(name, importer) {
|
|
175
|
+
const files = importer.mount.files;
|
|
176
|
+
const dirs = ancestors(importer.path);
|
|
177
|
+
for (const dir of dirs) {
|
|
178
|
+
const m = await at(files, `${dir}/node_modules/${name}`, name);
|
|
179
|
+
if (m) return m;
|
|
180
|
+
}
|
|
181
|
+
for (const dir of dirs) {
|
|
182
|
+
const m = await at(files, `${dir}/node_modules/.pnpm/node_modules/${name}`, name);
|
|
183
|
+
if (m) return m;
|
|
184
|
+
}
|
|
185
|
+
} };
|
|
186
|
+
}
|
|
187
|
+
const DEPENDENCY_FIELDS = [
|
|
188
|
+
"dependencies",
|
|
189
|
+
"peerDependencies",
|
|
190
|
+
"optionalDependencies",
|
|
191
|
+
"devDependencies"
|
|
192
|
+
];
|
|
193
|
+
/** The version range `importer`'s `package.json` gives `name`, if any. */
|
|
194
|
+
function rangeFor(name, importer) {
|
|
195
|
+
const m = importer.mount.manifest;
|
|
196
|
+
for (const field of DEPENDENCY_FIELDS) {
|
|
197
|
+
const range = m?.[field]?.[name];
|
|
198
|
+
if (range) return range;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Packages fetched on demand (default: the npm registry, through webrun-modules'
|
|
203
|
+
* `npmRegistrySource`) and kept in memory: each one is its own FilesApi tree. The
|
|
204
|
+
* version is the range the importer's `package.json` declares (the project's for the
|
|
205
|
+
* project's files), else the latest; one range loads once.
|
|
206
|
+
*/
|
|
207
|
+
function npmPackages(opts = {}) {
|
|
208
|
+
let registry;
|
|
209
|
+
const source = opts.source ?? {
|
|
210
|
+
matches: (ref) => "pkg" in ref,
|
|
211
|
+
load: async (ref) => {
|
|
212
|
+
registry ??= import("@statewalker/webrun-modules").then((m) => m.npmRegistrySource());
|
|
213
|
+
return (await registry).load(ref);
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
const byRange = /* @__PURE__ */ new Map();
|
|
217
|
+
const byVersion = /* @__PURE__ */ new Map();
|
|
218
|
+
return { get(name, importer) {
|
|
219
|
+
const range = rangeFor(name, importer);
|
|
220
|
+
const key = `${name}@${range ?? "latest"}`;
|
|
221
|
+
let mount = byRange.get(key);
|
|
222
|
+
if (!mount) {
|
|
223
|
+
mount = source.load({
|
|
224
|
+
pkg: name,
|
|
225
|
+
version: range
|
|
226
|
+
}).then((p) => {
|
|
227
|
+
const prefix = mountPrefix(p.name, p.version);
|
|
228
|
+
const seen = byVersion.get(prefix);
|
|
229
|
+
if (seen) return seen;
|
|
230
|
+
const m = {
|
|
231
|
+
prefix,
|
|
232
|
+
files: p.files,
|
|
233
|
+
root: "/",
|
|
234
|
+
manifest: p.manifest
|
|
235
|
+
};
|
|
236
|
+
byVersion.set(prefix, m);
|
|
237
|
+
return m;
|
|
238
|
+
});
|
|
239
|
+
byRange.set(key, mount);
|
|
240
|
+
}
|
|
241
|
+
return mount;
|
|
242
|
+
} };
|
|
243
|
+
}
|
|
244
|
+
/** The first store that has the package wins (`node_modules` first, then the registry). */
|
|
245
|
+
function chainPackages(...stores) {
|
|
246
|
+
return { async get(name, importer) {
|
|
247
|
+
let failure;
|
|
248
|
+
for (const s of stores) try {
|
|
249
|
+
const m = await s.get(name, importer);
|
|
250
|
+
if (m) return m;
|
|
251
|
+
} catch (e) {
|
|
252
|
+
failure ??= e;
|
|
253
|
+
}
|
|
254
|
+
if (failure) throw failure;
|
|
255
|
+
} };
|
|
256
|
+
}
|
|
257
|
+
//#endregion
|
|
258
|
+
//#region src/resolve.ts
|
|
259
|
+
/** Extensions tried, in order, for a path written without one (or with `.js` for a `.ts` file). */
|
|
260
|
+
const EXTENSIONS = [
|
|
261
|
+
".ts",
|
|
262
|
+
".tsx",
|
|
263
|
+
".mts",
|
|
264
|
+
".cts",
|
|
265
|
+
".js",
|
|
266
|
+
".jsx",
|
|
267
|
+
".mjs",
|
|
268
|
+
".cjs",
|
|
269
|
+
".json"
|
|
270
|
+
];
|
|
271
|
+
/** `path` as written, else with an extension, else its `index` file. */
|
|
272
|
+
async function resolveFile(mount, path) {
|
|
273
|
+
if (await isFile(mount, path)) return path;
|
|
274
|
+
const js = /\.(m|c)?jsx?$/.exec(path);
|
|
275
|
+
if (js) {
|
|
276
|
+
const base = path.slice(0, -js[0].length);
|
|
277
|
+
for (const ext of [`.${js[1] ?? ""}ts`, ".tsx"]) if (await isFile(mount, base + ext)) return base + ext;
|
|
278
|
+
}
|
|
279
|
+
for (const ext of EXTENSIONS) if (await isFile(mount, path + ext)) return path + ext;
|
|
280
|
+
const dir = path.endsWith("/") ? path.slice(0, -1) : path;
|
|
281
|
+
for (const ext of EXTENSIONS) if (await isFile(mount, `${dir}/index${ext}`)) return `${dir}/index${ext}`;
|
|
282
|
+
}
|
|
283
|
+
function exportsTarget(manifest, entry, c) {
|
|
284
|
+
try {
|
|
285
|
+
return exports(manifest, entry, {
|
|
286
|
+
conditions: c.conditions,
|
|
287
|
+
require: c.require,
|
|
288
|
+
browser: c.browser
|
|
289
|
+
})?.[0];
|
|
290
|
+
} catch {
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/** A package's file for `subpath`: `exports` first, then `module`/`main` (and `browser` when it is a string). */
|
|
295
|
+
async function resolvePackageEntry(mount, subpath, c) {
|
|
296
|
+
const manifest = mount.manifest ?? {};
|
|
297
|
+
const entry = subpath ? `./${subpath}` : ".";
|
|
298
|
+
if (manifest.exports !== void 0) {
|
|
299
|
+
const target = exportsTarget(manifest, entry, c);
|
|
300
|
+
if (!target) return void 0;
|
|
301
|
+
return joinWithin(mount.root, mount.root, target);
|
|
302
|
+
}
|
|
303
|
+
if (subpath) return resolveFile(mount, joinWithin(mount.root, mount.root, subpath) ?? "");
|
|
304
|
+
const fields = [
|
|
305
|
+
...c.browser && typeof manifest.browser === "string" ? [manifest.browser] : [],
|
|
306
|
+
...c.require ? [] : [manifest.module],
|
|
307
|
+
manifest.main,
|
|
308
|
+
"index.js"
|
|
309
|
+
].filter((f) => typeof f === "string");
|
|
310
|
+
for (const f of fields) {
|
|
311
|
+
const p = joinWithin(mount.root, mount.root, f);
|
|
312
|
+
const file = p && await resolveFile(mount, p);
|
|
313
|
+
if (file) return file;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Resolves `spec` as written in `importer`: a path of the same tree (`./x`, `../y.js`,
|
|
318
|
+
* `/z`), a `#imports` alias of the importer's package, or a package found by `packages`
|
|
319
|
+
* (with its `exports`, `module` and `main`).
|
|
320
|
+
*/
|
|
321
|
+
async function resolveSpecifier(spec, importer, packages, c) {
|
|
322
|
+
const { mount } = importer;
|
|
323
|
+
if (spec.startsWith("./") || spec.startsWith("../") || spec.startsWith("/") || spec === ".") {
|
|
324
|
+
const base = spec.startsWith("/") ? mount.root : dirOf(importer.path);
|
|
325
|
+
const target = joinWithin(mount.root, base, spec.startsWith("/") ? spec.slice(1) : spec);
|
|
326
|
+
const path = target && await resolveFile(mount, target);
|
|
327
|
+
return path ? {
|
|
328
|
+
mount,
|
|
329
|
+
path
|
|
330
|
+
} : void 0;
|
|
331
|
+
}
|
|
332
|
+
if (spec.startsWith("#")) try {
|
|
333
|
+
const target = imports(mount.manifest ?? {}, spec, {
|
|
334
|
+
conditions: c.conditions,
|
|
335
|
+
require: c.require,
|
|
336
|
+
browser: c.browser
|
|
337
|
+
})?.[0];
|
|
338
|
+
if (!target) return void 0;
|
|
339
|
+
if (!target.startsWith(".")) return resolveSpecifier(target, importer, packages, c);
|
|
340
|
+
const path = joinWithin(mount.root, mount.root, target);
|
|
341
|
+
return path && await isFile(mount, path) ? {
|
|
342
|
+
mount,
|
|
343
|
+
path
|
|
344
|
+
} : void 0;
|
|
345
|
+
} catch {
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
const { name, subpath } = parsePackageSpecifier(spec);
|
|
349
|
+
const pkg = await packages.get(name, importer);
|
|
350
|
+
if (!pkg) return void 0;
|
|
351
|
+
const path = await resolvePackageEntry(pkg, subpath, c);
|
|
352
|
+
return path && await isFile(pkg, path) ? {
|
|
353
|
+
mount: pkg,
|
|
354
|
+
path
|
|
355
|
+
} : void 0;
|
|
356
|
+
}
|
|
357
|
+
//#endregion
|
|
358
|
+
//#region src/bundle.ts
|
|
359
|
+
/** esbuild's namespace for the files the bundler serves; its source-map names drop it. */
|
|
360
|
+
const NS = "webrun";
|
|
361
|
+
/** esbuild's namespace for the host's modules (`modules`): `virtual:<specifier>` in maps. */
|
|
362
|
+
const VNS = "webrun-virtual";
|
|
363
|
+
/** Marks an `inject` entry, so that it resolves like an import, not like the entry point. */
|
|
364
|
+
const INJECT = "webrun-inject:";
|
|
365
|
+
/** esbuild `supported` flags that lower `await` to generators. */
|
|
366
|
+
const LOWER_AWAIT = {
|
|
367
|
+
"async-await": false,
|
|
368
|
+
"async-generator": false,
|
|
369
|
+
"for-await": false
|
|
370
|
+
};
|
|
371
|
+
const LOADERS = {
|
|
372
|
+
ts: "ts",
|
|
373
|
+
mts: "ts",
|
|
374
|
+
cts: "ts",
|
|
375
|
+
tsx: "tsx",
|
|
376
|
+
jsx: "jsx",
|
|
377
|
+
js: "js",
|
|
378
|
+
mjs: "js",
|
|
379
|
+
cjs: "js",
|
|
380
|
+
json: "json",
|
|
381
|
+
css: "css",
|
|
382
|
+
txt: "text",
|
|
383
|
+
wasm: "binary"
|
|
384
|
+
};
|
|
385
|
+
const loaderFor = (path) => LOADERS[/\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase() ?? ""] ?? "js";
|
|
386
|
+
const isExternal = (spec, patterns) => /^(https?:|data:)/.test(spec) || patterns.some((p) => typeof p === "string" ? p.endsWith("*") ? spec.startsWith(p.slice(0, -1)) : spec === p : p.test(spec));
|
|
387
|
+
/** A source name of esbuild's map → the file id it stands for. */
|
|
388
|
+
const sourceId = (s) => s.replace(/^(\.\.\/)*/, "").replace(new RegExp(`^${VNS}:`), "virtual:").replace(new RegExp(`^${NS}:`), "").replace("?type=module.mjs", "");
|
|
389
|
+
const toBase64 = (text) => {
|
|
390
|
+
const bytes = new TextEncoder().encode(text);
|
|
391
|
+
let bin = "";
|
|
392
|
+
for (let i = 0; i < bytes.length; i += 32768) bin += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
393
|
+
return btoa(bin);
|
|
394
|
+
};
|
|
395
|
+
/** `code` with its trailing map link replaced: by `map` inlined, or by a link to `name`. */
|
|
396
|
+
function linkMap(code, map, how, name) {
|
|
397
|
+
return `${code.replace(/\n?\/\/# sourceMappingURL=\S+\s*$/, "")}\n//# sourceMappingURL=${how === "inline" ? `data:application/json;base64,${toBase64(JSON.stringify(map))}` : `${name.split("/").pop()}.map`}\n`;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Bundles `entry` of a project into one module with esbuild (esbuild-wasm in browsers).
|
|
401
|
+
* Every file is read through FilesApi (the project's, or a package's from `packages`):
|
|
402
|
+
* esbuild resolves and loads nothing itself. esbuild transpiles TypeScript and JSX,
|
|
403
|
+
* converts CommonJS, lowers `await` when asked, and bundles, all in one pass, and its
|
|
404
|
+
* source map goes back through each step to the files it read; where a package ships
|
|
405
|
+
* its own map (TypeScript compiled to `.js`), to the package's original source. The
|
|
406
|
+
* map's sources are file ids: `~/src/app.ts`, `npm:pkg@1.2.3/src/index.ts`.
|
|
407
|
+
*/
|
|
408
|
+
/** Marks the id of a `.js` file in a `"type": "module"` package scope (see `moduleTypeOf`). */
|
|
409
|
+
const ESM_SUFFIX = "?type=module.mjs";
|
|
410
|
+
async function bundle(opts) {
|
|
411
|
+
const root = opts.root ?? "/";
|
|
412
|
+
const project = {
|
|
413
|
+
prefix: "~",
|
|
414
|
+
files: opts.files,
|
|
415
|
+
root,
|
|
416
|
+
manifest: await readManifest(opts.files, root)
|
|
417
|
+
};
|
|
418
|
+
const packages = opts.packages ?? nodeModulesPackages();
|
|
419
|
+
const external = opts.external ?? [];
|
|
420
|
+
const browser = (opts.platform ?? "browser") === "browser";
|
|
421
|
+
const conditions = opts.conditions ?? ["browser"];
|
|
422
|
+
const outfile = opts.outfile ?? "bundle.js";
|
|
423
|
+
const mounts = /* @__PURE__ */ new Map([[project.prefix, project]]);
|
|
424
|
+
const supplied = opts.modules;
|
|
425
|
+
const virtualSource = (spec) => typeof supplied === "function" ? supplied(spec) : supplied?.[spec];
|
|
426
|
+
/** The mount and path of a file id; the longest prefix wins (`npm:@a/b@1.0.0/…`). */
|
|
427
|
+
/**
|
|
428
|
+
* The module type of a `.js` file, as Node.js decides it: the `type` of the nearest
|
|
429
|
+
* `package.json` (tslib ships `modules/package.json` with `"type": "module"`). esbuild reads
|
|
430
|
+
* that only for files on its own file system; for ours, a file in a `"type": "module"` scope
|
|
431
|
+
* gets an id ending in ESM_SUFFIX (`.mjs`), so that esbuild gives its imports of CommonJS
|
|
432
|
+
* modules Node's interop: the default import is `module.exports`, even with `__esModule`.
|
|
433
|
+
* Vite gets the same from esbuild by pre-bundling dependencies from disk.
|
|
434
|
+
*/
|
|
435
|
+
const scopeTypes = /* @__PURE__ */ new Map();
|
|
436
|
+
const moduleTypeOf = async (mount, path) => {
|
|
437
|
+
const root = mount.root.replace(/\/$/, "");
|
|
438
|
+
for (let dir = dirOf(path); dir.length >= root.length; dir = dirOf(dir)) {
|
|
439
|
+
const key = `${mount.prefix}:${dir}`;
|
|
440
|
+
if (scopeTypes.has(key)) return scopeTypes.get(key);
|
|
441
|
+
const pj = `${dir === "/" ? "" : dir}/package.json`;
|
|
442
|
+
if (await isFile(mount, pj)) {
|
|
443
|
+
let type;
|
|
444
|
+
try {
|
|
445
|
+
type = JSON.parse(await readText(mount.files, pj)).type;
|
|
446
|
+
} catch {}
|
|
447
|
+
scopeTypes.set(key, type);
|
|
448
|
+
return type;
|
|
449
|
+
}
|
|
450
|
+
if (dir === root || dir === "/" || !dir) break;
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
const locate = (id) => {
|
|
454
|
+
if (id.endsWith(ESM_SUFFIX)) id = id.slice(0, -16);
|
|
455
|
+
let best;
|
|
456
|
+
for (const m of mounts.values()) if (id.startsWith(`${m.prefix}/`) && (!best || m.prefix.length > best.prefix.length)) best = m;
|
|
457
|
+
const path = best && pathOf(best, id);
|
|
458
|
+
if (!best || !path) throw new Error(`webrun-bundler: no file ${id}`);
|
|
459
|
+
return {
|
|
460
|
+
mount: best,
|
|
461
|
+
path
|
|
462
|
+
};
|
|
463
|
+
};
|
|
464
|
+
const plugin = {
|
|
465
|
+
name: "webrun-files",
|
|
466
|
+
setup(b) {
|
|
467
|
+
b.onResolve({ filter: /.*/ }, async (args) => {
|
|
468
|
+
const injected = args.path.startsWith(INJECT);
|
|
469
|
+
const spec = injected ? args.path.slice(14) : args.path;
|
|
470
|
+
if (args.kind === "entry-point" && !injected) {
|
|
471
|
+
const path = joinWithin(root, root, args.path.replace(/^\/+/, ""));
|
|
472
|
+
if (!path) return { errors: [{ text: `entry ${args.path} is outside the project` }] };
|
|
473
|
+
return {
|
|
474
|
+
path: idOf(project, path),
|
|
475
|
+
namespace: NS
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
if (virtualSource(spec) !== void 0) return {
|
|
479
|
+
path: spec,
|
|
480
|
+
namespace: VNS
|
|
481
|
+
};
|
|
482
|
+
if (isExternal(spec, external)) return {
|
|
483
|
+
path: spec,
|
|
484
|
+
external: true
|
|
485
|
+
};
|
|
486
|
+
const importer = injected || args.namespace === VNS ? {
|
|
487
|
+
mount: project,
|
|
488
|
+
path: `${root === "/" ? "" : root}/`
|
|
489
|
+
} : locate(args.importer);
|
|
490
|
+
const require = args.kind === "require-call" || args.kind === "require-resolve";
|
|
491
|
+
const failed = (why) => ({ errors: [{ text: `Could not resolve "${spec}" (imported by ${args.importer || "inject"})${why ? `: ${why}` : ""}` }] });
|
|
492
|
+
let r;
|
|
493
|
+
try {
|
|
494
|
+
r = await resolveSpecifier(spec, importer, packages, {
|
|
495
|
+
conditions,
|
|
496
|
+
require,
|
|
497
|
+
browser
|
|
498
|
+
});
|
|
499
|
+
} catch (e) {
|
|
500
|
+
return failed(e?.message ?? String(e));
|
|
501
|
+
}
|
|
502
|
+
if (!r) return failed();
|
|
503
|
+
mounts.set(r.mount.prefix, r.mount);
|
|
504
|
+
const esm = /\.js$/.test(r.path) && await moduleTypeOf(r.mount, r.path) === "module";
|
|
505
|
+
return {
|
|
506
|
+
path: idOf(r.mount, r.path) + (esm ? ESM_SUFFIX : ""),
|
|
507
|
+
namespace: NS
|
|
508
|
+
};
|
|
509
|
+
});
|
|
510
|
+
b.onLoad({
|
|
511
|
+
filter: /.*/,
|
|
512
|
+
namespace: VNS
|
|
513
|
+
}, (args) => ({
|
|
514
|
+
contents: virtualSource(args.path) ?? "",
|
|
515
|
+
loader: "js"
|
|
516
|
+
}));
|
|
517
|
+
b.onLoad({
|
|
518
|
+
filter: /.*/,
|
|
519
|
+
namespace: NS
|
|
520
|
+
}, async (args) => {
|
|
521
|
+
const { mount, path } = locate(args.path);
|
|
522
|
+
const loader = loaderFor(path);
|
|
523
|
+
if (loader === "binary") {
|
|
524
|
+
const chunks = [];
|
|
525
|
+
for await (const c of mount.files.read(path)) chunks.push(c);
|
|
526
|
+
const bytes = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
|
|
527
|
+
let at = 0;
|
|
528
|
+
for (const c of chunks) {
|
|
529
|
+
bytes.set(c, at);
|
|
530
|
+
at += c.length;
|
|
531
|
+
}
|
|
532
|
+
return {
|
|
533
|
+
contents: bytes,
|
|
534
|
+
loader
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
const text = await readText(mount.files, path);
|
|
538
|
+
if (!(loader === "js" || loader === "ts" || loader === "jsx" || loader === "tsx")) return {
|
|
539
|
+
contents: text,
|
|
540
|
+
loader
|
|
541
|
+
};
|
|
542
|
+
if (opts.sourcemap === false) return {
|
|
543
|
+
contents: withoutInputMap(text),
|
|
544
|
+
loader
|
|
545
|
+
};
|
|
546
|
+
return {
|
|
547
|
+
contents: await inlineInputMap(mount, path, text),
|
|
548
|
+
loader
|
|
549
|
+
};
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
};
|
|
553
|
+
const { plugins: extraPlugins = [], ...rest } = opts.esbuildOptions ?? {};
|
|
554
|
+
const result = await opts.esbuild.build({
|
|
555
|
+
entryPoints: [opts.entry],
|
|
556
|
+
bundle: true,
|
|
557
|
+
write: false,
|
|
558
|
+
format: opts.format ?? "esm",
|
|
559
|
+
platform: opts.platform ?? "browser",
|
|
560
|
+
target: opts.target ?? "es2022",
|
|
561
|
+
outfile,
|
|
562
|
+
absWorkingDir: "/",
|
|
563
|
+
metafile: true,
|
|
564
|
+
logLevel: "silent",
|
|
565
|
+
minify: opts.minify,
|
|
566
|
+
define: opts.define,
|
|
567
|
+
...opts.lowerAwait ? { supported: LOWER_AWAIT } : {},
|
|
568
|
+
...rest,
|
|
569
|
+
...opts.inject?.length ? { inject: opts.inject.map((s) => INJECT + s) } : {},
|
|
570
|
+
sourcemap: opts.sourcemap === false ? false : "external",
|
|
571
|
+
sourcesContent: opts.sourcemap !== false,
|
|
572
|
+
plugins: [...extraPlugins, plugin]
|
|
573
|
+
});
|
|
574
|
+
const out = result.outputFiles ?? [];
|
|
575
|
+
const jsFile = out.find((f) => !f.path.endsWith(".map"));
|
|
576
|
+
const mapFile = out.find((f) => f.path.endsWith(".map"));
|
|
577
|
+
if (!jsFile) throw new Error("webrun-bundler: esbuild produced no output");
|
|
578
|
+
if (!mapFile) return {
|
|
579
|
+
code: jsFile.text,
|
|
580
|
+
map: {
|
|
581
|
+
version: 3,
|
|
582
|
+
sources: [],
|
|
583
|
+
names: [],
|
|
584
|
+
mappings: ""
|
|
585
|
+
},
|
|
586
|
+
metafile: result.metafile,
|
|
587
|
+
warnings: result.warnings
|
|
588
|
+
};
|
|
589
|
+
const raw = JSON.parse(mapFile.text);
|
|
590
|
+
const map = {
|
|
591
|
+
...raw,
|
|
592
|
+
file: outfile.split("/").pop(),
|
|
593
|
+
sources: raw.sources.map(sourceId)
|
|
594
|
+
};
|
|
595
|
+
delete map.sourceRoot;
|
|
596
|
+
return {
|
|
597
|
+
code: linkMap(jsFile.text, map, opts.sourcemap || "external", outfile),
|
|
598
|
+
map,
|
|
599
|
+
metafile: result.metafile,
|
|
600
|
+
warnings: result.warnings
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* Transpiles one file (TypeScript, JSX, modern syntax down to `target`; `await` lowered
|
|
605
|
+
* when asked) with a source map back to it. A map the code carries (`sourceMappingURL`,
|
|
606
|
+
* inline) is composed in, so the result still traces to the original.
|
|
607
|
+
*/
|
|
608
|
+
async function transpile(code, opts) {
|
|
609
|
+
const r = await opts.esbuild.transform(code, {
|
|
610
|
+
loader: loaderFor(opts.path),
|
|
611
|
+
sourcefile: opts.path,
|
|
612
|
+
sourcemap: "external",
|
|
613
|
+
sourcesContent: true,
|
|
614
|
+
format: opts.format,
|
|
615
|
+
target: opts.target ?? "es2022",
|
|
616
|
+
minify: opts.minify,
|
|
617
|
+
define: opts.define,
|
|
618
|
+
...opts.lowerAwait ? { supported: LOWER_AWAIT } : {}
|
|
619
|
+
});
|
|
620
|
+
const map = JSON.parse(r.map);
|
|
621
|
+
return {
|
|
622
|
+
code: linkMap(r.code, map, opts.sourcemap ?? "external", opts.path.replace(/\.[^./]+$/, ".js")),
|
|
623
|
+
map,
|
|
624
|
+
warnings: r.warnings
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
//#endregion
|
|
628
|
+
export { bundle, chainPackages, inlineInputMap, loaderFor, nodeModulesPackages, npmPackages, resolveSpecifier, transpile };
|
|
629
|
+
|
|
630
|
+
//# sourceMappingURL=index.mjs.map
|