|
1 | 1 | import { readFile } from 'fs/promises'; |
2 | 2 | import { createHash } from 'node:crypto'; |
3 | 3 | import { access, writeFile } from 'node:fs/promises'; |
| 4 | +import remapping, { SourceMapInput } from '@ampproject/remapping'; |
| 5 | +import path from 'path'; |
4 | 6 |
|
| 7 | +type FileName = string; |
| 8 | +type SourceMapLookup = Record<FileName, SourceMapInput>; |
| 9 | + |
| 10 | +export function chainSourceMaps(finalMap: SourceMapInput, sourceMapLookup: SourceMapLookup) { |
| 11 | + return remapping(finalMap, (source) => { |
| 12 | + const sourceMap = sourceMapLookup[source]; |
| 13 | + if (sourceMap) { |
| 14 | + return sourceMap; |
| 15 | + } |
| 16 | + // If not the source, we do not want to traverse it further so we return null. |
| 17 | + // This is because sometimes npm packages have their own source maps but do |
| 18 | + // not have the original source files. |
| 19 | + return null; |
| 20 | + }); |
| 21 | +} |
5 | 22 |
|
6 | | -// Function to calculate file checksum |
7 | 23 | export async function calculateChecksum(content: string | Buffer) { |
8 | 24 | try { |
9 | 25 | const hash = createHash('sha256'); |
@@ -58,3 +74,35 @@ export async function saveBuildData( |
58 | 74 | throw error; |
59 | 75 | } |
60 | 76 | } |
| 77 | + |
| 78 | +export async function getSourceMapFromFile(filePath: string): Promise<SourceMapInput | null> { |
| 79 | + try { |
| 80 | + const content = await readFile(filePath, 'utf8'); |
| 81 | + |
| 82 | + // Look for the sourceMappingURL comment |
| 83 | + const sourceMapRegex = /\/\/[#@]\s*sourceMappingURL=(.+)$/m; |
| 84 | + const match = content.match(sourceMapRegex); |
| 85 | + |
| 86 | + if (!match) return null; |
| 87 | + |
| 88 | + const sourceMapUrl = match[1].trim(); |
| 89 | + |
| 90 | + if (sourceMapUrl.startsWith('data:application/json;base64,')) { |
| 91 | + // Inline base64-encoded source map |
| 92 | + const base64 = sourceMapUrl.slice('data:application/json;base64,'.length); |
| 93 | + const rawMap = Buffer.from(base64, 'base64').toString('utf8'); |
| 94 | + return JSON.parse(rawMap); |
| 95 | + } else { |
| 96 | + // External .map file |
| 97 | + const mapPath = path.resolve(path.dirname(filePath), sourceMapUrl); |
| 98 | + try { |
| 99 | + const rawMap = await readFile(mapPath, 'utf8'); |
| 100 | + return JSON.parse(rawMap); |
| 101 | + } catch (e) { |
| 102 | + return null; // map file not found or invalid |
| 103 | + } |
| 104 | + } |
| 105 | + } catch (err) { |
| 106 | + return null; // file doesn't exist or can't be read |
| 107 | + } |
| 108 | +} |
0 commit comments