{"bugs":{"url":"https://github.com/streamr-dev/streamr-client/issues"},"dist":{"shasum":"b8ee2a3d05d8a015bf1e5c49bdb79dfe22a9ba97","tarball":"https://registry.npmjs.org/streamr-client/-/streamr-client-5.0.0-beta.7.tgz","fileCount":170,"integrity":"sha512-TdivlY/6HCVPEbvd0SqqBT0552JITsWNjfgPXXu3LGhR8/KKa2Hj8+T6iNOJhNtPdJMko9aToxaZAu9iX0cA5Q==","signatures":[{"sig":"MEUCIQCLN+3KjEBr4mMpQXA5TOQnr+loGbkr3uAMoPJi4Y246gIgc7dtOxKnGquCrhc0N03iID7/agKRSWOFycq8QAH+Uic=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":15831811,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgNW8mCRA9TVsSAnZWagAAVpgP/0F3e6+pFEju3N4Z4DZS\nV8ynmr2g1B+pZiuGqAkBw8f04NVY/ISHItLXPEbhrYWZGuwdnodRI9tE2npQ\njXeyD+NJS3EdPpsQx7ces1yFQo5vv1XRbdHsdR2eF3b9s2CfLs65C09CKBTm\nPCQgki9O9TH9DSta4BXL32J4XWNiuhnTYkUof+1vomJSCr/RhDpkZxED0gwx\nfVqfLSYFMbkilIO9XggoFiZzU6AhqzyuE5AblHoy+HejHpMxD4GuGoaIch3i\nVURmJEPkAiAzxIq3ZebCExG+y3uNCjRCAlXJ6aFgBKy/vCkdo2PMyTAuEtuW\nuSwOsRjkbeakxbRBekA+qt+Fdn6qbuaufwdnIljCCrgw/6Fa/X1U0VRVC7Ni\np5xsWIYbe2NzYE+1BvNXyfIR/f5INYfKwb8T7GTQAAZN09kpDI/6DKNvNCNo\n3zqJROZ41xC7Tt7yO4n5W8L5l+V7WNWcYalgMWvoQ8cSqLO3Gdv8o8WYeTPt\naaNcN3Z1HxlwkP7hOc4i0kBcoBrBNyYGKSsS0cFC5YnwCD41TnHO/tt1o/8F\nE4N1XKk3y/jWjo2aFlZoVTud/rxcGkVOq3QgtzHN3vzTcYvUiCuESbK3erQl\nGhLqF+DdqbKtKyOJrXFJWqYQQtb9F7qj6ll/9QuUchG1zWtRb9F8jezepMUp\n7y0/\r\n=j8+z\r\n-----END PGP SIGNATURE-----\r\n"},"main":"dist/streamr-client.nodejs.js","name":"streamr-client","types":"dist/types/src/StreamrClient.d.ts","author":{"name":"Streamr"},"readme":"<p align=\"center\">\n  <a href=\"https://streamr.network\">\n    <img alt=\"Streamr\" src=\"https://raw.githubusercontent.com/streamr-dev/streamr-client-javascript/master/readme-header-img.png\" width=\"1320\" />\n  </a>\n</p>\n<h1 align=\"left\">\n  Streamr JavaScript Client\n</h1>\n\nBy using this client, you can easily interact with the [Streamr](https://streamr.network) API from JavaScript-based environments, such as browsers and [node.js](https://nodejs.org). You can, for example, subscribe to real-time data in streams, produce new data to streams, and create new streams.\n\nThe client uses websockets for producing and consuming messages to/from streams. It should work in all modern browsers.\n\n[![Build Status](https://travis-ci.com/streamr-dev/streamr-client-javascript.svg?branch=master)](https://travis-ci.com/streamr-dev/streamr-client-javascript)\n\n## Breaking changes notice\n\n* Date TBD: Support for unsigned data will be dropped.\n\n[Installation](#installation) · [Usage](#usage) · [Client options](#client-options) · [Authentication options](#authentication-options) · [Message handler callback](#message-handler-callback) · [StreamrClient object](#streamrclient-object) · [Stream object](#stream-object) · [Subscription options](#subscription-options) · [Data Unions](#data-unions) · [Utility functions](#utility-functions) · [Events](#binding-to-events) · [Partitioning](#partitioning) · [Logging](#logging) · [NPM Publishing](#publishing-latest)\n\n## Installation\n\nThe client is available on [npm](https://www.npmjs.com/package/streamr-client) and can be installed simply by:\n\n`npm install streamr-client`\n\nNode v14 or higher is recommended if you intend to use the client in a Node environment. For example, inside a script.\n\n## Usage\n\nHere are some quick examples. More detailed examples for the browser and node.js can be found [here](https://github.com/streamr-dev/streamr-client/tree/master/examples).\n\nIf you don't have an Ethereum account you can use the utility function `StreamrClient.generateEthereumAccount()`, which returns the address and private key of a fresh Ethereum account.\n\n### Creating a StreamrClient instance\n\n```js\nconst client = new StreamrClient({\n    auth: {\n        privateKey: 'your-private-key'\n    }\n})\n```\n\nWhen using Node.js remember to require the library with:\n\n```js\nconst StreamrClient = require('streamr-client')\n```\n\n### Subscribing to real-time events in a stream\n\n```js\nconst sub = await client.subscribe({\n    stream: 'streamId',\n    partition: 0, // Optional, defaults to zero. Use for partitioned streams to select partition.\n    // optional resend options here\n}, (message, metadata) => {\n    // This is the message handler which gets called for every incoming message in the stream.\n    // Do something with the message here!\n})\n```\n\n### Resending historical data\n\n```js\nconst sub = await client.resend({\n    stream: 'streamId',\n    resend: {\n        last: 5,\n    },\n}, (message) => {\n    // This is the message handler which gets called for every received message in the stream.\n    // Do something with the message here!\n})\n```\n\nSee \"Subscription options\" for resend options\n\n### Programmatically creating a stream\n\n```js\nconst stream = await client.getOrCreateStream({\n    name: 'My awesome stream created via the API',\n})\nconsole.log(`Stream ${stream.id} has been created!`)\n// Do something with the stream, for example call stream.publish(message)\n```\n\n### Publishing data points to a stream\n\n```js\n// Here's our example data point\nconst msg = {\n    temperature: 25.4,\n    humidity: 10,\n    happy: true\n}\n\n// Publish using the stream id only\nawait client.publish('my-stream-id', msg)\n\n// The first argument can also be the stream object\nawait client.publish(stream, msg)\n\n// Publish with a specific timestamp as a Date object (default is now)\nawait client.publish('my-stream-id', msg, new Date(54365472))\n\n// Publish with a specific timestamp in ms\nawait client.publish('my-stream-id', msg, 54365472)\n\n// Publish with a specific timestamp as a ISO8601 string\nawait client.publish('my-stream-id', msg, '2019-01-01T00:00:00.123Z')\n\n// Publish with a specific partition key (read more about partitioning further down this readme)\nawait client.publish('my-stream-id', msg, Date.now(), 'my-partition-key')\n\n// For convenience, stream.publish(...) equals client.publish(stream, ...)\nawait stream.publish(msg)\n```\n\n## Client options\n\n| Option                   | Default value                    | Description                                                                                                                                                                                                                                                                                                                             |\n| :----------------------- | :------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| url                      | wss://streamr.network/api/v1/ws  | Address of the Streamr websocket endpoint to connect to.                                                                                                                                                                                                                                                                                |\n| restUrl                  | <https://streamr.network/api/v1> | Base URL of the Streamr REST API.                                                                                                                                                                                                                                                                                                       |\n| auth                     | {}                               | Object that can contain different information to authenticate. More details below.                                                                                                                                                                                                                                                      |\n| publishWithSignature     | 'auto'                           | Determines if data points published to streams are signed or not. Possible values are: 'auto', 'always' and 'never'. Signing requires `auth.privateKey` or `auth.ethereum`.  'auto' will sign only if one of them is set. 'always' will throw an exception if none of them is set.                                                      |\n| verifySignatures         | 'auto'                           | Determines under which conditions signed and unsigned data points are accepted or rejected. 'always' accepts only signed and verified data points. 'never' accepts all data points. 'auto' verifies all signed data points before accepting them and accepts unsigned data points only for streams not supposed to contain signed data. |\n| autoConnect              | true                             | If set to `true`, the client connects automatically on the first call to `subscribe()`. Otherwise an explicit call to `connect()` is required.                                                                                                                                                                                          |\n| autoDisconnect           | true                             | If set to `true`, the client automatically disconnects when the last stream is unsubscribed. Otherwise the connection is left open and can be disconnected explicitly by calling `disconnect()`.                                                                                                                                        |\n| orderMessages            | true                             | If set to `true`, the subscriber handles messages in the correct order, requests missing messages and drops duplicates. Otherwise, the subscriber processes messages as they arrive without any check.                                                                                                                                  |\n| maxPublishQueueSize      | 10000                            | Only in effect when `autoConnect = true`. Controls the maximum number of messages to retain in internal queue when client has disconnected and is reconnecting to Streamr.                                                                                                                                                              |\n| publisherGroupKeys       | {}                               | Object defining the group key as a hex string used to encrypt for each stream id.                                                                                                                                                                                                                                                       |\n| publisherStoreKeyHistory | true                             | If `true`, the client will locally store every key used to encrypt messages at some point. If set to `false`, the client will not be able to answer subscribers asking for historical keys during resend requests.                                                                                                                      |\n| subscriberGroupKeys      | {}                               | Object defining, for each stream id, an object containing the group key used to decrypt for each publisher id. Not needed if `keyExchange` is defined.                                                                                                                                                                                  |\n| keyExchange              | {}                               | Defines RSA key pair to use for group key exchange. Can define `publicKey` and `privateKey` fields as strings in the PEM format, or stay empty to generate a key pair automatically. Can be set to `null` if no key exchange is required.                                                                                               |\n\n## Authentication options\n\nNote: **Authenticating with an API key has been deprecated.**\n\nNote: **Support for email/password authentication will be dropped in the future and cryptographic keys/wallets will be the only supported method.**\n\nIf you don't have an Ethereum account you can use the utility function `StreamrClient.generateEthereumAccount()`, which returns the address and private key of a fresh Ethereum account.\n\nAuthenticating with Ethereum also automatically creates an associated Streamr user, even if it doesn't already exist. Under the hood, the client will cryptographically sign a challenge to authenticate you as a Streamr user:\n\n```js\nconst client = new StreamrClient({\n    auth: {\n        privateKey: 'your-private-key'\n    }\n})\n```\n\nAuthenticating with an Ethereum private key contained in an Ethereum (web3) provider:\n\n```js\nconst client = new StreamrClient({\n    auth: {\n        ethereum: window.ethereum,\n    }\n})\n```\n\n(Authenticating with a pre-existing session token, for internal use by the Streamr app):\n\n```js\nconst client = new StreamrClient({\n    auth: {\n        sessionToken: 'session-token'\n    }\n})\n```\n\n## Connecting\n\nBy default the client will automatically connect and disconnect as needed, ideally you should not need to manage connection state explicitly.\nSpecifically, it will automatically connect when you publish or subscribe, and automatically disconnect once all subscriptions are removed and no\nmessages were recently published. This behaviour can be disabled using the `autoConnect` & `autoDisconnect` options when creating a `new\nStreamrClient`. Explicit calls to either `connect()` or `disconnect()` will disable all `autoConnect` & `autoDisconnect` functionality, but they can\nbe re-enabled by calling `enableAutoConnect()` or `enableAutoDisconnect()`.\n\nCalls that need a connection, such as `publish` or `subscribe` will fail with an error if you are disconnected and autoConnect is disabled.\n\n| Name                                | Description                                                                                                                                                                                         |\n| :---------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| connect()                           | Safely connects if not connected. Returns a promise. Resolves immediately if already connected. Only rejects if an error occurs during connection.                                                  |\n| disconnect()                        | Safely disconnects if not already disconnected, clearing all subscriptions. Returns a Promise.  Resolves immediately if already disconnected. Only rejects if an error occurs during disconnection. |\n| enableAutoConnect(enable = true)    | Enables autoConnect if it wasn't already enabled. Does not connect immediately. Use `enableAutoConnect(false)` to disable autoConnect.                                                              |\n| enableAutoDisconnect(enable = true) | Enables autoDisconnect if it wasn't already enabled. Does not disconnect immediately. Use `enableAutoConnect(false)` to disable autoDisconnect.                                                     |\n\n```js\nconst client = new StreamrClient({\n    auth: {\n        privateKey: 'your-private-key'\n    },\n    autoConnect: false,\n    autoDisconnect: false,\n})\n\nawait client.connect()\n```\n\n## Managing subscriptions\n\n| Name                         | Description                                                                                                                                                                     |\n| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| subscribe(options, callback) | Subscribes to a stream. Messages in this stream are passed to the `callback` function. See below for subscription options. Returns a Promise resolving a `Subscription` object. |\n| unsubscribe(Subscription)    | Unsubscribes the given `Subscription`. Returns a promise.                                                                                                                       |\n| unsubscribeAll(`streamId`)   | Unsubscribes all `Subscriptions` for `streamId`. Returns a promise.                                                                                                             |\n| getSubscriptions(`streamId`) | Returns a list of `Subscriptions` for `streamId`. Returns a promise.                                                                                                            |\n\n### Message handler callback\n\nThe second argument to `client.subscribe(options, callback)` is the callback function that will be called for each message as they arrive. Its arguments are as follows:\n\n| Argument      | Description                                                                                                                                                                                                                      |\n| :------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| payload       | A JS object containing the message payload itself                                                                                                                                                                                |\n| streamMessage | The whole [StreamMessage](https://github.com/streamr-dev/streamr-client-protocol-js/blob/master/src/protocol/message_layer/StreamMessage.js) object containing various metadata, for example `streamMessage.getTimestamp()` etc. |\n\n```js\nconst sub = await client.subscribe({\n    streamId: 'my-stream-id',\n}, (payload, streamMessage) => {\n    console.log({\n        payload, streamMessage\n    })\n})\n\n```\n\n### Subscription Options\n\nNote that only one of the resend options can be used for a particular subscription. The default functionality is to resend nothing, only subscribe to messages from the subscription moment onwards.\n\n| Name      | Description                                                                        |\n| :-------- | :--------------------------------------------------------------------------------- |\n| stream    | Stream id to subscribe to                                                          |\n| partition | Partition number to subscribe to. Defaults to partition 0.                         |\n| resend    | Object defining the resend options. Below are examples of its contents.            |\n| groupKeys | Object defining the group key as a hex string for each publisher id of the stream. |\n\n```js\n// Resend N most recent messages\nconst sub1 = await client.subscribe({\n    streamId: 'my-stream-id',\n    resend: {\n        last: 10,\n    }\n}, onMessage)\n\n// Resend from a specific message reference up to the newest message\nconst sub2 = await client.subscribe({\n    streamId: 'my-stream-id',\n    resend: {\n        from: {\n            timestamp: 12345,\n            sequenceNumber: 0, // optional\n        },\n        publisher: 'publisherId', // optional\n        msgChainId: 'msgChainId', // optional\n    }\n}, onMessage)\n\n// Resend a limited range of messages\nconst sub3 = await client.subscribe({\n    streamId: 'my-stream-id',\n    resend: {\n        from: {\n            timestamp: 12345,\n            sequenceNumber: 0, // optional\n        },\n        to: {\n            timestamp: 54321,\n            sequenceNumber: 0, // optional\n        },\n        publisher: 'publisherId', // optional\n        msgChainId: 'msgChainId', // optional\n    }\n}, onMessage)\n```\n\nIf you choose one of the above resend options when subscribing, you can listen on the completion of this resend by doing the following:\n\n```js\nconst sub = await client.subscribe(options)\nsub.on('resent', () => {\n    console.log('All caught up and received all requested historical messages! Now switching to real time!')\n})\n```\n\n## Stream API\n\nAll the below functions return a Promise which gets resolved with the result.\n\n| Name                                                | Description                                                                                                                                          |\n| :-------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- |\n| getStream(streamId)                                 | Fetches a stream object from the API.                                                                                                                |\n| listStreams(query)                                  | Fetches an array of stream objects from the API. For the query params, consult the [API docs](https://api-explorer.streamr.com).                     |\n| getStreamByName(name)                               | Fetches a stream which exactly matches the given name.                                                                                               |\n| createStream(properties)                            | Creates a stream with the given properties. For more information on the stream properties, consult the [API docs](https://api-explorer.streamr.com). |\n| getOrCreateStream(properties)                       | Gets a stream with the id or name given in `properties`, or creates it if one is not found.                                                          |\n| publish(streamId, message, timestamp, partitionKey) | Publishes a new message to the given stream.                                                                                                         |\n\n### Stream object\n\nAll the below functions return a Promise which gets resolved with the result.\n\n| Name                                      | Description                                                                                                                                                                                                                                                                   |\n| :---------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| update()                                  | Updates the properties of this stream object by sending them to the API.                                                                                                                                                                                                      |\n| delete()                                  | Deletes this stream.                                                                                                                                                                                                                                                          |\n| getPermissions()                          | Returns the list of permissions for this stream.                                                                                                                                                                                                                              |\n| hasPermission(operation, user)            | Returns a permission object, or null if no such permission was found. Valid `operation` values for streams are: stream_get, stream_edit, stream_delete, stream_publish, stream_subscribe, and stream_share. `user` is the username of a user, or null for public permissions. |\n| grantPermission(operation, user)          | Grants the permission to do `operation` to `user`, which are defined as above.                                                                                                                                                                                                |\n| revokePermission(permissionId)            | Revokes a permission identified by its `id`.                                                                                                                                                                                                                                  |\n| detectFields()                            | Updates the stream field config (schema) to match the latest data point in the stream.                                                                                                                                                                                        |\n| publish(message, timestamp, partitionKey) | Publishes a new message to this stream.                                                                                                                                                                                                                                       |\n\n## Data Unions\n\nThis library provides functions for working with Data Unions. To get a DataUnion instance, call `client.getDataUnion(address)`. To deploy a new DataUnion, call `deployDataUnion(options)`\n\nTODO: All `options`-parameters should be documented (see TypeScript interfaces for the definitions)\n\nThese DataUnion-specific options are used from `StreamrClient` options:\n| Property                 | Default                                                | Description                                                                                                      |\n| :----------------------- | :----------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------- |\n| tokenAddress             | 0x0Cf0Ee637<br>88A0849fE52<br>97F3407f701<br>E122cC023 | Token used by the DU                                                                                             |\n| factoryMainnetAddress    | TODO                                                   | Data Union factory that creates a new Data Union                                                                 |\n| minimumWithdrawTokenWei  | 1000000                                                | Threshold value set in AMB configs, smallest token amount that can pass over the bridge                          |\n\n\n### Admin Functions\n\n| Name                                                                        | Returns             | Description                                                    |\n| :-------------------------------------------------------------------------- | :------------------ | :------------------------------------------------------------- |\n| createSecret(\\[name])                                                       | string              | Create a secret for a Data Union                               |\n| addMembers(memberAddressList, \\[options])                                   | Transaction receipt | Add members                                                    |\n| removeMembers(memberAddressList, \\[options])                                | Transaction receipt | Remove members from Data Union                                 |\n| withdrawAllToMember(memberAddress, \\[options])                              |                     |                                                                |\n| withdrawAllToSigned(memberAddress, recipientAddress, signature, \\[options]) |                     |                                                                |\n| setAdminFee(newFeeFraction)                                                 | Transaction receipt | `newFeeFraction` is a `Number` between 0.0 and 1.0 (inclusive) |\n\nHere's an example how to deploy a data union contract and set the admin fee:\n\n```js\nconst client = new StreamrClient({\n    auth: { privateKey },\n})\n\nconst dataUnion = await client.deployDataUnion()\nawait client.setAdminFee(0.3, { dataUnion })\n```\n\n### Member functions\n\n| Name                                                            | Returns             | Description                                                                 |\n| :-------------------------------------------------------------- | :------------------ | :-------------------------------------------------------------------------- |\n| join(\\[secret])                                                 | JoinRequest         | Join the Data Union (if a valid secret is given, the promise waits until the automatic join request has been processed)  |\n| isMember(memberAddress)                                         | boolean             |                                                                             |\n| withdrawAll(\\[options])                                         | Transaction receipt | Withdraw funds from Data Union                                              |\n| withdrawAllTo(recipientAddress, \\[options])                     | Transaction receipt | Donate/move your earnings to recipientAddress instead of your memberAddress |\n| signWithdrawAllTo(recipientAddress)                             | Signature (string)  | Signature that can be used to withdraw tokens to given recipientAddress     |\n| signWithdrawAmountTo(recipientAddress, amountTokenWei)          | Signature (string)  | Signature that can be used to withdraw tokens to given recipientAddress     |\n\nHere's an example how to sign off on a withdraw to (any) recipientAddress:\n\n```js\nconst client = new StreamrClient({\n    auth: { privateKey },\n    dataUnion,\n})\n\nconst signature = await client.signWithdrawAllTo(recipientAddress)\n```\n\n### Query functions\n\nThese are available for everyone and anyone, to query publicly available info from a Data Union:\n\n| Name                                                       | Returns                                        | Description                             |\n| :--------------------------------------------------------- | :--------------------------------------------- | :-------------------------------------- |\n| getStats()                                                 | {activeMemberCount, totalEarnings, ...}        | Get Data Union's statistics             |\n| getMemberStats(memberAddress)                              | {earnings, proof, ...}                         | Get member's stats                      |\n| getWithdrawableEarnings(memberAddress)                     | `BigNumber` withdrawable DATA tokens in the DU |                                         |\n| getAdminFee()                                              | `Number` between 0.0 and 1.0 (inclusive)       | Admin's cut from revenues               |\n| getAdminAddress()                                          | Ethereum address                               | Data union admin's address              |\n| getVersion()                                               | `0`, `1` or `2`                                | `0` if the contract is not a data union |\n\nHere's an example how to get a member's withdrawable token balance (in \"wei\", where 1 DATA = 10^18 wei)\n\n```js\nconst client = new StreamrClient({\n    dataUnion,\n})\n\nconst withdrawableWei = await client.getMemberBalance(memberAddress)\n```\n\n## Utility functions\n\n| Name                                    | Description                                                                                                                                                                                                                                                       |\n| :-------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| StreamrClient.generateEthereumAccount() | Generates a random Ethereum private key and returns an object with fields `address` and privateKey. Note that this private key can be used to authenticate to the Streamr API by passing it in the authentication options, as described earlier in this document. |\n| getTokenBalance(address)                | `BigNumber`                                     | Mainnet DATA token balance                       |\n\n## Events\n\nThe client and the subscriptions can fire events as detailed below.\nYou can bind to them using `on`.\n\n| Name                                | Description                                                                              |\n| :---------------------------------- | :--------------------------------------------------------------------------------------- |\n| on(eventName, function)             | Binds a `function` to an event called `eventName`                                        |\n| once(eventName, function)           | Binds a `function` to an event called `eventName`. It gets called once and then removed. |\n| removeListener(eventName, function) | Unbinds the `function` from events called `eventName`                                    |\n\n### Events on the StreamrClient instance\n\n| Name         | Handler Arguments | Description                                                      |\n| :----------- | :---------------- | :--------------------------------------------------------------- |\n| connected    |                   | Fired when the client has connected (or reconnected).            |\n| disconnected |                   | Fired when the client has disconnected (or paused).              |\n| error        | Error             | Fired when the client encounters an error e.g. connection issues |\n\n```js\n// The StreamrClient emits various events\nclient.on('connected', () => {\n    // note no need to wait for this before doing work,\n    // with autoconnect enabled the client will happily establish a connection for you as required.\n    console.log('Yeah, we are connected now!')\n})\n```\n\n### Events on the Subscription object\n\n| Name         | Handler Arguments                                                                                                                                                         | Description                                                                                         |\n| :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------- |\n| unsubscribed |                                                                                                                                                                           | Fired when an unsubscription is acknowledged by the server.                                         |\n| resent       | [ResendResponseResent](https://github.com/streamr-dev/streamr-client-protocol-js/blob/master/src/protocol/control_layer/resend_response_resent/ResendResponseResentV1.js) | Fired after `resending` when the subscription has finished resending and message has been processed |\n| error        | Error object                                                                                                                                                              | Reports errors, for example problems with message content                                           |\n\n## Partitioning\n\nPartitioning (sharding) enables streams to scale horizontally. This section describes how to use partitioned streams via this library. To learn the basics of partitioning, see [the docs](https://streamr.network/docs/streams#partitioning).\n\n### Creating partitioned streams\n\nBy default, streams only have 1 partition when they are created. The partition count can be set to any positive number (1-100 is reasonable). An example of creating a partitioned stream using the JS client:\n\n```js\nconst stream = await client.createStream({\n    name: 'My partitioned stream',\n    partitions: 10,\n})\nconsole.log(`Stream created: ${stream.id}. It has ${stream.partitions} partitions.`)\n```\n\n### Publishing to partitioned streams\n\nIn most use cases, a user wants related events (e.g. events from a particular device) to be assigned to the same partition, so that the events retain a deterministic order and reach the same subscriber(s) to allow them to compute stateful aggregates correctly.\n\nThe library allows the user to choose a _partition key_, which simplifies publishing to partitioned streams by not requiring the user to assign a partition number explicitly. The same partition key always maps to the same partition. In an IoT use case, the device id can be used as partition key; in user interaction data it could be the user id, and so on.\n\nThe partition key can be given as an argument to the `publish` methods, and the library assigns a deterministic partition number automatically:\n\n```js\nawait client.publish('my-stream-id', msg, Date.now(), msg.vehicleId)\n\n// or, equivalently\nawait stream.publish(msg, Date.now(), msg.vehicleId)\n```\n\n### Subscribing to partitioned streams\n\nBy default, the JS client subscribes to the first partition (partition `0`) in a stream. The partition number can be explicitly given in the subscribe call:\n\n```js\nconst sub = await client.subscribe({\n    stream: 'my-stream-id',\n    partition: 4, // defaults to 0\n}, (payload) => {\n    console.log('Got message %o', payload)\n})\n```\n\nOr, to subscribe to multiple partitions, if the subscriber can handle the volume:\n\n```js\nconst handler = (payload, streamMessage) => {\n    console.log('Got message %o from partition %d', payload, streamMessage.getStreamPartition())\n}\n\nawait Promise.all([2, 3, 4].map(async (partition) => {\n    await client.subscribe({\n        stream: 'my-stream-id',\n        partition,\n    }, handler)\n}))\n```\n\n## Logging\n\nThe Streamr JS client library supports [debug](https://github.com/visionmedia/debug) for logging.\n\nIn node.js, start your app like this: `DEBUG=StreamrClient* node your-app.js`\n\nIn the browser, set `localStorage.debug = 'StreamrClient*'`\n\n## For Developers\n\nPublishing to npm is automated via Github Actions. Follow the steps below to publish `latest` or `beta`.\n\n### Publishing `latest`\n\n1.  Update version with either `npm version [patch|minor|major]`. Use\n    semantic versioning <https://semver.org/>. Files package.json and\n    package-lock.json will be automatically updated, and an appropriate\n    git commit and tag created.\n\n2.  `git push --follow-tags`\n\n3.  Wait for Github Actions to run tests\n\n4.  If tests passed, Github Actions will publish the new version to npm\n\n### Publishing `beta`\n\n1.  Update version with either `npm version [prepatch|preminor|premajor] --preid=beta`. Use semantic versioning\n    <https://semver.org/>. Files package.json and package-lock.json will be automatically updated, and an appropriate git commit and tag created.\n\n2.  `git push --follow-tags`\n\n3.  Wait for Github Actions to run tests\n\n4.  If tests passed, Github Actions will publish the new version to npm\n","browser":"dist/streamr-client.web.min.js","engines":{"node":">= 12"},"gitHead":"aaed908a20b8551070e8bf2835edd74d928d85f5","license":"Apache-2.0","scripts":{"dev":"webpack --progress --colors --watch --mode=development","test":"jest --detectOpenHandles","build":"rm -rf dist; NODE_ENV=production webpack --mode=production --progress && npm run build:types","eslint":"eslint --cache-location=node_modules/.cache/.eslintcache/ '*/**/*.{js,ts}'","prepack":"npm run build","coverage":"jest --coverage","prebuild":"npm run eslint -- --cache","benchmark":"npm run benchmarks","test-unit":"jest test/unit --detectOpenHandles","benchmarks":"node test/benchmarks/publish.js && node test/benchmarks/subscribe.js","test-types":"tsc --noEmit --project ./tsconfig.test.json","build:types":"tsc --emitDeclarationOnly","clear-cache":"rm -rf node_modules/.cache; rm -rf .cache; rm -rf dist; jest --clearCache;","test-flakey":"jest --forceExit test/flakey/*","test-browser":"node ./test/browser/server.js & node node_modules/nightwatch/bin/nightwatch ./test/browser/browser.js && pkill -f server.js","build-example":"cd examples/webpack && npm run build-with-parent","benchmark-build":"npm run build-benchmark","build-benchmark":"npm run benchmarks","install-example":"cd examples/webpack && npm ci","test-integration":"jest --forceExit test/integration","prebuild-benchmark":"npm run build -- --config-name=node-lib","test-integration-resend":"jest --forceExit --testTimeout=15000 --testNamePattern='(resend|Resend|resent|Resent)' test/integration/*.test.js","test-integration-no-resend":"jest --forceExit --testTimeout=10000 --testPathIgnorePatterns='resend|Resend' --testNamePattern='^((?!(resend|Resend|resent|Resent|gap|Gap)).)*$' test/integration/*.test.js","test-integration-dataunions":"jest --forceExit --testTimeout=15000 --runInBand test/integration/dataunion"},"_npmUser":{"name":"timoxley","email":"secoif@gmail.com"},"homepage":"https://github.com/streamr-dev/streamr-client#readme","#IMPORTANT":"babel-runtime must be in dependencies, not devDependencies","deprecated":"This is an unsupported beta version. Please use streamr-client@5.2.1 and above.","repository":{"url":"git://github.com/streamr-dev/streamr-client.git","type":"git"},"_npmVersion":"6.14.11","description":"JavaScript client library for Streamr","directories":{"test":"test","example":"examples"},"maintainers":[{"name":"kare","email":"kare.nuorteva@me.com"},{"name":"juhah","email":"juha.haavisto@streamr.com"},{"name":"fonty1","email":"mr.matto@gmail.com"},{"name":"hpihkala","email":"henri.pihkala@streamr.com"},{"name":"tumppi","email":"tuomas.koponen@streamr.com"},{"name":"timoxley","email":"secoif@gmail.com"},{"name":"harbu","email":"harbuzen@gmail.com"},{"name":"mariusz_io","email":"mariusz@mariusz.io"},{"name":"pzsavola","email":"petri.savolainen@spaceify.net"},{"name":"mmartinmo","email":"martin.moravek@streamr.com"},{"name":"juslesan","email":"santeri.juslenius@gmail.com"},{"name":"jtakalai","email":"juuso.takalainen@streamr.com"},{"name":"jwolff","email":"jwolff@isentropy.com"},{"name":"streamr-dev","email":"devtools@streamr.com"},{"name":"teogeb","email":"teo@streamr.com"}],"_nodeVersion":"14.15.4","dependencies":{"qs":"^6.9.6","ws":"^7.4.2","mem":"^8.0.0","once":"^1.4.0","uuid":"^8.3.2","debug":"^4.3.2","p-limit":"^3.1.0","p-queue":"^6.6.2","p-memoize":"^4.0.1","quick-lru":"^5.1.1","bufferutil":"^4.0.3","node-fetch":"^2.6.1","typescript":"^4.1.4","eventemitter3":"^4.0.7","@babel/runtime":"^7.12.13","utf-8-validate":"^5.0.4","lodash.uniqueid":"^4.0.1","promise-memoize":"^1.2.1","readable-stream":"^3.6.0","@ethersproject/abi":"^5.0.12","@ethersproject/sha2":"^5.0.7","node-webcrypto-ossl":"^2.1.2","@ethersproject/bytes":"^5.0.9","@ethersproject/wallet":"^5.0.10","node-abort-controller":"^1.1.0","@babel/runtime-corejs3":"^7.12.13","@ethersproject/address":"^5.0.9","webpack-node-externals":"^2.5.2","streamr-client-protocol":"^8.0.0-beta.2","@ethersproject/bignumber":"^5.0.13","@ethersproject/contracts":"^5.0.9","@ethersproject/keccak256":"^5.0.7","@ethersproject/providers":"^5.0.19","@ethersproject/transactions":"^5.0.9"},"_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"jest":"^26.6.3","sinon":"^9.2.4","buffer":"^6.0.3","eslint":"^7.20.0","ethers":"^5.0.26","core-js":"^3.8.3","express":"^4.17.1","webpack":"^4.46.0","@types/qs":"^6.9.5","benchmark":"^2.1.4","@babel/cli":"^7.12.10","nightwatch":"^1.5.1","@babel/core":"^7.12.10","@types/jest":"^26.0.20","async-mutex":"^0.2.6","geckodriver":"^1.22.1","jest-circus":"^26.6.3","webpack-cli":"^4.4.0","@types/debug":"^4.1.5","babel-loader":"^8.2.2","chromedriver":"^88.0.0","eslint-loader":"^4.0.2","webpack-merge":"^5.7.3","@babel/preset-env":"^7.12.11","streamr-test-utils":"^1.3.0","eslint-config-airbnb":"^18.2.1","eslint-plugin-import":"^2.22.1","eslint-plugin-promise":"^4.2.1","terser-webpack-plugin":"^4.2.3","webpack-bundle-analyzer":"^4.4.0","@babel/preset-typescript":"^7.12.13","@typescript-eslint/parser":"^4.15.1","git-revision-webpack-plugin":"^3.0.6","eslint-config-streamr-nodejs":"^1.3.0","@babel/plugin-transform-classes":"^7.12.1","@babel/plugin-transform-runtime":"^7.12.15","babel-plugin-add-module-exports":"^1.0.4","@typescript-eslint/eslint-plugin":"^4.15.1","@babel/plugin-proposal-class-properties":"^7.12.1","babel-plugin-transform-class-properties":"^6.24.1","@babel/plugin-transform-modules-commonjs":"^7.12.1"},"optionalDependencies":{"bufferutil":"^4.0.3","utf-8-validate":"^5.0.4"},"_npmOperationalInternal":{"tmp":"tmp/streamr-client_5.0.0-beta.7_1614114598071_0.27048253916917875","host":"s3://npm-registry-packages"},"_id":"streamr-client@5.0.0-beta.7","version":"5.0.0-beta.7"}