From 403fa86b3dcc73f6b2eff177218b7bd4d3128f63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Volf?= Date: Wed, 2 Mar 2022 22:37:05 +0100 Subject: [PATCH] fix: allowed overwrite across moved content preceded by split (#192) Co-authored-by: Anthony Fu --- src/MagicString.js | 19 +++++++------------ test/MagicString.js | 17 ++++++++++++++++- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/MagicString.js b/src/MagicString.js index 22ede0f..b5b0ed2 100644 --- a/src/MagicString.js +++ b/src/MagicString.js @@ -372,21 +372,16 @@ export default class MagicString { const last = this.byEnd[end]; if (first) { - if (end > first.end && first.next !== this.byStart[first.end]) { - throw new Error('Cannot overwrite across a split point'); - } - - first.edit(content, storeName, contentOnly); - - if (first !== last) { - let chunk = first.next; - while (chunk !== last) { - chunk.edit('', false); - chunk = chunk.next; + let chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); } - + chunk = chunk.next; chunk.edit('', false); } + + first.edit(content, storeName, contentOnly); } else { // must be inserting at the end const newChunk = new Chunk(start, end, '').edit(content, storeName); diff --git a/test/MagicString.js b/test/MagicString.js index 3d290a5..83ad2aa 100644 --- a/test/MagicString.js +++ b/test/MagicString.js @@ -824,13 +824,28 @@ describe('MagicString', () => { assert.equal(s.toString(), 'a&^...!?defghijkl'); }); - it('disallows overwriting across moved content', () => { + it('disallows overwriting partially overlapping moved content', () => { const s = new MagicString('abcdefghijkl'); s.move(6, 9, 3); assert.throws(() => s.overwrite(5, 7, 'XX'), /Cannot overwrite across a split point/); }); + it('disallows overwriting fully surrounding content moved away', () => { + const s = new MagicString('abcdefghijkl'); + + s.move(6, 9, 3); + assert.throws(() => s.overwrite(4, 11, 'XX'), /Cannot overwrite across a split point/); + }); + + it('disallows overwriting fully surrounding content moved away even if there is another split', () => { + const s = new MagicString('abcdefghijkl'); + + s.move(6, 9, 3); + s.appendLeft(5, 'foo'); + assert.throws(() => s.overwrite(4, 11, 'XX'), /Cannot overwrite across a split point/); + }); + it('allows later insertions at the end', () => { const s = new MagicString('abcdefg');