Skip to content

Instantly share code, notes, and snippets.

@SanariSan
Last active April 20, 2024 12:31
Show Gist options
  • Save SanariSan/b26fd4bfc1ea0c5ded29f8e3d7c58f58 to your computer and use it in GitHub Desktop.
Save SanariSan/b26fd4bfc1ea0c5ded29f8e3d7c58f58 to your computer and use it in GitHub Desktop.
Extract source from JS sourcemap
/**
* If you have a website source bundled with webpack and are lucky to have a sourcemap nearby,
* then you are able to fully reconstruct original code + folders structure.
* Place this file at the root of project.
* Provide the path to sourcemap + the path to where you'd like to extract original codebase.
*/
const fs = require('fs');
const path = require('path');
const sourceMap = require('source-map');
async function extractAndSaveSource(sourceMapPath, outputDir) {
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
// Read the source map
const rawSourceMap = JSON.parse(fs.readFileSync(sourceMapPath, 'utf8'));
// Use SourceMapConsumer to parse and process the source map
await sourceMap.SourceMapConsumer.with(rawSourceMap, null, (consumer) => {
consumer.sources.forEach((sourcePath) => {
const strippedSourcePath = sourcePath.replace(/^(\.\.[\/\\])+/, '');
const absoluteSourcePath = path.resolve(outputDir, strippedSourcePath);
const absoluteSourcePathDirname = path.dirname(absoluteSourcePath);
// Ensure the directory exists
if (!fs.existsSync(absoluteSourcePathDirname)) {
fs.mkdirSync(absoluteSourcePathDirname, { recursive: true });
}
// Write the original source content to the corresponding file
const content = consumer.sourceContentFor(sourcePath);
fs.writeFileSync(absoluteSourcePath, content, 'utf-8');
console.log(`Saved ${absoluteSourcePath}`);
});
});
}
const sourceMapPath = './static/js/main.13yf95js.js.map';
const outputDirectory = '/home/user/test/extractedSources';
extractAndSaveSource(sourceMapPath, outputDirectory);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment