{"name":"comlink","version":"2.3.6","description":"Comlink’s goal is to make [WebWorkers][WebWorker] enjoyable. Comlink removes the mental barrier of thinking about `postMessage` and hides the fact that you are working with workers.","main":"comlink.umd.js","module":"comlink.es6.js","types":"comlink.d.ts","scripts":{"test":"npm run linter && npm run unittest && npm run build","unittest":"karma start","linter":"prettier --write *.ts tests/*.js tests/fixtures/*.js","watchtest":"karma start --no-single-run --browsers ChromeHeadless","watchtestharmony":"karma start --no-single-run --browsers ChromeCanaryHeadlessHarmony","version":"sed -i.bak -e 's!comlinkjs@[0-9.]+!comlinkjs@'${npm_package_version}'!' README.md && git add README.md","mypublish":"npm run build && npm run test && cp README.md package.json dist && npm publish dist && sed -i.bak -e 's!\"comlinkjs\"!\"comlink\"!' dist/package.json && npm publish dist","build":"rm -rf dist && mkdir dist && npm run compile && npm run mangle_global && npm run minify","compile":"tsc --outDir dist -m none && mv dist/comlink.{,global.}js && mv dist/messagechanneladapter.{,global.}js && tsc --outDir dist -m es2015 && mv dist/comlink.{,es6.}js && mv dist/messagechanneladapter.{,es6.}js && tsc -d --outDir dist -m umd && mv dist/comlink.{,umd.}js && mv dist/messagechanneladapter.{,umd.}js","mangle_global":"sed -i.bak -e 's!exports.Comlink!self.Comlink!' dist/comlink.global.js && sed -i.bak 's!^.*\"__esModule\".*$!!' dist/comlink.global.js && sed -i.bak -e 's!exports.MessageChannelAdapter!self.MessageChannelAdapter!' dist/messagechanneladapter.global.js && sed -i.bak -e 's!^.*\"__esModule\".*$!!' dist/messagechanneladapter.global.js","minify":"babel-minify --mangle -o dist/comlink.global.{min.,}js && babel-minify --mangle -o dist/comlink.es6.{min.,}js && babel-minify --mangle -o dist/comlink.umd.{min.,}js && babel-minify --mangle -o dist/messagechanneladapter.global.{min.,}js && babel-minify --mangle -o dist/messagechanneladapter.es6.{min.,}js && babel-minify --mangle -o dist/messagechanneladapter.umd.{min.,}js"},"keywords":[],"author":{"name":"Surma","email":"surma@google.com"},"contributors":[{"name":"Surma","email":"surma@google.com"},{"name":"Ian Kilpatrick","email":"ikilpatrick@google.com"}],"repository":{"type":"git","url":"git+https://github.com/GoogleChromeLabs/comlink.git"},"license":"Apache-2.0","devDependencies":{"babel-minify":"0.4.0","chai":"4.1.2","karma":"2.0.2","karma-chai":"0.1.0","karma-chrome-launcher":"2.2.0","karma-firefox-launcher":"1.1.0","karma-mocha":"1.3.0","karma-safari-launcher":"1.0.0","karma-typescript":"3.0.12","mocha":"5.1.1","typescript":"2.8.3","prettier":"1.12.1"},"dependencies":{},"bugs":{"url":"https://github.com/GoogleChromeLabs/comlink/issues"},"homepage":"https://github.com/GoogleChromeLabs/comlink#readme","_id":"comlink@2.3.6","_npmVersion":"6.0.0","_nodeVersion":"10.0.0","_npmUser":{"name":"surma","email":"surma@surma.link"},"dist":{"integrity":"sha512-lK7EzwURBum8+nQXeFEQwZSU9dbA28da65KMY+0yiiCcqDInhTKunAT4Z1AyafTRubopOegFhlK/f2x6fXukkw==","shasum":"331d05fd1092372db8cfd9f15ad10abdad949dbd","tarball":"http://registry-npm.ywwl.com/comlink/download/comlink-2.3.6.tgz","fileCount":19,"unpackedSize":94821,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJa74RhCRA9TVsSAnZWagAAE8EQAJ5VPCQAovsYMKskZpKa\n6kL2PzRSJLNBxW0yjxCAyXQPxoveyFegkhUaVVYn+B82N0hg2MKT9ShpYJKQ\nMN9iMryaHJyp72kdTXsFbICdBTorIM/MqlgFo1kKIIdEgNcbQYRMeUFXvDUR\na8z6Ya1V4jT+bZ2kOxEurPzcmCtRkVWZwl8WG3MmjpYFcfWXpaVpafHMZ+P+\ndeP0xgrJTjCi0IqSLrBikjVREUHBcxyBxJIN7zIAIVWFgON/NGi+BBYHepXu\niEm8h8J0ETqvjY/8BkT4IX67z9w9m5BiujnH6ifZApTVigJKZnJK4YqBEIeI\nQL68taLxx3Gwko7KqBzrSSVO0R40LJEwosMuL9beKc+WTlYvrM3VXBjnvqYw\nsR/cmr0ow94jXJzGT8jIsyrjkGvVif5LYqSoUNkAMyN0xOcn1GodRFTUUggE\n9T89GTWAkt4e6qHFHbSbL6KaLISTYKvpyuYJEJ4IShwxYOOVHFJ1jmEvD2Fb\n+8tegwawnrCZB6225FwwRmLMA/rv/Zqe4TYhi31sN64yI2Oexn+5/yxWntJp\nkgZ/dOPDcxXtA6k11NZ3ptEQc9IJ0bHl8RBw+lme8J+GSNg4rc+keEPB+BBM\n/GTTITJv5RFIv9zNF8ne3gNXPEztD3jXtDacmEewqth2Rucxcqlgajh0nZ4g\n47xF\r\n=bgWt\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIE7wwv1xdPN5HFrrU+3FNtKq1cchSkFO9DqQ4RBxYkkqAiBMIG8JZpVXioYhbEE/Mhl72P+2qMSmLfTRICbMGkMXcQ=="}],"size":12751,"noattachment":false,"key":"/comlink/-/comlink-2.3.6.tgz"},"maintainers":[{"email":"jason@developit.ca","name":"developit"},{"email":"surma@surma.link","name":"surma"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/comlink_2.3.6_1525646431305_0.9243155684890678"},"_hasShrinkwrap":false,"readme":"# 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","publish_time":1525646431440,"_cnpm_publish_time":1525646431440,"dist-tags":{"alpha":"4.0.0-alpha.10","latest":"4.4.2","next":"4.0.0-alpha.10"}}