From 52f47407bab81f7cd8c7a6b11f39376bc935073f Mon Sep 17 00:00:00 2001 From: Rich-Harris Date: Sun, 10 Apr 2016 23:47:33 -0400 Subject: [PATCH] split unedited chunks when trimming, to ensure correct sourcemaps (#53) --- src/MagicString.js | 37 +++++++++++++++++++++---------------- test/index.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 16 deletions(-) diff --git a/src/MagicString.js b/src/MagicString.js index c9913b9..d12f6b0 100644 --- a/src/MagicString.js +++ b/src/MagicString.js @@ -354,18 +354,19 @@ MagicString.prototype = { do { let lastChunk = this.chunks[ this.chunks.length - 1 ]; - if ( rx.test( lastChunk.content ) ) { - lastChunk.edit( lastChunk.content.replace( rx, '' ) ); - } - if ( lastChunk.content.length || this.chunks.length === 1 ) { - break; + const match = rx.exec( lastChunk.content ); + if ( !match ) return this; + + if ( lastChunk.edited ) { + lastChunk.edit( lastChunk.content.slice( 0, match.index ) ); } else { - this.chunks.pop(); + lastChunk.split( match.index + lastChunk.start ); // generated chunk is discarded } - } while ( true ); - return this; + if ( match.index > 0 || this.chunks.length === 1 ) return this; + this.chunks.pop(); + } while ( true ); }, trimStart ( charType ) { @@ -376,17 +377,21 @@ MagicString.prototype = { do { let firstChunk = this.chunks[0]; - if ( rx.test( firstChunk.content ) ) { - firstChunk.edit( firstChunk.content.replace( rx, '' ) ); - } - if ( firstChunk.content.length || this.chunks.length === 1 ) { - break; + const match = rx.exec( firstChunk.content ); + if ( !match ) return this; + + const end = match.index + match[0].length; + + if ( firstChunk.edited ) { + firstChunk.edit( firstChunk.content.slice( match.index ) ); } else { - this.chunks.shift(); + const newChunk = firstChunk.split( end + firstChunk.start ); // existing chunk is discarded + this.chunks[0] = newChunk; } - } while ( true ); - return this; + if ( end < firstChunk.content.length || this.chunks.length === 1 ) return this; + this.chunks.shift(); + } while ( true ); } }; diff --git a/test/index.js b/test/index.js index 945dcd8..4161383 100644 --- a/test/index.js +++ b/test/index.js @@ -260,6 +260,34 @@ describe( 'MagicString', function () { assert.equal( loc.column, i ); }); }); + + it.only( 'generates a map with trimmed content (#53)', function () { + var s = new MagicString( 'abcdefghijkl ' ).trim(); + var map = s.generateMap({ + file: 'output', + source: 'input', + includeContent: true, + hires: true + }); + + var smc = new SourceMapConsumer( map ); + var loc = smc.originalPositionFor({ line: 1, column: 11 }); + + assert.equal( loc.column, 11 ); + + s = new MagicString( ' abcdefghijkl' ).trim(); + map = s.generateMap({ + file: 'output', + source: 'input', + includeContent: true, + hires: true + }); + + smc = new SourceMapConsumer( map ); + loc = smc.originalPositionFor({ line: 1, column: 1 }); + + assert.equal( loc.column, 2 ); + }); }); describe( 'getIndentString', function () {