From 5b97cfa20aba135d576f4dd40dfd50f1e3482b1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Volf?= Date: Sun, 17 Oct 2021 15:25:55 +0200 Subject: [PATCH 1/2] Add test for error --- test/MagicString.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) 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'); From 49e1bb62c047003692b19721c01fa09933a8a7be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Volf?= Date: Sun, 17 Oct 2021 15:31:17 +0200 Subject: [PATCH 2/2] Fix overwrite across split + moved content Covered by test case in previous commit. --- src/MagicString.js | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/src/MagicString.js b/src/MagicString.js index 14f5cb2..d20ed3f 100644 --- a/src/MagicString.js +++ b/src/MagicString.js @@ -362,21 +362,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);