From 8bd0c3afe913f692bee0eded423d379178848a5d Mon Sep 17 00:00:00 2001 From: Fran Nunez Rivera Date: Fri, 1 Nov 2019 16:14:16 +0100 Subject: [PATCH] Expose target when creating a proxy (wrap) to make comlink compatible with proxy-polyfill --- src/comlink.ts | 9 +++++---- tests/same_window.comlink.test.js | 6 ++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/comlink.ts b/src/comlink.ts index 8ef09856..97f00da8 100644 --- a/src/comlink.ts +++ b/src/comlink.ts @@ -178,8 +178,8 @@ function closeEndPoint(endpoint: Endpoint) { if (isMessagePort(endpoint)) endpoint.close(); } -export function wrap(ep: Endpoint): Remote { - return createProxy(ep) as any; +export function wrap(ep: Endpoint, target?: any): Remote { + return createProxy(ep, [], target) as any; } function throwIfProxyReleased(isReleased: boolean) { @@ -190,10 +190,11 @@ function throwIfProxyReleased(isReleased: boolean) { function createProxy( ep: Endpoint, - path: (string | number | symbol)[] = [] + path: (string | number | symbol)[] = [], + target: object = function() {} ): Remote { let isProxyReleased = false; - const proxy = new Proxy(function() {}, { + const proxy = new Proxy(target, { get(_target, prop) { throwIfProxyReleased(isProxyReleased); if (prop === releaseProxy) { diff --git a/tests/same_window.comlink.test.js b/tests/same_window.comlink.test.js index 6cd50e1f..ff4ea027 100644 --- a/tests/same_window.comlink.test.js +++ b/tests/same_window.comlink.test.js @@ -518,6 +518,12 @@ describe("Comlink in the same realm", function() { await instance[Comlink.releaseProxy](); expect(() => instance.method()).to.throw(); }); + + it('can proxy with a given target', async function() { + const thing = Comlink.wrap(this.port1, { value: {} }); + Comlink.expose({ value: 4 }, this.port2); + expect(await thing.value).to.equal(4); + }); }); function guardedIt(f) {