@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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["toBase64","resolvePackageExports","resolveImports"],"sources":["../src/paths.ts","../src/input-maps.ts","../src/packages.ts","../src/resolve.ts","../src/bundle.ts"],"sourcesContent":["import { normalizePath, tryReadText } from \"@statewalker/webrun-files\";\nimport type { Mount, PackageManifest } from \"./types.js\";\n\n/** `path` joined to `dir`, with `.` and `..` resolved; `undefined` when it leaves `root`. */\nexport function joinWithin(root: string, dir: string, path: string): string | undefined {\n const parts = (path.startsWith(\"/\") ? path : `${dir}/${path}`).split(\"/\");\n const out: string[] = [];\n for (const p of parts) {\n if (!p || p === \".\") continue;\n if (p === \"..\") {\n if (!out.length) return undefined;\n out.pop();\n } else out.push(p);\n }\n const joined = `/${out.join(\"/\")}`;\n const r = normalizePath(root);\n return r === \"/\" || joined === r || joined.startsWith(`${r}/`) ? joined : undefined;\n}\n\nexport const dirOf = (path: string) => path.slice(0, path.lastIndexOf(\"/\")) || \"/\";\n\n/** The id of a mount's file: `<prefix>/<path below root>`. */\nexport function idOf(mount: Mount, path: string): string {\n const r = normalizePath(mount.root);\n const rel = r === \"/\" ? path : path.slice(r.length);\n return `${mount.prefix}${rel || \"/\"}`;\n}\n\n/** A mount's file from its id; `undefined` when the id is not the mount's. */\nexport function pathOf(mount: Mount, id: string): string | undefined {\n if (!id.startsWith(`${mount.prefix}/`)) return undefined;\n const r = normalizePath(mount.root);\n const rel = id.slice(mount.prefix.length);\n return r === \"/\" ? rel : `${r}${rel}`;\n}\n\nexport async function isFile(mount: Mount, path: string): Promise<boolean> {\n const s = await mount.files.stats(path);\n return s?.kind === \"file\";\n}\n\nexport async function readManifest(\n files: Mount[\"files\"],\n dir: string,\n): Promise<PackageManifest | undefined> {\n const text = await tryReadText(files, `${dir === \"/\" ? \"\" : dir}/package.json`);\n if (text === undefined) return undefined;\n try {\n return JSON.parse(text) as PackageManifest;\n } catch {\n return undefined;\n }\n}\n\n/** `react` → `{ name: \"react\" }`; `@a/b/c.js` → `{ name: \"@a/b\", subpath: \"c.js\" }`. */\nexport function parsePackageSpecifier(spec: string): { name: string; subpath?: string } {\n const parts = spec.split(\"/\");\n const n = spec.startsWith(\"@\") ? 2 : 1;\n const name = parts.slice(0, n).join(\"/\");\n const subpath = parts.slice(n).join(\"/\");\n return subpath ? { name, subpath } : { name };\n}\n","import { tryReadText } from \"@statewalker/webrun-files\";\nimport { dirOf, idOf, joinWithin } from \"./paths.js\";\nimport type { Mount, SourceMap } from \"./types.js\";\n\n// The last `//# sourceMappingURL=…` (or `//@`) comment of a JS file.\nconst MAP_COMMENT = /\\/\\/[#@]\\s*sourceMappingURL=(\\S+)\\s*$/;\n\nconst toBase64 = (text: string) => {\n const bytes = new TextEncoder().encode(text);\n let bin = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000)\n bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n return btoa(bin);\n};\nconst fromBase64 = (b64: string) =>\n new TextDecoder().decode(Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)));\n\n/**\n * A file's own source map, made usable by esbuild, which reads only maps inlined in\n * the file it loads (it cannot follow a linked `.map` through a FilesApi):\n *\n * - a linked map (`//# sourceMappingURL=index.js.map`) is read from the same tree and\n * inlined; an inline `data:` map is kept;\n * - its sources become ids of the same tree (`npm:pkg@1.0.0/src/index.ts`), so the\n * bundle's map names the package's original files, not the published JavaScript;\n * - missing `sourcesContent` is filled from the tree when the original file ships\n * with the package.\n *\n * esbuild then composes it with its own: a bundled line traces to the original source.\n * A map that is missing or unreadable is dropped (the file maps to itself).\n */\n/**\n * `code` without its trailing `sourceMappingURL` comment (and without reading the map): for\n * bundles built with no source map, where an inlined input map would only add to what esbuild\n * parses and holds (a package's maps, with their sources' text, can outweigh its code).\n */\nexport function withoutInputMap(code: string): string {\n const end = code.trimEnd();\n const nl = end.lastIndexOf(\"\\n\");\n return MAP_COMMENT.test(end.slice(nl + 1)) ? end.slice(0, Math.max(0, nl)) : code;\n}\n\nexport async function inlineInputMap(mount: Mount, path: string, code: string): Promise<string> {\n const lines = code.trimEnd().split(\"\\n\");\n const last = lines[lines.length - 1] ?? \"\";\n const match = MAP_COMMENT.exec(last);\n if (!match) return code;\n const url = match[1] as string;\n const body = lines.slice(0, -1).join(\"\\n\");\n let text: string | undefined;\n let mapDir = dirOf(path);\n if (url.startsWith(\"data:\")) {\n const comma = url.indexOf(\",\");\n const meta = url.slice(5, comma);\n const payload = url.slice(comma + 1);\n try {\n text = meta.endsWith(\";base64\") ? fromBase64(payload) : decodeURIComponent(payload);\n } catch {\n text = undefined;\n }\n } else if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) {\n const mapPath = joinWithin(mount.root, dirOf(path), decodeURIComponent(url));\n if (mapPath) {\n text = await tryReadText(mount.files, mapPath);\n mapDir = dirOf(mapPath);\n }\n }\n let map: SourceMap;\n try {\n map = JSON.parse(text ?? \"\") as SourceMap;\n } catch {\n return body; // no usable map: the file is its own source\n }\n const sourceDir = map.sourceRoot\n ? (joinWithin(\"/\", mapDir, map.sourceRoot.replace(/\\/$/, \"\")) ?? mapDir)\n : mapDir;\n const contents: (string | null)[] = map.sourcesContent ? [...map.sourcesContent] : [];\n const sources: string[] = [];\n for (let i = 0; i < map.sources.length; i++) {\n const src = map.sources[i] as string;\n const local = /^[a-z][a-z0-9+.-]*:/i.test(src)\n ? undefined\n : joinWithin(mount.root, sourceDir, src);\n sources.push(local ? idOf(mount, local) : src);\n if (contents[i] == null && local) contents[i] = (await tryReadText(mount.files, local)) ?? null;\n }\n const fixed: SourceMap = { ...map, sources, sourcesContent: contents };\n delete fixed.sourceRoot;\n return `${body}\\n//# sourceMappingURL=data:application/json;base64,${toBase64(JSON.stringify(fixed))}\\n`;\n}\n","import type { Source } from \"@statewalker/webrun-modules\";\nimport { dirOf, readManifest } from \"./paths.js\";\nimport type { Importer, Mount, PackageStore } from \"./types.js\";\n\nconst mountPrefix = (name: string, version: string | undefined) =>\n `npm:${name}@${version ?? \"0.0.0\"}`;\n\n/**\n * Packages from `node_modules` folders, found as Node finds them: in the importing\n * file's directory and each parent, inside the importer's own FilesApi. A package\n * installed in the project (or in another package's `node_modules`) is read where it is.\n *\n * pnpm layouts: a package's own dependencies sit next to its real directory in\n * `node_modules/.pnpm`, which Node reaches through the symlink's real path and a FilesApi\n * cannot see. When the walk finds nothing, each ancestor's `node_modules/.pnpm/node_modules`\n * (pnpm's hoisted links to every installed package) is tried too.\n */\nexport function nodeModulesPackages(): PackageStore {\n const mounts = new Map<string, Mount>();\n const at = async (files: Mount[\"files\"], root: string, name: string) => {\n const known = mounts.get(root);\n if (known && known.files === files) return known;\n const manifest = await readManifest(files, root);\n if (!manifest) return undefined;\n const mount: Mount = { prefix: mountPrefix(name, manifest.version), files, root, manifest };\n mounts.set(root, mount);\n return mount;\n };\n const ancestors = (path: string) => {\n const dirs: string[] = [];\n for (let dir = dirOf(path); ; dir = dirOf(dir)) {\n dirs.push(dir === \"/\" ? \"\" : dir);\n if (dir === \"/\") return dirs;\n }\n };\n return {\n async get(name, importer) {\n const files = importer.mount.files;\n const dirs = ancestors(importer.path);\n for (const dir of dirs) {\n const m = await at(files, `${dir}/node_modules/${name}`, name);\n if (m) return m;\n }\n for (const dir of dirs) {\n const m = await at(files, `${dir}/node_modules/.pnpm/node_modules/${name}`, name);\n if (m) return m;\n }\n return undefined;\n },\n };\n}\n\nconst DEPENDENCY_FIELDS = [\n \"dependencies\",\n \"peerDependencies\",\n \"optionalDependencies\",\n \"devDependencies\",\n] as const;\n\n/** The version range `importer`'s `package.json` gives `name`, if any. */\nfunction rangeFor(name: string, importer: Importer): string | undefined {\n const m = importer.mount.manifest;\n for (const field of DEPENDENCY_FIELDS) {\n const range = m?.[field]?.[name];\n if (range) return range;\n }\n return undefined;\n}\n\n/**\n * Packages fetched on demand (default: the npm registry, through webrun-modules'\n * `npmRegistrySource`) and kept in memory: each one is its own FilesApi tree. The\n * version is the range the importer's `package.json` declares (the project's for the\n * project's files), else the latest; one range loads once.\n */\nexport function npmPackages(opts: { source?: Source } = {}): PackageStore {\n // Loaded only when used: a bundle of the bundler that brings its own source stays small.\n let registry: Promise<Source> | undefined;\n const source: Source = opts.source ?? {\n matches: (ref) => \"pkg\" in ref,\n load: async (ref) => {\n registry ??= import(\"@statewalker/webrun-modules\").then((m) => m.npmRegistrySource());\n return (await registry).load(ref);\n },\n };\n const byRange = new Map<string, Promise<Mount>>();\n const byVersion = new Map<string, Mount>();\n return {\n get(name, importer) {\n const range = rangeFor(name, importer);\n const key = `${name}@${range ?? \"latest\"}`;\n let mount = byRange.get(key);\n if (!mount) {\n mount = source.load({ pkg: name, version: range }).then((p) => {\n const prefix = mountPrefix(p.name, p.version);\n const seen = byVersion.get(prefix);\n if (seen) return seen; // two ranges, one version: one copy of the package\n const m: Mount = { prefix, files: p.files, root: \"/\", manifest: p.manifest };\n byVersion.set(prefix, m);\n return m;\n });\n byRange.set(key, mount);\n }\n return mount;\n },\n };\n}\n\n/** The first store that has the package wins (`node_modules` first, then the registry). */\nexport function chainPackages(...stores: PackageStore[]): PackageStore {\n return {\n async get(name, importer) {\n let failure: unknown;\n for (const s of stores) {\n try {\n const m = await s.get(name, importer);\n if (m) return m;\n } catch (e) {\n failure ??= e; // the next store may still have it\n }\n }\n if (failure) throw failure;\n return undefined;\n },\n };\n}\n","import { imports as resolveImports, exports as resolvePackageExports } from \"resolve.exports\";\nimport { dirOf, isFile, joinWithin, parsePackageSpecifier } from \"./paths.js\";\nimport type { Importer, Mount, PackageManifest, PackageStore } from \"./types.js\";\n\n/** Extensions tried, in order, for a path written without one (or with `.js` for a `.ts` file). */\nconst EXTENSIONS = [\".ts\", \".tsx\", \".mts\", \".cts\", \".js\", \".jsx\", \".mjs\", \".cjs\", \".json\"];\n\nexport interface Resolved {\n mount: Mount;\n path: string;\n}\n\n/** `path` as written, else with an extension, else its `index` file. */\nasync function resolveFile(mount: Mount, path: string): Promise<string | undefined> {\n if (await isFile(mount, path)) return path;\n // TypeScript sources import `./x.js` for `./x.ts`.\n const js = /\\.(m|c)?jsx?$/.exec(path);\n if (js) {\n const base = path.slice(0, -js[0].length);\n for (const ext of [`.${js[1] ?? \"\"}ts`, \".tsx\"])\n if (await isFile(mount, base + ext)) return base + ext;\n }\n for (const ext of EXTENSIONS) if (await isFile(mount, path + ext)) return path + ext;\n const dir = path.endsWith(\"/\") ? path.slice(0, -1) : path;\n for (const ext of EXTENSIONS)\n if (await isFile(mount, `${dir}/index${ext}`)) return `${dir}/index${ext}`;\n return undefined;\n}\n\ntype Conditions = { conditions: string[]; require: boolean; browser: boolean };\n\nfunction exportsTarget(\n manifest: PackageManifest,\n entry: string,\n c: Conditions,\n): string | undefined {\n try {\n const out = resolvePackageExports(manifest, entry, {\n conditions: c.conditions,\n require: c.require,\n browser: c.browser,\n }) as string[] | undefined;\n return out?.[0];\n } catch {\n return undefined;\n }\n}\n\n/** A package's file for `subpath`: `exports` first, then `module`/`main` (and `browser` when it is a string). */\nasync function resolvePackageEntry(\n mount: Mount,\n subpath: string | undefined,\n c: Conditions,\n): Promise<string | undefined> {\n const manifest = mount.manifest ?? {};\n const entry = subpath ? `./${subpath}` : \".\";\n if (manifest.exports !== undefined) {\n const target = exportsTarget(manifest, entry, c);\n if (!target) return undefined; // not exported: Node refuses it as well\n return joinWithin(mount.root, mount.root, target);\n }\n if (subpath) return resolveFile(mount, joinWithin(mount.root, mount.root, subpath) ?? \"\");\n const fields = [\n ...(c.browser && typeof manifest.browser === \"string\" ? [manifest.browser] : []),\n ...(c.require ? [] : [manifest.module]),\n manifest.main,\n \"index.js\",\n ].filter((f): f is string => typeof f === \"string\");\n for (const f of fields) {\n const p = joinWithin(mount.root, mount.root, f);\n const file = p && (await resolveFile(mount, p));\n if (file) return file;\n }\n return undefined;\n}\n\n/**\n * Resolves `spec` as written in `importer`: a path of the same tree (`./x`, `../y.js`,\n * `/z`), a `#imports` alias of the importer's package, or a package found by `packages`\n * (with its `exports`, `module` and `main`).\n */\nexport async function resolveSpecifier(\n spec: string,\n importer: Importer,\n packages: PackageStore,\n c: Conditions,\n): Promise<Resolved | undefined> {\n const { mount } = importer;\n if (spec.startsWith(\"./\") || spec.startsWith(\"../\") || spec.startsWith(\"/\") || spec === \".\") {\n const base = spec.startsWith(\"/\") ? mount.root : dirOf(importer.path);\n const target = joinWithin(mount.root, base, spec.startsWith(\"/\") ? spec.slice(1) : spec);\n const path = target && (await resolveFile(mount, target));\n return path ? { mount, path } : undefined;\n }\n if (spec.startsWith(\"#\")) {\n try {\n const out = resolveImports(mount.manifest ?? {}, spec, {\n conditions: c.conditions,\n require: c.require,\n browser: c.browser,\n }) as string[] | undefined;\n const target = out?.[0];\n if (!target) return undefined;\n if (!target.startsWith(\".\")) return resolveSpecifier(target, importer, packages, c);\n const path = joinWithin(mount.root, mount.root, target);\n return path && (await isFile(mount, path)) ? { mount, path } : undefined;\n } catch {\n return undefined;\n }\n }\n const { name, subpath } = parsePackageSpecifier(spec);\n const pkg = await packages.get(name, importer);\n if (!pkg) return undefined;\n const path = await resolvePackageEntry(pkg, subpath, c);\n return path && (await isFile(pkg, path)) ? { mount: pkg, path } : undefined;\n}\n","import { readText } from \"@statewalker/webrun-files\";\nimport type { Loader, Plugin } from \"esbuild-wasm\";\nimport { inlineInputMap, withoutInputMap } from \"./input-maps.js\";\nimport { nodeModulesPackages } from \"./packages.js\";\nimport { dirOf, idOf, isFile, joinWithin, pathOf, readManifest } from \"./paths.js\";\nimport { resolveSpecifier } from \"./resolve.js\";\nimport type {\n BundleOptions,\n BundleResult,\n ExternalPattern,\n Mount,\n SourceMap,\n TranspileOptions,\n TranspileResult,\n} from \"./types.js\";\n\n/** esbuild's namespace for the files the bundler serves; its source-map names drop it. */\nconst NS = \"webrun\";\n/** esbuild's namespace for the host's modules (`modules`): `virtual:<specifier>` in maps. */\nconst VNS = \"webrun-virtual\";\n/** Marks an `inject` entry, so that it resolves like an import, not like the entry point. */\nconst INJECT = \"webrun-inject:\";\n\n/** esbuild `supported` flags that lower `await` to generators. */\nconst LOWER_AWAIT = { \"async-await\": false, \"async-generator\": false, \"for-await\": false };\n\nconst LOADERS: Record<string, Loader> = {\n ts: \"ts\",\n mts: \"ts\",\n cts: \"ts\",\n tsx: \"tsx\",\n jsx: \"jsx\",\n js: \"js\",\n mjs: \"js\",\n cjs: \"js\",\n json: \"json\",\n css: \"css\",\n txt: \"text\",\n wasm: \"binary\",\n};\nexport const loaderFor = (path: string): Loader =>\n LOADERS[/\\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase() ?? \"\"] ?? \"js\";\n\nconst isExternal = (spec: string, patterns: ExternalPattern[]) =>\n /^(https?:|data:)/.test(spec) ||\n patterns.some((p) =>\n typeof p === \"string\"\n ? p.endsWith(\"*\")\n ? spec.startsWith(p.slice(0, -1))\n : spec === p\n : p.test(spec),\n );\n\n/** A source name of esbuild's map → the file id it stands for. */\nconst sourceId = (s: string) =>\n s\n .replace(/^(\\.\\.\\/)*/, \"\")\n .replace(new RegExp(`^${VNS}:`), \"virtual:\")\n .replace(new RegExp(`^${NS}:`), \"\")\n .replace(\"?type=module.mjs\", \"\"); // ESM_SUFFIX: the file's id, as in the map's other sources\n\nconst toBase64 = (text: string) => {\n const bytes = new TextEncoder().encode(text);\n let bin = \"\";\n for (let i = 0; i < bytes.length; i += 0x8000)\n bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n return btoa(bin);\n};\n\n/** `code` with its trailing map link replaced: by `map` inlined, or by a link to `name`. */\nfunction linkMap(code: string, map: SourceMap, how: \"external\" | \"inline\", name: string) {\n const body = code.replace(/\\n?\\/\\/# sourceMappingURL=\\S+\\s*$/, \"\");\n const url =\n how === \"inline\"\n ? `data:application/json;base64,${toBase64(JSON.stringify(map))}`\n : `${name.split(\"/\").pop()}.map`;\n return `${body}\\n//# sourceMappingURL=${url}\\n`;\n}\n\n/**\n * Bundles `entry` of a project into one module with esbuild (esbuild-wasm in browsers).\n * Every file is read through FilesApi (the project's, or a package's from `packages`):\n * esbuild resolves and loads nothing itself. esbuild transpiles TypeScript and JSX,\n * converts CommonJS, lowers `await` when asked, and bundles, all in one pass, and its\n * source map goes back through each step to the files it read; where a package ships\n * its own map (TypeScript compiled to `.js`), to the package's original source. The\n * map's sources are file ids: `~/src/app.ts`, `npm:pkg@1.2.3/src/index.ts`.\n */\n/** Marks the id of a `.js` file in a `\"type\": \"module\"` package scope (see `moduleTypeOf`). */\nconst ESM_SUFFIX = \"?type=module.mjs\";\n\nexport async function bundle(opts: BundleOptions): Promise<BundleResult> {\n const root = opts.root ?? \"/\";\n const project: Mount = {\n prefix: \"~\",\n files: opts.files,\n root,\n manifest: await readManifest(opts.files, root),\n };\n const packages = opts.packages ?? nodeModulesPackages();\n const external = opts.external ?? [];\n const browser = (opts.platform ?? \"browser\") === \"browser\";\n const conditions = opts.conditions ?? [\"browser\"];\n const outfile = opts.outfile ?? \"bundle.js\";\n const mounts = new Map<string, Mount>([[project.prefix, project]]);\n const supplied = opts.modules;\n const virtualSource = (spec: string) =>\n typeof supplied === \"function\" ? supplied(spec) : supplied?.[spec];\n\n /** The mount and path of a file id; the longest prefix wins (`npm:@a/b@1.0.0/…`). */\n /**\n * The module type of a `.js` file, as Node.js decides it: the `type` of the nearest\n * `package.json` (tslib ships `modules/package.json` with `\"type\": \"module\"`). esbuild reads\n * that only for files on its own file system; for ours, a file in a `\"type\": \"module\"` scope\n * gets an id ending in ESM_SUFFIX (`.mjs`), so that esbuild gives its imports of CommonJS\n * modules Node's interop: the default import is `module.exports`, even with `__esModule`.\n * Vite gets the same from esbuild by pre-bundling dependencies from disk.\n */\n const scopeTypes = new Map<string, string | undefined>();\n const moduleTypeOf = async (mount: Mount, path: string): Promise<string | undefined> => {\n const root = mount.root.replace(/\\/$/, \"\");\n for (let dir = dirOf(path); dir.length >= root.length; dir = dirOf(dir)) {\n const key = `${mount.prefix}:${dir}`;\n if (scopeTypes.has(key)) return scopeTypes.get(key);\n const pj = `${dir === \"/\" ? \"\" : dir}/package.json`;\n if (await isFile(mount, pj)) {\n let type: string | undefined;\n try {\n type = JSON.parse(await readText(mount.files, pj)).type;\n } catch {}\n scopeTypes.set(key, type);\n return type;\n }\n if (dir === root || dir === \"/\" || !dir) break;\n }\n return undefined;\n };\n\n const locate = (id: string) => {\n if (id.endsWith(ESM_SUFFIX)) id = id.slice(0, -ESM_SUFFIX.length);\n let best: Mount | undefined;\n for (const m of mounts.values())\n if (id.startsWith(`${m.prefix}/`) && (!best || m.prefix.length > best.prefix.length))\n best = m;\n const path = best && pathOf(best, id);\n if (!best || !path) throw new Error(`webrun-bundler: no file ${id}`);\n return { mount: best, path };\n };\n\n const plugin: Plugin = {\n name: \"webrun-files\",\n setup(b) {\n b.onResolve({ filter: /.*/ }, async (args) => {\n const injected = args.path.startsWith(INJECT);\n const spec = injected ? args.path.slice(INJECT.length) : args.path;\n if (args.kind === \"entry-point\" && !injected) {\n const path = joinWithin(root, root, args.path.replace(/^\\/+/, \"\"));\n if (!path) return { errors: [{ text: `entry ${args.path} is outside the project` }] };\n return { path: idOf(project, path), namespace: NS };\n }\n if (virtualSource(spec) !== undefined) return { path: spec, namespace: VNS };\n if (isExternal(spec, external)) return { path: spec, external: true };\n // The host's modules and `inject` entries import from the project's root.\n const importer =\n injected || args.namespace === VNS\n ? { mount: project, path: `${root === \"/\" ? \"\" : root}/` }\n : locate(args.importer);\n const require = args.kind === \"require-call\" || args.kind === \"require-resolve\";\n const failed = (why?: string) => ({\n errors: [\n {\n text: `Could not resolve \"${spec}\" (imported by ${args.importer || \"inject\"})${why ? `: ${why}` : \"\"}`,\n },\n ],\n });\n let r: Awaited<ReturnType<typeof resolveSpecifier>>;\n try {\n r = await resolveSpecifier(spec, importer, packages, {\n conditions,\n require,\n browser,\n });\n } catch (e) {\n return failed((e as Error)?.message ?? String(e));\n }\n if (!r) return failed();\n mounts.set(r.mount.prefix, r.mount);\n const esm = /\\.js$/.test(r.path) && (await moduleTypeOf(r.mount, r.path)) === \"module\";\n return { path: idOf(r.mount, r.path) + (esm ? ESM_SUFFIX : \"\"), namespace: NS };\n });\n b.onLoad({ filter: /.*/, namespace: VNS }, (args) => ({\n contents: virtualSource(args.path) ?? \"\",\n loader: \"js\",\n }));\n b.onLoad({ filter: /.*/, namespace: NS }, async (args) => {\n const { mount, path } = locate(args.path);\n const loader = loaderFor(path);\n if (loader === \"binary\") {\n const chunks: Uint8Array[] = [];\n for await (const c of mount.files.read(path)) chunks.push(c);\n const bytes = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));\n let at = 0;\n for (const c of chunks) {\n bytes.set(c, at);\n at += c.length;\n }\n return { contents: bytes, loader };\n }\n const text = await readText(mount.files, path);\n const js = loader === \"js\" || loader === \"ts\" || loader === \"jsx\" || loader === \"tsx\";\n // Without an output map, the inputs' own maps are not read: esbuild would only parse them.\n if (!js) return { contents: text, loader };\n if (opts.sourcemap === false) return { contents: withoutInputMap(text), loader };\n return { contents: await inlineInputMap(mount, path, text), loader };\n });\n },\n };\n\n const { plugins: extraPlugins = [], ...rest } = opts.esbuildOptions ?? {};\n const result = await opts.esbuild.build({\n entryPoints: [opts.entry],\n bundle: true,\n write: false,\n format: opts.format ?? \"esm\",\n platform: opts.platform ?? \"browser\",\n target: opts.target ?? \"es2022\",\n outfile,\n absWorkingDir: \"/\",\n metafile: true,\n logLevel: \"silent\",\n minify: opts.minify,\n define: opts.define,\n ...(opts.lowerAwait ? { supported: LOWER_AWAIT } : {}),\n ...rest,\n ...(opts.inject?.length ? { inject: opts.inject.map((s) => INJECT + s) } : {}),\n // `sourcemap: false`: no map at all (a large bundle's map, with every source's content,\n // can take more memory than the bundle).\n sourcemap: opts.sourcemap === false ? false : \"external\",\n sourcesContent: opts.sourcemap !== false,\n plugins: [...extraPlugins, plugin],\n });\n const out = result.outputFiles ?? [];\n const jsFile = out.find((f) => !f.path.endsWith(\".map\"));\n const mapFile = out.find((f) => f.path.endsWith(\".map\"));\n if (!jsFile) throw new Error(\"webrun-bundler: esbuild produced no output\");\n if (!mapFile)\n return {\n code: jsFile.text,\n map: { version: 3, sources: [], names: [], mappings: \"\" } as unknown as SourceMap,\n metafile: result.metafile as BundleResult[\"metafile\"],\n warnings: result.warnings,\n } as BundleResult;\n const raw = JSON.parse(mapFile.text) as SourceMap;\n const map: SourceMap = {\n ...raw,\n file: outfile.split(\"/\").pop(),\n sources: raw.sources.map(sourceId),\n };\n delete map.sourceRoot;\n return {\n code: linkMap(jsFile.text, map, opts.sourcemap || \"external\", outfile),\n map,\n metafile: result.metafile as BundleResult[\"metafile\"],\n warnings: result.warnings,\n };\n}\n\n/**\n * Transpiles one file (TypeScript, JSX, modern syntax down to `target`; `await` lowered\n * when asked) with a source map back to it. A map the code carries (`sourceMappingURL`,\n * inline) is composed in, so the result still traces to the original.\n */\nexport async function transpile(code: string, opts: TranspileOptions): Promise<TranspileResult> {\n const r = await opts.esbuild.transform(code, {\n loader: loaderFor(opts.path),\n sourcefile: opts.path,\n sourcemap: \"external\",\n sourcesContent: true,\n format: opts.format,\n target: opts.target ?? \"es2022\",\n minify: opts.minify,\n define: opts.define,\n ...(opts.lowerAwait ? { supported: LOWER_AWAIT } : {}),\n });\n const map = JSON.parse(r.map) as SourceMap;\n return {\n code: linkMap(r.code, map, opts.sourcemap ?? \"external\", opts.path.replace(/\\.[^./]+$/, \".js\")),\n map,\n warnings: r.warnings,\n };\n}\n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KAAK,CAAC;EAC9F;EACA,UAAU,EAAE;CACd;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@statewalker/webrun-bundler",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"private": false,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"description": "Transpiler, resolver and bundler on esbuild-wasm that reads everything through a FilesApi (MemFilesApi, OPFS, a FilesApi over a port; never node:fs) and fetches npm packages on demand. Every transformation keeps a source map: each line of a bundle traces back to the user's file or to the npm package's own source.",
|
|
7
|
+
"bugs": {
|
|
8
|
+
"url": "https://github.com/statewalker/webrun-sites/issues"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/statewalker/webrun-sites/tree/main/packages/webrun-bundler#readme",
|
|
11
|
+
"author": {
|
|
12
|
+
"name": "Mikhail Kotelnikov",
|
|
13
|
+
"email": "mikhail.kotelnikov@gmail.com"
|
|
14
|
+
},
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/statewalker/webrun-sites.git",
|
|
19
|
+
"directory": "packages/webrun-bundler"
|
|
20
|
+
},
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"source": "./src/index.ts",
|
|
24
|
+
"types": "./dist/index.d.mts",
|
|
25
|
+
"import": "./dist/index.mjs"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist",
|
|
30
|
+
"src"
|
|
31
|
+
],
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@statewalker/webrun-files": "^0.10.0",
|
|
34
|
+
"resolve.exports": "^2.0.3",
|
|
35
|
+
"@statewalker/webrun-modules": "^0.3.6"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"esbuild-wasm": "^0.28.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@jridgewell/trace-mapping": "^0.3.31",
|
|
42
|
+
"@statewalker/webrun-files-browser": "^0.10.2",
|
|
43
|
+
"@statewalker/webrun-files-mem": "^0.10.0",
|
|
44
|
+
"esbuild-wasm": "^0.28.2",
|
|
45
|
+
"playwright": "^1.63.0",
|
|
46
|
+
"rimraf": "^6.1.3",
|
|
47
|
+
"tsdown": "^0.23.0",
|
|
48
|
+
"typescript": "^7.0.2",
|
|
49
|
+
"vitest": "^5.0.3"
|
|
50
|
+
},
|
|
51
|
+
"sideEffects": false,
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public"
|
|
54
|
+
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"build": "tsdown",
|
|
57
|
+
"dev": "tsdown --watch",
|
|
58
|
+
"test": "vitest run",
|
|
59
|
+
"test:watch": "vitest",
|
|
60
|
+
"typecheck": "tsc --noEmit",
|
|
61
|
+
"clean": "rimraf dist",
|
|
62
|
+
"lint": "biome check --write .",
|
|
63
|
+
"format": "biome format --write .",
|
|
64
|
+
"test:browser": "node e2e/browser.mjs"
|
|
65
|
+
}
|
|
6
66
|
}
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import { originalPositionFor, TraceMap } from "@jridgewell/trace-mapping";
|
|
2
|
+
import type { FilesApi } from "@statewalker/webrun-files";
|
|
3
|
+
import { MemFilesApi } from "@statewalker/webrun-files-mem";
|
|
4
|
+
import type { Source } from "@statewalker/webrun-modules";
|
|
5
|
+
import * as esbuild from "esbuild-wasm";
|
|
6
|
+
import { describe, expect, it } from "vitest";
|
|
7
|
+
import { bundle, chainPackages, nodeModulesPackages, npmPackages, transpile } from "./index.js";
|
|
8
|
+
import type { SourceMap } from "./types.js";
|
|
9
|
+
|
|
10
|
+
// esbuild-wasm itself (its Node build runs the same WebAssembly as in browsers); every
|
|
11
|
+
// file comes from a MemFilesApi, nothing from a disk.
|
|
12
|
+
|
|
13
|
+
const enc = new TextEncoder();
|
|
14
|
+
async function filesOf(tree: Record<string, string>): Promise<FilesApi> {
|
|
15
|
+
const files = new MemFilesApi();
|
|
16
|
+
for (const [path, text] of Object.entries(tree)) await files.write(path, [enc.encode(text)]);
|
|
17
|
+
return files;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** 1-based line of the first line of `text` containing `marker`. */
|
|
21
|
+
const lineOf = (text: string, marker: string) =>
|
|
22
|
+
text.split("\n").findIndex((l) => l.includes(marker)) + 1;
|
|
23
|
+
|
|
24
|
+
/** Where the bundled line holding `marker` comes from. */
|
|
25
|
+
function trace(code: string, map: SourceMap, marker: string) {
|
|
26
|
+
const lines = code.split("\n");
|
|
27
|
+
const line = lines.findIndex((l) => l.includes(marker));
|
|
28
|
+
expect(line, `${marker} in the bundle`).toBeGreaterThanOrEqual(0);
|
|
29
|
+
const tm = new TraceMap(map as never);
|
|
30
|
+
const text = lines[line] as string;
|
|
31
|
+
// the first mapped column of the line
|
|
32
|
+
for (let column = 0; column < text.length; column++) {
|
|
33
|
+
const pos = originalPositionFor(tm, { line: line + 1, column });
|
|
34
|
+
if (pos.source) return { source: pos.source, line: pos.line };
|
|
35
|
+
}
|
|
36
|
+
return { source: null, line: null };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// The original TypeScript of a published package: types and comments make its lines differ
|
|
40
|
+
// from the compiled JavaScript's, so a trace that ends at the .js would be off.
|
|
41
|
+
const ESM_PKG_SRC = `/** Greeting helpers. */
|
|
42
|
+
export interface Options {
|
|
43
|
+
punctuation?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type Name = string;
|
|
47
|
+
|
|
48
|
+
export async function greet(name: Name, opts: Options = {}): Promise<string> {
|
|
49
|
+
await Promise.resolve();
|
|
50
|
+
return "hello " + name + (opts.punctuation ?? "!") + "MARK_ESM_PKG".slice(99);
|
|
51
|
+
}
|
|
52
|
+
`;
|
|
53
|
+
|
|
54
|
+
/** `esm-pkg` as npm ships it: compiled dist/, a linked map without sourcesContent, src/. */
|
|
55
|
+
async function esmPackage(): Promise<Record<string, string>> {
|
|
56
|
+
const out = await esbuild.transform(ESM_PKG_SRC, {
|
|
57
|
+
loader: "ts",
|
|
58
|
+
sourcefile: "../src/index.ts",
|
|
59
|
+
sourcemap: "external",
|
|
60
|
+
format: "esm",
|
|
61
|
+
target: "es2022",
|
|
62
|
+
});
|
|
63
|
+
const map = JSON.parse(out.map);
|
|
64
|
+
delete map.sourcesContent; // many packages ship maps without it: the bundler reads src/
|
|
65
|
+
return {
|
|
66
|
+
"/package.json": JSON.stringify({
|
|
67
|
+
name: "esm-pkg",
|
|
68
|
+
version: "1.2.3",
|
|
69
|
+
type: "module",
|
|
70
|
+
exports: { ".": { browser: "./dist/browser.js", default: "./dist/index.js" } },
|
|
71
|
+
}),
|
|
72
|
+
"/dist/browser.js": `${out.code}//# sourceMappingURL=browser.js.map\n`,
|
|
73
|
+
"/dist/browser.js.map": JSON.stringify(map),
|
|
74
|
+
"/dist/index.js": 'export const greet = () => "not the browser build";\n',
|
|
75
|
+
"/src/index.ts": ESM_PKG_SRC,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const CJS_PKG = {
|
|
80
|
+
"/package.json": JSON.stringify({ name: "cjs-pkg", version: "2.0.0", main: "lib/index.js" }),
|
|
81
|
+
"/lib/index.js": `"use strict";
|
|
82
|
+
exports.shout = function (s) {
|
|
83
|
+
return s.toUpperCase() + "!" + "MARK_CJS".slice(99);
|
|
84
|
+
};
|
|
85
|
+
`,
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const APP = `import cjs from "cjs-pkg";
|
|
89
|
+
import { greet } from "esm-pkg";
|
|
90
|
+
import data from "./data.json";
|
|
91
|
+
|
|
92
|
+
export async function main(name: string): Promise<string> {
|
|
93
|
+
const g = (await greet(name)) + "MARK_APP_AWAIT".slice(99);
|
|
94
|
+
return \`\${g} \${cjs.shout(name)} \${data.v}\${"MARK_APP_RETURN".slice(99)}\`;
|
|
95
|
+
}
|
|
96
|
+
`;
|
|
97
|
+
|
|
98
|
+
/** A registry `Source` over in-memory packages; counts loads. */
|
|
99
|
+
function fakeRegistry(packages: Record<string, Record<string, string>>) {
|
|
100
|
+
const loads: string[] = [];
|
|
101
|
+
const source: Source = {
|
|
102
|
+
matches: (ref) => "pkg" in ref,
|
|
103
|
+
async load(ref) {
|
|
104
|
+
if (!("pkg" in ref)) throw new Error("not a package");
|
|
105
|
+
loads.push(`${ref.pkg}@${ref.version ?? "latest"}`);
|
|
106
|
+
const tree = packages[ref.pkg];
|
|
107
|
+
if (!tree) throw new Error(`no package ${ref.pkg}`);
|
|
108
|
+
const files = await filesOf(tree);
|
|
109
|
+
const manifest = JSON.parse(tree["/package.json"] as string);
|
|
110
|
+
return { name: ref.pkg, version: manifest.version, files, manifest };
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
return { source, loads };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function run(code: string) {
|
|
117
|
+
const bytes = enc.encode(code);
|
|
118
|
+
let bin = "";
|
|
119
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
120
|
+
const url = `data:text/javascript;base64,${btoa(bin)}`;
|
|
121
|
+
return import(/* @vite-ignore */ url);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
describe("bundle", () => {
|
|
125
|
+
it("bundles from a FilesApi with packages fetched on demand; every line traces to its source", async () => {
|
|
126
|
+
const files = await filesOf({
|
|
127
|
+
"/package.json": JSON.stringify({
|
|
128
|
+
dependencies: { "esm-pkg": "^1.0.0", "cjs-pkg": "^2.0.0" },
|
|
129
|
+
}),
|
|
130
|
+
"/src/app.ts": APP,
|
|
131
|
+
"/src/data.json": '{ "v": 42 }',
|
|
132
|
+
});
|
|
133
|
+
const { source, loads } = fakeRegistry({ "esm-pkg": await esmPackage(), "cjs-pkg": CJS_PKG });
|
|
134
|
+
const r = await bundle({
|
|
135
|
+
esbuild,
|
|
136
|
+
files,
|
|
137
|
+
entry: "/src/app.ts",
|
|
138
|
+
packages: npmPackages({ source }),
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
expect(loads.sort()).toEqual(["cjs-pkg@^2.0.0", "esm-pkg@^1.0.0"]);
|
|
142
|
+
expect((await run(r.code)).main).toBeTypeOf("function");
|
|
143
|
+
expect(await (await run(r.code)).main("bob")).toBe("hello bob! BOB! 42");
|
|
144
|
+
expect(r.code).toMatch(/\/\/# sourceMappingURL=bundle\.js\.map\n$/);
|
|
145
|
+
|
|
146
|
+
// The user's TypeScript, line for line.
|
|
147
|
+
expect(trace(r.code, r.map, "MARK_APP_AWAIT")).toEqual({
|
|
148
|
+
source: "~/src/app.ts",
|
|
149
|
+
line: lineOf(APP, "MARK_APP_AWAIT"),
|
|
150
|
+
});
|
|
151
|
+
expect(trace(r.code, r.map, "MARK_APP_RETURN")).toEqual({
|
|
152
|
+
source: "~/src/app.ts",
|
|
153
|
+
line: lineOf(APP, "MARK_APP_RETURN"),
|
|
154
|
+
});
|
|
155
|
+
// Through the package's own map, to its original TypeScript (not dist/browser.js).
|
|
156
|
+
expect(trace(r.code, r.map, "MARK_ESM_PKG")).toEqual({
|
|
157
|
+
source: "npm:esm-pkg@1.2.3/src/index.ts",
|
|
158
|
+
line: lineOf(ESM_PKG_SRC, "MARK_ESM_PKG"),
|
|
159
|
+
});
|
|
160
|
+
// CommonJS, converted by esbuild, still maps to the package's file.
|
|
161
|
+
expect(trace(r.code, r.map, "MARK_CJS")).toEqual({
|
|
162
|
+
source: "npm:cjs-pkg@2.0.0/lib/index.js",
|
|
163
|
+
line: 3,
|
|
164
|
+
});
|
|
165
|
+
// The map carries every source's text, the package's TypeScript included.
|
|
166
|
+
const i = r.map.sources.indexOf("npm:esm-pkg@1.2.3/src/index.ts");
|
|
167
|
+
expect(r.map.sourcesContent?.[i]).toBe(ESM_PKG_SRC);
|
|
168
|
+
expect(r.map.sources).not.toContain("npm:esm-pkg@1.2.3/dist/browser.js");
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("sourcemap: false builds no map (the same code, no sourceMappingURL), warnings kept", async () => {
|
|
172
|
+
const files = await filesOf({
|
|
173
|
+
"/package.json": JSON.stringify({
|
|
174
|
+
dependencies: { "esm-pkg": "^1.0.0", "cjs-pkg": "^2.0.0" },
|
|
175
|
+
}),
|
|
176
|
+
"/src/app.ts": APP,
|
|
177
|
+
"/src/data.json": '{ "v": 42 }',
|
|
178
|
+
// esbuild warns about a comparison with -0.
|
|
179
|
+
"/src/warn.ts": "export const odd = (x: number) => x === -0;\n",
|
|
180
|
+
});
|
|
181
|
+
const { source } = fakeRegistry({ "esm-pkg": await esmPackage(), "cjs-pkg": CJS_PKG });
|
|
182
|
+
await files.write("/src/entry.ts", [
|
|
183
|
+
new TextEncoder().encode('export * from "./app.ts";\nexport * from "./warn.ts";\n'),
|
|
184
|
+
]);
|
|
185
|
+
const r = await bundle({
|
|
186
|
+
esbuild,
|
|
187
|
+
files,
|
|
188
|
+
entry: "/src/entry.ts",
|
|
189
|
+
packages: npmPackages({ source }),
|
|
190
|
+
sourcemap: false,
|
|
191
|
+
});
|
|
192
|
+
expect(await (await run(r.code)).main("bob")).toBe("hello bob! BOB! 42");
|
|
193
|
+
expect(r.code).not.toMatch(/sourceMappingURL/);
|
|
194
|
+
expect(r.map.mappings).toBe("");
|
|
195
|
+
expect(r.map.sources).toEqual([]);
|
|
196
|
+
expect(r.warnings?.map((w) => w.text).join(" ")).toMatch(/-0/);
|
|
197
|
+
// The package's own map is neither read nor inlined: esbuild gets its code alone.
|
|
198
|
+
const inputs = r.metafile?.inputs ?? {};
|
|
199
|
+
const pkgInput = Object.keys(inputs).find((k) => k.includes("esm-pkg@1.2.3/dist/browser.js"));
|
|
200
|
+
expect(pkgInput).toBeDefined();
|
|
201
|
+
const withMaps = await bundle({
|
|
202
|
+
esbuild,
|
|
203
|
+
files,
|
|
204
|
+
entry: "/src/entry.ts",
|
|
205
|
+
packages: npmPackages({ source }),
|
|
206
|
+
});
|
|
207
|
+
const mapped = withMaps.metafile?.inputs[pkgInput as string]?.bytes ?? 0;
|
|
208
|
+
expect(inputs[pkgInput as string]?.bytes ?? Infinity).toBeLessThan(mapped);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it("maps every line that comes from an input; only esbuild's own helpers have no source", async () => {
|
|
212
|
+
const files = await filesOf({
|
|
213
|
+
"/package.json": JSON.stringify({
|
|
214
|
+
dependencies: { "esm-pkg": "^1.0.0", "cjs-pkg": "^2.0.0" },
|
|
215
|
+
}),
|
|
216
|
+
"/src/app.ts": APP,
|
|
217
|
+
"/src/data.json": '{ "v": 42 }',
|
|
218
|
+
});
|
|
219
|
+
const { source } = fakeRegistry({ "esm-pkg": await esmPackage(), "cjs-pkg": CJS_PKG });
|
|
220
|
+
for (const lowerAwait of [false, true]) {
|
|
221
|
+
const r = await bundle({
|
|
222
|
+
esbuild,
|
|
223
|
+
files,
|
|
224
|
+
entry: "/src/app.ts",
|
|
225
|
+
packages: npmPackages({ source }),
|
|
226
|
+
lowerAwait,
|
|
227
|
+
});
|
|
228
|
+
const tm = new TraceMap(r.map as never);
|
|
229
|
+
const lines = r.code.split("\n");
|
|
230
|
+
// esbuild's runtime (`__commonJS`, `__toESM`, with lowering `__async`) comes first, up
|
|
231
|
+
// to the first module's comment; it is the only code no input wrote.
|
|
232
|
+
const firstModule = lines.findIndex((l) => l.startsWith("// webrun:"));
|
|
233
|
+
expect(firstModule).toBeGreaterThan(0);
|
|
234
|
+
// …and its closing `export { … };` clause, which lists the entry's exports.
|
|
235
|
+
const exportClause = lines.lastIndexOf("export {");
|
|
236
|
+
const unmapped: string[] = [];
|
|
237
|
+
lines.slice(firstModule, exportClause < 0 ? undefined : exportClause).forEach((text, i) => {
|
|
238
|
+
const code = text.trim();
|
|
239
|
+
if (!code || code.startsWith("//") || /^[\]{}()[;,]+$/.test(code)) return;
|
|
240
|
+
let mapped = false;
|
|
241
|
+
for (let column = 0; column < text.length && !mapped; column++)
|
|
242
|
+
mapped = !!originalPositionFor(tm, { line: firstModule + i + 1, column }).source;
|
|
243
|
+
if (!mapped) unmapped.push(code);
|
|
244
|
+
});
|
|
245
|
+
// Besides them, only esbuild's CommonJS wrapper lines: `var require_x = __commonJS({`
|
|
246
|
+
// and the module's function head.
|
|
247
|
+
expect(
|
|
248
|
+
unmapped.filter(
|
|
249
|
+
(l) => !/^var require_\w+ = __commonJS\(\{$|^"webrun:[^"]+"\(.*\) \{$/.test(l),
|
|
250
|
+
),
|
|
251
|
+
).toEqual([]);
|
|
252
|
+
if (lowerAwait) {
|
|
253
|
+
expect(r.code).not.toMatch(/\bawait\b/);
|
|
254
|
+
expect(trace(r.code, r.map, "MARK_APP_AWAIT").source).toBe("~/src/app.ts");
|
|
255
|
+
expect(trace(r.code, r.map, "MARK_ESM_PKG").source).toBe("npm:esm-pkg@1.2.3/src/index.ts");
|
|
256
|
+
expect(await (await run(r.code)).main("amy")).toBe("hello amy! AMY! 42");
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
it("reads packages from node_modules folders of the FilesApi, nested ones first", async () => {
|
|
262
|
+
const files = await filesOf({
|
|
263
|
+
"/src/main.js":
|
|
264
|
+
'import { a } from "a";\nimport { v } from "b";\nexport const out = a + "/" + v;\n',
|
|
265
|
+
"/node_modules/a/package.json": JSON.stringify({
|
|
266
|
+
name: "a",
|
|
267
|
+
version: "1.0.0",
|
|
268
|
+
main: "index.js",
|
|
269
|
+
}),
|
|
270
|
+
"/node_modules/a/index.js": 'export { v as a } from "b";\n',
|
|
271
|
+
"/node_modules/a/node_modules/b/package.json": JSON.stringify({
|
|
272
|
+
name: "b",
|
|
273
|
+
version: "2.0.0",
|
|
274
|
+
module: "m.js",
|
|
275
|
+
}),
|
|
276
|
+
"/node_modules/a/node_modules/b/m.js": 'export const v = "b2" + "MARK_B2".slice(99);\n',
|
|
277
|
+
"/node_modules/b/package.json": JSON.stringify({ name: "b", version: "1.0.0" }),
|
|
278
|
+
"/node_modules/b/index.js": 'export const v = "b1";\n',
|
|
279
|
+
});
|
|
280
|
+
const r = await bundle({ esbuild, files, entry: "/src/main.js" });
|
|
281
|
+
expect((await run(r.code)).out).toBe("b2/b1");
|
|
282
|
+
expect(trace(r.code, r.map, "MARK_B2").source).toBe("npm:b@2.0.0/m.js");
|
|
283
|
+
// a/index.js only re-exports: no code of its own, so esbuild maps nothing to it.
|
|
284
|
+
expect(r.map.sources).toEqual(
|
|
285
|
+
expect.arrayContaining(["~/src/main.js", "npm:b@2.0.0/m.js", "npm:b@1.0.0/index.js"]),
|
|
286
|
+
);
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
it('gives files in a "type": "module" scope Node\'s CommonJS interop (tslib\'s modules/)', async () => {
|
|
290
|
+
// tslib 2.3: exports "import" -> modules/index.js (modules/package.json: type module), which
|
|
291
|
+
// does `import tslib from "../tslib.js"` of a CommonJS file that sets __esModule. In Node
|
|
292
|
+
// (and Vite, which pre-bundles from disk) the default import is module.exports.
|
|
293
|
+
const files = await filesOf({
|
|
294
|
+
"/src/main.js": 'import { __extends } from "tslib";\nexport const out = typeof __extends;\n',
|
|
295
|
+
"/node_modules/tslib/package.json": JSON.stringify({
|
|
296
|
+
name: "tslib",
|
|
297
|
+
version: "2.3.0",
|
|
298
|
+
main: "tslib.js",
|
|
299
|
+
exports: {
|
|
300
|
+
".": { import: "./modules/index.js", module: "./tslib.es6.js", default: "./tslib.js" },
|
|
301
|
+
},
|
|
302
|
+
}),
|
|
303
|
+
"/node_modules/tslib/modules/package.json": JSON.stringify({ type: "module" }),
|
|
304
|
+
"/node_modules/tslib/modules/index.js":
|
|
305
|
+
'import tslib from "../tslib.js";\nconst { __extends } = tslib;\nexport { __extends };\n',
|
|
306
|
+
"/node_modules/tslib/tslib.js":
|
|
307
|
+
'Object.defineProperty(exports, "__esModule", { value: true });\nexports.__extends = function () {};\n',
|
|
308
|
+
"/node_modules/tslib/tslib.es6.js": "export function __extends() {}\n",
|
|
309
|
+
});
|
|
310
|
+
const r = await bundle({
|
|
311
|
+
esbuild,
|
|
312
|
+
files,
|
|
313
|
+
entry: "/src/main.js",
|
|
314
|
+
conditions: ["browser", "import"],
|
|
315
|
+
});
|
|
316
|
+
expect((await run(r.code)).out).toBe("function");
|
|
317
|
+
expect(r.map.sources).toContain("npm:tslib@2.3.0/modules/index.js");
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
it("keeps externals as imports, picks exports conditions, resolves .js to .ts and #imports", async () => {
|
|
321
|
+
const files = await filesOf({
|
|
322
|
+
"/package.json": JSON.stringify({ imports: { "#util": "./src/util.ts" } }),
|
|
323
|
+
"/src/worker.ts":
|
|
324
|
+
'import { DurableObject } from "cloudflare:workers";\nimport { readFileSync } from "node:fs";\nimport { which } from "dual";\nimport { util } from "#util";\nimport { helper } from "./helper.js";\nexport const all = [DurableObject, readFileSync, which, util, helper];\n',
|
|
325
|
+
"/src/util.ts": 'export const util: string = "util";\n',
|
|
326
|
+
"/src/helper.ts": 'export const helper: string = "helper";\n',
|
|
327
|
+
"/node_modules/dual/package.json": JSON.stringify({
|
|
328
|
+
name: "dual",
|
|
329
|
+
version: "1.0.0",
|
|
330
|
+
exports: { workerd: "./w.js", browser: "./b.js", default: "./d.js" },
|
|
331
|
+
}),
|
|
332
|
+
"/node_modules/dual/w.js": 'export const which = "workerd";\n',
|
|
333
|
+
"/node_modules/dual/b.js": 'export const which = "browser";\n',
|
|
334
|
+
"/node_modules/dual/d.js": 'export const which = "default";\n',
|
|
335
|
+
});
|
|
336
|
+
const r = await bundle({
|
|
337
|
+
esbuild,
|
|
338
|
+
files,
|
|
339
|
+
entry: "/src/worker.ts",
|
|
340
|
+
external: ["cloudflare:*", "node:*"],
|
|
341
|
+
conditions: ["workerd", "worker", "browser"],
|
|
342
|
+
platform: "neutral",
|
|
343
|
+
});
|
|
344
|
+
expect(r.code).toMatch(/from "cloudflare:workers"/);
|
|
345
|
+
expect(r.code).toMatch(/from "node:fs"/);
|
|
346
|
+
expect(r.code).toContain('"workerd"');
|
|
347
|
+
expect(r.code).not.toContain('"browser"');
|
|
348
|
+
expect(r.map.sources).toEqual(
|
|
349
|
+
expect.arrayContaining([
|
|
350
|
+
"~/src/worker.ts",
|
|
351
|
+
"~/src/util.ts",
|
|
352
|
+
"~/src/helper.ts",
|
|
353
|
+
"npm:dual@1.0.0/w.js",
|
|
354
|
+
]),
|
|
355
|
+
);
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
it("node_modules first, then the registry; unresolvable imports are esbuild errors", async () => {
|
|
359
|
+
const files = await filesOf({
|
|
360
|
+
"/package.json": JSON.stringify({ dependencies: { "cjs-pkg": "2" } }),
|
|
361
|
+
"/src/main.js":
|
|
362
|
+
'import local from "local";\nimport cjs from "cjs-pkg";\nexport const out = local + cjs.shout("a");\n',
|
|
363
|
+
"/node_modules/local/package.json": JSON.stringify({ name: "local", version: "0.1.0" }),
|
|
364
|
+
"/node_modules/local/index.js": 'export default "local:";\n',
|
|
365
|
+
});
|
|
366
|
+
const { source, loads } = fakeRegistry({ "cjs-pkg": CJS_PKG });
|
|
367
|
+
const packages = chainPackages(nodeModulesPackages(), npmPackages({ source }));
|
|
368
|
+
const r = await bundle({ esbuild, files, entry: "/src/main.js", packages });
|
|
369
|
+
expect((await run(r.code)).out).toBe("local:A!");
|
|
370
|
+
expect(loads).toEqual(["cjs-pkg@2"]);
|
|
371
|
+
|
|
372
|
+
await files.write("/src/bad.js", [enc.encode('import "nowhere";\n')]);
|
|
373
|
+
await expect(bundle({ esbuild, files, entry: "/src/bad.js", packages })).rejects.toThrow(
|
|
374
|
+
/Could not resolve "nowhere"/,
|
|
375
|
+
);
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
it("host modules (by name or function) and inject; their lines map to virtual:<specifier>", async () => {
|
|
379
|
+
const files = await filesOf({
|
|
380
|
+
"/src/main.ts":
|
|
381
|
+
'import { env } from "cloudflare:workers";\nimport { join } from "node:path";\nimport { tag } from "./tag.ts";\nexport const out = [env.NAME, join("a", "b"), tag, new Response("r").kind];\n',
|
|
382
|
+
"/src/tag.ts": 'export const tag: string = "tag";\n',
|
|
383
|
+
"/src/shim.ts":
|
|
384
|
+
'export class Response { kind = "shimmed"; constructor(public body: string) {} }\n',
|
|
385
|
+
});
|
|
386
|
+
const r = await bundle({
|
|
387
|
+
esbuild,
|
|
388
|
+
files,
|
|
389
|
+
entry: "/src/main.ts",
|
|
390
|
+
modules: (spec) =>
|
|
391
|
+
spec === "cloudflare:workers"
|
|
392
|
+
? 'export const env = { NAME: "host-env" };\n'
|
|
393
|
+
: spec.startsWith("node:")
|
|
394
|
+
? `export const join = (...p) => p.join("/") + ${JSON.stringify(`<${spec}>`)};\n`
|
|
395
|
+
: undefined,
|
|
396
|
+
inject: ["/src/shim.ts"],
|
|
397
|
+
});
|
|
398
|
+
expect((await run(r.code)).out).toEqual(["host-env", "a/b<node:path>", "tag", "shimmed"]);
|
|
399
|
+
expect(r.map.sources).toEqual(
|
|
400
|
+
expect.arrayContaining([
|
|
401
|
+
"virtual:cloudflare:workers",
|
|
402
|
+
"virtual:node:path",
|
|
403
|
+
"~/src/main.ts",
|
|
404
|
+
"~/src/shim.ts",
|
|
405
|
+
]),
|
|
406
|
+
);
|
|
407
|
+
// a record works too, and an unknown specifier still resolves as usual
|
|
408
|
+
const r2 = await bundle({
|
|
409
|
+
esbuild,
|
|
410
|
+
files,
|
|
411
|
+
entry: "/src/main.ts",
|
|
412
|
+
modules: {
|
|
413
|
+
"cloudflare:workers": "export const env = { NAME: 1 };\n",
|
|
414
|
+
"node:path": "export const join = () => 2;\n",
|
|
415
|
+
},
|
|
416
|
+
});
|
|
417
|
+
expect((await run(r2.code)).out.slice(0, 3)).toEqual([1, 2, "tag"]);
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
it("pnpm layouts: a package's own dependencies come from node_modules/.pnpm/node_modules", async () => {
|
|
421
|
+
const files = await filesOf({
|
|
422
|
+
"/app/main.js": 'import { a } from "a";\nexport const out = a;\n',
|
|
423
|
+
// node_modules/a is a symlink into .pnpm in a real install; its dependency b is only
|
|
424
|
+
// next to a's real directory, reachable through pnpm's hoisted links.
|
|
425
|
+
"/app/node_modules/a/package.json": JSON.stringify({ name: "a", version: "1.0.0" }),
|
|
426
|
+
"/app/node_modules/a/index.js": 'import { b } from "b";\nexport const a = "a+" + b;\n',
|
|
427
|
+
"/app/node_modules/.pnpm/node_modules/b/package.json": JSON.stringify({
|
|
428
|
+
name: "b",
|
|
429
|
+
version: "4.0.0",
|
|
430
|
+
}),
|
|
431
|
+
"/app/node_modules/.pnpm/node_modules/b/index.js": 'export const b = "b";\n',
|
|
432
|
+
});
|
|
433
|
+
const r = await bundle({ esbuild, files, root: "/app", entry: "/main.js" });
|
|
434
|
+
expect((await run(r.code)).out).toBe("a+b");
|
|
435
|
+
expect(r.map.sources).toContain("npm:b@4.0.0/index.js");
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
it("inline maps: the bundle carries its own map", async () => {
|
|
439
|
+
const files = await filesOf({ "/a.ts": "export const a: number = 1; // MARK_A\n" });
|
|
440
|
+
const r = await bundle({ esbuild, files, entry: "/a.ts", sourcemap: "inline" });
|
|
441
|
+
const b64 = /sourceMappingURL=data:application\/json;base64,(\S+)/.exec(r.code)?.[1];
|
|
442
|
+
expect(
|
|
443
|
+
JSON.parse(
|
|
444
|
+
new TextDecoder().decode(Uint8Array.from(atob(b64 as string), (c) => c.charCodeAt(0))),
|
|
445
|
+
),
|
|
446
|
+
).toEqual(r.map);
|
|
447
|
+
});
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
describe("transpile", () => {
|
|
451
|
+
it("one file, its map back to it; await lowered when asked", async () => {
|
|
452
|
+
const src =
|
|
453
|
+
"type T = number;\n\nexport async function f(x: T) {\n return (await x) + 1 + 'MARK_F'.length * 0;\n}\n";
|
|
454
|
+
const r = await transpile(src, { esbuild, path: "~/src/f.ts", lowerAwait: true });
|
|
455
|
+
expect(r.code).not.toMatch(/\bawait\b/);
|
|
456
|
+
expect(trace(r.code, r.map, "MARK_F")).toEqual({ source: "~/src/f.ts", line: 4 });
|
|
457
|
+
expect(r.code).toMatch(/\/\/# sourceMappingURL=f\.js\.map\n$/);
|
|
458
|
+
});
|
|
459
|
+
});
|