|
| 1 | +import type { PluginBuild } from "esbuild"; |
| 2 | +import { |
| 3 | + addDebugIdToSource, |
| 4 | + DEFAULT_EXTENSIONS, |
| 5 | + stringToUUID, |
| 6 | + addDebugIdToSourcemap, |
| 7 | +} from "./common"; |
| 8 | +import { readFile, writeFile } from "fs/promises"; |
| 9 | +import * as path from "path"; |
| 10 | + |
| 11 | +export default { |
| 12 | + name: "esbuild-plugin-debug-ids", |
| 13 | + setup({ onEnd, initialOptions }: PluginBuild) { |
| 14 | + if ( |
| 15 | + initialOptions.bundle !== true || |
| 16 | + initialOptions.sourcemap === undefined |
| 17 | + ) { |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + initialOptions.metafile = true; |
| 22 | + |
| 23 | + onEnd(async (result) => { |
| 24 | + const assets = Object.keys(result.metafile?.outputs || {}); |
| 25 | + const assetsWithCorrectExt = assets.filter((file) => |
| 26 | + DEFAULT_EXTENSIONS.some((ext) => file.endsWith(ext)) |
| 27 | + ); |
| 28 | + |
| 29 | + if (assetsWithCorrectExt.length === 0) { |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + const promises = assetsWithCorrectExt.map(async (key) => { |
| 34 | + const sourcemapKey = `${key}.map`; |
| 35 | + |
| 36 | + // If we don't have a sourcemap, don't do anything |
| 37 | + if (!assets.includes(sourcemapKey)) { |
| 38 | + return Promise.resolve(); |
| 39 | + } |
| 40 | + |
| 41 | + const sourcePath = path.join(process.cwd(), key); |
| 42 | + const source = await readFile(sourcePath, { encoding: "utf-8" }); |
| 43 | + const debugId = stringToUUID(source); |
| 44 | + const updatedSource = addDebugIdToSource(source, debugId); |
| 45 | + await writeFile(sourcePath, updatedSource); |
| 46 | + |
| 47 | + const sourcemapPath = path.join(process.cwd(), sourcemapKey); |
| 48 | + const sourcemap = await readFile(sourcemapPath, { encoding: "utf-8" }); |
| 49 | + const updatedSourcemap = addDebugIdToSourcemap(sourcemap, debugId); |
| 50 | + await writeFile(sourcemapPath, updatedSourcemap); |
| 51 | + }); |
| 52 | + |
| 53 | + await Promise.all(promises); |
| 54 | + }); |
| 55 | + }, |
| 56 | +}; |
0 commit comments