rollup-plugin-sourcemaps2
Version:
Rollup plugin for grabbing source maps from sourceMappingURLs
80 lines (76 loc) • 3.26 kB
JavaScript
const fs = require('node:fs');
const node_util = require('node:util');
const pluginUtils = require('@rollup/pluginutils');
const sourceMapResolve_js = require('./source-map-resolve.cjs');
const { createFilter } = pluginUtils;
function sourcemaps(// eslint-disable-next-line @typescript-eslint/unbound-method
{ include, exclude, readFile = fs.readFile } = {}) {
// Create a filter function based on the include and exclude options
const filter = createFilter(include, exclude);
// Promisify the readFile function
const promisifiedReadFile = node_util.promisify(readFile);
return {
name: 'sourcemaps',
load: async function(id) {
let code;
// If the id does not pass the filter, return null
if (!filter(id)) {
return null;
}
try {
// Try to read the file with the given id
code = (await promisifiedReadFile(id)).toString();
// Add the file to the watch list
this.addWatchFile(id);
} catch {
try {
// If reading fails, try again without a query suffix that some plugins use
const cleanId = id.replace(/\?.*$/, '');
code = (await promisifiedReadFile(cleanId)).toString();
// Add the file to the watch list
this.addWatchFile(cleanId);
} catch {
// If reading still fails, warn and return null
this.warn('Failed reading file');
return null;
}
}
let map;
try {
// Try to resolve the source map for the code
const result = await sourceMapResolve_js.resolveSourceMap(code, id, promisifiedReadFile);
// If the code contained no sourceMappingURL, return the code
if (result === null) {
return code;
}
// If the source map was resolved, assign it to map
map = result.map;
} catch {
// If resolving the source map fails, warn and return the code
this.warn('Failed resolving source map');
return code;
}
// If the sources are not included in the map, try to resolve them
if (map.sourcesContent === undefined) {
try {
const { sourcesContent } = await sourceMapResolve_js.resolveSources(map, id, promisifiedReadFile);
// If all sources are strings, assign them to map.sourcesContent
if (sourcesContent.every((item)=>typeof item === 'string')) {
map.sourcesContent = sourcesContent;
}
} catch {
// If resolving the sources fails, warn
this.warn('Failed resolving sources for source map');
}
}
// Return the code and the map
return {
code,
map
};
}
};
}
module.exports = sourcemaps;
//# sourceMappingURL=index.cjs.map
;