[
  {
    "path": ".gitignore",
    "content": "*.pem\n*.swp\nnode_modules\n*.bak\ndist\n.*_cache*\npackage-lock.json\n"
  },
  {
    "path": ".husky/pre-commit",
    "content": "#!/usr/bin/env sh\n. \"$(dirname -- \"$0\")/_/husky.sh\"\n\nnpm test\n"
  },
  {
    "path": ".travis.yml",
    "content": "sudo: required\n\nservices:\n  - docker\n\nscript:\n  - docker build -t comlink .\n  - docker run --rm -v `pwd`:/usr/src comlink\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# v3 -> v4\n\n- Added support for NodeJS 11+ workers\n- `Comlink.proxy()` is now called `Comlink.wrap()`\n- `Comlink.proxyValue()` is now called `Comlink.proxy()`\n- Transferable values are _not_ transferred by default anymore. They need to be wrapped with `Comlink.transfer()`\n- Rewrote TypeScript types\n- New folder structure in the GitHub repo and in the npm module\n"
  },
  {
    "path": "CODEOWNERS",
    "content": "@surma\n"
  },
  {
    "path": "CONTRIBUTING",
    "content": "Want to contribute? Great! First, read this page (including the small print at the end).\n\n### Before you contribute\nBefore we can use your code, you must sign the\n[Google Individual Contributor License Agreement]\n(https://cla.developers.google.com/about/google-individual)\n(CLA), which you can do online. The CLA is necessary mainly because you own the\ncopyright to your changes, even after your contribution becomes part of our\ncodebase, so we need your permission to use and distribute your code. We also\nneed to be sure of various other things—for instance that you'll tell us if you\nknow that your code infringes on other people's patents. You don't have to sign\nthe CLA until after you've submitted your code for review and a member has\napproved it, but you must do it before we can put your code into our codebase.\nBefore you start working on a larger contribution, you should get in touch with\nus first through the issue tracker with your idea so that we can help out and\npossibly guide you. Coordinating up front makes it much easier to avoid\nfrustration later on.\n\n### Code reviews\nAll submissions, including submissions by project members, require review. We\nuse Github pull requests for this purpose.\n\n### The small print\nContributions made by corporations are covered by a different agreement than\nthe one above, the\n[Software Grant and Corporate Contributor License Agreement]\n(https://cla.developers.google.com/about/google-corporate).\n"
  },
  {
    "path": "CONTRIBUTORS",
    "content": "# People who have agreed to one of the CLAs and can contribute patches.\n# The AUTHORS file lists the copyright holders; this file\n# lists people.  For example, Google employees are listed here\n# but not in AUTHORS, because Google holds the copyright.\n#\n# https://developers.google.com/open-source/cla/individual\n# https://developers.google.com/open-source/cla/corporate\n#\n# Names should be added to this file as:\n#     Name <email address>\nSurma <surma@google.com>\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM selenium/node-chrome:latest@sha256:31be7ba7ebe6db9f9b266c10fc5f6fce7568791a6ade91b6b6d20a29a988ef5b\n\nUSER root\n\nRUN apt-get update -qqy \\\n  && rm -rf /var/lib/apt/lists/* /var/cache/apt/* \\\n  && rm /bin/sh && ln -s /bin/bash /bin/sh \\\n  && chown seluser /usr/local\n\nENV NVM_DIR /usr/local/nvm\nRUN wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash \\\n  && source $NVM_DIR/nvm.sh \\\n  && nvm install v11\n\nENV CHROME_BIN /opt/google/chrome/chrome\nENV INSIDE_DOCKER=1\n\nWORKDIR /usr/src\nENTRYPOINT source $NVM_DIR/nvm.sh && npm i && npm test\n"
  },
  {
    "path": "LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2017 Google Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": "README.md",
    "content": "# Comlink\n\nComlink 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.\n\nAt a more abstract level it is an RPC implementation for `postMessage` and [ES6 Proxies][es6 proxy].\n\n```\n$ npm install --save comlink\n```\n\n![Comlink in action](https://user-images.githubusercontent.com/234957/54164510-cdab2d80-4454-11e9-92d0-7356aa6c5746.png)\n\n## Browsers support & bundle size\n\n![Chrome 56+](https://img.shields.io/badge/Chrome-56+-green.svg?style=flat-square)\n![Edge 15+](https://img.shields.io/badge/Edge-15+-green.svg?style=flat-square)\n![Firefox 52+](https://img.shields.io/badge/Firefox-52+-green.svg?style=flat-square)\n![Opera 43+](https://img.shields.io/badge/Opera-43+-green.svg?style=flat-square)\n![Safari 10.1+](https://img.shields.io/badge/Safari-10.1+-green.svg?style=flat-square)\n![Samsung Internet 6.0+](https://img.shields.io/badge/Samsung_Internet-6.0+-green.svg?style=flat-square)\n\nBrowsers without [ES6 Proxy] support can use the [proxy-polyfill].\n\n**Size**: ~2.5k, ~1.2k gzip’d, ~1.1k brotli’d\n\n## Introduction\n\nOn 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.\n\nComlink 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.\n\n## Examples\n\n### [Running a simple function](./docs/examples/01-simple-example)\n\n**main.js**\n\n```javascript\nimport * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\nasync function init() {\n  const worker = new Worker(\"worker.js\");\n  // WebWorkers use `postMessage` and therefore work with Comlink.\n  const obj = Comlink.wrap(worker);\n  alert(`Counter: ${await obj.counter}`);\n  await obj.inc();\n  alert(`Counter: ${await obj.counter}`);\n}\ninit();\n```\n\n**worker.js**\n\n```javascript\nimportScripts(\"https://unpkg.com/comlink/dist/umd/comlink.js\");\n// importScripts(\"../../../dist/umd/comlink.js\");\n\nconst obj = {\n  counter: 0,\n  inc() {\n    this.counter++;\n  },\n};\n\nComlink.expose(obj);\n```\n\n### [Callbacks](./docs/examples/02-callback-example)\n\n**main.js**\n\n```javascript\nimport * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n// import * as Comlink from \"../../../dist/esm/comlink.mjs\";\nfunction callback(value) {\n  alert(`Result: ${value}`);\n}\nasync function init() {\n  const remoteFunction = Comlink.wrap(new Worker(\"worker.js\"));\n  await remoteFunction(Comlink.proxy(callback));\n}\ninit();\n```\n\n**worker.js**\n\n```javascript\nimportScripts(\"https://unpkg.com/comlink/dist/umd/comlink.js\");\n// importScripts(\"../../../dist/umd/comlink.js\");\n\nasync function remoteFunction(cb) {\n  await cb(\"A string from a worker\");\n}\n\nComlink.expose(remoteFunction);\n```\n\n### [`SharedWorker`](./docs/examples/07-sharedworker-example)\n\nWhen using Comlink with a [`SharedWorker`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker) you have to:\n\n1. Use the [`port`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker/port) property, of the `SharedWorker` instance, when calling `Comlink.wrap`.\n2. Call `Comlink.expose` within the [`onconnect`](https://developer.mozilla.org/en-US/docs/Web/API/SharedWorkerGlobalScope/onconnect) callback of the shared worker.\n\n**Pro tip:** You can access DevTools for any shared worker currently running in Chrome by going to: **chrome://inspect/#workers**\n\n**main.js**\n\n```javascript\nimport * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\nasync function init() {\n  const worker = new SharedWorker(\"worker.js\");\n  /**\n   * SharedWorkers communicate via the `postMessage` function in their `port` property.\n   * Therefore you must use the SharedWorker's `port` property when calling `Comlink.wrap`.\n   */\n  const obj = Comlink.wrap(worker.port);\n  alert(`Counter: ${await obj.counter}`);\n  await obj.inc();\n  alert(`Counter: ${await obj.counter}`);\n}\ninit();\n```\n\n**worker.js**\n\n```javascript\nimportScripts(\"https://unpkg.com/comlink/dist/umd/comlink.js\");\n// importScripts(\"../../../dist/umd/comlink.js\");\n\nconst obj = {\n  counter: 0,\n  inc() {\n    this.counter++;\n  },\n};\n\n/**\n * When a connection is made into this shared worker, expose `obj`\n * via the connection `port`.\n */\nonconnect = function (event) {\n  const port = event.ports[0];\n\n  Comlink.expose(obj, port);\n};\n\n// Single line alternative:\n// onconnect = (e) => Comlink.expose(obj, e.ports[0]);\n```\n\n**For additional examples, please see the [docs/examples](./docs/examples) directory in the project.**\n\n## API\n\n### `Comlink.wrap(endpoint)` and `Comlink.expose(value, endpoint?, allowedOrigins?)`\n\nComlink’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\nRegExp or strings defining which origins should be allowed access (defaults to special case of `['*']` for all origins).\n\n`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.\n\n### `Comlink.transfer(value, transferables)` and `Comlink.proxy(value)`\n\nBy 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.\n\nIf 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:\n\n```js\nconst data = new Uint8Array([1, 2, 3, 4, 5]);\nawait myProxy.someFunction(Comlink.transfer(data, [data.buffer]));\n```\n\nLastly, 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.\n\n```js\nmyProxy.onready = Comlink.proxy((data) => {\n  /* ... */\n});\n```\n\n### Transfer handlers and event listeners\n\nIt is common that you want to use Comlink to add an event listener, where the event source is on another thread:\n\n```js\nbutton.addEventListener(\"click\", myProxy.onClick.bind(myProxy));\n```\n\nWhile 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.\n\nEach 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:\n\n```js\nComlink.transferHandlers.set(\"EVENT\", {\n  canHandle: (obj) => obj instanceof Event,\n  serialize: (ev) => {\n    return [\n      {\n        target: {\n          id: ev.target.id,\n          classList: [...ev.target.classList],\n        },\n      },\n      [],\n    ];\n  },\n  deserialize: (obj) => obj,\n});\n```\n\nNote 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.\n\n### `Comlink.releaseProxy`\n\nEvery proxy created by Comlink has the `[releaseProxy]()` method.\nCalling it will detach the proxy and the exposed object from the message channel, allowing both ends to be garbage collected.\n\n```js\nconst proxy = Comlink.wrap(port);\n// ... use the proxy ...\nproxy[Comlink.releaseProxy]();\n```\n\nIf the browser supports the [WeakRef proposal], `[releaseProxy]()` will be called automatically when the proxy created by `wrap()` gets garbage collected.\n\n### `Comlink.finalizer`\n\nIf 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.\n\n### `Comlink.createEndpoint`\n\nEvery proxy created by Comlink has the `[createEndpoint]()` method.\nCalling it will return a new `MessagePort`, that has been hooked up to the same object as the proxy that `[createEndpoint]()` has been called on.\n\n```js\nconst port = myProxy[Comlink.createEndpoint]();\nconst newProxy = Comlink.wrap(port);\n```\n\n### `Comlink.windowEndpoint(window, context = self, targetOrigin = \"*\")`\n\nWindows 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()`.\n\n`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).\n\nFor a usage example, take a look at the non-worker examples in the `docs` folder.\n\n## TypeScript\n\nComlink does provide TypeScript types. When you `expose()` something of type `T`, the corresponding `wrap()` call will return something of type `Comlink.Remote<T>`. 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 <type>`.\n\n## Node\n\nComlink works with Node’s [`worker_threads`][worker_threads] module. Take a look at the example in the `docs` folder.\n\n[webworker]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API\n[umd]: https://github.com/umdjs/umd\n[transferable]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects\n[messageport]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort\n[examples]: https://github.com/GoogleChromeLabs/comlink/tree/master/docs/examples\n[dist]: https://github.com/GoogleChromeLabs/comlink/tree/master/dist\n[delivrjs]: https://cdn.jsdelivr.net/\n[es6 proxy]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy\n[proxy-polyfill]: https://github.com/GoogleChrome/proxy-polyfill\n[endpoint]: src/protocol.ts\n[structured cloning]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\n[structured clone table]: structured-clone-table.md\n[event]: https://developer.mozilla.org/en-US/docs/Web/API/Event\n[worker_threads]: https://nodejs.org/api/worker_threads.html\n[weakref proposal]: https://github.com/tc39/proposal-weakrefs\n\n## Additional Resources\n\n- [Simplify Web Worker code with Comlink](https://davidea.st/articles/comlink-simple-web-worker)\n\n---\n\nLicense Apache-2.0\n"
  },
  {
    "path": "docs/examples/01-simple-example/README.md",
    "content": "This example shows how to setup Comlink between a website and a worker.\n"
  },
  {
    "path": "docs/examples/01-simple-example/index.html",
    "content": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  // import * as Comlink from \"../../../dist/esm/comlink.mjs\";\n\n  async function init() {\n    const worker = new Worker(\"worker.js\");\n    // WebWorkers use `postMessage` and therefore work with Comlink.\n    const obj = Comlink.wrap(worker);\n\n    alert(`Counter: ${await obj.counter}`);\n    await obj.inc();\n    alert(`Counter: ${await obj.counter}`);\n  }\n\n  init();\n</script>\n"
  },
  {
    "path": "docs/examples/01-simple-example/worker.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimportScripts(\"https://unpkg.com/comlink/dist/umd/comlink.js\");\n// importScripts(\"../../../dist/umd/comlink.js\");\n\nconst obj = {\n  counter: 0,\n  inc() {\n    this.counter++;\n  },\n};\n\nComlink.expose(obj);\n"
  },
  {
    "path": "docs/examples/02-callback-example/README.md",
    "content": "This example shows how to pass callbacks.\n"
  },
  {
    "path": "docs/examples/02-callback-example/index.html",
    "content": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  // import * as Comlink from \"../../../dist/esm/comlink.mjs\";\n\n  function callback(value) {\n    alert(`Result: ${value}`);\n  }\n\n  async function init() {\n    const remoteFunction = Comlink.wrap(new Worker(\"worker.js\"));\n    await remoteFunction(Comlink.proxy(callback));\n  }\n\n  init();\n</script>\n"
  },
  {
    "path": "docs/examples/02-callback-example/worker.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimportScripts(\"https://unpkg.com/comlink/dist/umd/comlink.js\");\n// importScripts(\"../../../dist/umd/comlink.js\");\n\nasync function remoteFunction(cb) {\n  await cb(\"A string from a worker\");\n}\n\nComlink.expose(remoteFunction);\n"
  },
  {
    "path": "docs/examples/03-classes-example/README.md",
    "content": "This example shows how to export and use classes.\n"
  },
  {
    "path": "docs/examples/03-classes-example/index.html",
    "content": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  // import * as Comlink from \"../../../dist/esm/comlink.mjs\";\n\n  let instance1, instance2;\n  async function showState() {\n    alert(`instance1.counter = ${await instance1.counter},\n      instance2.counter = ${await instance2.counter}`);\n  }\n\n  async function init() {\n    const MyClass = Comlink.wrap(new Worker(\"worker.js\"));\n    instance1 = await new MyClass();\n    instance2 = await new MyClass(42);\n    await showState();\n    await instance1.increment();\n    await instance2.increment(23);\n    await showState();\n  }\n\n  init();\n</script>\n"
  },
  {
    "path": "docs/examples/03-classes-example/worker.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimportScripts(\"https://unpkg.com/comlink/dist/umd/comlink.js\");\n// importScripts(\"../../../dist/umd/comlink.js\");\n\nclass MyClass {\n  constructor(init = 0) {\n    console.log(init);\n    this._counter = init;\n  }\n\n  get counter() {\n    return this._counter;\n  }\n\n  increment(delta = 1) {\n    this._counter += delta;\n  }\n}\n\nComlink.expose(MyClass);\n"
  },
  {
    "path": "docs/examples/04-eventlistener-example/README.md",
    "content": "This example shows how a simple `TransferHandler` can allow to use remote event listeners or event targets.\n"
  },
  {
    "path": "docs/examples/04-eventlistener-example/event.transferhandler.js",
    "content": "Comlink.transferHandlers.set(\"event\", {\n  canHandle(obj) {\n    return obj instanceof Event;\n  },\n  serialize(obj) {\n    return [\n      {\n        targetId: obj && obj.target && obj.target.id,\n        targetClassList: obj &&\n          obj.target &&\n          obj.target.classList && [...obj.target.classList],\n        detail: obj && obj.detail,\n      },\n      [],\n    ];\n  },\n  deserialize(obj) {\n    return obj;\n  },\n});\n"
  },
  {
    "path": "docs/examples/04-eventlistener-example/index.html",
    "content": "<!DOCTYPE html>\nOpen DevTools and click the button.\n<button id=\"mainbtn\" class=\"btn btn--big\">Click me</button>\n<script src=\"https://unpkg.com/comlink/dist/umd/comlink.js\"></script>\n<!-- <script src=\"../../../dist/umd/comlink.js\"></script> -->\n<script src=\"./event.transferhandler.js\"></script>\n<script>\n  const worker = new Worker(\"worker.js\");\n  const api = Comlink.wrap(worker);\n\n  document\n    .querySelector(\"#mainbtn\")\n    .addEventListener(\"click\", api.onclick.bind(api));\n</script>\n"
  },
  {
    "path": "docs/examples/04-eventlistener-example/worker.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimportScripts(\"https://unpkg.com/comlink/dist/umd/comlink.js\");\n// importScripts(\"../../../dist/umd/comlink.js\");\nimportScripts(\"event.transferhandler.js\");\n\nComlink.expose({\n  onclick(ev) {\n    console.log(\n      `Click! Button id: ${ev.targetId}, Button classes: ${JSON.stringify(\n        ev.targetClassList\n      )}`\n    );\n  },\n});\n"
  },
  {
    "path": "docs/examples/05-serviceworker-example/README.md",
    "content": "This example shows how to setup Comlink between a website and a service worker.\n"
  },
  {
    "path": "docs/examples/05-serviceworker-example/index.html",
    "content": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  // import * as Comlink from \"../../../dist/esm/comlink.mjs\";\n\n  async function initComlink() {\n    const { port1, port2 } = new MessageChannel();\n    const msg = {\n      comlinkInit: true,\n      port: port1,\n    };\n    navigator.serviceWorker.controller.postMessage(msg, [port1]);\n\n    const swProxy = Comlink.wrap(port2);\n    console.log(await swProxy.counter);\n    await swProxy.inc();\n    console.log(await swProxy.counter);\n  }\n\n  if (navigator.serviceWorker.controller) {\n    initComlink();\n  }\n  navigator.serviceWorker.addEventListener(\"controllerchange\", initComlink);\n  navigator.serviceWorker.register(\"worker.js\");\n</script>\n"
  },
  {
    "path": "docs/examples/05-serviceworker-example/worker.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimportScripts(\"https://unpkg.com/comlink/dist/umd/comlink.js\");\n// importScripts(\"../../../dist/umd/comlink.js\");\n\naddEventListener(\"install\", () => skipWaiting());\naddEventListener(\"activate\", () => clients.claim());\n\nconst obj = {\n  counter: 0,\n  inc() {\n    this.counter++;\n  },\n};\n\nself.addEventListener(\"message\", (event) => {\n  if (event.data.comlinkInit) {\n    Comlink.expose(obj, event.data.port);\n    return;\n  }\n});\n"
  },
  {
    "path": "docs/examples/06-node-example/main.mjs",
    "content": "import { Worker } from \"worker_threads\";\nimport * as Comlink from \"../../../dist/esm/comlink.mjs\";\nimport nodeEndpoint from \"../../../dist/esm/node-adapter.mjs\";\n\nasync function init() {\n  const worker = new Worker(\"./worker.mjs\");\n\n  const api = Comlink.wrap(nodeEndpoint(worker));\n  console.log(await api.doMath());\n}\ninit();\n"
  },
  {
    "path": "docs/examples/06-node-example/worker.mjs",
    "content": "import { parentPort } from \"worker_threads\";\nimport * as Comlink from \"../../../dist/esm/comlink.mjs\";\nimport nodeEndpoint from \"../../../dist/esm/node-adapter.mjs\";\n\nconst api = {\n  doMath() {\n    return 4;\n  },\n};\nComlink.expose(api, nodeEndpoint(parentPort));\n"
  },
  {
    "path": "docs/examples/07-sharedworker-example/README.md",
    "content": "This example shows how to setup Comlink between a website and a `SharedWorker`.\n"
  },
  {
    "path": "docs/examples/07-sharedworker-example/index.html",
    "content": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  // import * as Comlink from \"../../../dist/esm/comlink.mjs\";\n\n  async function init() {\n    const worker = new SharedWorker(\"worker.js\");\n    /**\n     * SharedWorkers communicate via the `postMessage` function in their `port` property.\n     * Therefore you must use the SharedWorker's `port` property when calling `Comlink.wrap`.\n     */\n    const obj = Comlink.wrap(worker.port);\n\n    alert(`Counter: ${await obj.counter}`);\n    await obj.inc();\n    alert(`Counter: ${await obj.counter}`);\n  }\n\n  init();\n</script>\n"
  },
  {
    "path": "docs/examples/07-sharedworker-example/worker.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimportScripts(\"https://unpkg.com/comlink/dist/umd/comlink.js\");\n// importScripts(\"../../../dist/umd/comlink.js\");\n\nconst obj = {\n  counter: 0,\n  inc() {\n    this.counter++;\n  },\n};\n\n/**\n * When a connection is made into this shared worker, expose `obj`\n * via the connection `port`.\n */\nonconnect = function (event) {\n  const port = event.ports[0];\n\n  Comlink.expose(obj, port);\n};\n\n// Single line alternative:\n// onconnect = (e) => Comlink.expose(obj, e.ports[0]);\n"
  },
  {
    "path": "docs/examples/99-nonworker-examples/iframes/README.md",
    "content": "This example shows how to set up Comlink between a window and an embedded iframe using `Comlink.windowEndpoint()`.\n"
  },
  {
    "path": "docs/examples/99-nonworker-examples/iframes/iframe.html",
    "content": "<!DOCTYPE html>\n\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  // import * as Comlink from \"../../../../dist/esm/comlink.mjs\";\n  function add(a, b) {\n    return a + b;\n  }\n  Comlink.expose(add, Comlink.windowEndpoint(self.parent));\n</script>\n"
  },
  {
    "path": "docs/examples/99-nonworker-examples/iframes/index.html",
    "content": "<!DOCTYPE html>\n\n<iframe src=\"iframe.html\"></iframe>\n<script type=\"module\">\n  import * as Comlink from \"https://unpkg.com/comlink/dist/esm/comlink.mjs\";\n  // import * as Comlink from \"../../../../dist/esm/comlink.mjs\";\n  async function main() {\n    const ifr = document.querySelector(\"iframe\");\n    await new Promise((resolve) => (ifr.onload = resolve));\n    const f = Comlink.wrap(Comlink.windowEndpoint(ifr.contentWindow));\n    alert(`1 + 3 = ${await f(1, 3)}`);\n  }\n  main();\n</script>\n"
  },
  {
    "path": "docs/index.html",
    "content": "<!DOCTYPE html>\n<meta\n  http-equiv=\"refresh\"\n  content=\"0; https://github.com/GoogleChromeLabs/comlink\"\n/>\n"
  },
  {
    "path": "karma.conf.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nmodule.exports = function (config) {\n  const configuration = {\n    basePath: \"\",\n    frameworks: [\"mocha\", \"chai\", \"detectBrowsers\"],\n    files: [\n      {\n        pattern: \"tests/fixtures/*\",\n        included: false,\n      },\n      {\n        pattern: \"dist/**/*.@(mjs|js)\",\n        included: false,\n      },\n      {\n        pattern: \"tests/*.test.js\",\n        type: \"module\",\n      },\n    ],\n    reporters: [\"progress\"],\n    port: 9876,\n    colors: true,\n    logLevel: config.LOG_INFO,\n    autoWatch: true,\n    singleRun: true,\n    concurrency: Infinity,\n    detectBrowsers: {\n      enabled: true,\n      usePhantomJS: false,\n      preferHeadless: true,\n      postDetection: (availableBrowsers) => {\n        if (process.env.INSIDE_DOCKER) {\n          return [\"DockerChrome\"];\n        } else if (process.env.CHROME_ONLY) {\n          return [\"ChromeHeadless\"];\n        } else {\n          // Filtering SafariTechPreview because I am having\n          // local issues and I have no idea how to fix them.\n          // I know that’s not a good reason to disable tests,\n          // but Safari TP is relatively unimportant.\n          return availableBrowsers.filter(\n            (browser) => browser !== \"SafariTechPreview\"\n          );\n        }\n      },\n    },\n    customLaunchers: {\n      DockerChrome: {\n        base: \"ChromeHeadless\",\n        flags: [\"--no-sandbox\"],\n      },\n    },\n  };\n\n  config.set(configuration);\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"comlink\",\n  \"version\": \"4.4.2\",\n  \"description\": \"Comlink makes WebWorkers enjoyable\",\n  \"main\": \"dist/umd/comlink.js\",\n  \"module\": \"dist/esm/comlink.mjs\",\n  \"types\": \"dist/umd/comlink.d.ts\",\n  \"sideEffects\": false,\n  \"scripts\": {\n    \"build\": \"rollup -c\",\n    \"test:unit\": \"karma start\",\n    \"test:node\": \"mocha ./tests/node/main.mjs\",\n    \"test:types\": \"tsc -p ./tests/tsconfig.json\",\n    \"test:types:watch\": \"npm run test:types -- --watch\",\n    \"test\": \"npm run fmt_test && npm run build && npm run test:types && npm run test:unit && npm run test:node\",\n    \"fmt\": \"prettier --write './*.{mjs,js,ts,md,json,html}' './{src,docs,tests}/{,**/}*.{mjs,js,ts,md,json,html}'\",\n    \"fmt_test\": \"test $(prettier -l './*.{mjs,js,ts,md,json,html}' './{src,docs,tests}/{**/,}*.{mjs,js,ts,md,json,html}' | wc -l) -eq 0\",\n    \"watchtest\": \"CHROME_ONLY=1 karma start --no-single-run\"\n  },\n  \"author\": {\n    \"name\": \"Surma\",\n    \"email\": \"surma@google.com\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/GoogleChromeLabs/comlink.git\"\n  },\n  \"license\": \"Apache-2.0\",\n  \"devDependencies\": {\n    \"@rollup/plugin-terser\": \"0.4.0\",\n    \"@rollup/plugin-typescript\": \"11.0.0\",\n    \"chai\": \"^4.3.7\",\n    \"conditional-type-checks\": \"1.0.6\",\n    \"husky\": \"8.0.3\",\n    \"karma\": \"6.4.1\",\n    \"karma-chai\": \"0.1.0\",\n    \"karma-chrome-launcher\": \"3.1.1\",\n    \"karma-detect-browsers\": \"2.3.3\",\n    \"karma-firefox-launcher\": \"2.1.2\",\n    \"karma-mocha\": \"2.0.1\",\n    \"karma-safari-launcher\": \"1.0.0\",\n    \"karma-safaritechpreview-launcher\": \"2.0.2\",\n    \"mocha\": \"10.2.0\",\n    \"prettier\": \"2.8.3\",\n    \"rimraf\": \"4.1.2\",\n    \"rollup\": \"3.10.1\",\n    \"tslib\": \"2.4.1\",\n    \"typescript\": \"4.9.4\"\n  }\n}\n"
  },
  {
    "path": "renovate.json",
    "content": "{\n  \"extends\": [\":library\"],\n  \"assignees\": [\"surma\"]\n}\n"
  },
  {
    "path": "rollup.config.mjs",
    "content": "import typescript from \"@rollup/plugin-typescript\";\nimport terser from \"@rollup/plugin-terser\";\nimport { sync } from \"rimraf\";\n\nfunction config({ format, minify, input, ext = \"js\" }) {\n  const dir = `dist/${format}/`;\n  const minifierSuffix = minify ? \".min\" : \"\";\n  return {\n    input: `./src/${input}.ts`,\n    output: {\n      name: \"Comlink\",\n      file: `${dir}/${input}${minifierSuffix}.${ext}`,\n      format,\n      sourcemap: true,\n    },\n    plugins: [\n      typescript({\n        tsconfig: \"./tsconfig.json\",\n        compilerOptions: {\n          declaration: true,\n          declarationDir: \".\",\n          sourceMap: true,\n          outDir: \"dist\",\n        },\n      }),\n      minify\n        ? terser({\n            compress: true,\n            mangle: true,\n          })\n        : undefined,\n    ].filter(Boolean),\n  };\n}\n\nsync(\"dist\");\n\nexport default [\n  { input: \"comlink\", format: \"esm\", minify: false, ext: \"mjs\" },\n  { input: \"comlink\", format: \"esm\", minify: true, ext: \"mjs\" },\n  { input: \"comlink\", format: \"esm\", minify: false },\n  { input: \"comlink\", format: \"esm\", minify: true },\n  { input: \"comlink\", format: \"umd\", minify: false },\n  { input: \"comlink\", format: \"umd\", minify: true },\n  { input: \"node-adapter\", format: \"esm\", minify: false, ext: \"mjs\" },\n  { input: \"node-adapter\", format: \"esm\", minify: true, ext: \"mjs\" },\n  { input: \"node-adapter\", format: \"umd\", minify: false },\n  { input: \"node-adapter\", format: \"umd\", minify: true },\n].map(config);\n"
  },
  {
    "path": "src/comlink.ts",
    "content": "/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n  Endpoint,\n  EventSource,\n  Message,\n  MessageType,\n  PostMessageWithOrigin,\n  WireValue,\n  WireValueType,\n} from \"./protocol\";\nexport type { Endpoint };\n\nexport const proxyMarker = Symbol(\"Comlink.proxy\");\nexport const createEndpoint = Symbol(\"Comlink.endpoint\");\nexport const releaseProxy = Symbol(\"Comlink.releaseProxy\");\nexport const finalizer = Symbol(\"Comlink.finalizer\");\n\nconst throwMarker = Symbol(\"Comlink.thrown\");\n\n/**\n * Interface of values that were marked to be proxied with `comlink.proxy()`.\n * Can also be implemented by classes.\n */\nexport interface ProxyMarked {\n  [proxyMarker]: true;\n}\n\n/**\n * Takes a type and wraps it in a Promise, if it not already is one.\n * This is to avoid `Promise<Promise<T>>`.\n *\n * This is the inverse of `Unpromisify<T>`.\n */\ntype Promisify<T> = T extends Promise<unknown> ? T : Promise<T>;\n/**\n * Takes a type that may be Promise and unwraps the Promise type.\n * If `P` is not a Promise, it returns `P`.\n *\n * This is the inverse of `Promisify<T>`.\n */\ntype Unpromisify<P> = P extends Promise<infer T> ? T : P;\n\n/**\n * Takes the raw type of a remote property and returns the type that is visible to the local thread on the proxy.\n *\n * Note: This needs to be its own type alias, otherwise it will not distribute over unions.\n * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types\n */\ntype RemoteProperty<T> =\n  // If the value is a method, comlink will proxy it automatically.\n  // Objects are only proxied if they are marked to be proxied.\n  // Otherwise, the property is converted to a Promise that resolves the cloned value.\n  T extends Function | ProxyMarked ? Remote<T> : Promisify<T>;\n\n/**\n * 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\n * argument) and returns the type that the local thread has to supply.\n *\n * This is the inverse of `RemoteProperty<T>`.\n *\n * Note: This needs to be its own type alias, otherwise it will not distribute over unions. See\n * https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types\n */\ntype LocalProperty<T> = T extends Function | ProxyMarked\n  ? Local<T>\n  : Unpromisify<T>;\n\n/**\n * Proxies `T` if it is a `ProxyMarked`, clones it otherwise (as handled by structured cloning and transfer handlers).\n */\nexport type ProxyOrClone<T> = T extends ProxyMarked ? Remote<T> : T;\n/**\n * Inverse of `ProxyOrClone<T>`.\n */\nexport type UnproxyOrClone<T> = T extends RemoteObject<ProxyMarked>\n  ? Local<T>\n  : T;\n\n/**\n * Takes the raw type of a remote object in the other thread and returns the type as it is visible to the local thread\n * when proxied with `Comlink.proxy()`.\n *\n * This does not handle call signatures, which is handled by the more general `Remote<T>` type.\n *\n * @template T The raw type of a remote object as seen in the other thread.\n */\nexport type RemoteObject<T> = { [P in keyof T]: RemoteProperty<T[P]> };\n/**\n * Takes the type of an object as a remote thread would see it through a proxy (e.g. when passed in as a function\n * argument) and returns the type that the local thread has to supply.\n *\n * This does not handle call signatures, which is handled by the more general `Local<T>` type.\n *\n * This is the inverse of `RemoteObject<T>`.\n *\n * @template T The type of a proxied object.\n */\nexport type LocalObject<T> = { [P in keyof T]: LocalProperty<T[P]> };\n\n/**\n * Additional special comlink methods available on each proxy returned by `Comlink.wrap()`.\n */\nexport interface ProxyMethods {\n  [createEndpoint]: () => Promise<MessagePort>;\n  [releaseProxy]: () => void;\n}\n\n/**\n * Takes the raw type of a remote object, function or class in the other thread and returns the type as it is visible to\n * the local thread from the proxy return value of `Comlink.wrap()` or `Comlink.proxy()`.\n */\nexport type Remote<T> =\n  // Handle properties\n  RemoteObject<T> &\n    // Handle call signature (if present)\n    (T extends (...args: infer TArguments) => infer TReturn\n      ? (\n          ...args: { [I in keyof TArguments]: UnproxyOrClone<TArguments[I]> }\n        ) => Promisify<ProxyOrClone<Unpromisify<TReturn>>>\n      : unknown) &\n    // Handle construct signature (if present)\n    // The return of construct signatures is always proxied (whether marked or not)\n    (T extends { new (...args: infer TArguments): infer TInstance }\n      ? {\n          new (\n            ...args: {\n              [I in keyof TArguments]: UnproxyOrClone<TArguments[I]>;\n            }\n          ): Promisify<Remote<TInstance>>;\n        }\n      : unknown) &\n    // Include additional special comlink methods available on the proxy.\n    ProxyMethods;\n\n/**\n * Expresses that a type can be either a sync or async.\n */\ntype MaybePromise<T> = Promise<T> | T;\n\n/**\n * Takes the raw type of a remote object, function or class as a remote thread would see it through a proxy (e.g. when\n * passed in as a function argument) and returns the type the local thread has to supply.\n *\n * This is the inverse of `Remote<T>`. It takes a `Remote<T>` and returns its original input `T`.\n */\nexport type Local<T> =\n  // Omit the special proxy methods (they don't need to be supplied, comlink adds them)\n  Omit<LocalObject<T>, keyof ProxyMethods> &\n    // Handle call signatures (if present)\n    (T extends (...args: infer TArguments) => infer TReturn\n      ? (\n          ...args: { [I in keyof TArguments]: ProxyOrClone<TArguments[I]> }\n        ) => // The raw function could either be sync or async, but is always proxied automatically\n        MaybePromise<UnproxyOrClone<Unpromisify<TReturn>>>\n      : unknown) &\n    // Handle construct signature (if present)\n    // The return of construct signatures is always proxied (whether marked or not)\n    (T extends { new (...args: infer TArguments): infer TInstance }\n      ? {\n          new (\n            ...args: {\n              [I in keyof TArguments]: ProxyOrClone<TArguments[I]>;\n            }\n          ): // The raw constructor could either be sync or async, but is always proxied automatically\n          MaybePromise<Local<Unpromisify<TInstance>>>;\n        }\n      : unknown);\n\nconst isObject = (val: unknown): val is object =>\n  (typeof val === \"object\" && val !== null) || typeof val === \"function\";\n\n/**\n * Customizes the serialization of certain values as determined by `canHandle()`.\n *\n * @template T The input type being handled by this transfer handler.\n * @template S The serialized type sent over the wire.\n */\nexport interface TransferHandler<T, S> {\n  /**\n   * Gets called for every value to determine whether this transfer handler\n   * should serialize the value, which includes checking that it is of the right\n   * type (but can perform checks beyond that as well).\n   */\n  canHandle(value: unknown): value is T;\n\n  /**\n   * Gets called with the value if `canHandle()` returned `true` to produce a\n   * value that can be sent in a message, consisting of structured-cloneable\n   * values and/or transferrable objects.\n   */\n  serialize(value: T): [S, Transferable[]];\n\n  /**\n   * Gets called to deserialize an incoming value that was serialized in the\n   * other thread with this transfer handler (known through the name it was\n   * registered under).\n   */\n  deserialize(value: S): T;\n}\n\n/**\n * Internal transfer handle to handle objects marked to proxy.\n */\nconst proxyTransferHandler: TransferHandler<object, MessagePort> = {\n  canHandle: (val): val is ProxyMarked =>\n    isObject(val) && (val as ProxyMarked)[proxyMarker],\n  serialize(obj) {\n    const { port1, port2 } = new MessageChannel();\n    expose(obj, port1);\n    return [port2, [port2]];\n  },\n  deserialize(port) {\n    port.start();\n    return wrap(port);\n  },\n};\n\ninterface ThrownValue {\n  [throwMarker]: unknown; // just needs to be present\n  value: unknown;\n}\ntype SerializedThrownValue =\n  | { isError: true; value: Error }\n  | { isError: false; value: unknown };\ntype PendingListenersMap = Map<\n  string,\n  (value: WireValue | PromiseLike<WireValue>) => void\n>;\ntype EndpointWithPendingListeners = {\n  endpoint: Endpoint;\n  pendingListeners: PendingListenersMap;\n};\n\n/**\n * Internal transfer handler to handle thrown exceptions.\n */\nconst throwTransferHandler: TransferHandler<\n  ThrownValue,\n  SerializedThrownValue\n> = {\n  canHandle: (value): value is ThrownValue =>\n    isObject(value) && throwMarker in value,\n  serialize({ value }) {\n    let serialized: SerializedThrownValue;\n    if (value instanceof Error) {\n      serialized = {\n        isError: true,\n        value: {\n          message: value.message,\n          name: value.name,\n          stack: value.stack,\n        },\n      };\n    } else {\n      serialized = { isError: false, value };\n    }\n    return [serialized, []];\n  },\n  deserialize(serialized) {\n    if (serialized.isError) {\n      throw Object.assign(\n        new Error(serialized.value.message),\n        serialized.value\n      );\n    }\n    throw serialized.value;\n  },\n};\n\n/**\n * Allows customizing the serialization of certain values.\n */\nexport const transferHandlers = new Map<\n  string,\n  TransferHandler<unknown, unknown>\n>([\n  [\"proxy\", proxyTransferHandler],\n  [\"throw\", throwTransferHandler],\n]);\n\nfunction isAllowedOrigin(\n  allowedOrigins: (string | RegExp)[],\n  origin: string\n): boolean {\n  for (const allowedOrigin of allowedOrigins) {\n    if (origin === allowedOrigin || allowedOrigin === \"*\") {\n      return true;\n    }\n    if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nexport function expose(\n  obj: any,\n  ep: Endpoint = globalThis as any,\n  allowedOrigins: (string | RegExp)[] = [\"*\"]\n) {\n  ep.addEventListener(\"message\", function callback(ev: MessageEvent) {\n    if (!ev || !ev.data) {\n      return;\n    }\n    if (!isAllowedOrigin(allowedOrigins, ev.origin)) {\n      console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);\n      return;\n    }\n    const { id, type, path } = {\n      path: [] as string[],\n      ...(ev.data as Message),\n    };\n    const argumentList = (ev.data.argumentList || []).map(fromWireValue);\n    let returnValue;\n    try {\n      const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);\n      const rawValue = path.reduce((obj, prop) => obj[prop], obj);\n      switch (type) {\n        case MessageType.GET:\n          {\n            returnValue = rawValue;\n          }\n          break;\n        case MessageType.SET:\n          {\n            parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);\n            returnValue = true;\n          }\n          break;\n        case MessageType.APPLY:\n          {\n            returnValue = rawValue.apply(parent, argumentList);\n          }\n          break;\n        case MessageType.CONSTRUCT:\n          {\n            const value = new rawValue(...argumentList);\n            returnValue = proxy(value);\n          }\n          break;\n        case MessageType.ENDPOINT:\n          {\n            const { port1, port2 } = new MessageChannel();\n            expose(obj, port2);\n            returnValue = transfer(port1, [port1]);\n          }\n          break;\n        case MessageType.RELEASE:\n          {\n            returnValue = undefined;\n          }\n          break;\n        default:\n          return;\n      }\n    } catch (value) {\n      returnValue = { value, [throwMarker]: 0 };\n    }\n    Promise.resolve(returnValue)\n      .catch((value) => {\n        return { value, [throwMarker]: 0 };\n      })\n      .then((returnValue) => {\n        const [wireValue, transferables] = toWireValue(returnValue);\n        ep.postMessage({ ...wireValue, id }, transferables);\n        if (type === MessageType.RELEASE) {\n          // detach and deactive after sending release response above.\n          ep.removeEventListener(\"message\", callback as any);\n          closeEndPoint(ep);\n          if (finalizer in obj && typeof obj[finalizer] === \"function\") {\n            obj[finalizer]();\n          }\n        }\n      })\n      .catch((error) => {\n        // Send Serialization Error To Caller\n        const [wireValue, transferables] = toWireValue({\n          value: new TypeError(\"Unserializable return value\"),\n          [throwMarker]: 0,\n        });\n        ep.postMessage({ ...wireValue, id }, transferables);\n      });\n  } as any);\n  if (ep.start) {\n    ep.start();\n  }\n}\n\nfunction isMessagePort(endpoint: Endpoint): endpoint is MessagePort {\n  return endpoint.constructor.name === \"MessagePort\";\n}\n\nfunction closeEndPoint(endpoint: Endpoint) {\n  if (isMessagePort(endpoint)) endpoint.close();\n}\n\nexport function wrap<T>(ep: Endpoint, target?: any): Remote<T> {\n  const pendingListeners : PendingListenersMap = new Map();\n\n  ep.addEventListener(\"message\", function handleMessage(ev: Event) {\n    const { data } = ev as MessageEvent;\n    if (!data || !data.id) {\n      return;\n    }\n    const resolver = pendingListeners.get(data.id);\n    if (!resolver) {\n      return;\n    }\n\n    try {\n      resolver(data);\n    } finally {\n      pendingListeners.delete(data.id);\n    }\n  });\n\n  return createProxy<T>({ endpoint: ep, pendingListeners }, [], target) as any;\n}\n\nfunction throwIfProxyReleased(isReleased: boolean) {\n  if (isReleased) {\n    throw new Error(\"Proxy has been released and is not useable\");\n  }\n}\n\nfunction releaseEndpoint(epWithPendingListeners: EndpointWithPendingListeners) {\n  return requestResponseMessage(epWithPendingListeners, {\n    type: MessageType.RELEASE,\n  }).then(() => {\n    closeEndPoint(epWithPendingListeners.endpoint);\n  });\n}\n\ninterface FinalizationRegistry<T> {\n  new (cb: (heldValue: T) => void): FinalizationRegistry<T>;\n  register(\n    weakItem: object,\n    heldValue: T,\n    unregisterToken?: object | undefined\n  ): void;\n  unregister(unregisterToken: object): void;\n}\ndeclare var FinalizationRegistry: FinalizationRegistry<EndpointWithPendingListeners>;\n\nconst proxyCounter = new WeakMap<EndpointWithPendingListeners, number>();\nconst proxyFinalizers =\n  \"FinalizationRegistry\" in globalThis &&\n  new FinalizationRegistry(\n    (epWithPendingListeners: EndpointWithPendingListeners) => {\n      const newCount = (proxyCounter.get(epWithPendingListeners) || 0) - 1;\n      proxyCounter.set(epWithPendingListeners, newCount);\n      if (newCount === 0) {\n        releaseEndpoint(epWithPendingListeners).finally(() => {\n          epWithPendingListeners.pendingListeners.clear();\n        });\n      }\n    }\n  );\n\nfunction registerProxy(\n  proxy: object,\n  epWithPendingListeners: EndpointWithPendingListeners\n) {\n  const newCount = (proxyCounter.get(epWithPendingListeners) || 0) + 1;\n  proxyCounter.set(epWithPendingListeners, newCount);\n  if (proxyFinalizers) {\n    proxyFinalizers.register(proxy, epWithPendingListeners, proxy);\n  }\n}\n\nfunction unregisterProxy(proxy: object) {\n  if (proxyFinalizers) {\n    proxyFinalizers.unregister(proxy);\n  }\n}\n\nfunction createProxy<T>(\n  epWithPendingListeners: EndpointWithPendingListeners,\n  path: (string | number | symbol)[] = [],\n  target: object = function () {}\n): Remote<T> {\n  let isProxyReleased = false;\n  const proxy = new Proxy(target, {\n    get(_target, prop) {\n      throwIfProxyReleased(isProxyReleased);\n      if (prop === releaseProxy) {\n        return () => {\n          unregisterProxy(proxy);\n          releaseEndpoint(epWithPendingListeners).finally(() => {\n            epWithPendingListeners.pendingListeners.clear();\n          });\n          isProxyReleased = true;\n        };\n      }\n      if (prop === \"then\") {\n        if (path.length === 0) {\n          return { then: () => proxy };\n        }\n        const r = requestResponseMessage(epWithPendingListeners, {\n          type: MessageType.GET,\n          path: path.map((p) => p.toString()),\n        }).then(fromWireValue);\n        return r.then.bind(r);\n      }\n      return createProxy(epWithPendingListeners, [...path, prop]);\n    },\n    set(_target, prop, rawValue) {\n      throwIfProxyReleased(isProxyReleased);\n      // FIXME: ES6 Proxy Handler `set` methods are supposed to return a\n      // boolean. To show good will, we return true asynchronously ¯\\_(ツ)_/¯\n      const [value, transferables] = toWireValue(rawValue);\n      return requestResponseMessage(\n        epWithPendingListeners,\n        {\n          type: MessageType.SET,\n          path: [...path, prop].map((p) => p.toString()),\n          value,\n        },\n        transferables\n      ).then(fromWireValue) as any;\n    },\n    apply(_target, _thisArg, rawArgumentList) {\n      throwIfProxyReleased(isProxyReleased);\n      const last = path[path.length - 1];\n      if ((last as any) === createEndpoint) {\n        return requestResponseMessage(epWithPendingListeners, {\n          type: MessageType.ENDPOINT,\n        }).then(fromWireValue);\n      }\n      // We just pretend that `bind()` didn’t happen.\n      if (last === \"bind\") {\n        return createProxy(epWithPendingListeners, path.slice(0, -1));\n      }\n      const [argumentList, transferables] = processArguments(rawArgumentList);\n      return requestResponseMessage(\n        epWithPendingListeners,\n        {\n          type: MessageType.APPLY,\n          path: path.map((p) => p.toString()),\n          argumentList,\n        },\n        transferables\n      ).then(fromWireValue);\n    },\n    construct(_target, rawArgumentList) {\n      throwIfProxyReleased(isProxyReleased);\n      const [argumentList, transferables] = processArguments(rawArgumentList);\n      return requestResponseMessage(\n        epWithPendingListeners,\n        {\n          type: MessageType.CONSTRUCT,\n          path: path.map((p) => p.toString()),\n          argumentList,\n        },\n        transferables\n      ).then(fromWireValue);\n    },\n  });\n  registerProxy(proxy, epWithPendingListeners);\n  return proxy as any;\n}\n\nfunction myFlat<T>(arr: (T | T[])[]): T[] {\n  return Array.prototype.concat.apply([], arr);\n}\n\nfunction processArguments(argumentList: any[]): [WireValue[], Transferable[]] {\n  const processed = argumentList.map(toWireValue);\n  return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];\n}\n\nconst transferCache = new WeakMap<any, Transferable[]>();\nexport function transfer<T>(obj: T, transfers: Transferable[]): T {\n  transferCache.set(obj, transfers);\n  return obj;\n}\n\nexport function proxy<T extends {}>(obj: T): T & ProxyMarked {\n  return Object.assign(obj, { [proxyMarker]: true }) as any;\n}\n\nexport function windowEndpoint(\n  w: PostMessageWithOrigin,\n  context: EventSource = globalThis,\n  targetOrigin = \"*\"\n): Endpoint {\n  return {\n    postMessage: (msg: any, transferables: Transferable[]) =>\n      w.postMessage(msg, targetOrigin, transferables),\n    addEventListener: context.addEventListener.bind(context),\n    removeEventListener: context.removeEventListener.bind(context),\n  };\n}\n\nfunction toWireValue(value: any): [WireValue, Transferable[]] {\n  for (const [name, handler] of transferHandlers) {\n    if (handler.canHandle(value)) {\n      const [serializedValue, transferables] = handler.serialize(value);\n      return [\n        {\n          type: WireValueType.HANDLER,\n          name,\n          value: serializedValue,\n        },\n        transferables,\n      ];\n    }\n  }\n  return [\n    {\n      type: WireValueType.RAW,\n      value,\n    },\n    transferCache.get(value) || [],\n  ];\n}\n\nfunction fromWireValue(value: WireValue): any {\n  switch (value.type) {\n    case WireValueType.HANDLER:\n      return transferHandlers.get(value.name)!.deserialize(value.value);\n    case WireValueType.RAW:\n      return value.value;\n  }\n}\n\nfunction requestResponseMessage(\n  epWithPendingListeners: EndpointWithPendingListeners,\n  msg: Message,\n  transfers?: Transferable[]\n): Promise<WireValue> {\n  const ep = epWithPendingListeners.endpoint;\n  const pendingListeners = epWithPendingListeners.pendingListeners;\n  return new Promise((resolve) => {\n    const id = generateUUID();\n    pendingListeners.set(id, resolve);\n    if (ep.start) {\n      ep.start();\n    }\n    ep.postMessage({ id, ...msg }, transfers);\n});\n}\n\nfunction generateUUID(): string {\n  return new Array(4)\n    .fill(0)\n    .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))\n    .join(\"-\");\n}\n"
  },
  {
    "path": "src/node-adapter.ts",
    "content": "/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Endpoint } from \"./protocol\";\n\nexport interface NodeEndpoint {\n  postMessage(message: any, transfer?: any[]): void;\n  on(\n    type: string,\n    listener: EventListenerOrEventListenerObject,\n    options?: {}\n  ): void;\n  off(\n    type: string,\n    listener: EventListenerOrEventListenerObject,\n    options?: {}\n  ): void;\n  start?: () => void;\n}\n\nexport default function nodeEndpoint(nep: NodeEndpoint): Endpoint {\n  const listeners = new WeakMap();\n  return {\n    postMessage: nep.postMessage.bind(nep),\n    addEventListener: (_, eh) => {\n      const l = (data: any) => {\n        if (\"handleEvent\" in eh) {\n          eh.handleEvent({ data } as MessageEvent);\n        } else {\n          eh({ data } as MessageEvent);\n        }\n      };\n      nep.on(\"message\", l);\n      listeners.set(eh, l);\n    },\n    removeEventListener: (_, eh) => {\n      const l = listeners.get(eh);\n      if (!l) {\n        return;\n      }\n      nep.off(\"message\", l);\n      listeners.delete(eh);\n    },\n    start: nep.start && nep.start.bind(nep),\n  };\n}\n"
  },
  {
    "path": "src/protocol.ts",
    "content": "/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface EventSource {\n  addEventListener(\n    type: string,\n    listener: EventListenerOrEventListenerObject,\n    options?: {}\n  ): void;\n\n  removeEventListener(\n    type: string,\n    listener: EventListenerOrEventListenerObject,\n    options?: {}\n  ): void;\n}\n\nexport interface PostMessageWithOrigin {\n  postMessage(\n    message: any,\n    targetOrigin: string,\n    transfer?: Transferable[]\n  ): void;\n}\n\nexport interface Endpoint extends EventSource {\n  postMessage(message: any, transfer?: Transferable[]): void;\n\n  start?: () => void;\n}\n\nexport const enum WireValueType {\n  RAW = \"RAW\",\n  PROXY = \"PROXY\",\n  THROW = \"THROW\",\n  HANDLER = \"HANDLER\",\n}\n\nexport interface RawWireValue {\n  id?: string;\n  type: WireValueType.RAW;\n  value: {};\n}\n\nexport interface HandlerWireValue {\n  id?: string;\n  type: WireValueType.HANDLER;\n  name: string;\n  value: unknown;\n}\n\nexport type WireValue = RawWireValue | HandlerWireValue;\n\nexport type MessageID = string;\n\nexport const enum MessageType {\n  GET = \"GET\",\n  SET = \"SET\",\n  APPLY = \"APPLY\",\n  CONSTRUCT = \"CONSTRUCT\",\n  ENDPOINT = \"ENDPOINT\",\n  RELEASE = \"RELEASE\",\n}\n\nexport interface GetMessage {\n  id?: MessageID;\n  type: MessageType.GET;\n  path: string[];\n}\n\nexport interface SetMessage {\n  id?: MessageID;\n  type: MessageType.SET;\n  path: string[];\n  value: WireValue;\n}\n\nexport interface ApplyMessage {\n  id?: MessageID;\n  type: MessageType.APPLY;\n  path: string[];\n  argumentList: WireValue[];\n}\n\nexport interface ConstructMessage {\n  id?: MessageID;\n  type: MessageType.CONSTRUCT;\n  path: string[];\n  argumentList: WireValue[];\n}\n\nexport interface EndpointMessage {\n  id?: MessageID;\n  type: MessageType.ENDPOINT;\n}\n\nexport interface ReleaseMessage {\n  id?: MessageID;\n  type: MessageType.RELEASE;\n}\n\nexport type Message =\n  | GetMessage\n  | SetMessage\n  | ApplyMessage\n  | ConstructMessage\n  | EndpointMessage\n  | ReleaseMessage;\n"
  },
  {
    "path": "structured-clone-table.md",
    "content": "# Behavior of [Structured Clone]\n\n[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.\n\n| Input                      |     Output     | Notes                                                                                        |\n| -------------------------- | :------------: | -------------------------------------------------------------------------------------------- |\n| `[1,2,3]`                  |   `[1,2,3]`    | Full copy                                                                                    |\n| `{a: 1, b: 2}`             | `{a: 1, b: 2}` | Full copy                                                                                    |\n| `{a: 1, b() { return 2; }` |    `{a: 1}`    | Full copy, functions omitted                                                                 |\n| `new MyClass()`            |    `{...}`     | Just the properties                                                                          |\n| `Map`                      |     `Map`      | [`Map`][map] is structured cloneable                                                         |\n| `Set`                      |     `Set`      | [`Set`][set] is structured cloneable                                                         |\n| `ArrayBuffer`              | `ArrayBuffer`  | [`ArrayBuffer`][arraybuffer] is structured cloneable                                         |\n| `Uint32Array`              | `Uint32Array`  | [`Uint32Array`][uint32array] and all the other typed arrays are structured cloneable         |\n| `Event`                    |       ❌       |                                                                                              |\n| Any DOM element            |       ❌       |                                                                                              |\n| `MessagePort`              |       ❌       | Only transferable, not structured cloneable                                                  |\n| `Request`                  |       ❌       |                                                                                              |\n| `Response`                 |       ❌       |                                                                                              |\n| `ReadableStream`           |       ❌       | [Streams are planned to be transferable][transferable streams], but not structured cloneable |\n\n[structured clone]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\n[map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\n[set]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\n[arraybuffer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer\n[uint32array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array\n[transferable streams]: https://github.com/whatwg/streams/blob/master/transferable-streams-explainer.md\n"
  },
  {
    "path": "tests/cross-origin.comlink.test.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Comlink from \"/base/dist/esm/comlink.mjs\";\n\ndescribe(\"Comlink origin filtering\", function () {\n  it(\"rejects messages from unknown origin\", async function () {\n    // expose on our window so comlink is listening to window postmessage\n    const obj = { my: \"value\" };\n    Comlink.expose(obj, self, [/^http:\\/\\/localhost(:[0-9]+)?\\/?$/]);\n\n    let handler;\n    // juggle async timings to get the attack started\n    const attackComplete = new Promise((resolve, reject) => {\n      handler = (ev) => {\n        if (ev.data === \"ready\" && ev.origin === \"null\") {\n          // tell the iframe it can start the attack\n          ifr.contentWindow.postMessage(\"start\", \"*\");\n        } else if (ev.data === \"done\") {\n          // confirm the attack failed, the prototype was not updated\n          expect(Object.prototype.foo).to.be.undefined;\n          expect(obj.my).to.equal(\"value\");\n          resolve();\n        }\n      };\n      window.addEventListener(\"message\", handler);\n    });\n    // create a sandboxed iframe for the attack\n    const ifr = document.createElement(\"iframe\");\n    ifr.sandbox.add(\"allow-scripts\");\n    ifr.src = \"/base/tests/fixtures/attack-iframe.html\";\n    document.body.appendChild(ifr);\n    // wait for the iframe to load\n    await new Promise((resolve) => (ifr.onload = resolve));\n    // and wait for the attack to complete\n    await attackComplete;\n    window.removeEventListener(\"message\", handler);\n    ifr.remove();\n  });\n  it(\"accepts messages from matching origin\", async function () {\n    // expose on our window so comlink is listening to window postmessage\n    const obj = { my: \"value\" };\n    Comlink.expose(obj, self, [/^http:\\/\\/localhost(:[0-9]+)?\\/?$/]);\n\n    let handler;\n    // juggle async timings to get the attack started\n    const attackComplete = new Promise((resolve, reject) => {\n      handler = (ev) => {\n        if (ev.data === \"ready\" && ev.origin === window.origin) {\n          // tell the iframe it can start the attack\n          ifr.contentWindow.postMessage(\"start\", \"*\");\n        } else if (ev.data === \"done\") {\n          // confirm the attack succeeded, the prototype was updated\n          expect(Object.prototype.foo).to.equal(\"x\");\n          expect(obj.my).to.equal(\"value\");\n          resolve();\n        }\n      };\n      window.addEventListener(\"message\", handler);\n    });\n    // create a sandboxed iframe for the attack, but with same origin\n    const ifr = document.createElement(\"iframe\");\n    ifr.sandbox.add(\"allow-scripts\", \"allow-same-origin\");\n    ifr.src = \"/base/tests/fixtures/attack-iframe.html\";\n    document.body.appendChild(ifr);\n    // wait for the iframe to load\n    await new Promise((resolve) => (ifr.onload = resolve));\n    // and wait for the attack to complete\n    await attackComplete;\n    window.removeEventListener(\"message\", handler);\n    ifr.remove();\n  });\n});\n"
  },
  {
    "path": "tests/fixtures/attack-iframe.html",
    "content": "<html>\n  <body>\n    <script>\n      window.addEventListener(\"message\", (ev) => {\n        if (ev.data === \"start\") {\n          // send back a message to modify the prototype\n          parent.postMessage(\n            {\n              type: \"SET\",\n              value: { type: \"RAW\", value: \"x\" },\n              path: [\"__proto__\", \"foo\"],\n            },\n            \"*\"\n          );\n          parent.postMessage(\"done\", \"*\");\n        }\n      });\n      parent.postMessage(\"ready\", \"*\");\n    </script>\n  </body>\n</html>\n"
  },
  {
    "path": "tests/fixtures/iframe.html",
    "content": "<script type=\"module\">\n  import * as Comlink from \"/base/dist/esm/comlink.mjs\";\n\n  Comlink.expose((a, b) => a + b, Comlink.windowEndpoint(self.parent));\n</script>\n"
  },
  {
    "path": "tests/fixtures/two-way-iframe.html",
    "content": "<script type=\"module\">\n  import * as Comlink from \"/base/dist/esm/comlink.mjs\";\n\n  const parentEndpoint = Comlink.windowEndpoint(self.parent);\n  const wrappedParent = Comlink.wrap(parentEndpoint);\n\n  Comlink.expose(async (a, b) => {\n    return a + (await wrappedParent(b));\n  }, parentEndpoint);\n</script>\n"
  },
  {
    "path": "tests/fixtures/worker.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimportScripts(\"/base/dist/umd/comlink.js\");\n\nComlink.expose((a, b) => a + b);\n"
  },
  {
    "path": "tests/iframe.comlink.test.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Comlink from \"/base/dist/esm/comlink.mjs\";\n\ndescribe(\"Comlink across iframes\", function () {\n  beforeEach(function () {\n    this.ifr = document.createElement(\"iframe\");\n    this.ifr.sandbox.add(\"allow-scripts\", \"allow-same-origin\");\n    this.ifr.src = \"/base/tests/fixtures/iframe.html\";\n    document.body.appendChild(this.ifr);\n    return new Promise((resolve) => (this.ifr.onload = resolve));\n  });\n\n  afterEach(function () {\n    this.ifr.remove();\n  });\n\n  it(\"can communicate\", async function () {\n    const proxy = Comlink.wrap(Comlink.windowEndpoint(this.ifr.contentWindow));\n    expect(await proxy(1, 3)).to.equal(4);\n  });\n});\n"
  },
  {
    "path": "tests/node/main.mjs",
    "content": "import { Worker } from \"worker_threads\";\nimport * as Comlink from \"../../dist/esm/comlink.mjs\";\nimport nodeEndpoint from \"../../dist/esm/node-adapter.mjs\";\nimport { expect } from \"chai\";\n\ndescribe(\"node\", () => {\n  describe(\"Comlink across workers\", function () {\n    beforeEach(function () {\n      this.worker = new Worker(\"./tests/node/worker.mjs\");\n    });\n\n    afterEach(function () {\n      this.worker.terminate();\n    });\n\n    it(\"can communicate\", async function () {\n      const proxy = Comlink.wrap(nodeEndpoint(this.worker));\n      expect(await proxy(1, 3)).to.equal(4);\n    });\n\n    it(\"can tunnels a new endpoint with createEndpoint\", async function () {\n      const proxy = Comlink.wrap(nodeEndpoint(this.worker));\n      const otherEp = await proxy[Comlink.createEndpoint]();\n      const otherProxy = Comlink.wrap(otherEp);\n      expect(await otherProxy(20, 1)).to.equal(21);\n    });\n\n    it(\"releaseProxy closes MessagePort created by createEndpoint\", async function () {\n      const proxy = Comlink.wrap(nodeEndpoint(this.worker));\n      const otherEp = await proxy[Comlink.createEndpoint]();\n      const otherProxy = Comlink.wrap(otherEp);\n      expect(await otherProxy(20, 1)).to.equal(21);\n\n      await new Promise((resolve) => {\n        otherEp.close = resolve; // Resolve the promise when the MessagePort is closed.\n        otherProxy[Comlink.releaseProxy](); // Release the proxy, which should close the MessagePort.\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "tests/node/worker.mjs",
    "content": "import { parentPort } from \"worker_threads\";\nimport * as Comlink from \"../../dist/esm/comlink.mjs\";\nimport nodeEndpoint from \"../../dist/esm/node-adapter.mjs\";\n\nComlink.expose((a, b) => a + b, nodeEndpoint(parentPort));\n"
  },
  {
    "path": "tests/same_window.comlink.test.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Comlink from \"/base/dist/esm/comlink.mjs\";\n\nclass SampleClass {\n  constructor(counterInit = 1) {\n    this._counter = counterInit;\n    this._promise = Promise.resolve(4);\n  }\n\n  static get SOME_NUMBER() {\n    return 4;\n  }\n\n  static ADD(a, b) {\n    return a + b;\n  }\n\n  get counter() {\n    return this._counter;\n  }\n\n  set counter(value) {\n    this._counter = value;\n  }\n\n  get promise() {\n    return this._promise;\n  }\n\n  method() {\n    return 4;\n  }\n\n  increaseCounter(delta = 1) {\n    this._counter += delta;\n  }\n\n  promiseFunc() {\n    return new Promise((resolve) => setTimeout((_) => resolve(4), 100));\n  }\n\n  proxyFunc() {\n    return Comlink.proxy({\n      counter: 0,\n      inc() {\n        this.counter++;\n      },\n    });\n  }\n\n  throwsAnError() {\n    throw Error(\"OMG\");\n  }\n}\n\ndescribe(\"Comlink in the same realm\", function () {\n  beforeEach(function () {\n    const { port1, port2 } = new MessageChannel();\n    port1.start();\n    port2.start();\n    this.port1 = port1;\n    this.port2 = port2;\n  });\n\n  it(\"can work with objects\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose({ value: 4 }, this.port2);\n    expect(await thing.value).to.equal(4);\n  });\n\n  it(\"can work with functions on an object\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose({ f: (_) => 4 }, this.port2);\n    expect(await thing.f()).to.equal(4);\n  });\n\n  it(\"can work with functions\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose((_) => 4, this.port2);\n    expect(await thing()).to.equal(4);\n  });\n\n  it(\"can work with objects that have undefined properties\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose({ x: undefined }, this.port2);\n    expect(await thing.x).to.be.undefined;\n  });\n\n  it(\"can keep the stack and message of thrown errors\", async function () {\n    let stack;\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose((_) => {\n      const error = Error(\"OMG\");\n      stack = error.stack;\n      throw error;\n    }, this.port2);\n    try {\n      await thing();\n      throw \"Should have thrown\";\n    } catch (err) {\n      expect(err).to.not.eq(\"Should have thrown\");\n      expect(err.message).to.equal(\"OMG\");\n      expect(err.stack).to.equal(stack);\n    }\n  });\n\n  it(\"can forward an async function error\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(\n      {\n        async throwError() {\n          throw new Error(\"Should have thrown\");\n        },\n      },\n      this.port2\n    );\n    try {\n      await thing.throwError();\n    } catch (err) {\n      expect(err.message).to.equal(\"Should have thrown\");\n    }\n  });\n\n  it(\"can rethrow non-error objects\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose((_) => {\n      throw { test: true };\n    }, this.port2);\n    try {\n      await thing();\n      throw \"Should have thrown\";\n    } catch (err) {\n      expect(err).to.not.equal(\"Should have thrown\");\n      expect(err.test).to.equal(true);\n    }\n  });\n\n  it(\"can rethrow scalars\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose((_) => {\n      throw \"oops\";\n    }, this.port2);\n    try {\n      await thing();\n      throw \"Should have thrown\";\n    } catch (err) {\n      expect(err).to.not.equal(\"Should have thrown\");\n      expect(err).to.equal(\"oops\");\n      expect(typeof err).to.equal(\"string\");\n    }\n  });\n\n  it(\"can rethrow null\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose((_) => {\n      throw null;\n    }, this.port2);\n    try {\n      await thing();\n      throw \"Should have thrown\";\n    } catch (err) {\n      expect(err).to.not.equal(\"Should have thrown\");\n      expect(err).to.equal(null);\n      expect(typeof err).to.equal(\"object\");\n    }\n  });\n\n  it(\"can work with parameterized functions\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose((a, b) => a + b, this.port2);\n    expect(await thing(1, 3)).to.equal(4);\n  });\n\n  it(\"can work with functions that return promises\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(\n      (_) => new Promise((resolve) => setTimeout((_) => resolve(4), 100)),\n      this.port2\n    );\n    expect(await thing()).to.equal(4);\n  });\n\n  it(\"can work with classes\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    expect(await instance.method()).to.equal(4);\n  });\n\n  it(\"can pass parameters to class constructor\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing(23);\n    expect(await instance.counter).to.equal(23);\n  });\n\n  it(\"can access a class in an object\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose({ SampleClass }, this.port2);\n    const instance = await new thing.SampleClass();\n    expect(await instance.method()).to.equal(4);\n  });\n\n  it(\"can work with class instance properties\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    expect(await instance._counter).to.equal(1);\n  });\n\n  it(\"can set class instance properties\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    expect(await instance._counter).to.equal(1);\n    await (instance._counter = 4);\n    expect(await instance._counter).to.equal(4);\n  });\n\n  it(\"can work with class instance methods\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    expect(await instance.counter).to.equal(1);\n    await instance.increaseCounter();\n    expect(await instance.counter).to.equal(2);\n  });\n\n  it(\"can handle throwing class instance methods\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    return instance\n      .throwsAnError()\n      .then((_) => Promise.reject())\n      .catch((err) => {});\n  });\n\n  it(\"can work with class instance methods multiple times\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    expect(await instance.counter).to.equal(1);\n    await instance.increaseCounter();\n    await instance.increaseCounter(5);\n    expect(await instance.counter).to.equal(7);\n  });\n\n  it(\"can work with class instance methods that return promises\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    expect(await instance.promiseFunc()).to.equal(4);\n  });\n\n  it(\"can work with class instance properties that are promises\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    expect(await instance._promise).to.equal(4);\n  });\n\n  it(\"can work with class instance getters that are promises\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    expect(await instance.promise).to.equal(4);\n  });\n\n  it(\"can work with static class properties\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    expect(await thing.SOME_NUMBER).to.equal(4);\n  });\n\n  it(\"can work with static class methods\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    expect(await thing.ADD(1, 3)).to.equal(4);\n  });\n\n  it(\"can work with bound class instance methods\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    expect(await instance.counter).to.equal(1);\n    const method = instance.increaseCounter.bind(instance);\n    await method();\n    expect(await instance.counter).to.equal(2);\n  });\n\n  it(\"can work with class instance getters\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    expect(await instance.counter).to.equal(1);\n    await instance.increaseCounter();\n    expect(await instance.counter).to.equal(2);\n  });\n\n  it(\"can work with class instance setters\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    expect(await instance._counter).to.equal(1);\n    await (instance.counter = 4);\n    expect(await instance._counter).to.equal(4);\n  });\n\n  const hasBroadcastChannel = (_) => \"BroadcastChannel\" in self;\n  guardedIt(hasBroadcastChannel)(\n    \"will work with BroadcastChannel\",\n    async function () {\n      const b1 = new BroadcastChannel(\"comlink_bc_test\");\n      const b2 = new BroadcastChannel(\"comlink_bc_test\");\n      const thing = Comlink.wrap(b1);\n      Comlink.expose((b) => 40 + b, b2);\n      expect(await thing(2)).to.equal(42);\n    }\n  );\n\n  // Buffer transfers seem to have regressed in Safari 11.1, it’s fixed in 11.2.\n  const isNotSafari11_1 = (_) =>\n    !/11\\.1(\\.[0-9]+)? Safari/.test(navigator.userAgent);\n  guardedIt(isNotSafari11_1)(\"will transfer buffers\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose((b) => b.byteLength, this.port2);\n    const buffer = new Uint8Array([1, 2, 3]).buffer;\n    expect(await thing(Comlink.transfer(buffer, [buffer]))).to.equal(3);\n    expect(buffer.byteLength).to.equal(0);\n  });\n\n  guardedIt(isNotSafari11_1)(\"will copy TypedArrays\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose((b) => b, this.port2);\n    const array = new Uint8Array([1, 2, 3]);\n    const receive = await thing(array);\n    expect(array).to.not.equal(receive);\n    expect(array.byteLength).to.equal(receive.byteLength);\n    expect([...array]).to.deep.equal([...receive]);\n  });\n\n  guardedIt(isNotSafari11_1)(\"will copy nested TypedArrays\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose((b) => b, this.port2);\n    const array = new Uint8Array([1, 2, 3]);\n    const receive = await thing({\n      v: 1,\n      array,\n    });\n    expect(array).to.not.equal(receive.array);\n    expect(array.byteLength).to.equal(receive.array.byteLength);\n    expect([...array]).to.deep.equal([...receive.array]);\n  });\n\n  guardedIt(isNotSafari11_1)(\n    \"will transfer deeply nested buffers\",\n    async function () {\n      const thing = Comlink.wrap(this.port1);\n      Comlink.expose((a) => a.b.c.d.byteLength, this.port2);\n      const buffer = new Uint8Array([1, 2, 3]).buffer;\n      expect(\n        await thing(Comlink.transfer({ b: { c: { d: buffer } } }, [buffer]))\n      ).to.equal(3);\n      expect(buffer.byteLength).to.equal(0);\n    }\n  );\n\n  it(\"will transfer a message port\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose((a) => a.postMessage(\"ohai\"), this.port2);\n    const { port1, port2 } = new MessageChannel();\n    await thing(Comlink.transfer(port2, [port2]));\n    return new Promise((resolve) => {\n      port1.onmessage = (event) => {\n        expect(event.data).to.equal(\"ohai\");\n        resolve();\n      };\n    });\n  });\n\n  it(\"will wrap marked return values\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(\n      (_) =>\n        Comlink.proxy({\n          counter: 0,\n          inc() {\n            this.counter += 1;\n          },\n        }),\n      this.port2\n    );\n    const obj = await thing();\n    expect(await obj.counter).to.equal(0);\n    await obj.inc();\n    expect(await obj.counter).to.equal(1);\n  });\n\n  it(\"will wrap marked return values from class instance methods\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    const obj = await instance.proxyFunc();\n    expect(await obj.counter).to.equal(0);\n    await obj.inc();\n    expect(await obj.counter).to.equal(1);\n  });\n\n  it(\"will wrap marked parameter values\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    const local = {\n      counter: 0,\n      inc() {\n        this.counter++;\n      },\n    };\n    Comlink.expose(async function (f) {\n      await f.inc();\n    }, this.port2);\n    expect(local.counter).to.equal(0);\n    await thing(Comlink.proxy(local));\n    expect(await local.counter).to.equal(1);\n  });\n\n  it(\"will wrap marked assignments\", function (done) {\n    const thing = Comlink.wrap(this.port1);\n    const obj = {\n      onready: null,\n      call() {\n        this.onready();\n      },\n    };\n    Comlink.expose(obj, this.port2);\n\n    thing.onready = Comlink.proxy(() => done());\n    thing.call();\n  });\n\n  it(\"will wrap marked parameter values, simple function\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(async function (f) {\n      await f();\n    }, this.port2);\n    // Weird code because Mocha\n    await new Promise(async (resolve) => {\n      thing(Comlink.proxy((_) => resolve()));\n    });\n  });\n\n  it(\"will wrap multiple marked parameter values, simple function\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(async function (f1, f2, f3) {\n      return (await f1()) + (await f2()) + (await f3());\n    }, this.port2);\n    // Weird code because Mocha\n    expect(\n      await thing(\n        Comlink.proxy((_) => 1),\n        Comlink.proxy((_) => 2),\n        Comlink.proxy((_) => 3)\n      )\n    ).to.equal(6);\n  });\n\n  it(\"will proxy deeply nested values\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    const obj = {\n      a: {\n        v: 4,\n      },\n      b: Comlink.proxy({\n        v: 5,\n      }),\n    };\n    Comlink.expose(obj, this.port2);\n\n    const a = await thing.a;\n    const b = await thing.b;\n    expect(await a.v).to.equal(4);\n    expect(await b.v).to.equal(5);\n    await (a.v = 8);\n    await (b.v = 9);\n    // Workaround for a weird scheduling inconsistency in Firefox.\n    // This test failed, but not when run in isolation, and only\n    // in Firefox. I think there might be problem with task ordering.\n    await new Promise((resolve) => setTimeout(resolve, 1));\n    expect(await thing.a.v).to.equal(4);\n    expect(await thing.b.v).to.equal(9);\n  });\n\n  it(\"will handle undefined parameters\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose({ f: (_) => 4 }, this.port2);\n    expect(await thing.f(undefined)).to.equal(4);\n  });\n\n  it(\"can handle destructuring\", async function () {\n    Comlink.expose(\n      {\n        a: 4,\n        get b() {\n          return 5;\n        },\n        c() {\n          return 6;\n        },\n      },\n      this.port2\n    );\n    const { a, b, c } = Comlink.wrap(this.port1);\n    expect(await a).to.equal(4);\n    expect(await b).to.equal(5);\n    expect(await c()).to.equal(6);\n  });\n\n  it(\"lets users define transfer handlers\", function (done) {\n    Comlink.transferHandlers.set(\"event\", {\n      canHandle(obj) {\n        return obj instanceof Event;\n      },\n      serialize(obj) {\n        return [obj.data, []];\n      },\n      deserialize(data) {\n        return new MessageEvent(\"message\", { data });\n      },\n    });\n\n    Comlink.expose((ev) => {\n      expect(ev).to.be.an.instanceOf(Event);\n      expect(ev.data).to.deep.equal({ a: 1 });\n      done();\n    }, this.port1);\n    const thing = Comlink.wrap(this.port2);\n\n    const { port1, port2 } = new MessageChannel();\n    port1.addEventListener(\"message\", thing.bind(this));\n    port1.start();\n    port2.postMessage({ a: 1 });\n  });\n\n  it(\"can tunnels a new endpoint with createEndpoint\", async function () {\n    Comlink.expose(\n      {\n        a: 4,\n        c() {\n          return 5;\n        },\n      },\n      this.port2\n    );\n    const proxy = Comlink.wrap(this.port1);\n    const otherEp = await proxy[Comlink.createEndpoint]();\n    const otherProxy = Comlink.wrap(otherEp);\n    expect(await otherProxy.a).to.equal(4);\n    expect(await proxy.a).to.equal(4);\n    expect(await otherProxy.c()).to.equal(5);\n    expect(await proxy.c()).to.equal(5);\n  });\n\n  it(\"released proxy should no longer be useable and throw an exception\", async function () {\n    const thing = Comlink.wrap(this.port1);\n    Comlink.expose(SampleClass, this.port2);\n    const instance = await new thing();\n    await instance[Comlink.releaseProxy]();\n    expect(() => instance.method()).to.throw();\n  });\n\n  it(\"released proxy should invoke finalizer\", async function () {\n    let finalized = false;\n    Comlink.expose(\n      {\n        a: \"thing\",\n        [Comlink.finalizer]: () => {\n          finalized = true;\n        },\n      },\n      this.port2\n    );\n    const instance = Comlink.wrap(this.port1);\n    expect(await instance.a).to.equal(\"thing\");\n    await instance[Comlink.releaseProxy]();\n    // wait a beat to let the events process\n    await new Promise((resolve) => setTimeout(resolve, 1));\n    expect(finalized).to.be.true;\n  });\n\n  // commented out this test as it could be unreliable in various browsers as\n  // it has to wait for GC to kick in which could happen at any timing\n  // this does seem to work when testing locally\n  it.skip(\"released proxy via GC should invoke finalizer\", async function () {\n    let finalized = false;\n    Comlink.expose(\n      {\n        a: \"thing\",\n        [Comlink.finalizer]: () => {\n          finalized = true;\n        },\n      },\n      this.port2\n    );\n\n    let registry;\n\n    // set a long enough timeout to wait for a garbage collection\n    this.timeout(10000);\n    // promise will resolve when the proxy is garbage collected\n    await new Promise(async (resolve, reject) => {\n      registry = new FinalizationRegistry((heldValue) => {\n        heldValue();\n      });\n\n      const instance = Comlink.wrap(this.port1);\n      registry.register(instance, resolve);\n      expect(await instance.a).to.equal(\"thing\");\n    });\n    // wait a beat to let the events process\n    await new Promise((resolve) => setTimeout(resolve, 1));\n    expect(finalized).to.be.true;\n  });\n\n  it(\"can proxy with a given target\", async function () {\n    const thing = Comlink.wrap(this.port1, { value: {} });\n    Comlink.expose({ value: 4 }, this.port2);\n    expect(await thing.value).to.equal(4);\n  });\n\n  it(\"can handle unserializable types\", async function () {\n    const thing = Comlink.wrap(this.port1, { value: {} });\n    Comlink.expose({ value: () => \"boom\" }, this.port2);\n\n    try {\n      await thing.value;\n    } catch (err) {\n      expect(err.message).to.equal(\"Unserializable return value\");\n    }\n  });\n});\n\nfunction guardedIt(f) {\n  return f() ? it : xit;\n}\n"
  },
  {
    "path": "tests/tsconfig.json",
    "content": "{\n  \"extends\": \"../tsconfig.json\",\n  \"compilerOptions\": {\n    \"noEmit\": true\n  },\n  \"include\": [\"./**/*.ts\"]\n}\n"
  },
  {
    "path": "tests/two-way-iframe.comlink.test.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Comlink from \"/base/dist/esm/comlink.mjs\";\n\ndescribe(\"Comlink across iframes\", function () {\n  beforeEach(function () {\n    this.ifr = document.createElement(\"iframe\");\n    this.ifr.sandbox.add(\"allow-scripts\", \"allow-same-origin\");\n    this.ifr.src = \"/base/tests/fixtures/two-way-iframe.html\";\n    document.body.appendChild(this.ifr);\n    return new Promise((resolve) => (this.ifr.onload = resolve));\n  });\n\n  afterEach(function () {\n    this.ifr.remove();\n  });\n\n  it(\"can communicate both ways\", async function () {\n    let called = false;\n    const iframe = Comlink.windowEndpoint(this.ifr.contentWindow);\n    Comlink.expose((a) => {\n      called = true;\n      return ++a;\n    }, iframe);\n    const proxy = Comlink.wrap(iframe);\n    expect(await proxy(1, 3)).to.equal(5);\n    expect(called).to.equal(true);\n  });\n});\n"
  },
  {
    "path": "tests/type-checks.ts",
    "content": "import { assert, Has, NotHas, IsAny, IsExact } from \"conditional-type-checks\";\n\nimport * as Comlink from \"../src/comlink.js\";\n\nasync function closureSoICanUseAwait() {\n  {\n    function simpleNumberFunction() {\n      return 4;\n    }\n\n    const proxy = Comlink.wrap<typeof simpleNumberFunction>(0 as any);\n    assert<IsAny<typeof proxy>>(false);\n    const v = proxy();\n    assert<Has<typeof v, Promise<number>>>(true);\n  }\n\n  {\n    function simpleObjectFunction() {\n      return { a: 3 };\n    }\n\n    const proxy = Comlink.wrap<typeof simpleObjectFunction>(0 as any);\n    const v = await proxy();\n    assert<Has<typeof v, { a: number }>>(true);\n  }\n\n  {\n    async function simpleAsyncFunction() {\n      return { a: 3 };\n    }\n\n    const proxy = Comlink.wrap<typeof simpleAsyncFunction>(0 as any);\n    const v = await proxy();\n    assert<Has<typeof v, { a: number }>>(true);\n  }\n\n  {\n    function functionWithProxy() {\n      return Comlink.proxy({ a: 3 });\n    }\n\n    const proxy = Comlink.wrap<typeof functionWithProxy>(0 as any);\n    const subproxy = await proxy();\n    const prop = subproxy.a;\n    assert<Has<typeof prop, Promise<number>>>(true);\n  }\n\n  {\n    class X {\n      static staticFunc() {\n        return 4;\n      }\n      private f = 4;\n      public g = 9;\n      sayHi() {\n        return \"hi\";\n      }\n    }\n\n    const proxy = Comlink.wrap<typeof X>(0 as any);\n    assert<Has<typeof proxy, { staticFunc: () => Promise<number> }>>(true);\n    const instance = await new proxy();\n    assert<Has<typeof instance, { sayHi: () => Promise<string> }>>(true);\n    assert<Has<typeof instance, { g: Promise<number> }>>(true);\n    assert<NotHas<typeof instance, { f: Promise<number> }>>(true);\n    assert<IsAny<typeof instance>>(false);\n  }\n\n  {\n    const x = {\n      a: 4,\n      b() {\n        return 9;\n      },\n      c: {\n        d: 3,\n      },\n    };\n\n    const proxy = Comlink.wrap<typeof x>(0 as any);\n    assert<IsAny<typeof proxy>>(false);\n    const a = proxy.a;\n    assert<Has<typeof a, Promise<number>>>(true);\n    assert<IsAny<typeof a>>(false);\n    const b = proxy.b;\n    assert<Has<typeof b, () => Promise<number>>>(true);\n    assert<IsAny<typeof b>>(false);\n    const subproxy = proxy.c;\n    assert<Has<typeof subproxy, Promise<{ d: number }>>>(true);\n    assert<IsAny<typeof subproxy>>(false);\n    const copy = await proxy.c;\n    assert<Has<typeof copy, { d: number }>>(true);\n  }\n\n  {\n    Comlink.wrap(new MessageChannel().port1);\n    Comlink.expose({}, new MessageChannel().port2);\n\n    interface Baz {\n      baz: number;\n      method(): number;\n    }\n\n    class Foo {\n      constructor(cParam: string) {\n        const self = this;\n        assert<IsExact<typeof self.proxyProp, Bar & Comlink.ProxyMarked>>(true);\n      }\n      prop1: string = \"abc\";\n      proxyProp = Comlink.proxy(new Bar());\n      methodWithTupleParams(...args: [string] | [number, string]): number {\n        return 123;\n      }\n      methodWithProxiedReturnValue(): Baz & Comlink.ProxyMarked {\n        return Comlink.proxy({ baz: 123, method: () => 123 });\n      }\n      methodWithProxyParameter(param: Baz & Comlink.ProxyMarked): void {}\n    }\n\n    class Bar {\n      prop2: string | number = \"abc\";\n      method(param: string): number {\n        return 123;\n      }\n      methodWithProxiedReturnValue(): Baz & Comlink.ProxyMarked {\n        return Comlink.proxy({ baz: 123, method: () => 123 });\n      }\n    }\n    const proxy = Comlink.wrap<Foo>(Comlink.windowEndpoint(self));\n    assert<IsExact<typeof proxy, Comlink.Remote<Foo>>>(true);\n\n    proxy[Comlink.releaseProxy]();\n    const endp = proxy[Comlink.createEndpoint]();\n    assert<IsExact<typeof endp, Promise<MessagePort>>>(true);\n\n    assert<IsAny<typeof proxy.prop1>>(false);\n    assert<Has<typeof proxy.prop1, Promise<string>>>(true);\n\n    const r1 = proxy.methodWithTupleParams(123, \"abc\");\n    assert<IsExact<typeof r1, Promise<number>>>(true);\n\n    const r2 = proxy.methodWithTupleParams(\"abc\");\n    assert<IsExact<typeof r2, Promise<number>>>(true);\n\n    assert<\n      IsExact<typeof proxy.proxyProp, Comlink.Remote<Bar & Comlink.ProxyMarked>>\n    >(true);\n\n    assert<IsAny<typeof proxy.proxyProp.prop2>>(false);\n    assert<Has<typeof proxy.proxyProp.prop2, Promise<string>>>(true);\n    assert<Has<typeof proxy.proxyProp.prop2, Promise<number>>>(true);\n\n    const r3 = proxy.proxyProp.method(\"param\");\n    assert<IsAny<typeof r3>>(false);\n    assert<Has<typeof r3, Promise<number>>>(true);\n\n    // @ts-expect-error\n    proxy.proxyProp.method(123);\n\n    // @ts-expect-error\n    proxy.proxyProp.method();\n\n    const r4 = proxy.methodWithProxiedReturnValue();\n    assert<IsAny<typeof r4>>(false);\n    assert<\n      IsExact<typeof r4, Promise<Comlink.Remote<Baz & Comlink.ProxyMarked>>>\n    >(true);\n\n    const r5 = proxy.proxyProp.methodWithProxiedReturnValue();\n    assert<\n      IsExact<typeof r5, Promise<Comlink.Remote<Baz & Comlink.ProxyMarked>>>\n    >(true);\n\n    const r6 = (await proxy.methodWithProxiedReturnValue()).baz;\n    assert<IsAny<typeof r6>>(false);\n    assert<Has<typeof r6, Promise<number>>>(true);\n\n    const r7 = (await proxy.methodWithProxiedReturnValue()).method();\n    assert<IsAny<typeof r7>>(false);\n    assert<Has<typeof r7, Promise<number>>>(true);\n\n    const ProxiedFooClass = Comlink.wrap<typeof Foo>(\n      Comlink.windowEndpoint(self)\n    );\n    const inst1 = await new ProxiedFooClass(\"test\");\n    assert<IsExact<typeof inst1, Comlink.Remote<Foo>>>(true);\n    inst1[Comlink.releaseProxy]();\n    inst1[Comlink.createEndpoint]();\n\n    // @ts-expect-error\n    await new ProxiedFooClass(123);\n\n    // @ts-expect-error\n    await new ProxiedFooClass();\n\n    //\n    // Tests for advanced proxy use cases\n    //\n\n    // Type round trips\n    // This tests that Local is the exact inverse of Remote for objects:\n    assert<\n      IsExact<\n        Comlink.Local<Comlink.Remote<Comlink.ProxyMarked>>,\n        Comlink.ProxyMarked\n      >\n    >(true);\n    // This tests that Local is the exact inverse of Remote for functions, with one difference:\n    // The local version of a remote function can be either implemented as a sync or async function,\n    // because Remote<T> always makes the function async.\n    assert<\n      IsExact<\n        Comlink.Local<Comlink.Remote<(a: number) => string>>,\n        (a: number) => string | Promise<string>\n      >\n    >(true);\n\n    interface Subscriber<T> {\n      closed?: boolean;\n      next?: (value: T) => void;\n    }\n    interface Unsubscribable {\n      unsubscribe(): void;\n    }\n    /** A Subscribable that can get proxied by Comlink */\n    interface ProxyableSubscribable<T> extends Comlink.ProxyMarked {\n      subscribe(\n        subscriber: Comlink.Remote<Subscriber<T> & Comlink.ProxyMarked>\n      ): Unsubscribable & Comlink.ProxyMarked;\n    }\n\n    /** Simple parameter object that gets cloned (not proxied) */\n    interface Params {\n      textDocument: string;\n    }\n\n    class Registry {\n      async registerProvider(\n        provider: Comlink.Remote<\n          ((params: Params) => ProxyableSubscribable<string>) &\n            Comlink.ProxyMarked\n        >\n      ) {\n        const resultPromise = provider({ textDocument: \"foo\" });\n        assert<\n          IsExact<\n            typeof resultPromise,\n            Promise<Comlink.Remote<ProxyableSubscribable<string>>>\n          >\n        >(true);\n        const result = await resultPromise;\n\n        const subscriptionPromise = result.subscribe({\n          [Comlink.proxyMarker]: true,\n          next: (value) => {\n            assert<IsExact<typeof value, string>>(true);\n          },\n        });\n        assert<\n          IsExact<\n            typeof subscriptionPromise,\n            Promise<Comlink.Remote<Unsubscribable & Comlink.ProxyMarked>>\n          >\n        >(true);\n        const subscriber = Comlink.proxy({\n          next: (value: string) => console.log(value),\n        });\n        result.subscribe(subscriber);\n\n        const r1 = (await subscriptionPromise).unsubscribe();\n        assert<IsExact<typeof r1, Promise<void>>>(true);\n      }\n    }\n    const proxy2 = Comlink.wrap<Registry>(Comlink.windowEndpoint(self));\n\n    proxy2.registerProvider(\n      // Synchronous callback\n      Comlink.proxy(({ textDocument }: Params) => {\n        const subscribable = Comlink.proxy({\n          subscribe(\n            subscriber: Comlink.Remote<Subscriber<string> & Comlink.ProxyMarked>\n          ): Unsubscribable & Comlink.ProxyMarked {\n            // Important to test here is that union types (such as Function | undefined) distribute properly\n            // when wrapped in Promises/proxied\n\n            assert<IsAny<typeof subscriber.closed>>(false);\n            assert<\n              IsExact<\n                typeof subscriber.closed,\n                Promise<true> | Promise<false> | Promise<undefined> | undefined\n              >\n            >(true);\n\n            assert<IsAny<typeof subscriber.next>>(false);\n            assert<\n              IsExact<\n                typeof subscriber.next,\n                | Comlink.Remote<(value: string) => void>\n                | Promise<undefined>\n                | undefined\n              >\n            >(true);\n\n            // @ts-expect-error\n            subscriber.next();\n\n            if (subscriber.next) {\n              // Only checking for presence is not enough, since it could be a Promise\n              // @ts-expect-error\n              subscriber.next();\n            }\n\n            if (typeof subscriber.next === \"function\") {\n              subscriber.next(\"abc\");\n            }\n\n            return Comlink.proxy({ unsubscribe() {} });\n          },\n        });\n        assert<Has<typeof subscribable, Comlink.ProxyMarked>>(true);\n        return subscribable;\n      })\n    );\n    proxy2.registerProvider(\n      // Async callback\n      Comlink.proxy(async ({ textDocument }: Params) => {\n        const subscribable = Comlink.proxy({\n          subscribe(\n            subscriber: Comlink.Remote<Subscriber<string> & Comlink.ProxyMarked>\n          ): Unsubscribable & Comlink.ProxyMarked {\n            assert<IsAny<typeof subscriber.next>>(false);\n            assert<\n              IsExact<\n                typeof subscriber.next,\n                | Comlink.Remote<(value: string) => void>\n                | Promise<undefined>\n                | undefined\n              >\n            >(true);\n\n            // Only checking for presence is not enough, since it could be a Promise\n            if (typeof subscriber.next === \"function\") {\n              subscriber.next(\"abc\");\n            }\n            return Comlink.proxy({ unsubscribe() {} });\n          },\n        });\n        return subscribable;\n      })\n    );\n  }\n\n  // Transfer handlers\n  {\n    const urlTransferHandler: Comlink.TransferHandler<URL, string> = {\n      canHandle: (val): val is URL => {\n        assert<IsExact<typeof val, unknown>>(true);\n        return val instanceof URL;\n      },\n      serialize: (url) => {\n        assert<IsExact<typeof url, URL>>(true);\n        return [url.href, []];\n      },\n      deserialize: (str) => {\n        assert<IsExact<typeof str, string>>(true);\n        return new URL(str);\n      },\n    };\n    Comlink.transferHandlers.set(\"URL\", urlTransferHandler);\n  }\n}\n"
  },
  {
    "path": "tests/worker.comlink.test.js",
    "content": "/**\n * Copyright 2017 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Comlink from \"/base/dist/esm/comlink.mjs\";\n\ndescribe(\"Comlink across workers\", function () {\n  beforeEach(function () {\n    this.worker = new Worker(\"/base/tests/fixtures/worker.js\");\n  });\n\n  afterEach(function () {\n    this.worker.terminate();\n  });\n\n  it(\"can communicate\", async function () {\n    const proxy = Comlink.wrap(this.worker);\n    expect(await proxy(1, 3)).to.equal(4);\n  });\n\n  it(\"can tunnels a new endpoint with createEndpoint\", async function () {\n    const proxy = Comlink.wrap(this.worker);\n    const otherEp = await proxy[Comlink.createEndpoint]();\n    const otherProxy = Comlink.wrap(otherEp);\n    expect(await otherProxy(20, 1)).to.equal(21);\n  });\n\n  it(\"releaseProxy closes MessagePort created by createEndpoint\", async function () {\n    const proxy = Comlink.wrap(this.worker);\n    const otherEp = await proxy[Comlink.createEndpoint]();\n    const otherProxy = Comlink.wrap(otherEp);\n    expect(await otherProxy(20, 1)).to.equal(21);\n\n    await new Promise((resolve) => {\n      otherEp.close = resolve; // Resolve the promise when the MessagePort is closed.\n      otherProxy[Comlink.releaseProxy](); // Release the proxy, which should close the MessagePort.\n    });\n  });\n});\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    /* Basic Options */\n    \"target\": \"es2015\" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */,\n    \"module\": \"esnext\" /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,\n    \"lib\": [\n      \"esnext\",\n      \"dom\"\n    ] /* Specify library files to be included in the compilation:  */,\n    // \"allowJs\": true,                       /* Allow javascript files to be compiled. */\n    // \"checkJs\": true,                       /* Report errors in .js files. */\n    // \"jsx\": \"preserve\",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */\n    \"declaration\": true /* Generates corresponding '.d.ts' file. */,\n    // \"sourceMap\": true,                     /* Generates corresponding '.map' file. */\n    // \"outFile\": \"./\",                       /* Concatenate and emit output to single file. */\n    // \"outDir\": \"./\",                        /* Redirect output structure to the directory. */\n    // \"rootDir\": \"./\",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */\n    // \"removeComments\": false,                /* Do not emit comments to output. */\n    // \"noEmit\": true,                        /* Do not emit outputs. */\n    // \"importHelpers\": true,                 /* Import emit helpers from 'tslib'. */\n    // \"downlevelIteration\": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */\n    // \"isolatedModules\": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */\n\n    /* Strict Type-Checking Options */\n    \"strict\": true /* Enable all strict type-checking options. */,\n    // \"noImplicitAny\": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */\n    // \"strictNullChecks\": true,              /* Enable strict null checks. */\n    // \"noImplicitThis\": true,                /* Raise error on 'this' expressions with an implied 'any' type. */\n    // \"alwaysStrict\": true,                  /* Parse in strict mode and emit \"use strict\" for each source file. */\n\n    /* Additional Checks */\n    // \"noUnusedLocals\": true,                /* Report errors on unused locals. */\n    // \"noUnusedParameters\": true,            /* Report errors on unused parameters. */\n    // \"noImplicitReturns\": true,             /* Report error when not all code paths in function return a value. */\n    // \"noFallthroughCasesInSwitch\": true,    /* Report errors for fallthrough cases in switch statement. */\n\n    /* Module Resolution Options */\n    \"moduleResolution\": \"node\" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */\n    // \"baseUrl\": \"./\",                       /* Base directory to resolve non-absolute module names. */\n    // \"paths\": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */\n    // \"rootDirs\": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */\n    // \"typeRoots\": [],                       /* List of folders to include type definitions from. */\n    // \"types\": [],                           /* Type declaration files to be included in compilation. */\n    // \"allowSyntheticDefaultImports\": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */\n    // \"preserveSymlinks\": true,              /* Do not resolve the real path of symlinks. */\n\n    /* Source Map Options */\n    // \"sourceRoot\": \"./\",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */\n    // \"mapRoot\": \"./\",                       /* Specify the location where debugger should locate map files instead of generated locations. */\n    // \"inlineSourceMap\": true,               /* Emit a single file with source maps instead of having a separate file. */\n    // \"inlineSources\": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */\n\n    /* Experimental Options */\n    // \"experimentalDecorators\": true,        /* Enables experimental support for ES7 decorators. */\n    // \"emitDecoratorMetadata\": true,         /* Enables experimental support for emitting type metadata for decorators. */\n  },\n  \"include\": [\"src/**/*.ts\"],\n  \"exclude\": [\"dist\"]\n}\n"
  }
]