Tools for reading and editing source mapped files
npm install --save toptensoftware/mapped-source
Load a file
let ms = MappedSource.fromFile("file.js");filename- name of the loaded filecode- content of the filelineMap- a line mapping of offet to line/column position - see heresourceMap- source map consume - see herefromOffset- given a file offset returns the original position (if mapped by source map file, otherwise position in this file).
// File name
let filename = ms.filename;
// Code
let code = ms.code;
// LineMapping
let offset = ms.lineMap.toOffset({line: 10, column: 20});
let pos = ms.lineMap.fromOffset(1000);
// Returns source:null, line: null, column: null if not mapped
let originalPos = ms.sourceMap.originalPositionFor({line: 10, column: 20});
// Returns position in this file if not mapped
let originalPos = ms.originalPositionFor({line: 10, column: 20});
let originalPos = ms.fromOffset(1000);To edit a source mapped file, first load it as described above
then call createEditable() to get an EditableMappedSource
let ems = MappedSource.fromFile("test.js").createEditable();EditableMappedSource supports:
code- the current code contentsubstring(start, end)- returns a newEditableMappedSourcewith a subsection of the original string and cropped mapped pointssplice(offset, length, str)- replaceslengthcharacters atoffsetwithstr.insert(offset, str)- insertsstratoffset.delete(offset, length)- deleteslengthcharacters atoffset.append(str)- appendsstr.createSourceMap()- create a JSON serializable source map objectsave(filename)- saves the file and updated source map
All edit operations update both the original code string and any affected mapped points.
Note that splice, insert and append can accept either a string
or another EditableMappedSource as the string content parameter. If
another EditableMappedSource is used, the source map is updated to
include the new mapped points.