Skip to content

Instantly share code, notes, and snippets.

@craftamap
Created May 13, 2024 15:18
Show Gist options
  • Save craftamap/f98e0d58c425c26dca7282874640c92f to your computer and use it in GitHub Desktop.
Save craftamap/f98e0d58c425c26dca7282874640c92f to your computer and use it in GitHub Desktop.
import * as fsPromises from 'node:fs/promises'
import * as fs from 'node:fs'
import * as path from 'path'
import { SourceMapConsumer } from 'source-map'
import * as archiver from 'archiver'
async function readHarFile(fileName) {
const harFileContent = await fsPromises.readFile(fileName, 'utf8')
const harFile = JSON.parse(harFileContent)
return harFile
}
const harFile = await readHarFile(process.argv[2])
let filesWithSourceMap = harFile.log.entries
.filter(entry => entry.response.content.text?.includes('//# sourceMappingURL='));
const output = fs.createWriteStream('/tmp/output.zip');
const archive = archiver.default('zip')
archive.pipe(output)
const knownFiles = new Set();
for (const entryIdx in filesWithSourceMap) {
const entry = filesWithSourceMap[entryIdx]
console.log(entryIdx, '/', filesWithSourceMap.length)
// create a file to stream archive data to.
const originalUrl = entry.request.url;
const sourceMapPath = entry.response.content.text.split('//# sourceMappingURL=').at(-1);
const u = new URL(originalUrl)
u.pathname = path.resolve(u.pathname, '../' + sourceMapPath)
console.log('fetching', u)
const response = await fetch(u)
const text = await response.text()
const result = await SourceMapConsumer.with(text, null, async function (consumer) {
return consumer.sources
.filter(source => !source.startsWith('/node_modules'))
.map(source => {
return [source, consumer.sourceContentFor(source)]
})
})
result.forEach(([path, content]) => {
if (knownFiles.has(path)) {
console.log('I already have seen', path)
}
knownFiles.add(path)
try {
// it can be undefined?
if (content) {
archive.append(content, { name: path })
} else {
console.error('warning: content is undefined for path', path)
}
} catch (e) {
console.error('error', e)
}
})
}
await archive.finalize()
{
"name": "har-to-sourcemap",
"packageManager": "yarn@4.2.2",
"private": true,
"dependencies": {
"archiver": "7.0.1",
"source-map": "0.7.4"
},
"devDependencies": {
"@types/archiver": "6.0.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment