import type { OutputChunk, Plugin as RollupPlugin } from "rollup"; interface SourcemapUrlPluginOptions { replaceUrl: (url: string) => string; } export const sourcemapUrl = ( options: SourcemapUrlPluginOptions, ): RollupPlugin => ({ name: "sourcemap-url", generateBundle(outputOptions, bundle) { for (const fileName of Object.keys(bundle)) { const chunk = bundle[fileName] as OutputChunk; if (chunk.map) { const splitCode = chunk.code.split("\n"); let lineIndex = splitCode.length - 1; // find the last line that is not empty while (lineIndex >= 0 && splitCode[lineIndex].trim() === "") { lineIndex--; } if (lineIndex < 0) { // empty file continue; } const match = splitCode[lineIndex].match( /\/\/# sourceMappingURL=([^\s]+)/, ); // if the last line is a sourceMappingURL, replace it if (match && match[1]) { splitCode[lineIndex] = `//# sourceMappingURL=${options.replaceUrl(match[1])}`; chunk.code = splitCode.join("\n"); } } } }, });