Skip to content

Commit 5c0498b

Browse files
committed
fix: chainable should return the proxy function instead
1 parent a7d5693 commit 5c0498b

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/index.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,19 +25,28 @@ export default class MagicStringStack implements MagicString {
2525
this._stack.unshift(this._current)
2626

2727
// We proxy every function to `this._current` so we can swap it out
28-
return new Proxy(new MagicString(''), {
28+
const proxy = new Proxy(new MagicString(''), {
2929
get: (_, p, receiver) => {
3030
if (Reflect.has(this, p))
3131
return Reflect.get(this, p, receiver)
32-
let parent = Reflect.get(this._current, p, receiver)
33-
if (typeof parent === 'function')
34-
parent = parent.bind(this._current)
32+
const parent = Reflect.get(this._current, p, receiver)
33+
if (typeof parent === 'function') {
34+
return (...args: any) => {
35+
const result = parent.apply(this._current, args)
36+
// If the function returns the current instance (chainable), we return the proxy instead
37+
if (result === this._current)
38+
return proxy
39+
return result
40+
}
41+
}
3542
return parent
3643
},
3744
set: (_, p, value) => {
3845
return Reflect.set(this, p, value, this)
3946
},
4047
}) as any
48+
49+
return proxy
4150
}
4251

4352
/**

test/index.test.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,12 @@ it('should support clone', () => {
8888
expect(s2.toString()).toBe('goodbye there')
8989
})
9090

91+
it('chainable should return the proxied version', () => {
92+
const s = new MagicStringStack('hello world')
93+
const s2 = s.update(0, 5, 'goodbye')
94+
expect(s2).toBe(s)
95+
})
96+
9197
function removeEmptyKeys(obj: any) {
9298
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => !(v == null || (Array.isArray(v) && !v.length))))
9399
}

0 commit comments

Comments
 (0)