Skip to content

Commit 26bf1b9

Browse files
committed
feat: support rollback, fix #1
1 parent 8773f54 commit 26bf1b9

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

src/index.ts

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
1+
/* eslint-disable ts/no-unsafe-declaration-merging */
12
import type { DecodedSourceMap, MagicStringOptions, SourceMap, SourceMapOptions } from 'magic-string'
23
import MagicString from 'magic-string'
34
import remapping from '@ampproject/remapping'
45

56
// Thanks to @sxzz & @starknt for the solution
6-
// eslint-disable-next-line ts/no-unsafe-declaration-merging
77
export default interface MagicStringStack extends MagicString {}
8-
// eslint-disable-next-line ts/no-unsafe-declaration-merging
98
export default class MagicStringStack implements MagicString {
9+
/**
10+
* The stack of MagicString instances.
11+
* Lastest instance is pushed to the front of the array.
12+
*/
1013
private _stack: MagicString[] = []
14+
/**
15+
* Prepresents the current MagicString instance.
16+
* It should be in the this._stack[0]
17+
*/
1118
private _current: MagicString
1219

1320
constructor(
@@ -44,6 +51,16 @@ export default class MagicStringStack implements MagicString {
4451
this._stack.unshift(newOne)
4552
}
4653

54+
/**
55+
* Rollback to the previous commit.
56+
*/
57+
rollback() {
58+
if (this._stack.length <= 1)
59+
throw new Error('Cannot rollback on the first commit')
60+
this._stack.shift()
61+
this._current = this._stack[0]
62+
}
63+
4764
get original() {
4865
return this._current.original
4966
}

test/index.test.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ it('should work', () => {
2323
expect(ss.toString()).toMatchInlineSnapshot(`"answer = 42"`)
2424

2525
ss.commit()
26+
ss.commit() // empty commit
27+
ss.commit() // empty commit
2628

2729
s.prepend('var ').append(';')
2830
ss.prepend('var ').append(';')
@@ -69,11 +71,23 @@ it('replace after replace', () => {
6971
`)
7072
})
7173

72-
it('should be sub instance', () => {
74+
it('should be sub instance of MagicString', () => {
7375
const s = new MagicStringStack('')
7476
expect(s instanceof MagicString).toBe(true)
7577
})
7678

79+
it('should support clone', () => {
80+
const s = new MagicStringStack('hello world')
81+
s.update(0, 5, 'goodbye')
82+
s.commit()
83+
const s2 = s.clone()
84+
expect(s.generateMap()).toEqual(s2.generateMap())
85+
s2.update(8, 13, 'there')
86+
s2.commit()
87+
expect(s.toString()).toBe('goodbye world')
88+
expect(s2.toString()).toBe('goodbye there')
89+
})
90+
7791
function removeEmptyKeys(obj: any) {
7892
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => !(v == null || (Array.isArray(v) && !v.length))))
7993
}

0 commit comments

Comments
 (0)