diff --git a/src/Chunk.ts b/src/Chunk.ts index 5ed196b..9f8ec6d 100644 --- a/src/Chunk.ts +++ b/src/Chunk.ts @@ -164,11 +164,14 @@ export default class Chunk { if (trimmed.length) { if (trimmed !== this.content) { - this.split(this.start + trimmed.length).edit('', undefined, true) if (this.edited) { - // save the change, if it has been edited + // the content of an edited chunk no longer lines up with its range in the + // original string, so there is no index to split at - trim it in place this.edit(trimmed, this.storeName, true) } + else { + this.split(this.start + trimmed.length).edit('', undefined, true) + } } return true } @@ -190,12 +193,15 @@ export default class Chunk { if (trimmed.length) { if (trimmed !== this.content) { - const newChunk = this.split(this.end - trimmed.length) if (this.edited) { - // save the change, if it has been edited - newChunk.edit(trimmed, this.storeName, true) + // the content of an edited chunk no longer lines up with its range in the + // original string, so there is no index to split at - trim it in place + this.edit(trimmed, this.storeName, true) + } + else { + this.split(this.end - trimmed.length) + this.edit('', undefined, true) } - this.edit('', undefined, true) } return true } diff --git a/test/MagicString.test.ts b/test/MagicString.test.ts index fdf0a78..9cd4e85 100644 --- a/test/MagicString.test.ts +++ b/test/MagicString.test.ts @@ -1675,6 +1675,31 @@ describe('magicString', () => { assert.equal(s.toString(), 'abcd') }) + it('should trim a replacement that is longer than the range it replaces', () => { + const s = new MagicString('ab') + s.overwrite(0, 1, ' xyz') + s.trimStart() + + assert.equal(s.toString(), 'xyzb') + + for (const line of s.generateDecodedMap({ source: 'in.js' }).mappings) { + for (const segment of line) { + if (segment.length > 1) { + assert.ok(segment[1]! >= 0 && segment[2]! >= 0 && segment[3]! >= 0, `segment ${JSON.stringify(segment)} points outside the original`) + } + } + } + }) + + it('should trim the end of a replacement that is longer than the range it replaces', () => { + const s = new MagicString('ab') + s.overwrite(1, 2, 'xyz ') + s.trimEnd() + + assert.equal(s.toString(), 'axyz') + assert.equal(s.slice(0, 2), 'axyz') + }) + it('should trim original content before replaced content', () => { const s = new MagicString('abc def')