| 37 | * as a source map. |
| 38 | **/ |
| 39 | export function encodeSourceMap(textMap: string[], sourceRoot?: string): SDK.SourceMap.SourceMapV3Object { |
| 40 | let mappings = ''; |
| 41 | const sources: string[] = []; |
| 42 | const names: string[] = []; |
| 43 | let sourcesContent: Array<null|string>|undefined; |
| 44 | |
| 45 | const state = { |
| 46 | line: -1, |
| 47 | column: 0, |
| 48 | srcFile: 0, |
| 49 | srcLine: 0, |
| 50 | srcColumn: 0, |
| 51 | srcName: 0, |
| 52 | }; |
| 53 | |
| 54 | for (const mapping of textMap) { |
| 55 | let match = mapping.match(/^(\d+):(\d+)(?:\s*=>\s*([^:]+):(\d+):(\d+)(?:@(\S+))?)?$/); |
| 56 | if (!match) { |
| 57 | match = mapping.match(/^([^:]+):\s*(.+)$/); |
| 58 | if (!match) { |
| 59 | throw new Error(`Cannot parse mapping "${mapping}"`); |
| 60 | } |
| 61 | (sourcesContent = sourcesContent ?? [])[getOrAddString(sources, match[1])] = match[2]; |
| 62 | continue; |
| 63 | } |
| 64 | |
| 65 | const lastState = Object.assign({}, state); |
| 66 | state.line = Number(match[1]); |
| 67 | state.column = Number(match[2]); |
| 68 | const hasSource = match[3] !== undefined; |
| 69 | const hasName = hasSource && (match[6] !== undefined); |
| 70 | if (hasSource) { |
| 71 | state.srcFile = getOrAddString(sources, match[3]); |
| 72 | state.srcLine = Number(match[4]); |
| 73 | state.srcColumn = Number(match[5]); |
| 74 | if (hasName) { |
| 75 | state.srcName = getOrAddString(names, match[6]); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | if (state.line < lastState.line) { |
| 80 | throw new Error('Line numbers must be increasing'); |
| 81 | } |
| 82 | |
| 83 | const isNewLine = state.line !== lastState.line; |
| 84 | |
| 85 | if (isNewLine) { |
| 86 | // Fixup for the first line mapping. |
| 87 | if (lastState.line === -1) { |
| 88 | lastState.line = 0; |
| 89 | } |
| 90 | // Insert semicolons for all the new lines. |
| 91 | mappings += ';'.repeat(state.line - lastState.line); |
| 92 | // Reset the compiled code column counter. |
| 93 | lastState.column = 0; |
| 94 | } else { |
| 95 | mappings += ','; |
| 96 | } |