Repository: GoogleChromeLabs/comlink Branch: main Commit: 114a4a6448a8 Files: 57 Total size: 114.5 KB Directory structure: gitextract_piinu2uq/ ├── .gitignore ├── .husky/ │ └── pre-commit ├── .travis.yml ├── CHANGELOG.md ├── CODEOWNERS ├── CONTRIBUTING ├── CONTRIBUTORS ├── Dockerfile ├── LICENSE ├── README.md ├── docs/ │ ├── examples/ │ │ ├── 01-simple-example/ │ │ │ ├── README.md │ │ │ ├── index.html │ │ │ └── worker.js │ │ ├── 02-callback-example/ │ │ │ ├── README.md │ │ │ ├── index.html │ │ │ └── worker.js │ │ ├── 03-classes-example/ │ │ │ ├── README.md │ │ │ ├── index.html │ │ │ └── worker.js │ │ ├── 04-eventlistener-example/ │ │ │ ├── README.md │ │ │ ├── event.transferhandler.js │ │ │ ├── index.html │ │ │ └── worker.js │ │ ├── 05-serviceworker-example/ │ │ │ ├── README.md │ │ │ ├── index.html │ │ │ └── worker.js │ │ ├── 06-node-example/ │ │ │ ├── main.mjs │ │ │ └── worker.mjs │ │ ├── 07-sharedworker-example/ │ │ │ ├── README.md │ │ │ ├── index.html │ │ │ └── worker.js │ │ └── 99-nonworker-examples/ │ │ └── iframes/ │ │ ├── README.md │ │ ├── iframe.html │ │ └── index.html │ └── index.html ├── karma.conf.js ├── package.json ├── renovate.json ├── rollup.config.mjs ├── src/ │ ├── comlink.ts │ ├── node-adapter.ts │ └── protocol.ts ├── structured-clone-table.md ├── tests/ │ ├── cross-origin.comlink.test.js │ ├── fixtures/ │ │ ├── attack-iframe.html │ │ ├── iframe.html │ │ ├── two-way-iframe.html │ │ └── worker.js │ ├── iframe.comlink.test.js │ ├── node/ │ │ ├── main.mjs │ │ └── worker.mjs │ ├── same_window.comlink.test.js │ ├── tsconfig.json │ ├── two-way-iframe.comlink.test.js │ ├── type-checks.ts │ └── worker.comlink.test.js └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.pem *.swp node_modules *.bak dist .*_cache* package-lock.json ================================================ FILE: .husky/pre-commit ================================================ #!/usr/bin/env sh . "$(dirname -- "$0")/_/husky.sh" npm test ================================================ FILE: .travis.yml ================================================ sudo: required services: - docker script: - docker build -t comlink . - docker run --rm -v `pwd`:/usr/src comlink ================================================ FILE: CHANGELOG.md ================================================ # v3 -> v4 - Added support for NodeJS 11+ workers - `Comlink.proxy()` is now called `Comlink.wrap()` - `Comlink.proxyValue()` is now called `Comlink.proxy()` - Transferable values are _not_ transferred by default anymore. They need to be wrapped with `Comlink.transfer()` - Rewrote TypeScript types - New folder structure in the GitHub repo and in the npm module ================================================ FILE: CODEOWNERS ================================================ @surma ================================================ FILE: CONTRIBUTING ================================================ Want to contribute? Great! First, read this page (including the small print at the end). ### Before you contribute Before we can use your code, you must sign the [Google Individual Contributor License Agreement] (https://cla.developers.google.com/about/google-individual) (CLA), which you can do online. The CLA is necessary mainly because you own the copyright to your changes, even after your contribution becomes part of our codebase, so we need your permission to use and distribute your code. We also need to be sure of various other things—for instance that you'll tell us if you know that your code infringes on other people's patents. You don't have to sign the CLA until after you've submitted your code for review and a member has approved it, but you must do it before we can put your code into our codebase. Before you start working on a larger contribution, you should get in touch with us first through the issue tracker with your idea so that we can help out and possibly guide you. Coordinating up front makes it much easier to avoid frustration later on. ### Code reviews All submissions, including submissions by project members, require review. We use Github pull requests for this purpose. ### The small print Contributions made by corporations are covered by a different agreement than the one above, the [Software Grant and Corporate Contributor License Agreement] (https://cla.developers.google.com/about/google-corporate). ================================================ FILE: CONTRIBUTORS ================================================ # People who have agreed to one of the CLAs and can contribute patches. # The AUTHORS file lists the copyright holders; this file # lists people. For example, Google employees are listed here # but not in AUTHORS, because Google holds the copyright. # # https://developers.google.com/open-source/cla/individual # https://developers.google.com/open-source/cla/corporate # # Names should be added to this file as: # Name Surma ================================================ FILE: Dockerfile ================================================ FROM selenium/node-chrome:latest@sha256:31be7ba7ebe6db9f9b266c10fc5f6fce7568791a6ade91b6b6d20a29a988ef5b USER root RUN apt-get update -qqy \ && rm -rf /var/lib/apt/lists/* /var/cache/apt/* \ && rm /bin/sh && ln -s /bin/bash /bin/sh \ && chown seluser /usr/local ENV NVM_DIR /usr/local/nvm RUN wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash \ && source $NVM_DIR/nvm.sh \ && nvm install v11 ENV CHROME_BIN /opt/google/chrome/chrome ENV INSIDE_DOCKER=1 WORKDIR /usr/src ENTRYPOINT source $NVM_DIR/nvm.sh && npm i && npm test ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Comlink Comlink makes [WebWorkers][webworker] enjoyable. Comlink is a **tiny library (1.1kB)**, that removes the mental barrier of thinking about `postMessage` and hides the fact that you are working with workers. At a more abstract level it is an RPC implementation for `postMessage` and [ES6 Proxies][es6 proxy]. ``` $ npm install --save comlink ``` ![Comlink in action](https://user-images.githubusercontent.com/234957/54164510-cdab2d80-4454-11e9-92d0-7356aa6c5746.png) ## Browsers support & bundle size ![Chrome 56+](https://img.shields.io/badge/Chrome-56+-green.svg?style=flat-square) ![Edge 15+](https://img.shields.io/badge/Edge-15+-green.svg?style=flat-square) ![Firefox 52+](https://img.shields.io/badge/Firefox-52+-green.svg?style=flat-square) ![Opera 43+](https://img.shields.io/badge/Opera-43+-green.svg?style=flat-square) ![Safari 10.1+](https://img.shields.io/badge/Safari-10.1+-green.svg?style=flat-square) ![Samsung Internet 6.0+](https://img.shields.io/badge/Samsung_Internet-6.0+-green.svg?style=flat-square) Browsers without [ES6 Proxy] support can use the [proxy-polyfill]. **Size**: ~2.5k, ~1.2k gzip’d, ~1.1k brotli’d ## Introduction On mobile phones, and especially on low-end mobile phones, it is important to keep the main thread as idle as possible so it can respond to user interactions quickly and provide a jank-free experience. **The UI thread ought to be for UI work only**. WebWorkers are a web API that allow you to run code in a separate thread. To communicate with another thread, WebWorkers offer the `postMessage` API. You can send JavaScript objects as messages using `myWorker.postMessage(someObject)`, triggering a `message` event inside the worker. Comlink turns this messaged-based API into a something more developer-friendly by providing an RPC implementation: Values from one thread can be used within the other thread (and vice versa) just like local values. ## Examples ### [Running a simple function](./docs/examples/01-simple-example) **main.js** ```javascript import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs"; async function init() { const worker = new Worker("worker.js"); // WebWorkers use `postMessage` and therefore work with Comlink. const obj = Comlink.wrap(worker); alert(`Counter: ${await obj.counter}`); await obj.inc(); alert(`Counter: ${await obj.counter}`); } init(); ``` **worker.js** ```javascript importScripts("https://unpkg.com/comlink/dist/umd/comlink.js"); // importScripts("../../../dist/umd/comlink.js"); const obj = { counter: 0, inc() { this.counter++; }, }; Comlink.expose(obj); ``` ### [Callbacks](./docs/examples/02-callback-example) **main.js** ```javascript import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs"; // import * as Comlink from "../../../dist/esm/comlink.mjs"; function callback(value) { alert(`Result: ${value}`); } async function init() { const remoteFunction = Comlink.wrap(new Worker("worker.js")); await remoteFunction(Comlink.proxy(callback)); } init(); ``` **worker.js** ```javascript importScripts("https://unpkg.com/comlink/dist/umd/comlink.js"); // importScripts("../../../dist/umd/comlink.js"); async function remoteFunction(cb) { await cb("A string from a worker"); } Comlink.expose(remoteFunction); ``` ### [`SharedWorker`](./docs/examples/07-sharedworker-example) When using Comlink with a [`SharedWorker`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker) you have to: 1. Use the [`port`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker/port) property, of the `SharedWorker` instance, when calling `Comlink.wrap`. 2. Call `Comlink.expose` within the [`onconnect`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorkerGlobalScope/onconnect) callback of the shared worker. **Pro tip:** You can access DevTools for any shared worker currently running in Chrome by going to: **chrome://inspect/#workers** **main.js** ```javascript import * as Comlink from "https://unpkg.com/comlink/dist/esm/comlink.mjs"; async function init() { const worker = new SharedWorker("worker.js"); /** * SharedWorkers communicate via the `postMessage` function in their `port` property. * Therefore you must use the SharedWorker's `port` property when calling `Comlink.wrap`. */ const obj = Comlink.wrap(worker.port); alert(`Counter: ${await obj.counter}`); await obj.inc(); alert(`Counter: ${await obj.counter}`); } init(); ``` **worker.js** ```javascript importScripts("https://unpkg.com/comlink/dist/umd/comlink.js"); // importScripts("../../../dist/umd/comlink.js"); const obj = { counter: 0, inc() { this.counter++; }, }; /** * When a connection is made into this shared worker, expose `obj` * via the connection `port`. */ onconnect = function (event) { const port = event.ports[0]; Comlink.expose(obj, port); }; // Single line alternative: // onconnect = (e) => Comlink.expose(obj, e.ports[0]); ``` **For additional examples, please see the [docs/examples](./docs/examples) directory in the project.** ## API ### `Comlink.wrap(endpoint)` and `Comlink.expose(value, endpoint?, allowedOrigins?)` Comlink’s goal is to make _exposed_ values from one thread available in the other. `expose` exposes `value` on `endpoint`, where `endpoint` is a [`postMessage`-like interface][endpoint] and `allowedOrigins` is an array of RegExp or strings defining which origins should be allowed access (defaults to special case of `['*']` for all origins). `wrap` wraps the _other_ end of the message channel and returns a proxy. The proxy will have all properties and functions of the exposed value, but access and invocations are inherently asynchronous. This means that a function that returns a number will now return _a promise_ for a number. **As a rule of thumb: If you are using the proxy, put `await` in front of it.** Exceptions will be caught and re-thrown on the other side. ### `Comlink.transfer(value, transferables)` and `Comlink.proxy(value)` By default, every function parameter, return value and object property value is copied, in the sense of [structured cloning]. Structured cloning can be thought of as deep copying, but has some limitations. See [this table][structured clone table] for details. If you want a value to be transferred rather than copied — provided the value is or contains a [`Transferable`][transferable] — you can wrap the value in a `transfer()` call and provide a list of transferable values: ```js const data = new Uint8Array([1, 2, 3, 4, 5]); await myProxy.someFunction(Comlink.transfer(data, [data.buffer])); ``` Lastly, you can use `Comlink.proxy(value)`. When using this Comlink will neither copy nor transfer the value, but instead send a proxy. Both threads now work on the same value. This is useful for callbacks, for example, as functions are neither structured cloneable nor transferable. ```js myProxy.onready = Comlink.proxy((data) => { /* ... */ }); ``` ### Transfer handlers and event listeners It is common that you want to use Comlink to add an event listener, where the event source is on another thread: ```js button.addEventListener("click", myProxy.onClick.bind(myProxy)); ``` While this won’t throw immediately, `onClick` will never actually be called. This is because [`Event`][event] is neither structured cloneable nor transferable. As a workaround, Comlink offers transfer handlers. Each function parameter and return value is given to _all_ registered transfer handlers. If one of the event handler signals that it can process the value by returning `true` from `canHandle()`, it is now responsible for serializing the value to structured cloneable data and for deserializing the value. A transfer handler has be set up on _both sides_ of the message channel. Here’s an example transfer handler for events: ```js Comlink.transferHandlers.set("EVENT", { canHandle: (obj) => obj instanceof Event, serialize: (ev) => { return [ { target: { id: ev.target.id, classList: [...ev.target.classList], }, }, [], ]; }, deserialize: (obj) => obj, }); ``` Note that this particular transfer handler won’t create an actual `Event`, but just an object that has the `event.target.id` and `event.target.classList` property. Often, this is enough. If not, the transfer handler can be easily augmented to provide all necessary data. ### `Comlink.releaseProxy` Every proxy created by Comlink has the `[releaseProxy]()` method. Calling it will detach the proxy and the exposed object from the message channel, allowing both ends to be garbage collected. ```js const proxy = Comlink.wrap(port); // ... use the proxy ... proxy[Comlink.releaseProxy](); ``` If the browser supports the [WeakRef proposal], `[releaseProxy]()` will be called automatically when the proxy created by `wrap()` gets garbage collected. ### `Comlink.finalizer` If an exposed object has a property `[Comlink.finalizer]`, the property will be invoked as a function when the proxy is being released. This can happen either through a manual invocation of `[releaseProxy]()` or automatically during garbage collection if the runtime supports the [WeakRef proposal] (see `Comlink.releaseProxy` above). Note that when the finalizer function is invoked, the endpoint is closed and no more communication can happen. ### `Comlink.createEndpoint` Every proxy created by Comlink has the `[createEndpoint]()` method. Calling it will return a new `MessagePort`, that has been hooked up to the same object as the proxy that `[createEndpoint]()` has been called on. ```js const port = myProxy[Comlink.createEndpoint](); const newProxy = Comlink.wrap(port); ``` ### `Comlink.windowEndpoint(window, context = self, targetOrigin = "*")` Windows and Web Workers have a slightly different variants of `postMessage`. If you want to use Comlink to communicate with an iframe or another window, you need to wrap it with `windowEndpoint()`. `window` is the window that should be communicate with. `context` is the `EventTarget` on which messages _from_ the `window` can be received (often `self`). `targetOrigin` is passed through to `postMessage` and allows to filter messages by origin. For details, see the documentation for [`Window.postMessage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage). For a usage example, take a look at the non-worker examples in the `docs` folder. ## TypeScript Comlink does provide TypeScript types. When you `expose()` something of type `T`, the corresponding `wrap()` call will return something of type `Comlink.Remote`. While this type has been battle-tested over some time now, it is implemented on a best-effort basis. There are some nuances that are incredibly hard if not impossible to encode correctly in TypeScript’s type system. It _may_ sometimes be necessary to force a certain type using `as unknown as `. ## Node Comlink works with Node’s [`worker_threads`][worker_threads] module. Take a look at the example in the `docs` folder. [webworker]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API [umd]: https://github.com/umdjs/umd [transferable]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects [messageport]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort [examples]: https://github.com/GoogleChromeLabs/comlink/tree/master/docs/examples [dist]: https://github.com/GoogleChromeLabs/comlink/tree/master/dist [delivrjs]: https://cdn.jsdelivr.net/ [es6 proxy]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy [proxy-polyfill]: https://github.com/GoogleChrome/proxy-polyfill [endpoint]: src/protocol.ts [structured cloning]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [structured clone table]: structured-clone-table.md [event]: https://developer.mozilla.org/en-US/docs/Web/API/Event [worker_threads]: https://nodejs.org/api/worker_threads.html [weakref proposal]: https://github.com/tc39/proposal-weakrefs ## Additional Resources - [Simplify Web Worker code with Comlink](https://davidea.st/articles/comlink-simple-web-worker) --- License Apache-2.0 ================================================ FILE: docs/examples/01-simple-example/README.md ================================================ This example shows how to setup Comlink between a website and a worker. ================================================ FILE: docs/examples/01-simple-example/index.html ================================================ ================================================ FILE: docs/examples/01-simple-example/worker.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ importScripts("https://unpkg.com/comlink/dist/umd/comlink.js"); // importScripts("../../../dist/umd/comlink.js"); const obj = { counter: 0, inc() { this.counter++; }, }; Comlink.expose(obj); ================================================ FILE: docs/examples/02-callback-example/README.md ================================================ This example shows how to pass callbacks. ================================================ FILE: docs/examples/02-callback-example/index.html ================================================ ================================================ FILE: docs/examples/02-callback-example/worker.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ importScripts("https://unpkg.com/comlink/dist/umd/comlink.js"); // importScripts("../../../dist/umd/comlink.js"); async function remoteFunction(cb) { await cb("A string from a worker"); } Comlink.expose(remoteFunction); ================================================ FILE: docs/examples/03-classes-example/README.md ================================================ This example shows how to export and use classes. ================================================ FILE: docs/examples/03-classes-example/index.html ================================================ ================================================ FILE: docs/examples/03-classes-example/worker.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ importScripts("https://unpkg.com/comlink/dist/umd/comlink.js"); // importScripts("../../../dist/umd/comlink.js"); class MyClass { constructor(init = 0) { console.log(init); this._counter = init; } get counter() { return this._counter; } increment(delta = 1) { this._counter += delta; } } Comlink.expose(MyClass); ================================================ FILE: docs/examples/04-eventlistener-example/README.md ================================================ This example shows how a simple `TransferHandler` can allow to use remote event listeners or event targets. ================================================ FILE: docs/examples/04-eventlistener-example/event.transferhandler.js ================================================ Comlink.transferHandlers.set("event", { canHandle(obj) { return obj instanceof Event; }, serialize(obj) { return [ { targetId: obj && obj.target && obj.target.id, targetClassList: obj && obj.target && obj.target.classList && [...obj.target.classList], detail: obj && obj.detail, }, [], ]; }, deserialize(obj) { return obj; }, }); ================================================ FILE: docs/examples/04-eventlistener-example/index.html ================================================ Open DevTools and click the button. ================================================ FILE: docs/examples/04-eventlistener-example/worker.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ importScripts("https://unpkg.com/comlink/dist/umd/comlink.js"); // importScripts("../../../dist/umd/comlink.js"); importScripts("event.transferhandler.js"); Comlink.expose({ onclick(ev) { console.log( `Click! Button id: ${ev.targetId}, Button classes: ${JSON.stringify( ev.targetClassList )}` ); }, }); ================================================ FILE: docs/examples/05-serviceworker-example/README.md ================================================ This example shows how to setup Comlink between a website and a service worker. ================================================ FILE: docs/examples/05-serviceworker-example/index.html ================================================ ================================================ FILE: docs/examples/05-serviceworker-example/worker.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ importScripts("https://unpkg.com/comlink/dist/umd/comlink.js"); // importScripts("../../../dist/umd/comlink.js"); addEventListener("install", () => skipWaiting()); addEventListener("activate", () => clients.claim()); const obj = { counter: 0, inc() { this.counter++; }, }; self.addEventListener("message", (event) => { if (event.data.comlinkInit) { Comlink.expose(obj, event.data.port); return; } }); ================================================ FILE: docs/examples/06-node-example/main.mjs ================================================ import { Worker } from "worker_threads"; import * as Comlink from "../../../dist/esm/comlink.mjs"; import nodeEndpoint from "../../../dist/esm/node-adapter.mjs"; async function init() { const worker = new Worker("./worker.mjs"); const api = Comlink.wrap(nodeEndpoint(worker)); console.log(await api.doMath()); } init(); ================================================ FILE: docs/examples/06-node-example/worker.mjs ================================================ import { parentPort } from "worker_threads"; import * as Comlink from "../../../dist/esm/comlink.mjs"; import nodeEndpoint from "../../../dist/esm/node-adapter.mjs"; const api = { doMath() { return 4; }, }; Comlink.expose(api, nodeEndpoint(parentPort)); ================================================ FILE: docs/examples/07-sharedworker-example/README.md ================================================ This example shows how to setup Comlink between a website and a `SharedWorker`. ================================================ FILE: docs/examples/07-sharedworker-example/index.html ================================================ ================================================ FILE: docs/examples/07-sharedworker-example/worker.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ importScripts("https://unpkg.com/comlink/dist/umd/comlink.js"); // importScripts("../../../dist/umd/comlink.js"); const obj = { counter: 0, inc() { this.counter++; }, }; /** * When a connection is made into this shared worker, expose `obj` * via the connection `port`. */ onconnect = function (event) { const port = event.ports[0]; Comlink.expose(obj, port); }; // Single line alternative: // onconnect = (e) => Comlink.expose(obj, e.ports[0]); ================================================ FILE: docs/examples/99-nonworker-examples/iframes/README.md ================================================ This example shows how to set up Comlink between a window and an embedded iframe using `Comlink.windowEndpoint()`. ================================================ FILE: docs/examples/99-nonworker-examples/iframes/iframe.html ================================================ ================================================ FILE: docs/examples/99-nonworker-examples/iframes/index.html ================================================ ================================================ FILE: docs/index.html ================================================ ================================================ FILE: karma.conf.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ module.exports = function (config) { const configuration = { basePath: "", frameworks: ["mocha", "chai", "detectBrowsers"], files: [ { pattern: "tests/fixtures/*", included: false, }, { pattern: "dist/**/*.@(mjs|js)", included: false, }, { pattern: "tests/*.test.js", type: "module", }, ], reporters: ["progress"], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, singleRun: true, concurrency: Infinity, detectBrowsers: { enabled: true, usePhantomJS: false, preferHeadless: true, postDetection: (availableBrowsers) => { if (process.env.INSIDE_DOCKER) { return ["DockerChrome"]; } else if (process.env.CHROME_ONLY) { return ["ChromeHeadless"]; } else { // Filtering SafariTechPreview because I am having // local issues and I have no idea how to fix them. // I know that’s not a good reason to disable tests, // but Safari TP is relatively unimportant. return availableBrowsers.filter( (browser) => browser !== "SafariTechPreview" ); } }, }, customLaunchers: { DockerChrome: { base: "ChromeHeadless", flags: ["--no-sandbox"], }, }, }; config.set(configuration); }; ================================================ FILE: package.json ================================================ { "name": "comlink", "version": "4.4.2", "description": "Comlink makes WebWorkers enjoyable", "main": "dist/umd/comlink.js", "module": "dist/esm/comlink.mjs", "types": "dist/umd/comlink.d.ts", "sideEffects": false, "scripts": { "build": "rollup -c", "test:unit": "karma start", "test:node": "mocha ./tests/node/main.mjs", "test:types": "tsc -p ./tests/tsconfig.json", "test:types:watch": "npm run test:types -- --watch", "test": "npm run fmt_test && npm run build && npm run test:types && npm run test:unit && npm run test:node", "fmt": "prettier --write './*.{mjs,js,ts,md,json,html}' './{src,docs,tests}/{,**/}*.{mjs,js,ts,md,json,html}'", "fmt_test": "test $(prettier -l './*.{mjs,js,ts,md,json,html}' './{src,docs,tests}/{**/,}*.{mjs,js,ts,md,json,html}' | wc -l) -eq 0", "watchtest": "CHROME_ONLY=1 karma start --no-single-run" }, "author": { "name": "Surma", "email": "surma@google.com" }, "repository": { "type": "git", "url": "https://github.com/GoogleChromeLabs/comlink.git" }, "license": "Apache-2.0", "devDependencies": { "@rollup/plugin-terser": "0.4.0", "@rollup/plugin-typescript": "11.0.0", "chai": "^4.3.7", "conditional-type-checks": "1.0.6", "husky": "8.0.3", "karma": "6.4.1", "karma-chai": "0.1.0", "karma-chrome-launcher": "3.1.1", "karma-detect-browsers": "2.3.3", "karma-firefox-launcher": "2.1.2", "karma-mocha": "2.0.1", "karma-safari-launcher": "1.0.0", "karma-safaritechpreview-launcher": "2.0.2", "mocha": "10.2.0", "prettier": "2.8.3", "rimraf": "4.1.2", "rollup": "3.10.1", "tslib": "2.4.1", "typescript": "4.9.4" } } ================================================ FILE: renovate.json ================================================ { "extends": [":library"], "assignees": ["surma"] } ================================================ FILE: rollup.config.mjs ================================================ import typescript from "@rollup/plugin-typescript"; import terser from "@rollup/plugin-terser"; import { sync } from "rimraf"; function config({ format, minify, input, ext = "js" }) { const dir = `dist/${format}/`; const minifierSuffix = minify ? ".min" : ""; return { input: `./src/${input}.ts`, output: { name: "Comlink", file: `${dir}/${input}${minifierSuffix}.${ext}`, format, sourcemap: true, }, plugins: [ typescript({ tsconfig: "./tsconfig.json", compilerOptions: { declaration: true, declarationDir: ".", sourceMap: true, outDir: "dist", }, }), minify ? terser({ compress: true, mangle: true, }) : undefined, ].filter(Boolean), }; } sync("dist"); export default [ { input: "comlink", format: "esm", minify: false, ext: "mjs" }, { input: "comlink", format: "esm", minify: true, ext: "mjs" }, { input: "comlink", format: "esm", minify: false }, { input: "comlink", format: "esm", minify: true }, { input: "comlink", format: "umd", minify: false }, { input: "comlink", format: "umd", minify: true }, { input: "node-adapter", format: "esm", minify: false, ext: "mjs" }, { input: "node-adapter", format: "esm", minify: true, ext: "mjs" }, { input: "node-adapter", format: "umd", minify: false }, { input: "node-adapter", format: "umd", minify: true }, ].map(config); ================================================ FILE: src/comlink.ts ================================================ /** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import { Endpoint, EventSource, Message, MessageType, PostMessageWithOrigin, WireValue, WireValueType, } from "./protocol"; export type { Endpoint }; export const proxyMarker = Symbol("Comlink.proxy"); export const createEndpoint = Symbol("Comlink.endpoint"); export const releaseProxy = Symbol("Comlink.releaseProxy"); export const finalizer = Symbol("Comlink.finalizer"); const throwMarker = Symbol("Comlink.thrown"); /** * Interface of values that were marked to be proxied with `comlink.proxy()`. * Can also be implemented by classes. */ export interface ProxyMarked { [proxyMarker]: true; } /** * Takes a type and wraps it in a Promise, if it not already is one. * This is to avoid `Promise>`. * * This is the inverse of `Unpromisify`. */ type Promisify = T extends Promise ? T : Promise; /** * Takes a type that may be Promise and unwraps the Promise type. * If `P` is not a Promise, it returns `P`. * * This is the inverse of `Promisify`. */ type Unpromisify

= P extends Promise ? T : P; /** * Takes the raw type of a remote property and returns the type that is visible to the local thread on the proxy. * * Note: This needs to be its own type alias, otherwise it will not distribute over unions. * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types */ type RemoteProperty = // If the value is a method, comlink will proxy it automatically. // Objects are only proxied if they are marked to be proxied. // Otherwise, the property is converted to a Promise that resolves the cloned value. T extends Function | ProxyMarked ? Remote : Promisify; /** * Takes the raw type of a property as a remote thread would see it through a proxy (e.g. when passed in as a function * argument) and returns the type that the local thread has to supply. * * This is the inverse of `RemoteProperty`. * * Note: This needs to be its own type alias, otherwise it will not distribute over unions. See * https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types */ type LocalProperty = T extends Function | ProxyMarked ? Local : Unpromisify; /** * Proxies `T` if it is a `ProxyMarked`, clones it otherwise (as handled by structured cloning and transfer handlers). */ export type ProxyOrClone = T extends ProxyMarked ? Remote : T; /** * Inverse of `ProxyOrClone`. */ export type UnproxyOrClone = T extends RemoteObject ? Local : T; /** * Takes the raw type of a remote object in the other thread and returns the type as it is visible to the local thread * when proxied with `Comlink.proxy()`. * * This does not handle call signatures, which is handled by the more general `Remote` type. * * @template T The raw type of a remote object as seen in the other thread. */ export type RemoteObject = { [P in keyof T]: RemoteProperty }; /** * Takes the type of an object as a remote thread would see it through a proxy (e.g. when passed in as a function * argument) and returns the type that the local thread has to supply. * * This does not handle call signatures, which is handled by the more general `Local` type. * * This is the inverse of `RemoteObject`. * * @template T The type of a proxied object. */ export type LocalObject = { [P in keyof T]: LocalProperty }; /** * Additional special comlink methods available on each proxy returned by `Comlink.wrap()`. */ export interface ProxyMethods { [createEndpoint]: () => Promise; [releaseProxy]: () => void; } /** * Takes the raw type of a remote object, function or class in the other thread and returns the type as it is visible to * the local thread from the proxy return value of `Comlink.wrap()` or `Comlink.proxy()`. */ export type Remote = // Handle properties RemoteObject & // Handle call signature (if present) (T extends (...args: infer TArguments) => infer TReturn ? ( ...args: { [I in keyof TArguments]: UnproxyOrClone } ) => Promisify>> : unknown) & // Handle construct signature (if present) // The return of construct signatures is always proxied (whether marked or not) (T extends { new (...args: infer TArguments): infer TInstance } ? { new ( ...args: { [I in keyof TArguments]: UnproxyOrClone; } ): Promisify>; } : unknown) & // Include additional special comlink methods available on the proxy. ProxyMethods; /** * Expresses that a type can be either a sync or async. */ type MaybePromise = Promise | T; /** * Takes the raw type of a remote object, function or class as a remote thread would see it through a proxy (e.g. when * passed in as a function argument) and returns the type the local thread has to supply. * * This is the inverse of `Remote`. It takes a `Remote` and returns its original input `T`. */ export type Local = // Omit the special proxy methods (they don't need to be supplied, comlink adds them) Omit, keyof ProxyMethods> & // Handle call signatures (if present) (T extends (...args: infer TArguments) => infer TReturn ? ( ...args: { [I in keyof TArguments]: ProxyOrClone } ) => // The raw function could either be sync or async, but is always proxied automatically MaybePromise>> : unknown) & // Handle construct signature (if present) // The return of construct signatures is always proxied (whether marked or not) (T extends { new (...args: infer TArguments): infer TInstance } ? { new ( ...args: { [I in keyof TArguments]: ProxyOrClone; } ): // The raw constructor could either be sync or async, but is always proxied automatically MaybePromise>>; } : unknown); const isObject = (val: unknown): val is object => (typeof val === "object" && val !== null) || typeof val === "function"; /** * Customizes the serialization of certain values as determined by `canHandle()`. * * @template T The input type being handled by this transfer handler. * @template S The serialized type sent over the wire. */ export interface TransferHandler { /** * Gets called for every value to determine whether this transfer handler * should serialize the value, which includes checking that it is of the right * type (but can perform checks beyond that as well). */ canHandle(value: unknown): value is T; /** * Gets called with the value if `canHandle()` returned `true` to produce a * value that can be sent in a message, consisting of structured-cloneable * values and/or transferrable objects. */ serialize(value: T): [S, Transferable[]]; /** * Gets called to deserialize an incoming value that was serialized in the * other thread with this transfer handler (known through the name it was * registered under). */ deserialize(value: S): T; } /** * Internal transfer handle to handle objects marked to proxy. */ const proxyTransferHandler: TransferHandler = { canHandle: (val): val is ProxyMarked => isObject(val) && (val as ProxyMarked)[proxyMarker], serialize(obj) { const { port1, port2 } = new MessageChannel(); expose(obj, port1); return [port2, [port2]]; }, deserialize(port) { port.start(); return wrap(port); }, }; interface ThrownValue { [throwMarker]: unknown; // just needs to be present value: unknown; } type SerializedThrownValue = | { isError: true; value: Error } | { isError: false; value: unknown }; type PendingListenersMap = Map< string, (value: WireValue | PromiseLike) => void >; type EndpointWithPendingListeners = { endpoint: Endpoint; pendingListeners: PendingListenersMap; }; /** * Internal transfer handler to handle thrown exceptions. */ const throwTransferHandler: TransferHandler< ThrownValue, SerializedThrownValue > = { canHandle: (value): value is ThrownValue => isObject(value) && throwMarker in value, serialize({ value }) { let serialized: SerializedThrownValue; if (value instanceof Error) { serialized = { isError: true, value: { message: value.message, name: value.name, stack: value.stack, }, }; } else { serialized = { isError: false, value }; } return [serialized, []]; }, deserialize(serialized) { if (serialized.isError) { throw Object.assign( new Error(serialized.value.message), serialized.value ); } throw serialized.value; }, }; /** * Allows customizing the serialization of certain values. */ export const transferHandlers = new Map< string, TransferHandler >([ ["proxy", proxyTransferHandler], ["throw", throwTransferHandler], ]); function isAllowedOrigin( allowedOrigins: (string | RegExp)[], origin: string ): boolean { for (const allowedOrigin of allowedOrigins) { if (origin === allowedOrigin || allowedOrigin === "*") { return true; } if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) { return true; } } return false; } export function expose( obj: any, ep: Endpoint = globalThis as any, allowedOrigins: (string | RegExp)[] = ["*"] ) { ep.addEventListener("message", function callback(ev: MessageEvent) { if (!ev || !ev.data) { return; } if (!isAllowedOrigin(allowedOrigins, ev.origin)) { console.warn(`Invalid origin '${ev.origin}' for comlink proxy`); return; } const { id, type, path } = { path: [] as string[], ...(ev.data as Message), }; const argumentList = (ev.data.argumentList || []).map(fromWireValue); let returnValue; try { const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj); const rawValue = path.reduce((obj, prop) => obj[prop], obj); switch (type) { case MessageType.GET: { returnValue = rawValue; } break; case MessageType.SET: { parent[path.slice(-1)[0]] = fromWireValue(ev.data.value); returnValue = true; } break; case MessageType.APPLY: { returnValue = rawValue.apply(parent, argumentList); } break; case MessageType.CONSTRUCT: { const value = new rawValue(...argumentList); returnValue = proxy(value); } break; case MessageType.ENDPOINT: { const { port1, port2 } = new MessageChannel(); expose(obj, port2); returnValue = transfer(port1, [port1]); } break; case MessageType.RELEASE: { returnValue = undefined; } break; default: return; } } catch (value) { returnValue = { value, [throwMarker]: 0 }; } Promise.resolve(returnValue) .catch((value) => { return { value, [throwMarker]: 0 }; }) .then((returnValue) => { const [wireValue, transferables] = toWireValue(returnValue); ep.postMessage({ ...wireValue, id }, transferables); if (type === MessageType.RELEASE) { // detach and deactive after sending release response above. ep.removeEventListener("message", callback as any); closeEndPoint(ep); if (finalizer in obj && typeof obj[finalizer] === "function") { obj[finalizer](); } } }) .catch((error) => { // Send Serialization Error To Caller const [wireValue, transferables] = toWireValue({ value: new TypeError("Unserializable return value"), [throwMarker]: 0, }); ep.postMessage({ ...wireValue, id }, transferables); }); } as any); if (ep.start) { ep.start(); } } function isMessagePort(endpoint: Endpoint): endpoint is MessagePort { return endpoint.constructor.name === "MessagePort"; } function closeEndPoint(endpoint: Endpoint) { if (isMessagePort(endpoint)) endpoint.close(); } export function wrap(ep: Endpoint, target?: any): Remote { const pendingListeners : PendingListenersMap = new Map(); ep.addEventListener("message", function handleMessage(ev: Event) { const { data } = ev as MessageEvent; if (!data || !data.id) { return; } const resolver = pendingListeners.get(data.id); if (!resolver) { return; } try { resolver(data); } finally { pendingListeners.delete(data.id); } }); return createProxy({ endpoint: ep, pendingListeners }, [], target) as any; } function throwIfProxyReleased(isReleased: boolean) { if (isReleased) { throw new Error("Proxy has been released and is not useable"); } } function releaseEndpoint(epWithPendingListeners: EndpointWithPendingListeners) { return requestResponseMessage(epWithPendingListeners, { type: MessageType.RELEASE, }).then(() => { closeEndPoint(epWithPendingListeners.endpoint); }); } interface FinalizationRegistry { new (cb: (heldValue: T) => void): FinalizationRegistry; register( weakItem: object, heldValue: T, unregisterToken?: object | undefined ): void; unregister(unregisterToken: object): void; } declare var FinalizationRegistry: FinalizationRegistry; const proxyCounter = new WeakMap(); const proxyFinalizers = "FinalizationRegistry" in globalThis && new FinalizationRegistry( (epWithPendingListeners: EndpointWithPendingListeners) => { const newCount = (proxyCounter.get(epWithPendingListeners) || 0) - 1; proxyCounter.set(epWithPendingListeners, newCount); if (newCount === 0) { releaseEndpoint(epWithPendingListeners).finally(() => { epWithPendingListeners.pendingListeners.clear(); }); } } ); function registerProxy( proxy: object, epWithPendingListeners: EndpointWithPendingListeners ) { const newCount = (proxyCounter.get(epWithPendingListeners) || 0) + 1; proxyCounter.set(epWithPendingListeners, newCount); if (proxyFinalizers) { proxyFinalizers.register(proxy, epWithPendingListeners, proxy); } } function unregisterProxy(proxy: object) { if (proxyFinalizers) { proxyFinalizers.unregister(proxy); } } function createProxy( epWithPendingListeners: EndpointWithPendingListeners, path: (string | number | symbol)[] = [], target: object = function () {} ): Remote { let isProxyReleased = false; const proxy = new Proxy(target, { get(_target, prop) { throwIfProxyReleased(isProxyReleased); if (prop === releaseProxy) { return () => { unregisterProxy(proxy); releaseEndpoint(epWithPendingListeners).finally(() => { epWithPendingListeners.pendingListeners.clear(); }); isProxyReleased = true; }; } if (prop === "then") { if (path.length === 0) { return { then: () => proxy }; } const r = requestResponseMessage(epWithPendingListeners, { type: MessageType.GET, path: path.map((p) => p.toString()), }).then(fromWireValue); return r.then.bind(r); } return createProxy(epWithPendingListeners, [...path, prop]); }, set(_target, prop, rawValue) { throwIfProxyReleased(isProxyReleased); // FIXME: ES6 Proxy Handler `set` methods are supposed to return a // boolean. To show good will, we return true asynchronously ¯\_(ツ)_/¯ const [value, transferables] = toWireValue(rawValue); return requestResponseMessage( epWithPendingListeners, { type: MessageType.SET, path: [...path, prop].map((p) => p.toString()), value, }, transferables ).then(fromWireValue) as any; }, apply(_target, _thisArg, rawArgumentList) { throwIfProxyReleased(isProxyReleased); const last = path[path.length - 1]; if ((last as any) === createEndpoint) { return requestResponseMessage(epWithPendingListeners, { type: MessageType.ENDPOINT, }).then(fromWireValue); } // We just pretend that `bind()` didn’t happen. if (last === "bind") { return createProxy(epWithPendingListeners, path.slice(0, -1)); } const [argumentList, transferables] = processArguments(rawArgumentList); return requestResponseMessage( epWithPendingListeners, { type: MessageType.APPLY, path: path.map((p) => p.toString()), argumentList, }, transferables ).then(fromWireValue); }, construct(_target, rawArgumentList) { throwIfProxyReleased(isProxyReleased); const [argumentList, transferables] = processArguments(rawArgumentList); return requestResponseMessage( epWithPendingListeners, { type: MessageType.CONSTRUCT, path: path.map((p) => p.toString()), argumentList, }, transferables ).then(fromWireValue); }, }); registerProxy(proxy, epWithPendingListeners); return proxy as any; } function myFlat(arr: (T | T[])[]): T[] { return Array.prototype.concat.apply([], arr); } function processArguments(argumentList: any[]): [WireValue[], Transferable[]] { const processed = argumentList.map(toWireValue); return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))]; } const transferCache = new WeakMap(); export function transfer(obj: T, transfers: Transferable[]): T { transferCache.set(obj, transfers); return obj; } export function proxy(obj: T): T & ProxyMarked { return Object.assign(obj, { [proxyMarker]: true }) as any; } export function windowEndpoint( w: PostMessageWithOrigin, context: EventSource = globalThis, targetOrigin = "*" ): Endpoint { return { postMessage: (msg: any, transferables: Transferable[]) => w.postMessage(msg, targetOrigin, transferables), addEventListener: context.addEventListener.bind(context), removeEventListener: context.removeEventListener.bind(context), }; } function toWireValue(value: any): [WireValue, Transferable[]] { for (const [name, handler] of transferHandlers) { if (handler.canHandle(value)) { const [serializedValue, transferables] = handler.serialize(value); return [ { type: WireValueType.HANDLER, name, value: serializedValue, }, transferables, ]; } } return [ { type: WireValueType.RAW, value, }, transferCache.get(value) || [], ]; } function fromWireValue(value: WireValue): any { switch (value.type) { case WireValueType.HANDLER: return transferHandlers.get(value.name)!.deserialize(value.value); case WireValueType.RAW: return value.value; } } function requestResponseMessage( epWithPendingListeners: EndpointWithPendingListeners, msg: Message, transfers?: Transferable[] ): Promise { const ep = epWithPendingListeners.endpoint; const pendingListeners = epWithPendingListeners.pendingListeners; return new Promise((resolve) => { const id = generateUUID(); pendingListeners.set(id, resolve); if (ep.start) { ep.start(); } ep.postMessage({ id, ...msg }, transfers); }); } function generateUUID(): string { return new Array(4) .fill(0) .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)) .join("-"); } ================================================ FILE: src/node-adapter.ts ================================================ /** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: Apache-2.0 */ import { Endpoint } from "./protocol"; export interface NodeEndpoint { postMessage(message: any, transfer?: any[]): void; on( type: string, listener: EventListenerOrEventListenerObject, options?: {} ): void; off( type: string, listener: EventListenerOrEventListenerObject, options?: {} ): void; start?: () => void; } export default function nodeEndpoint(nep: NodeEndpoint): Endpoint { const listeners = new WeakMap(); return { postMessage: nep.postMessage.bind(nep), addEventListener: (_, eh) => { const l = (data: any) => { if ("handleEvent" in eh) { eh.handleEvent({ data } as MessageEvent); } else { eh({ data } as MessageEvent); } }; nep.on("message", l); listeners.set(eh, l); }, removeEventListener: (_, eh) => { const l = listeners.get(eh); if (!l) { return; } nep.off("message", l); listeners.delete(eh); }, start: nep.start && nep.start.bind(nep), }; } ================================================ FILE: src/protocol.ts ================================================ /** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: Apache-2.0 */ export interface EventSource { addEventListener( type: string, listener: EventListenerOrEventListenerObject, options?: {} ): void; removeEventListener( type: string, listener: EventListenerOrEventListenerObject, options?: {} ): void; } export interface PostMessageWithOrigin { postMessage( message: any, targetOrigin: string, transfer?: Transferable[] ): void; } export interface Endpoint extends EventSource { postMessage(message: any, transfer?: Transferable[]): void; start?: () => void; } export const enum WireValueType { RAW = "RAW", PROXY = "PROXY", THROW = "THROW", HANDLER = "HANDLER", } export interface RawWireValue { id?: string; type: WireValueType.RAW; value: {}; } export interface HandlerWireValue { id?: string; type: WireValueType.HANDLER; name: string; value: unknown; } export type WireValue = RawWireValue | HandlerWireValue; export type MessageID = string; export const enum MessageType { GET = "GET", SET = "SET", APPLY = "APPLY", CONSTRUCT = "CONSTRUCT", ENDPOINT = "ENDPOINT", RELEASE = "RELEASE", } export interface GetMessage { id?: MessageID; type: MessageType.GET; path: string[]; } export interface SetMessage { id?: MessageID; type: MessageType.SET; path: string[]; value: WireValue; } export interface ApplyMessage { id?: MessageID; type: MessageType.APPLY; path: string[]; argumentList: WireValue[]; } export interface ConstructMessage { id?: MessageID; type: MessageType.CONSTRUCT; path: string[]; argumentList: WireValue[]; } export interface EndpointMessage { id?: MessageID; type: MessageType.ENDPOINT; } export interface ReleaseMessage { id?: MessageID; type: MessageType.RELEASE; } export type Message = | GetMessage | SetMessage | ApplyMessage | ConstructMessage | EndpointMessage | ReleaseMessage; ================================================ FILE: structured-clone-table.md ================================================ # Behavior of [Structured Clone] [Structured clone] is JavaScript’s algorithm to create “deep copies” of values. It is used for `postMessage()` and therefore is used extensively under the hood with Comlink. By default, every function parameter and function return value is structured cloned. Here is a table of how the structured clone algorithm handles different kinds of values. Or to phrase it differently: If you pass a value from the left side as a parameter into a proxy’d function, the actual function code will get what is listed on the right side. | Input | Output | Notes | | -------------------------- | :------------: | -------------------------------------------------------------------------------------------- | | `[1,2,3]` | `[1,2,3]` | Full copy | | `{a: 1, b: 2}` | `{a: 1, b: 2}` | Full copy | | `{a: 1, b() { return 2; }` | `{a: 1}` | Full copy, functions omitted | | `new MyClass()` | `{...}` | Just the properties | | `Map` | `Map` | [`Map`][map] is structured cloneable | | `Set` | `Set` | [`Set`][set] is structured cloneable | | `ArrayBuffer` | `ArrayBuffer` | [`ArrayBuffer`][arraybuffer] is structured cloneable | | `Uint32Array` | `Uint32Array` | [`Uint32Array`][uint32array] and all the other typed arrays are structured cloneable | | `Event` | ❌ | | | Any DOM element | ❌ | | | `MessagePort` | ❌ | Only transferable, not structured cloneable | | `Request` | ❌ | | | `Response` | ❌ | | | `ReadableStream` | ❌ | [Streams are planned to be transferable][transferable streams], but not structured cloneable | [structured clone]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map [set]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set [arraybuffer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer [uint32array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array [transferable streams]: https://github.com/whatwg/streams/blob/master/transferable-streams-explainer.md ================================================ FILE: tests/cross-origin.comlink.test.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as Comlink from "/base/dist/esm/comlink.mjs"; describe("Comlink origin filtering", function () { it("rejects messages from unknown origin", async function () { // expose on our window so comlink is listening to window postmessage const obj = { my: "value" }; Comlink.expose(obj, self, [/^http:\/\/localhost(:[0-9]+)?\/?$/]); let handler; // juggle async timings to get the attack started const attackComplete = new Promise((resolve, reject) => { handler = (ev) => { if (ev.data === "ready" && ev.origin === "null") { // tell the iframe it can start the attack ifr.contentWindow.postMessage("start", "*"); } else if (ev.data === "done") { // confirm the attack failed, the prototype was not updated expect(Object.prototype.foo).to.be.undefined; expect(obj.my).to.equal("value"); resolve(); } }; window.addEventListener("message", handler); }); // create a sandboxed iframe for the attack const ifr = document.createElement("iframe"); ifr.sandbox.add("allow-scripts"); ifr.src = "/base/tests/fixtures/attack-iframe.html"; document.body.appendChild(ifr); // wait for the iframe to load await new Promise((resolve) => (ifr.onload = resolve)); // and wait for the attack to complete await attackComplete; window.removeEventListener("message", handler); ifr.remove(); }); it("accepts messages from matching origin", async function () { // expose on our window so comlink is listening to window postmessage const obj = { my: "value" }; Comlink.expose(obj, self, [/^http:\/\/localhost(:[0-9]+)?\/?$/]); let handler; // juggle async timings to get the attack started const attackComplete = new Promise((resolve, reject) => { handler = (ev) => { if (ev.data === "ready" && ev.origin === window.origin) { // tell the iframe it can start the attack ifr.contentWindow.postMessage("start", "*"); } else if (ev.data === "done") { // confirm the attack succeeded, the prototype was updated expect(Object.prototype.foo).to.equal("x"); expect(obj.my).to.equal("value"); resolve(); } }; window.addEventListener("message", handler); }); // create a sandboxed iframe for the attack, but with same origin const ifr = document.createElement("iframe"); ifr.sandbox.add("allow-scripts", "allow-same-origin"); ifr.src = "/base/tests/fixtures/attack-iframe.html"; document.body.appendChild(ifr); // wait for the iframe to load await new Promise((resolve) => (ifr.onload = resolve)); // and wait for the attack to complete await attackComplete; window.removeEventListener("message", handler); ifr.remove(); }); }); ================================================ FILE: tests/fixtures/attack-iframe.html ================================================ ================================================ FILE: tests/fixtures/iframe.html ================================================ ================================================ FILE: tests/fixtures/two-way-iframe.html ================================================ ================================================ FILE: tests/fixtures/worker.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ importScripts("/base/dist/umd/comlink.js"); Comlink.expose((a, b) => a + b); ================================================ FILE: tests/iframe.comlink.test.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as Comlink from "/base/dist/esm/comlink.mjs"; describe("Comlink across iframes", function () { beforeEach(function () { this.ifr = document.createElement("iframe"); this.ifr.sandbox.add("allow-scripts", "allow-same-origin"); this.ifr.src = "/base/tests/fixtures/iframe.html"; document.body.appendChild(this.ifr); return new Promise((resolve) => (this.ifr.onload = resolve)); }); afterEach(function () { this.ifr.remove(); }); it("can communicate", async function () { const proxy = Comlink.wrap(Comlink.windowEndpoint(this.ifr.contentWindow)); expect(await proxy(1, 3)).to.equal(4); }); }); ================================================ FILE: tests/node/main.mjs ================================================ import { Worker } from "worker_threads"; import * as Comlink from "../../dist/esm/comlink.mjs"; import nodeEndpoint from "../../dist/esm/node-adapter.mjs"; import { expect } from "chai"; describe("node", () => { describe("Comlink across workers", function () { beforeEach(function () { this.worker = new Worker("./tests/node/worker.mjs"); }); afterEach(function () { this.worker.terminate(); }); it("can communicate", async function () { const proxy = Comlink.wrap(nodeEndpoint(this.worker)); expect(await proxy(1, 3)).to.equal(4); }); it("can tunnels a new endpoint with createEndpoint", async function () { const proxy = Comlink.wrap(nodeEndpoint(this.worker)); const otherEp = await proxy[Comlink.createEndpoint](); const otherProxy = Comlink.wrap(otherEp); expect(await otherProxy(20, 1)).to.equal(21); }); it("releaseProxy closes MessagePort created by createEndpoint", async function () { const proxy = Comlink.wrap(nodeEndpoint(this.worker)); const otherEp = await proxy[Comlink.createEndpoint](); const otherProxy = Comlink.wrap(otherEp); expect(await otherProxy(20, 1)).to.equal(21); await new Promise((resolve) => { otherEp.close = resolve; // Resolve the promise when the MessagePort is closed. otherProxy[Comlink.releaseProxy](); // Release the proxy, which should close the MessagePort. }); }); }); }); ================================================ FILE: tests/node/worker.mjs ================================================ import { parentPort } from "worker_threads"; import * as Comlink from "../../dist/esm/comlink.mjs"; import nodeEndpoint from "../../dist/esm/node-adapter.mjs"; Comlink.expose((a, b) => a + b, nodeEndpoint(parentPort)); ================================================ FILE: tests/same_window.comlink.test.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as Comlink from "/base/dist/esm/comlink.mjs"; class SampleClass { constructor(counterInit = 1) { this._counter = counterInit; this._promise = Promise.resolve(4); } static get SOME_NUMBER() { return 4; } static ADD(a, b) { return a + b; } get counter() { return this._counter; } set counter(value) { this._counter = value; } get promise() { return this._promise; } method() { return 4; } increaseCounter(delta = 1) { this._counter += delta; } promiseFunc() { return new Promise((resolve) => setTimeout((_) => resolve(4), 100)); } proxyFunc() { return Comlink.proxy({ counter: 0, inc() { this.counter++; }, }); } throwsAnError() { throw Error("OMG"); } } describe("Comlink in the same realm", function () { beforeEach(function () { const { port1, port2 } = new MessageChannel(); port1.start(); port2.start(); this.port1 = port1; this.port2 = port2; }); it("can work with objects", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose({ value: 4 }, this.port2); expect(await thing.value).to.equal(4); }); it("can work with functions on an object", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose({ f: (_) => 4 }, this.port2); expect(await thing.f()).to.equal(4); }); it("can work with functions", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose((_) => 4, this.port2); expect(await thing()).to.equal(4); }); it("can work with objects that have undefined properties", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose({ x: undefined }, this.port2); expect(await thing.x).to.be.undefined; }); it("can keep the stack and message of thrown errors", async function () { let stack; const thing = Comlink.wrap(this.port1); Comlink.expose((_) => { const error = Error("OMG"); stack = error.stack; throw error; }, this.port2); try { await thing(); throw "Should have thrown"; } catch (err) { expect(err).to.not.eq("Should have thrown"); expect(err.message).to.equal("OMG"); expect(err.stack).to.equal(stack); } }); it("can forward an async function error", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose( { async throwError() { throw new Error("Should have thrown"); }, }, this.port2 ); try { await thing.throwError(); } catch (err) { expect(err.message).to.equal("Should have thrown"); } }); it("can rethrow non-error objects", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose((_) => { throw { test: true }; }, this.port2); try { await thing(); throw "Should have thrown"; } catch (err) { expect(err).to.not.equal("Should have thrown"); expect(err.test).to.equal(true); } }); it("can rethrow scalars", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose((_) => { throw "oops"; }, this.port2); try { await thing(); throw "Should have thrown"; } catch (err) { expect(err).to.not.equal("Should have thrown"); expect(err).to.equal("oops"); expect(typeof err).to.equal("string"); } }); it("can rethrow null", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose((_) => { throw null; }, this.port2); try { await thing(); throw "Should have thrown"; } catch (err) { expect(err).to.not.equal("Should have thrown"); expect(err).to.equal(null); expect(typeof err).to.equal("object"); } }); it("can work with parameterized functions", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose((a, b) => a + b, this.port2); expect(await thing(1, 3)).to.equal(4); }); it("can work with functions that return promises", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose( (_) => new Promise((resolve) => setTimeout((_) => resolve(4), 100)), this.port2 ); expect(await thing()).to.equal(4); }); it("can work with classes", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); expect(await instance.method()).to.equal(4); }); it("can pass parameters to class constructor", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(23); expect(await instance.counter).to.equal(23); }); it("can access a class in an object", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose({ SampleClass }, this.port2); const instance = await new thing.SampleClass(); expect(await instance.method()).to.equal(4); }); it("can work with class instance properties", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); expect(await instance._counter).to.equal(1); }); it("can set class instance properties", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); expect(await instance._counter).to.equal(1); await (instance._counter = 4); expect(await instance._counter).to.equal(4); }); it("can work with class instance methods", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); expect(await instance.counter).to.equal(1); await instance.increaseCounter(); expect(await instance.counter).to.equal(2); }); it("can handle throwing class instance methods", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); return instance .throwsAnError() .then((_) => Promise.reject()) .catch((err) => {}); }); it("can work with class instance methods multiple times", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); expect(await instance.counter).to.equal(1); await instance.increaseCounter(); await instance.increaseCounter(5); expect(await instance.counter).to.equal(7); }); it("can work with class instance methods that return promises", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); expect(await instance.promiseFunc()).to.equal(4); }); it("can work with class instance properties that are promises", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); expect(await instance._promise).to.equal(4); }); it("can work with class instance getters that are promises", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); expect(await instance.promise).to.equal(4); }); it("can work with static class properties", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); expect(await thing.SOME_NUMBER).to.equal(4); }); it("can work with static class methods", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); expect(await thing.ADD(1, 3)).to.equal(4); }); it("can work with bound class instance methods", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); expect(await instance.counter).to.equal(1); const method = instance.increaseCounter.bind(instance); await method(); expect(await instance.counter).to.equal(2); }); it("can work with class instance getters", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); expect(await instance.counter).to.equal(1); await instance.increaseCounter(); expect(await instance.counter).to.equal(2); }); it("can work with class instance setters", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); expect(await instance._counter).to.equal(1); await (instance.counter = 4); expect(await instance._counter).to.equal(4); }); const hasBroadcastChannel = (_) => "BroadcastChannel" in self; guardedIt(hasBroadcastChannel)( "will work with BroadcastChannel", async function () { const b1 = new BroadcastChannel("comlink_bc_test"); const b2 = new BroadcastChannel("comlink_bc_test"); const thing = Comlink.wrap(b1); Comlink.expose((b) => 40 + b, b2); expect(await thing(2)).to.equal(42); } ); // Buffer transfers seem to have regressed in Safari 11.1, it’s fixed in 11.2. const isNotSafari11_1 = (_) => !/11\.1(\.[0-9]+)? Safari/.test(navigator.userAgent); guardedIt(isNotSafari11_1)("will transfer buffers", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose((b) => b.byteLength, this.port2); const buffer = new Uint8Array([1, 2, 3]).buffer; expect(await thing(Comlink.transfer(buffer, [buffer]))).to.equal(3); expect(buffer.byteLength).to.equal(0); }); guardedIt(isNotSafari11_1)("will copy TypedArrays", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose((b) => b, this.port2); const array = new Uint8Array([1, 2, 3]); const receive = await thing(array); expect(array).to.not.equal(receive); expect(array.byteLength).to.equal(receive.byteLength); expect([...array]).to.deep.equal([...receive]); }); guardedIt(isNotSafari11_1)("will copy nested TypedArrays", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose((b) => b, this.port2); const array = new Uint8Array([1, 2, 3]); const receive = await thing({ v: 1, array, }); expect(array).to.not.equal(receive.array); expect(array.byteLength).to.equal(receive.array.byteLength); expect([...array]).to.deep.equal([...receive.array]); }); guardedIt(isNotSafari11_1)( "will transfer deeply nested buffers", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose((a) => a.b.c.d.byteLength, this.port2); const buffer = new Uint8Array([1, 2, 3]).buffer; expect( await thing(Comlink.transfer({ b: { c: { d: buffer } } }, [buffer])) ).to.equal(3); expect(buffer.byteLength).to.equal(0); } ); it("will transfer a message port", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose((a) => a.postMessage("ohai"), this.port2); const { port1, port2 } = new MessageChannel(); await thing(Comlink.transfer(port2, [port2])); return new Promise((resolve) => { port1.onmessage = (event) => { expect(event.data).to.equal("ohai"); resolve(); }; }); }); it("will wrap marked return values", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose( (_) => Comlink.proxy({ counter: 0, inc() { this.counter += 1; }, }), this.port2 ); const obj = await thing(); expect(await obj.counter).to.equal(0); await obj.inc(); expect(await obj.counter).to.equal(1); }); it("will wrap marked return values from class instance methods", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); const obj = await instance.proxyFunc(); expect(await obj.counter).to.equal(0); await obj.inc(); expect(await obj.counter).to.equal(1); }); it("will wrap marked parameter values", async function () { const thing = Comlink.wrap(this.port1); const local = { counter: 0, inc() { this.counter++; }, }; Comlink.expose(async function (f) { await f.inc(); }, this.port2); expect(local.counter).to.equal(0); await thing(Comlink.proxy(local)); expect(await local.counter).to.equal(1); }); it("will wrap marked assignments", function (done) { const thing = Comlink.wrap(this.port1); const obj = { onready: null, call() { this.onready(); }, }; Comlink.expose(obj, this.port2); thing.onready = Comlink.proxy(() => done()); thing.call(); }); it("will wrap marked parameter values, simple function", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(async function (f) { await f(); }, this.port2); // Weird code because Mocha await new Promise(async (resolve) => { thing(Comlink.proxy((_) => resolve())); }); }); it("will wrap multiple marked parameter values, simple function", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(async function (f1, f2, f3) { return (await f1()) + (await f2()) + (await f3()); }, this.port2); // Weird code because Mocha expect( await thing( Comlink.proxy((_) => 1), Comlink.proxy((_) => 2), Comlink.proxy((_) => 3) ) ).to.equal(6); }); it("will proxy deeply nested values", async function () { const thing = Comlink.wrap(this.port1); const obj = { a: { v: 4, }, b: Comlink.proxy({ v: 5, }), }; Comlink.expose(obj, this.port2); const a = await thing.a; const b = await thing.b; expect(await a.v).to.equal(4); expect(await b.v).to.equal(5); await (a.v = 8); await (b.v = 9); // Workaround for a weird scheduling inconsistency in Firefox. // This test failed, but not when run in isolation, and only // in Firefox. I think there might be problem with task ordering. await new Promise((resolve) => setTimeout(resolve, 1)); expect(await thing.a.v).to.equal(4); expect(await thing.b.v).to.equal(9); }); it("will handle undefined parameters", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose({ f: (_) => 4 }, this.port2); expect(await thing.f(undefined)).to.equal(4); }); it("can handle destructuring", async function () { Comlink.expose( { a: 4, get b() { return 5; }, c() { return 6; }, }, this.port2 ); const { a, b, c } = Comlink.wrap(this.port1); expect(await a).to.equal(4); expect(await b).to.equal(5); expect(await c()).to.equal(6); }); it("lets users define transfer handlers", function (done) { Comlink.transferHandlers.set("event", { canHandle(obj) { return obj instanceof Event; }, serialize(obj) { return [obj.data, []]; }, deserialize(data) { return new MessageEvent("message", { data }); }, }); Comlink.expose((ev) => { expect(ev).to.be.an.instanceOf(Event); expect(ev.data).to.deep.equal({ a: 1 }); done(); }, this.port1); const thing = Comlink.wrap(this.port2); const { port1, port2 } = new MessageChannel(); port1.addEventListener("message", thing.bind(this)); port1.start(); port2.postMessage({ a: 1 }); }); it("can tunnels a new endpoint with createEndpoint", async function () { Comlink.expose( { a: 4, c() { return 5; }, }, this.port2 ); const proxy = Comlink.wrap(this.port1); const otherEp = await proxy[Comlink.createEndpoint](); const otherProxy = Comlink.wrap(otherEp); expect(await otherProxy.a).to.equal(4); expect(await proxy.a).to.equal(4); expect(await otherProxy.c()).to.equal(5); expect(await proxy.c()).to.equal(5); }); it("released proxy should no longer be useable and throw an exception", async function () { const thing = Comlink.wrap(this.port1); Comlink.expose(SampleClass, this.port2); const instance = await new thing(); await instance[Comlink.releaseProxy](); expect(() => instance.method()).to.throw(); }); it("released proxy should invoke finalizer", async function () { let finalized = false; Comlink.expose( { a: "thing", [Comlink.finalizer]: () => { finalized = true; }, }, this.port2 ); const instance = Comlink.wrap(this.port1); expect(await instance.a).to.equal("thing"); await instance[Comlink.releaseProxy](); // wait a beat to let the events process await new Promise((resolve) => setTimeout(resolve, 1)); expect(finalized).to.be.true; }); // commented out this test as it could be unreliable in various browsers as // it has to wait for GC to kick in which could happen at any timing // this does seem to work when testing locally it.skip("released proxy via GC should invoke finalizer", async function () { let finalized = false; Comlink.expose( { a: "thing", [Comlink.finalizer]: () => { finalized = true; }, }, this.port2 ); let registry; // set a long enough timeout to wait for a garbage collection this.timeout(10000); // promise will resolve when the proxy is garbage collected await new Promise(async (resolve, reject) => { registry = new FinalizationRegistry((heldValue) => { heldValue(); }); const instance = Comlink.wrap(this.port1); registry.register(instance, resolve); expect(await instance.a).to.equal("thing"); }); // wait a beat to let the events process await new Promise((resolve) => setTimeout(resolve, 1)); expect(finalized).to.be.true; }); 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); }); it("can handle unserializable types", async function () { const thing = Comlink.wrap(this.port1, { value: {} }); Comlink.expose({ value: () => "boom" }, this.port2); try { await thing.value; } catch (err) { expect(err.message).to.equal("Unserializable return value"); } }); }); function guardedIt(f) { return f() ? it : xit; } ================================================ FILE: tests/tsconfig.json ================================================ { "extends": "../tsconfig.json", "compilerOptions": { "noEmit": true }, "include": ["./**/*.ts"] } ================================================ FILE: tests/two-way-iframe.comlink.test.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as Comlink from "/base/dist/esm/comlink.mjs"; describe("Comlink across iframes", function () { beforeEach(function () { this.ifr = document.createElement("iframe"); this.ifr.sandbox.add("allow-scripts", "allow-same-origin"); this.ifr.src = "/base/tests/fixtures/two-way-iframe.html"; document.body.appendChild(this.ifr); return new Promise((resolve) => (this.ifr.onload = resolve)); }); afterEach(function () { this.ifr.remove(); }); it("can communicate both ways", async function () { let called = false; const iframe = Comlink.windowEndpoint(this.ifr.contentWindow); Comlink.expose((a) => { called = true; return ++a; }, iframe); const proxy = Comlink.wrap(iframe); expect(await proxy(1, 3)).to.equal(5); expect(called).to.equal(true); }); }); ================================================ FILE: tests/type-checks.ts ================================================ import { assert, Has, NotHas, IsAny, IsExact } from "conditional-type-checks"; import * as Comlink from "../src/comlink.js"; async function closureSoICanUseAwait() { { function simpleNumberFunction() { return 4; } const proxy = Comlink.wrap(0 as any); assert>(false); const v = proxy(); assert>>(true); } { function simpleObjectFunction() { return { a: 3 }; } const proxy = Comlink.wrap(0 as any); const v = await proxy(); assert>(true); } { async function simpleAsyncFunction() { return { a: 3 }; } const proxy = Comlink.wrap(0 as any); const v = await proxy(); assert>(true); } { function functionWithProxy() { return Comlink.proxy({ a: 3 }); } const proxy = Comlink.wrap(0 as any); const subproxy = await proxy(); const prop = subproxy.a; assert>>(true); } { class X { static staticFunc() { return 4; } private f = 4; public g = 9; sayHi() { return "hi"; } } const proxy = Comlink.wrap(0 as any); assert Promise }>>(true); const instance = await new proxy(); assert Promise }>>(true); assert }>>(true); assert }>>(true); assert>(false); } { const x = { a: 4, b() { return 9; }, c: { d: 3, }, }; const proxy = Comlink.wrap(0 as any); assert>(false); const a = proxy.a; assert>>(true); assert>(false); const b = proxy.b; assert Promise>>(true); assert>(false); const subproxy = proxy.c; assert>>(true); assert>(false); const copy = await proxy.c; assert>(true); } { Comlink.wrap(new MessageChannel().port1); Comlink.expose({}, new MessageChannel().port2); interface Baz { baz: number; method(): number; } class Foo { constructor(cParam: string) { const self = this; assert>(true); } prop1: string = "abc"; proxyProp = Comlink.proxy(new Bar()); methodWithTupleParams(...args: [string] | [number, string]): number { return 123; } methodWithProxiedReturnValue(): Baz & Comlink.ProxyMarked { return Comlink.proxy({ baz: 123, method: () => 123 }); } methodWithProxyParameter(param: Baz & Comlink.ProxyMarked): void {} } class Bar { prop2: string | number = "abc"; method(param: string): number { return 123; } methodWithProxiedReturnValue(): Baz & Comlink.ProxyMarked { return Comlink.proxy({ baz: 123, method: () => 123 }); } } const proxy = Comlink.wrap(Comlink.windowEndpoint(self)); assert>>(true); proxy[Comlink.releaseProxy](); const endp = proxy[Comlink.createEndpoint](); assert>>(true); assert>(false); assert>>(true); const r1 = proxy.methodWithTupleParams(123, "abc"); assert>>(true); const r2 = proxy.methodWithTupleParams("abc"); assert>>(true); assert< IsExact> >(true); assert>(false); assert>>(true); assert>>(true); const r3 = proxy.proxyProp.method("param"); assert>(false); assert>>(true); // @ts-expect-error proxy.proxyProp.method(123); // @ts-expect-error proxy.proxyProp.method(); const r4 = proxy.methodWithProxiedReturnValue(); assert>(false); assert< IsExact>> >(true); const r5 = proxy.proxyProp.methodWithProxiedReturnValue(); assert< IsExact>> >(true); const r6 = (await proxy.methodWithProxiedReturnValue()).baz; assert>(false); assert>>(true); const r7 = (await proxy.methodWithProxiedReturnValue()).method(); assert>(false); assert>>(true); const ProxiedFooClass = Comlink.wrap( Comlink.windowEndpoint(self) ); const inst1 = await new ProxiedFooClass("test"); assert>>(true); inst1[Comlink.releaseProxy](); inst1[Comlink.createEndpoint](); // @ts-expect-error await new ProxiedFooClass(123); // @ts-expect-error await new ProxiedFooClass(); // // Tests for advanced proxy use cases // // Type round trips // This tests that Local is the exact inverse of Remote for objects: assert< IsExact< Comlink.Local>, Comlink.ProxyMarked > >(true); // This tests that Local is the exact inverse of Remote for functions, with one difference: // The local version of a remote function can be either implemented as a sync or async function, // because Remote always makes the function async. assert< IsExact< Comlink.Local string>>, (a: number) => string | Promise > >(true); interface Subscriber { closed?: boolean; next?: (value: T) => void; } interface Unsubscribable { unsubscribe(): void; } /** A Subscribable that can get proxied by Comlink */ interface ProxyableSubscribable extends Comlink.ProxyMarked { subscribe( subscriber: Comlink.Remote & Comlink.ProxyMarked> ): Unsubscribable & Comlink.ProxyMarked; } /** Simple parameter object that gets cloned (not proxied) */ interface Params { textDocument: string; } class Registry { async registerProvider( provider: Comlink.Remote< ((params: Params) => ProxyableSubscribable) & Comlink.ProxyMarked > ) { const resultPromise = provider({ textDocument: "foo" }); assert< IsExact< typeof resultPromise, Promise>> > >(true); const result = await resultPromise; const subscriptionPromise = result.subscribe({ [Comlink.proxyMarker]: true, next: (value) => { assert>(true); }, }); assert< IsExact< typeof subscriptionPromise, Promise> > >(true); const subscriber = Comlink.proxy({ next: (value: string) => console.log(value), }); result.subscribe(subscriber); const r1 = (await subscriptionPromise).unsubscribe(); assert>>(true); } } const proxy2 = Comlink.wrap(Comlink.windowEndpoint(self)); proxy2.registerProvider( // Synchronous callback Comlink.proxy(({ textDocument }: Params) => { const subscribable = Comlink.proxy({ subscribe( subscriber: Comlink.Remote & Comlink.ProxyMarked> ): Unsubscribable & Comlink.ProxyMarked { // Important to test here is that union types (such as Function | undefined) distribute properly // when wrapped in Promises/proxied assert>(false); assert< IsExact< typeof subscriber.closed, Promise | Promise | Promise | undefined > >(true); assert>(false); assert< IsExact< typeof subscriber.next, | Comlink.Remote<(value: string) => void> | Promise | undefined > >(true); // @ts-expect-error subscriber.next(); if (subscriber.next) { // Only checking for presence is not enough, since it could be a Promise // @ts-expect-error subscriber.next(); } if (typeof subscriber.next === "function") { subscriber.next("abc"); } return Comlink.proxy({ unsubscribe() {} }); }, }); assert>(true); return subscribable; }) ); proxy2.registerProvider( // Async callback Comlink.proxy(async ({ textDocument }: Params) => { const subscribable = Comlink.proxy({ subscribe( subscriber: Comlink.Remote & Comlink.ProxyMarked> ): Unsubscribable & Comlink.ProxyMarked { assert>(false); assert< IsExact< typeof subscriber.next, | Comlink.Remote<(value: string) => void> | Promise | undefined > >(true); // Only checking for presence is not enough, since it could be a Promise if (typeof subscriber.next === "function") { subscriber.next("abc"); } return Comlink.proxy({ unsubscribe() {} }); }, }); return subscribable; }) ); } // Transfer handlers { const urlTransferHandler: Comlink.TransferHandler = { canHandle: (val): val is URL => { assert>(true); return val instanceof URL; }, serialize: (url) => { assert>(true); return [url.href, []]; }, deserialize: (str) => { assert>(true); return new URL(str); }, }; Comlink.transferHandlers.set("URL", urlTransferHandler); } } ================================================ FILE: tests/worker.comlink.test.js ================================================ /** * Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as Comlink from "/base/dist/esm/comlink.mjs"; describe("Comlink across workers", function () { beforeEach(function () { this.worker = new Worker("/base/tests/fixtures/worker.js"); }); afterEach(function () { this.worker.terminate(); }); it("can communicate", async function () { const proxy = Comlink.wrap(this.worker); expect(await proxy(1, 3)).to.equal(4); }); it("can tunnels a new endpoint with createEndpoint", async function () { const proxy = Comlink.wrap(this.worker); const otherEp = await proxy[Comlink.createEndpoint](); const otherProxy = Comlink.wrap(otherEp); expect(await otherProxy(20, 1)).to.equal(21); }); it("releaseProxy closes MessagePort created by createEndpoint", async function () { const proxy = Comlink.wrap(this.worker); const otherEp = await proxy[Comlink.createEndpoint](); const otherProxy = Comlink.wrap(otherEp); expect(await otherProxy(20, 1)).to.equal(21); await new Promise((resolve) => { otherEp.close = resolve; // Resolve the promise when the MessagePort is closed. otherProxy[Comlink.releaseProxy](); // Release the proxy, which should close the MessagePort. }); }); }); ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { /* Basic Options */ "target": "es2015" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */, "module": "esnext" /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, "lib": [ "esnext", "dom" ] /* Specify library files to be included in the compilation: */, // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ "declaration": true /* Generates corresponding '.d.ts' file. */, // "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ // "outDir": "./", /* Redirect output structure to the directory. */ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "removeComments": false, /* Do not emit comments to output. */ // "noEmit": true, /* Do not emit outputs. */ // "importHelpers": true, /* Import emit helpers from 'tslib'. */ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ /* Strict Type-Checking Options */ "strict": true /* Enable all strict type-checking options. */, // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ // "strictNullChecks": true, /* Enable strict null checks. */ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ /* Additional Checks */ // "noUnusedLocals": true, /* Report errors on unused locals. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ /* Module Resolution Options */ "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "typeRoots": [], /* List of folders to include type definitions from. */ // "types": [], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ /* Source Map Options */ // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ /* Experimental Options */ // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ }, "include": ["src/**/*.ts"], "exclude": ["dist"] }