{"_id":"ts-nats","_rev":"43-79f5610486a04a10e36d1c03af74d110","name":"ts-nats","dist-tags":{"latest":"1.2.15","next":"1.2.15","alpha":"2.0.0-2"},"versions":{"0.0.9":{"name":"ts-nats","version":"0.0.9","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/nats.{d.ts,js} lib/","cover":"nyc report --reporter=html && open coverage/index.html","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm:beta":"npm publish --tag=next"},"engines":{"node":">= 4.5.0"},"dependencies":{"lodash":"^4.17.10","nuid":"^1.0.0"},"devDependencies":{"@types/node":"^9.6.13","ava":"^1.0.0-beta.6","dependency-check":"2.5.x","if-node-version":"^1.1.1","nyc":"^12.0.2","ts-node":"^6.0.3","typescript":"^2.8.3"},"typings":"./lib/nats.d.ts","ava":{"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**"]},"gitHead":"8dced5da279c6944cb84382839c7d333738ad60b","_id":"ts-nats@0.0.9","_npmVersion":"6.1.0","_nodeVersion":"9.5.0","_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"dist":{"integrity":"sha512-d6/CJFgQZMaCCnaOGml1CH2uNKUdb4LiTvMyPfMIveWZjQpbWosDfkL9QZ08y+cObuYhjtnZR3Q9BzwRrna2Tg==","shasum":"7d3d0e5c5c7df6c77c484853ce3bfb70594f946e","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-0.0.9.tgz","fileCount":130,"unpackedSize":5861875,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbWjW0CRA9TVsSAnZWagAAquQP/2K3MQePY2vgF8j0MaLo\noz93SmRQbJc1JYCMnQqnzpgsxhqtw5ZlVHeK/CKcCNf0BG5okFPJ+4kbvtHY\n2ee3JL/iJ18pxUliBzWuXae3Dfa3jQjF4ToaaNL2Keynj4/Eq8c9jZA9YbC9\naOoYkEN+k70frGzkhZQ+IlfjQBID+AqtmUMuyBHGiyGccHfdyIoM3zeuktul\n/qbGAGGzzTZXFGEUViZk5/KPvolChreKmP8FZ51kvbMpcFPPrzOG+9NpsXIL\nohBvnnz+MBwZ7mb5S9ywmGUWyXtJtnBuvmdw63PWu607ZGNf771vHV+cW835\nOHrfi4zKvcuk6MkOPCJBn6Yc3eSv5IW2dyUBmbh7cdM/M0oXwjOj3dtS/k+k\n04m+K9om4NhCLTkgUfn40c3TS3/+JsuCnwoArVw6D2M3azCW9dUBCNvIm3v0\n+Fkuo5j2VITKspQ7HBVuzbNG50fCiCZOuKhsRhUxaeyvqcO2gkCJfh1QMwO7\njF/EkDJkWRwL0iCedMwGPC93sjTTylmsScJ4CusDpOt/1UnQcoTstz3VR3Kb\ncBX5a3k+KKZyoTkdf5Xq+EaST7fq1BKl/9fW2AMkPtWZMGKppqFvwMzLK6Gg\nsS1oNBD8T3BzzEDtd/Rp7yf2awBUu82ZJZi5QsS3lOzgDsg63gWEar/dvt91\nUBHw\r\n=yJpU\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCWMOGxh1hZd+My7JyT3RonS4WP3Bs6Hcr2Nq++TGHOEwIgXpxKWsQhq0EJUQ56IVwYCkuxue2jsuOFanCSIZTg6D4="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_0.0.9_1532638644416_0.84452158991165"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"0.0.10":{"name":"ts-nats","version":"0.0.10","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover":"nyc report --reporter=html && open coverage/index.html","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm:beta":"npm run build && npm run copy:dist && npm publish --tag=next"},"engines":{"node":">= 4.5.0"},"dependencies":{"lodash":"^4.17.10","nuid":"^1.0.0"},"devDependencies":{"@types/node":"^9.6.13","ava":"^1.0.0-beta.6","dependency-check":"2.5.x","if-node-version":"^1.1.1","nyc":"^12.0.2","ts-node":"^6.0.3","typescript":"^2.8.3"},"typings":"./lib/nats.d.ts","ava":{"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**"]},"readme":"# NATS - Node.js Client\n\nA [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/ts-nats.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/ts-nats/master.svg)]()\n[![Coveralls github branch](https://img.shields.io/coveralls/github/nats-io/ts-nats/master.svg)]()\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/nats)\n[![npm](https://img.shields.io/npm/dt/ts-nats.svg)](https://www.npmjs.com/package/nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n\n## Installation\n\n```bash\nnpm install ts-nats\n```\n\n## Basic Usage\n\n```typescript\n\n```\n\n## Wildcard Subscriptions\n\n```javascript\n\n// \"*\" matches any token, at any level of the subject.\nnats.subscribe('foo.*.baz', function(msg, reply, subject) {\n  console.log('Msg received on [' + subject + '] : ' + msg);\n});\n\nnats.subscribe('foo.bar.*', function(msg, reply, subject) {\n  console.log('Msg received on [' + subject + '] : ' + msg);\n});\n\n// \">\" matches any length of the tail of a subject, and can only be\n// the last token E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz',\n// 'foo.foo.bar.bax.22'\nnats.subscribe('foo.>', function(msg, reply, subject) {\n  console.log('Msg received on [' + subject + '] : ' + msg);\n});\n\n```\n\n## Queue Groups\n\n```javascript\n// All subscriptions with the same queue name will form a queue group.\n// Each message will be delivered to only one subscriber per queue group,\n// queuing semantics. You can have as many queue groups as you wish.\n// Normal subscribers will continue to work as expected.\nnats.subscribe('foo', {'queue':'job.workers'}, function() {\n  received += 1;\n});\n\n```\n## Clustered Usage\n\n```javascript\nvar nats = require('nats');\n\nvar servers = ['nats://nats.io:4222', 'nats://nats.io:5222', 'nats://nats.io:6222'];\n\n// Randomly connect to a server in the cluster group.\nvar nc = nats.connect({'servers': servers});\n\n// currentServer is the URL of the connected server.\nconsole.log(\"Connected to \" + nc.currentServer.url.host);\n\n// Preserve order when connecting to servers.\nnc = nats.connect({'dontRandomize': true, 'servers':servers});\n\n```\n## TLS\n\n```javascript\nvar nats = require('nats');\nvar fs = require('fs');\n\n// Simple TLS connect\nvar nc = nats.connect({port: TLSPORT, tls: true});\n\n// Overriding and not verifying the server\nvar tlsOptions = {\n  rejectUnauthorized: false,\n};\nvar nc = nats.connect({port: TLSPORT, tls: tlsOptions});\n// nc.stream.authorized will be false\n\n// Use a specified CA for self-signed server certificates\nvar tlsOptions = {\n  ca: [ fs.readFileSync('./test/certs/ca.pem') ]\n};\nvar nc = nats.connect({port: TLSPORT, tls: tlsOptions});\n// nc.stream.authorized should be true\n\n// Use a client certificate if the server requires\nvar tlsOptions = {\n  key: fs.readFileSync('./test/certs/client-key.pem'),\n  cert: fs.readFileSync('./test/certs/client-cert.pem'),\n  ca: [ fs.readFileSync('./test/certs/ca.pem') ]\n};\nvar nc = nats.connect({port: TLSPORT, tls: tlsOptions});\n\n```\n## Authentication\n```javascript\n\n// Connect with username and password in the url\nvar nc = NATS.connect(\"nats://foo:bar@localhost:4222\");\n\n// Connect with username and password inside object\nvar nc = NATS.connect({'url':\"nats://localhost:4222\", 'user':'foo', 'pass':'bar'});\n\n// Connect with token in url\nvar nc = NATS.connect(\"nats://mytoken@localhost:4222\");\n\n// Connect with token inside object\nvar nc = NATS.connect({'url':\"nats://localhost:4222\", 'token':'mytoken'});\n\n```\n## Advanced Usage\n\n```javascript\n\n// Publish with closure, callback fires when server has processed the message\nnats.publish('foo', 'You done?', function() {\n  console.log('msg processed!');\n});\n\n// Flush connection to server, callback fires when all messages have\n// been processed.\nnats.flush(function() {\n  console.log('All clear!');\n});\n\n// If you want to make sure NATS yields during the processing\n// of messages, you can use an option to specify a yieldTime in ms.\n// During the processing of the inbound stream, we will yield if we\n// spend more then yieldTime milliseconds processing.\nvar nc = nats.connect({port: PORT, yieldTime: 10});\n\n// Timeouts for subscriptions\nvar sid = nats.subscribe('foo', function() {\n  received += 1;\n});\n\n// Timeout unless a certain number of messages have been received\nnats.timeout(sid, timeout_ms, expected, function() {\n  timeout = true;\n});\n\n// Auto-unsubscribe after MAX_WANTED messages received\nnats.subscribe('foo', {'max':MAX_WANTED});\nnats.unsubscribe(sid, MAX_WANTED);\n\n// Multiple connections\nvar nats = require('nats');\nvar nc1 = nats.connect();\nvar nc2 = nats.connect();\n\nnc1.subscribe('foo');\nnc2.publish('foo');\n\n// Encodings\n\n// By default messages received will be decoded using UTF8. To change that,\n// set the encoding option on the connection.\n\nnc = nats.connect({'servers':servers, 'encoding': 'ascii'});\n\n\n\n// PreserveBuffers\n\n// To prevent payload conversion from a Buffer to a string, set the \n// preserveBuffers option to true. Message payload return will be a Buffer.\n\nnc = nats.connect({'preserveBuffers': true});\n\n// Reconnect Attempts and Time between reconnects\n\n// By default a NATS connection will try to reconnect to a server 10 times\n// waiting 2 seconds between reconnect attempts. If the maximum number of\n// retries is reached, the client will close the connection.\n// To change the default behaviour specify the max number of connection\n// attempts in `maxReconnectAttempts` (set to -1 to retry forever), and the \n// time in milliseconds between reconnects in `reconnectTimeWait`.\n\nnc = nats.connect({'maxReconnectAttempts': -1, 'reconnectTimeWait': 250});\n\nnc.on('error', function(err) {\n\tconsole.log(err);\n});\n\nnc.on('connect', function(nc) {\n\tconsole.log('connected');\n});\n\nnc.on('disconnect', function() {\n\tconsole.log('disconnect');\n});\n\nnc.on('reconnecting', function() {\n\tconsole.log('reconnecting');\n});\n\nnc.on('reconnect', function(nc) {\n\tconsole.log('reconnect');\n});\n\nnc.on('close', function() {\n\tconsole.log('close');\n});\n\n```\n\nSee examples and benchmarks for more information.\n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Aliases                                      | Default                   | Description\n|--------                |---------                                     |---------                  |------------\n| `encoding`             |                                              | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `json`                 |                                              | `false`                   | If true, message payloads are converted to/from JSON\n| `maxPingOut`           |                                              | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` |                                              | `10`                      | Sets the maximun number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 | `client`                                     |                           | Optional client name\n| `noRandomize`          | `dontRandomize`, `NoRandomize`               | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 | `password`                                   |                           | Sets the password for a connection\n| `pedantic`             |                                              | `false`                   | Turns on strict subject format checks\n| `pingInterval`         |                                              | `120000`                  | Number of milliseconds between client-sent pings\n| `preserveBuffers`      |                                              | `false`                   | If true, data for a message is returned as Buffer\n| `reconnect`            |                                              | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    |                                              | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              | `urls`                                       |                           | Array of connection `url`s\n| `tls`                  | `secure`                                     | `false`                   | This property can be a boolean or an Object. If true the client requires a TLS connection. If false a non-tls connection is required.  The value can also be an object specifying TLS certificate data. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                                              |                           | Sets a authorization token for a connection\n| `url`                  | `uri`                                        | `\"nats://localhost:4222\"` | Connection url\n| `useOldRequestStyle`   |                                              | `false`                   | If set to `true` calls to `request()` and `requestOne()` will create an inbox subscription per call.\n| `user`                 |                                              |                           | Sets the username for a connection\n| `verbose`              |                                              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   |                                              | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                                              |                           | If set, processing will yield at least the specified number of milliseconds to IO callbacks before processing inbound messages \n\n\n  \n  \n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build node-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"8dced5da279c6944cb84382839c7d333738ad60b","_id":"ts-nats@0.0.10","_npmVersion":"6.1.0","_nodeVersion":"9.5.0","_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"dist":{"integrity":"sha512-AgFWvbCOxjJ2y8jOfBvo0B9O9rTfj/EbnDrjZm5zMPXaY8kYdKHhKn6QaFtE7X7qYQ/2klbRi3WiPPvDNNIqvw==","shasum":"8d1d4f89170d3fd819432f51184306ed73960da9","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-0.0.10.tgz","fileCount":130,"unpackedSize":5861902,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbWjjuCRA9TVsSAnZWagAA2SUP/009g5E1+WY1wy2J/nfx\nvMDtRPGtoHIgGkBWVde6GeH8JnanS/G2ihbGToSSqdSILlhgpPJiyNfNmO0B\nyPyNi7OaasT5+ulQdv4FzeJggKRpV5n3MTrOlK6Ozae+o0tfF9H1YYxne9KV\nrqfSQ2qlJI5SS+VhQD0DsozJibzJig7BVAnV8bY7DWQBgH2JME1/0voQMOls\nlLrzHxu6PUEwvzPmoNmOm5476XH/93NaaXCHI+1SZWoXA36qZlOlHW15KBy3\nvxI6oNRRl/qgtz88GQR19NT9MWypuVzNjTuRRUGK+bOjG69p/c7J2JLK5gpB\nGPsn+X0/clYyi6bH1RqoblGO1Jk7f7vtQi5A/pv3VveGfR/cJPYhD3JTg9a8\nhpzTdLNCg+ezZdgivos/nOzkRadtlxGBoO1m4WkNC7K+99qbrrFlI/Emlu1c\ndg8YYGtBKjV8MXcjCKeDM+N9+J8uUkb1bXKYVioglK4wtbrUuhSOMEX/Oqwa\nhiYLzlpwST5zUqm5CxPIhJTZDMmXUrujj15ZA6w49EI8XjFns+1lSii77I5J\n/6ZSFhkqlxNWi0ZCMBeubuTpq+3TJma88+/pQhNBaaBtM8J+yPzdX3Bjk2Zx\nZuno+Bhsp6r6Edtkb0YCu5s5gyPyWw7lUjFFk1quj2Y3lI4rRQsX1gTv/qNB\nU/GJ\r\n=vJkt\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIEHz+N4eB1MFEt0UdKOCKizIKpsZe3q1qjSaa7kKEPSfAiEA1zeN2uT1EyPXBjZ6zRE06o/EqigoG7CUjoeu2XHd+To="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_0.0.10_1532639469916_0.695301633975467"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.0.1":{"name":"ts-nats","version":"1.0.1","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=text-lcov | coveralls","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run build && npm run copy:dist && npm publish","publish-npm:beta":"npm run build && npm run copy:dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 4.5.0"},"dependencies":{"nuid":"^1.0.0"},"devDependencies":{"@types/node":"^9.6.13","ava":"^1.0.0-beta.6","coveralls":"^3.0.2","dependency-check":"2.5.x","if-node-version":"^1.1.1","nyc":"^12.0.2","ts-node":"^6.0.3","typedoc":"^0.11.1","typedoc-plugin-markdown":"^1.1.13","typescript":"^2.8.3","why-is-node-running":"^2.0.2"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**","examples/**","benchmark/**"]},"gitHead":"b9a63da5ff7430b9709f1f991fd446190aeaf40c","_id":"ts-nats@1.0.1","_npmVersion":"6.1.0","_nodeVersion":"9.5.0","_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"dist":{"integrity":"sha512-Pd/vVNsZRK78OQqHU4G7hxcJlVWQxoPjc4mKj4UIMQq0rCmpSUwBcwfs3FzOtLx7RCrUCnsqh6wQ0Zaz4pIstg==","shasum":"5f5f17c21ca3ba9c6c2900900938fad972069f7b","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.0.1.tgz","fileCount":70,"unpackedSize":4616180,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbX5mwCRA9TVsSAnZWagAAdHoP/jBet+paWYltrtYuz7M5\nyqeAnYFUArvdDdpmyf+Z2tYKSx6E0Ed7JVMh/W1DkWZbHdA9w9MdW63/8HfT\n4wru7MSMyVVeEN+r6Fr0JH8HFGTgk3uP9wP/sjz6SUtd1x4jBFj75p2m7KCG\ndmsdIGQvYhAqxhdxeYcmwwazGy6bUcE8aeIPvHW72TWmKNQweS6lLL119vp8\nSRmvV7L8wKylto/W/AtxZdo4STQ7hbANiQv00Y83MOd6OniTUFuYDRufeycn\nqkfSLnCyvIXVr+x/W0MXxo8erxIzXP59EOnuie/zCE6p5fsxy413JhjaOCdW\nEvYSPIUQmyxPPCmnJ4urcT6ITYn63qjE5NuquVn1kpiYPCqJJ+RiTmnHsjVg\nNSG1sD0OY5Ldo6o2+YrfRHJGilG/p+FzbGQFWXP7F7ZL6weSCOYLRu8L4uYp\nFAJe1Y8gmJG0c5nUIw96v9p1YWdV8BiceYp2+IhKzLHkJtVrzyPJ/6xQ0/JU\nLc6f0+r8NcsLi37mM3Ed3Ejzs81QpdIkw5muw194TQ8IskaxjcizOXDgVKcj\nvsLh1r3NX7OpVrgDxqtbRaqe68O5KfBYXAOPR+N5WtYIWxGhmLNFQX+6b2U3\nAgeq8XxlC1MRqgSmC8UXbmnpYyd/9zCLTDcX+5zpehO9NmZh+l3NaCbpqjFR\nic79\r\n=TncC\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCB7wBfJPALc+LlVx3I4agDJDiQDdNuFYO9Nn2OZXRQTAIhAJR5yeLStNi3tM9nLtNLJ+KFNMLEQ3w8/5/dcIFNPcjT"}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.0.1_1532991920030_0.44128058196291176"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.0.2":{"name":"ts-nats","version":"1.0.2","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=text-lcov | coveralls","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run build && npm run copy:dist && npm publish","publish-npm:beta":"npm run build && npm run copy:dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 4.5.0"},"dependencies":{"nuid":"^1.0.0"},"devDependencies":{"@types/node":"^9.6.13","ava":"^1.0.0-beta.6","coveralls":"^3.0.2","dependency-check":"2.5.x","if-node-version":"^1.1.1","nyc":"^12.0.2","ts-node":"^6.0.3","typedoc":"^0.11.1","typedoc-plugin-markdown":"^1.1.13","typescript":"^2.9.2","why-is-node-running":"^2.0.2"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**","examples/**","benchmark/**"]},"gitHead":"03ce5fbdbb434a88096801c524db46f2f7218e84","_id":"ts-nats@1.0.2","_npmVersion":"6.2.0","_nodeVersion":"10.8.0","_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"dist":{"integrity":"sha512-ihlJpZCCfd4KMAa5y3P893ZNxJyAlQENlz6p+MzqFqbPcQJkiFYV6WdIjrVHaZkyLDsWQ3Bfw5G+jodul276pg==","shasum":"0f2b5f89a7c44f7f42c631a64bebb3f59c40bdf9","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.0.2.tgz","fileCount":73,"unpackedSize":4728462,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbbLG0CRA9TVsSAnZWagAAnR4P/jcC8pooCUArbTiNptMh\n2JjZnW1GgGRLChnW4QXx7SRaqmiPQDPt847aLSncbYv2W+S8LLOo9S3Qdrjl\nSwe18qV3a7brvssf0/dykQICDqRKWhCN5kUwrSMnOmVFaCVpSeFjmbUWSIoP\nGuFJCvTIoaDH7H8flReHqH4XYdjq6zmPh2tGledPe/FQMxGIqrjJXOTXsApB\nBIRrQihuERM28crOs5kX+dcKeKtycCTT4yI249Kc4qt7r9EokYyHsRC4xeYy\nIOOMEggqYvykAwchUFU7FYNo0Z9wjeqNT/uJY/glRt+hG4pDcZZFinGL0HQT\nshNElQdHb7yHrUqvwqE1p8hF1IsSxD1YyXeN6ofw/H/eiOITPTmcurShTRpu\n/TijbugwkQD+z7QcF5w55DBlk7XAVQEqYlxFtiW94YUK5/QkYxSim7YOYle+\naQCCfYCBMrH1iXUvzCZypbi/KV0ISeDFChNVh+wYgByC/w58HXJfaT1eNR0g\n/2WWSwkQGouQPxQFW5f7j5jVoo9m52lNM+cvaRNFFV6fIhmQ6dWPiSgjthBB\nzQeFc+TAkIagaQyQj0V2yPUmAyl/84hzGNUsjz5xCefEOaffXWo+MIJQKMcF\nfq78czjEJDLWYNGhfxPunp9LCaUN/wvpky+s/Hz7WzA8ZI5GzSAMuanqS6Vo\nF/qd\r\n=P5I5\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFaDd3OSIW6pG+fhTMB1QrheIpPSj0ubVW6O3SQc7zVxAiEA3Qi2AcY+paOzoYz+bE0MXi5xwu3I9X0wvLoDFZbfo1I="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.0.2_1533850035353_0.5344047584931233"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.0.3":{"name":"ts-nats","version":"1.0.3","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=text-lcov | coveralls","dist":"npm run build && npm run copy:dist","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run dist && npm publish","publish-npm:beta":"npm run dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 4.5.0"},"dependencies":{"nuid":"^1.0.0"},"devDependencies":{"@types/node":"^9.6.13","ava":"1.0.0-beta.7","coveralls":"^3.0.2","dependency-check":"2.5.x","if-node-version":"^1.1.1","nyc":"^12.0.2","ts-node":"^6.0.3","typedoc":"^0.11.1","typedoc-plugin-markdown":"^1.1.13","typescript":"^2.9.2","why-is-node-running":"^2.0.2"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**","examples/**","benchmark/**"]},"readme":"# TypeScript NATS - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/ts-nats.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/ts-nats/master.svg)]()\n[![Coveralls github branch](https://img.shields.io/coveralls/github/nats-io/ts-nats/master.svg)](https://coveralls.io/github/nats-io/ts-nats)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dt/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/ts-nats/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/ts-nats/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS have the `tls` protocol instead of `nats`.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions.\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc10 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc10 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions can be created.\n// - all open subscriptions drain (except the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - publishing or performing request reply results in an error\n// - only action for the client is to close the connection\nawait nc10.drain();\n\n// when drain resolves, client must close - no further interaction with\n// the library is possible.\nnc10.close();\n\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc12 = await connect({payload: Payload.STRING});\nlet nc13 = await connect({payload: Payload.JSON});\nlet nc14 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc14 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc15 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximun number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `tls`                  | `false`                   | This property can be a boolean or an Object. If true the client requires a TLS connection. If false a non-tls connection is required.  The value can also be an object specifying TLS certificate data. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"4c883a9e9fe9d5ba13effcec125fb492d3afcae4","_id":"ts-nats@1.0.3","_npmVersion":"6.4.0","_nodeVersion":"10.8.0","_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"dist":{"integrity":"sha512-PeH/hchUfRZ7tFZUBYVv9e1cDCmgyEPZRLBWsmgNonrOZf4BCp7Eoefh/pfuWP2tuB6MTF5RYsAizA3+9mmCmQ==","shasum":"e6a1ab5350e3e51719ef737ea3e08cb12019cf9b","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.0.3.tgz","fileCount":71,"unpackedSize":5272793,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbdz76CRA9TVsSAnZWagAAw0AP/0Q7KTmmqWyOUjfniAR5\nz5zDPvcI6ln+qvUcq/72s5gVuxyBQWnCk2oCoxCSADOu1clAt+enforckD6u\no83AUQrYUh/bk9lJzKmrmZrU5cq6V7ytP6I8vaWJhamelURXc6Wlpp2WDyq7\nNErd9szshV7U5nJMZKLewIuJGbIef4CY8BVQpirmkVFu6HCxNz1y+QE1Z9vr\n3pJOkWi6zimeKYqCgysF6ii1PQ28JT/DwNKKIbL8Ajq1lEtWzf8/Lvkjtt4Y\nlSx3yz189i8MUa0Ed7IYB+YIsUrUUMjub8HYK1sSftpPqNa6fY/GF4LCL1Mj\nuuiQHzEm/zO4FX0oPJ6URMPCS9qp4l0oYgyU1MvXNzz7QgqrCAQlF0lHHTHZ\n1BumJBiNT13ukPj88LIeZ0lT3mqNBkOhLndPXTC/U2XMMeVyXjj8NVgmgGSA\ncrOIPyNgbcKYogtnEkV5MDyGfsQs7Xxy4XZ5q/PExL02D7HYCRNr5fcN6MW9\n7T1OUbCOFzIGpU/gWv7EBo1SK39Utpmx2ENmNov3Cod34Z6gRkEGviZkOHc+\n6Hem46MdB1dDzwiy/K4x2ftVL74mP6a73rxLbGse0PQgjVOU5B3ivDlnEeAe\n8rj5nfsBm/MKNjLcH1UEOtvtKxvUILU515fcvaLCIU7NJlApFsOYkCytsiWZ\nru5c\r\n=rnmo\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICcjNbjPSM6JRaSxY18EteBCe21KAmImirGFWCsPGHKDAiBscz2AyFESUdHy4YNI68cvOGyjoX8KCrzcRwSNL+QgHA=="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.0.3_1534541561296_0.815562007739562"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.0.4":{"name":"ts-nats","version":"1.0.4","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=text-lcov | coveralls","dist":"npm run build && npm run copy:dist","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run dist && npm publish","publish-npm:beta":"npm run dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 4.5.0"},"dependencies":{"nuid":"^1.0.0"},"devDependencies":{"@types/node":"^9.6.13","ava":"1.0.0-beta.7","coveralls":"^3.0.2","dependency-check":"2.5.x","if-node-version":"^1.1.1","nyc":"^12.0.2","ts-node":"^6.0.3","typedoc":"^0.11.1","typedoc-plugin-markdown":"^1.1.13","typescript":"^2.9.2","why-is-node-running":"^2.0.2"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**","examples/**","benchmark/**"]},"readme":"# TypeScript NATS - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/ts-nats.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/ts-nats/master.svg)]()\n[![Coveralls github branch](https://img.shields.io/coveralls/github/nats-io/ts-nats/master.svg)](https://coveralls.io/github/nats-io/ts-nats)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dt/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/ts-nats/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/ts-nats/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS have the `tls` protocol instead of `nats`.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions.\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc10 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc10 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc10.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc12 = await connect({payload: Payload.STRING});\nlet nc13 = await connect({payload: Payload.JSON});\nlet nc14 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc14 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc15 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximun number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `tls`                  | `false`                   | This property can be a boolean or an Object. If true the client requires a TLS connection. If false a non-tls connection is required.  The value can also be an object specifying TLS certificate data. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"2350dec1a0fac2f683a538bd6b8884140e8bdf59","_id":"ts-nats@1.0.4","_npmVersion":"6.4.0","_nodeVersion":"10.8.0","_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"dist":{"integrity":"sha512-iCYG9CC8vGIMIu0P7pcVpdIEzccqk0QJRh99yxBqIZ5ABKPel2mve8PzdmwAs5dDc2un+l4idq07MFZYIZpf8Q==","shasum":"0a3ad0eff117ee0e8df66e7409ac1bb5261dea02","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.0.4.tgz","fileCount":71,"unpackedSize":5268324,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbhGkxCRA9TVsSAnZWagAAL4EP/0C1oc41mFjpsg5oZGOq\ntx2mSHzxqUW7uYBfyefRC2J2Pn45C6CGm3Jzc2SEeL/vb/wUrf4IzpYKBhG1\nalWkC4U7Y2i0VTTFShhYP0WsEByJjORgPEaBf+9niTx8bVHPZSwF80mAd1ws\nkCT/G9wzQHQq/bwdrt1Q4GY98GYrcoUUxBUCT01uKZfpJcgRb1O1DLpqelOs\nlTl4MHkCzaoAo3nLYOakpmdK3TUJU3mxsD/krhR7q0KiydYzkuccFuXDqZvL\nXtwJrP7sXPSU3mj2wgEHBHw9yhhZklbjLuJzGuPATodolMKP9Z4o8xyJ0DQF\nH4Tz1+Q5lC7/4GmuVf8x33bbEzDyO5sq/lcoTvoK2X3OsX5qZuS8vHYJXFyk\nS4l+F7i95C2kbsJCKnWuFi/9F42dv4z0mGzUH+0bEWt4t6BsXD5ipmaDUEOV\niqgRbfGPO7VrdP60d6itRD2T6tKn2s3YnwgoZ7wS/8tWL/HRabSysgnKw077\n/LjN/kz91gzcwTkLnKcPr5rVq88+MYpeZEeaT8Hc0DexQ2zdNVHwSY69Su1m\nrnaDLWL4phgehsxCP1qBV5r+IQLqx4xkjf1O/k/zn0aIJPKGOJ7x1qMMeMvG\nPhnqQxkIu//RqKm8SvJBDSXJ5+QvpodwUpEKE/mO2/i7FLv//xjDs+wpUJFJ\nV/Fp\r\n=+Rxf\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIGxc9VevqBV73aU8NRD9W1YAbb02v1/drFZMUFpBLI12AiEAws4t+iWsV104dI0Q/BuGq5uOGtAi0ZqvBfsmpbEf/Ng="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.0.4_1535404336410_0.7266461977347352"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.1.0":{"name":"ts-nats","version":"1.1.0","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=text-lcov | coveralls","dist":"npm run build && npm run copy:dist","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run dist && npm publish","publish-npm:beta":"npm run dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 6.14.4"},"dependencies":{"nuid":"^1.0.0","ts-nkeys":"^1.0.10"},"devDependencies":{"@types/node":"^10.12.18","ava":"^1.1.0","coveralls":"^3.0.2","dependency-check":"3.3.0","if-node-version":"^1.1.1","nyc":"^13.1.0","ts-node":"^7.0.1","typedoc":"^0.14.2","typedoc-plugin-markdown":"^1.1.21","typescript":"^3.2.2","why-is-node-running":"^2.0.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**","examples/**","benchmark/**"]},"gitHead":"62066a0f4d5f0303f4623e0355b5d2e680123a0e","_id":"ts-nats@1.1.0","_npmVersion":"6.4.1","_nodeVersion":"10.11.0","_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"dist":{"integrity":"sha512-Z+irlUgepngnDZ7xCiOeyTu9vxSqynSQiRdC+Yxm4WaAC4FkBJwbd0mI56lEZeYwYhk5dkJYq33qugQxyz+twg==","shasum":"4a08494563d7cab5b7590df22f129526713d641d","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.1.0.tgz","fileCount":75,"unpackedSize":6399522,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcR0N0CRA9TVsSAnZWagAAoJkP/0NypyFTfr35vzGRCKYJ\nZEonSV9ocsNGskOLqDMcmzsvQqpiwiQqKvjY6ETgZmaAfiCBb0tYYBdsKndb\n/nakuWmmN7lKt2KZYqnTNzlImemIPhvu0ITFLK7YfF5Ckbjl815wohdkT1EJ\nVE+sqof7upoYS19FVeGGONlFTCric400BLFlsc/G15LqVC4uoLF3lZ+KVcrv\nBGP5Ge+8gRuwM62GWuZVBf0Nd0sFQxH5CmkxOQSAWSBP3lzTmu1qZyCce8bB\ndCDtGwVFsJPkyJ2jFqb9DNB/m4HZ3anzUV8agn0TIznSrn5cDMe4kHdCIJmi\nGL6VjO9yZTN6O3MoNUqZStJUv0vTXa8+i2BZFWBzD5AF6j8smUelYi42qWn6\ndSujwfiIh+H7b4kbZBScUJgTsGtWcobXGTxefdEvAcTc0k7FyWddP/HJkNI3\nuCIvpJLSRaMOKJ4O1uL5CIBgxo03IJVBFpSumGiSVC3on72YQsCv+7vhNF5I\nLQTX+KLc8RpOHY99dRl4Ud7P3y0bCggsE1F7T5nvG0WZsQPbJzGofawpH/yl\nbRKOhxw2pXT6ZSWSlqc6/6QDS7AtksSC5esC6Njiq2zhF36sAb1bHNEmXWvh\nYvE8jLl240hMjVe3IgEF945foiCzuiGUSr2F4jXY3r+PrB7HpeoIwx8XKxzn\nk/yy\r\n=LGMF\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAerANriA5mumYodY+VBy9KX4uaYWjfmtR75pAfkke3LAiBiZoYc612NU9pXHdDPBNMY0b0v+91E+5/nFriVDio75w=="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.1.0_1548174195200_0.5366924275131417"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.1.2":{"name":"ts-nats","version":"1.1.2","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=text-lcov | coveralls","dist":"npm run build && npm run copy:dist","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run dist && npm publish","publish-npm:beta":"npm run dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 6.14.4"},"dependencies":{"nuid":"^1.0.0","ts-nkeys":"^1.0.10"},"devDependencies":{"@types/node":"^10.12.24","ava":"^1.2.1","coveralls":"^3.0.2","dependency-check":"3.3.0","if-node-version":"^1.1.1","nyc":"^13.2.0","ts-node":"^7.0.1","typedoc":"^0.14.2","typedoc-plugin-markdown":"^1.1.26","typescript":"^3.3.3","why-is-node-running":"^2.0.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**","examples/**","benchmark/**"]},"gitHead":"fe194975bf68655b21fe530877435442af44d4e4","_id":"ts-nats@1.1.2","_nodeVersion":"10.11.0","_npmVersion":"6.6.0","dist":{"integrity":"sha512-yNWPdwSbjrroo4QSA/PqhgL1kydCE/JRyZ29tJk4jVK67orTNEQpfjZnbr+KdiffMYAcaYV7hFgTTQZeGYqDrA==","shasum":"df4edbd9bdb28da216eea88ebf6cbd6ac79e41f7","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.1.2.tgz","fileCount":74,"unpackedSize":6411434,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcXfWjCRA9TVsSAnZWagAAQ7UP/iEns6ngrsMS9vq6nuui\njF4eGYCCA5RR9eD56gv+l1rpkQPM4s1ldpL/AmBbjb7qkaBi7loicZsUW0n7\ncrOP168PDcY388zGMDU7atWIG1rPwo6nSSFBBKAFC06bMZ+R7kXLJzLrLPxF\ntgFDspM4ThYws+t+bly8rF3wpsxTdEBDlxKde1zOpXg+MJZZ53FDBN44iIbf\nmfOgJqlAhFoArRsrWjYldAoQcbMBpm2xpFN6nefNihvA7l4ZP4s9Eli8614M\n1CeAeFVRNJmVdDsM1zohaPNLXhJtB5qtmDZyoYnPGIPkq5QykaqJjy5YEVD0\nYbnXThpFtATgIe8B6QZ6A7oMQeeq10pt0vfkTEkNe6187xLqCWjR/e3rh/au\nAP+pOwzbcpDuXdF0REIcE7CUbj9agrkQclWs7pYWTRNRu0yuGE9WKhN8XCXs\nuyOMAW0iX9LRKyFgt+YNbJKAwTmukCr+PHJi34Wme5pJknbAWCKPhN1HRIjj\n5Couw/xtXivxZKZNSbN4oLpF4vHtk9cJlUKtIVhmUh5hUBpYetyApXL+MB44\nqekZdlErRxPSLBg/ksX/9eZ/nC+tRxONr+FdtaNozndJwX+OMniUQjdyf8el\nTDLtZ/UhCfyEHAHg0N5Sd0y0WfjfYjCOjgxuqrdHhWWi1DV+J5jjMEHUr9/T\nbJaD\r\n=lnm0\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIC9UanFCAGCwAE5v/X7GrJEvRQwZqiW0LCGBdDbJUs4kAiBFjdR31R24vvA/MHQII8ye5vrKTygy+huk5EhmLOPiLQ=="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.1.2_1549661602897_0.3501321629132397"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.1.3":{"name":"ts-nats","version":"1.1.3","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=text-lcov | coveralls","dist":"npm run build && npm run copy:dist","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run dist && npm publish","publish-npm:beta":"npm run dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 6.14.4"},"dependencies":{"nuid":"^1.0.0","ts-nkeys":"^1.0.10"},"devDependencies":{"@types/node":"^10.12.24","ava":"^1.2.1","coveralls":"^3.0.2","dependency-check":"3.3.0","if-node-version":"^1.1.1","nyc":"^13.2.0","ts-node":"^7.0.1","typedoc":"^0.14.2","typedoc-plugin-markdown":"^1.1.26","typescript":"^3.3.3","why-is-node-running":"^2.0.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**","examples/**","benchmark/**"]},"gitHead":"6b17812a0e595ff1f1917ece49fe4f1840017ee8","_id":"ts-nats@1.1.3","_npmVersion":"6.4.1","_nodeVersion":"11.4.0","_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"dist":{"integrity":"sha512-yFNUIXucR6rycS3wjqVsn3kOF7QM/Q9F5u73TizRIsKxaasEfq+GsQBpDErsMfEJ8zTwHmGtwbKwyEpUTm3KnA==","shasum":"657e4226bf204efc4cf859113b93483a860d0d21","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.1.3.tgz","fileCount":74,"unpackedSize":5673321,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcklbTCRA9TVsSAnZWagAAo/gP/jtQrsufE30oxGT1/epJ\nKo5Zd9rrcjM6D2kSyOLeWt5lGZ1CYv2b6fUo37JlBHemJHt+6drWdujM4mq+\ngqgK67a1oe7eWV8zg2CdPc1sZtf+YGpttTDEitadX4oLXXf2FUCv/953q/YC\nQLrgZVZt7NaPE71RyWEVycEg3xkvIncDj1vw8HuFJGeFzR+bCt0CKJeoDsq4\n9Vznq/NpOmj/t8Ne3tm3Qxj5eeiQpKQ94EOMISy5+pIGjbzAn9bAns6/t8AN\ntk37qTucYTFbojjgTiLXKHonRv+TqqBtl9EAO/18ypNY4RS1md3I+hh7N7rK\n+mZ5CQMEvDOTvkbb1sTeGljmrJkmW06eeEVeJJUwVEW8bngCMXQ6iQQf4Znr\nQOo0e0P/8def75xXzt7Jut5ERvM4IPaqh7nmVzYU/g93IuoUZmM+EeI4Mlo/\nzb9kZuIjsmivHxKXD/+shMagcVtobbpo3xED4cSVEbM9nMsnR9UI+j8sEkfq\n94M2Pvzly7BkpqUJB4NACt7iwuxQB9TCxVrXus1PVWKtYzzt3QM3/PbYFyUN\ngMS+Pnt+Im2kxxZaNRU8zqbP+9iIjNwb1HIUK4awgEPM3MBSA5i5WKgXJ8mL\n/oNk0PwWHK6YVZNUEXmQWmaNuBIAPaHOtqR/ODLDMwH6HlLrGdbrwOsvOq7/\nQVaH\r\n=dW73\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQD3EosDiNens8AXoQCEPc8a5UhjIAUtV76EnvSMwws9IQIgDmlwa2c19YLZbxpzXq2pXaBwklQyHfDygnJHxl/jU5A="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.1.3_1553094354357_0.9021953117941843"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.1.4":{"name":"ts-nats","version":"1.1.4","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=text-lcov | coveralls","dist":"npm run build && npm run copy:dist","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run dist && npm publish","publish-npm:beta":"npm run dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 6.14.4"},"dependencies":{"nuid":"^1.0.0","ts-nkeys":"^1.0.10"},"devDependencies":{"@types/node":"^10.14.1","ava":"^1.3.1","coveralls":"^3.0.3","dependency-check":"3.3.0","if-node-version":"^1.1.1","nyc":"^13.3.0","ts-node":"^7.0.1","typedoc":"^0.14.2","typedoc-plugin-markdown":"^1.1.27","typescript":"^3.3.4000","why-is-node-running":"^2.0.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**","examples/**","benchmark/**"]},"gitHead":"83d200f68d07655a0525d4ecedbc4497a096762e","_id":"ts-nats@1.1.4","_npmVersion":"6.4.1","_nodeVersion":"11.4.0","_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"dist":{"integrity":"sha512-+WxJpjEXmeyw5lQBA3eFaNOt489PiC/QSopdnsrNg8QthEWscI1jqLy1VJFXAz+coFzHzN+xpg7qummprc+oBA==","shasum":"00db2249e3136e9722729b35b6a57b6e8547d6d6","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.1.4.tgz","fileCount":74,"unpackedSize":5673252,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcklrJCRA9TVsSAnZWagAA5y8P/1kfMLidwcKYJ6NVwPNJ\nShTKqY/mRcypfttEF4FPELP0rqXHWp1TRHv5+eP1jErWof8YMYbglVZLRccY\noS84/6qI27gSvL21f/4GULzcxkbbaPJ/jh25hj6i8nyzEy4GQJKbQghfE3VC\nPcVfjfGqQZusSzyPIKxzUAABzN4voWHCGqwcHBS/2I0NEokVJFJsjh35G6iM\ngljxAr8df7pwuzX66eA7tRMWmGa7NwhrzMqI0RQcz8k/6pcNJEJps3iSBkL+\nsB4QvijTEwUNG3PDndTdfc/SWIxMCRUhTgeejSlH8PZBKMRWEmQWNxJo53y9\nDVgWugNG/Z+3bAMbEGaMBdm1KEZqfUC2yHa1ug7omazZTiVHpuZ+n6olNRaN\n55+YrVd1SHOskSvIGdNW1MGYyWqLU3kEFikvQn1wzw4DSA8xjcGIqSgAjnEG\nMuiSIiBrFDcgK1TkxojuQ3MyWKWpoZscLkkuejrL5t/wCqvFBh6JG422PYo+\ntuMnXsLJGQkGK1NxmxESGA4B7PtncGh3/gwKMU18YSq+jueLkxSzQv9kjaWS\nR0jVLgrSUQP/eFfWYoQJ6chp0YIGKC2Fpo8iRRY1xhRErhfx3uGkrIOuXvQJ\nvI+5BpRzlimqKKWEXgXelkmZZMvepE+qEjuo7i/JFww6/E3P9nCNDAMnikQC\ngQqP\r\n=TK9h\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIBllliltuBt92ZZvcwczOdbDDCzLDk4K7LfY07e0MiMaAiAMAf5RQ9SzkjMrhwWUU740dq0ZYvoq1lxBGQER4eXCIg=="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.1.4_1553095368551_0.7014428527158891"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.0":{"name":"ts-nats","version":"1.2.0","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=text-lcov | coveralls","dist":"npm run build && npm run copy:dist","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run dist && npm publish","publish-npm:beta":"npm run dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 6.14.4"},"dependencies":{"nuid":"^1.0.0","ts-nkeys":"^1.0.10"},"devDependencies":{"@types/node":"^10.14.1","ava":"^1.3.1","coveralls":"^3.0.3","dependency-check":"3.3.0","if-node-version":"^1.1.1","nyc":"^13.3.0","ts-node":"^7.0.1","typedoc":"^0.14.2","typedoc-plugin-markdown":"^1.1.27","typescript":"^3.3.4000","why-is-node-running":"^2.0.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**","examples/**","benchmark/**"]},"gitHead":"947692ff9611ef21302d902e1126ca8949472aa8","_id":"ts-nats@1.2.0","_nodeVersion":"10.11.0","_npmVersion":"6.9.0","dist":{"integrity":"sha512-Ph7oel0o7HW3A5gJfygbdt4f9ezog05u/DWNi2oTOs5WoESUGBQhWdrGDyJ7KtcmZ1Rb4hxh3JVwI0d5idjGQg==","shasum":"723512a710fe4db5c73424bed3c292eb14680baa","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.0.tgz","fileCount":74,"unpackedSize":5745675,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJclQGYCRA9TVsSAnZWagAAUYIP/3bIt8bD7elAo5nSvzlN\nG4S7t+mqbXmhK1k0TRCxZW8YhVSyS+P2YV3/fS5FUy67Pm/gtd5qH3NifrnP\nzhBpFFTchy49MYqU4k8RG7dG1OhE9o1CQo1phv2TTXb9zeZDvAy/wuGxkP4+\npymFU7Li9Q0Nm05Xsw/EjNfVo2y/mYJ17ao06RhGQSdArfwkhWhE5p8vRYf+\nys+/SIzMN1NfYLUPibmfkNnTcZEHXuHaTwJMK7O5YR2eQR844WmseCEO9Lw9\n5NSP4SfzJgBA4sCMjNUeNN6KHxEGMS2LM/IA1IZ9M80Zigp2S17q7qhb5lSs\nkKJBqLKDxf2K3vgEweDiR6b/JTmkgvXTPWqwnY6B0kJ8PZLfHnSjPJ7pCLPk\nBMGxSWh+/n31Q+YfLw5IcEi9AWAbh/3CxJ+WQxMH2q+PGnP9DvvN5AxOAkk0\nRuTx6triT/xZG8RiIAFm/TGb7c4/WM3Mkxz2IikvOGilYruT8syPHdZ9bnJY\nvZuTWACgBZ/V3lDMShN0SyWr7/aPyU6IYhdr9KTzUM71GXKGsXEC8+AIKk65\nUu78sHhvPApsNJnH0oy9rVr03GWxJAYl+4xXOB7KWoiFgoXwMxqASbiwaxDX\neF8Gbg9cjeexf/qwVQEgI8AxwfLb+B8nfxAcf7zKvUk5dDhCFka0e6oh/iKY\nHs6l\r\n=99KD\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCQyF3w2GDrpmbLwHc4gMbJCu/0b2mC/B8qgwHnrB4a2wIgZ4IcxSCZAHEkAWux6j5qMr5uwymmNU8bm5qi+s45K/c="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.0_1553269143702_0.6779067447995648"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.2":{"name":"ts-nats","version":"1.2.2","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=text-lcov | coveralls","dist":"npm run build && npm run copy:dist","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run dist && npm publish","publish-npm:beta":"npm run dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 6.14.4"},"dependencies":{"nuid":"^1.1.0","ts-nkeys":"^1.0.12"},"devDependencies":{"@types/node":"^10.14.4","ava":"^1.4.1","coveralls":"^3.0.3","dependency-check":"3.3.0","if-node-version":"^1.1.1","nyc":"^13.3.0","ts-node":"^7.0.1","typedoc":"^0.14.2","typedoc-plugin-markdown":"^1.1.27","typescript":"^3.3.4000","why-is-node-running":"^2.0.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**","examples/**","benchmark/**"]},"gitHead":"f55cc9c1d74021ade99d433ced4cb9516c957d09","_id":"ts-nats@1.2.2","_nodeVersion":"10.11.0","_npmVersion":"6.9.0","dist":{"integrity":"sha512-OeBHgpbv9yuAyvbjnJD4KZIcYTPCBHK1Hr+kEsBIzXL5t3NDD83B9mV2HaF+h0aKwUXFhKkfKCuyAqf3I/ZUKA==","shasum":"bd3875864ea750d65342e3169c8626e5e7b668ea","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.2.tgz","fileCount":74,"unpackedSize":5774710,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcnk5PCRA9TVsSAnZWagAAyIEP/0LM4lsZIWpjSKzfuzWe\nViILjPNx+HozUoiWwGM9zwEaVZxDlKfZDOfz3cAgQasFLjoHdun0xVB1CdXq\n4h1DPNEicMcvYy1ewVfROMSrTL6926vGdEUXEGyRYFDXO8QStbbycav3MlPX\n+AJjuZ1PpGXi3TVEFDRbg4W03A2IvCce+9fJDOoIpyJEzwQ7PUy+ERdl7RSP\nYWNwU7Wa2W4ZekxQivht8lnvfkH3yE5L1llp+d0nnIq5BnXhsr2pPY9Abyjh\n4MqzXZFwF7bwS71EPFWypeOXSV+4JLoK77hsWr9QpcUH6HVEGcBkCSspyPGJ\nHJaTwjBhG7v9jYYM4r8xvJRDkSmpgOLgMMKDTic1ti6bZQi2ylXABB4pWPrW\nV5yY8wzFyIZ13JBIheol3olG2DpECudqnSAxL1RmFufVCBqlqi2F2SyRgRKb\nHSLOJOWppc0KXsnAKVx9trrmu4pC9IhCLCaf9avMMEgNR4coXsTvMLhbABXz\nGFp5iZbRNXAib7N1EcP176DEwjIBMbX+GomNeyoBA78O/W8sQWgQl5SVmGMT\nfRyYQ1TVSwotxQiH6mZqFERC41sOexWMX0EbA+tHlmefyypVzSCn+T/1kckl\n2PtQgfr4v7hzdgzztR79oqv1WwsYGaKetQFGsJvh+09sgnsnYQDC11S7JjlI\nAnf0\r\n=jv6U\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIC2FURhErlnXEidBhcBypeGn7AjEaBfb6kAHeG7CYPInAiEA5FUjKbkiKfG21gmGn+dme4QELwadu+TLPl5u1+NDY/0="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.2_1553878606006_0.8180617683722611"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.4":{"name":"ts-nats","version":"1.2.4","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/ts-nats.git"},"bugs":{"url":"https://github.com/nats-io/ts-nats/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./lib/src/nats.d.ts","scripts":{"build":"npm run clean:dist && tsc","clean":"npm run clean:dist","clean:dist":"rm -rf lib","copy:dist":"cp lib/src/* lib/","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=text-lcov | coveralls","dist":"npm run build && npm run copy:dist","pack":"npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run dist && npm publish","publish-npm:beta":"npm run dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 6.14.4"},"dependencies":{"nuid":"^1.1.0","ts-nkeys":"^1.0.12"},"devDependencies":{"@types/node":"^10.14.4","ava":"^1.4.1","coveralls":"^3.0.3","dependency-check":"3.3.0","if-node-version":"^1.1.1","nyc":"^13.3.0","ts-node":"^7.0.1","typedoc":"^0.14.2","typedoc-plugin-markdown":"^1.1.27","typescript":"^3.3.4000","why-is-node-running":"^2.0.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":[],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"exclude":["lib/test/**","examples/**","benchmark/**"]},"gitHead":"ae8719082bf0abcec4a841fabab9ffda6460f5f8","_id":"ts-nats@1.2.4","_nodeVersion":"10.11.0","_npmVersion":"6.9.0","dist":{"integrity":"sha512-bIC+PlwHplRqhooa9kE+QPcQ9RPGUXD2ruvdf6LoFpP6MjE6exVoRhYSydm0e5wk7VfuXpTbH1NoopTKHwlOKA==","shasum":"be04c05bce305f586d6ac6a9b12b7d6cf6580502","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.4.tgz","fileCount":74,"unpackedSize":5772647,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcrnkFCRA9TVsSAnZWagAAQxgQAIdt/Dl9cIPCYqSizl4t\nyxXBGyVhCMbKpk0E7LwIPXcny+td9+qb2uV5rD7CGLXKErstuLzqkRS4xgGu\nDzy+b7kYPkl0vQ9g07i+y61HYxn9w7B62D+c6LrrT39TGsH27jB/ZMtm6lv5\nOE3w8dErDjXXYhOPBRDcVS0aG5tEf2EjACo+FFhFtVbiKX8941Nk4GEg/yNi\nLZj34pDYmMJgkv5w3HE9T/6RkDO/V2+07weB0kLmHA5tz3sQb0FiIgJ859qu\ndiB5lUyozSadtb9S3MFHzkCI4SwQdRmHL2HVMTwRZG2qDVmnJWO3M3xvmZn3\nzD18hBITHblXP7P0BRMFcMGwY/oYN1gsCJhjLMXMcE4m6Q3a+R3fcQgTdd4a\ngPZYUk6bndiNHus8ItLcF2yOok/3KbpMP7fT0WNiv99ykt8fg0EeFJqP8ncs\na+2u0ywVQpZ9hpnmksyw1qRCb94Xp9EE3mms/MwtxDwmVfJ9G1QERSX2/DI9\ndWA1rzkgqTHDeQi1HV1DXknjkWO+sbmwMUi5E+XZpjGlEnikl2YgF/nIvM/S\nHjV08B09K2Bl3yiQJhMNd6DDnRutJCUZGS+bYfNB+KWQnJFHXSfAD902Il71\npICE46LL1aRqedzvH9il/2BxD2H/eKfZMTvxgt8BnWNZ6DCvCGFbpYnGzQZJ\nA7Wp\r\n=CdBY\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICGzB+RbPZSJQsB3PRjTh9Dplq/f1RswX0ExbL10ziKaAiAh6DHAdfKE0bVnh/6dSqig9lu7zfEVHXWBL3mf0aTqVw=="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.4_1554938116320_0.48949754414301294"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.7-1":{"name":"ts-nats","version":"1.2.7-1","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean:dist && tsc && npm run copy:dist","clean":"npm run clean:dist","clean:dist":"rm -rf lib/ .nyc_output/ *.d.ts coverage/","copy:dist":"cp lib/src/* lib/ && mv lib/*.d.ts ./ && rm -Rf lib/benchmark lib/examples lib/src lib/test","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","dist":"npm run build && npm run copy:dist","pack":"npm run build && npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","publish-npm":"npm run dist && npm publish","publish-npm:beta":"npm run dist && npm publish --tag=next","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.0","ts-nkeys":"^1.0.14"},"devDependencies":{"@types/node":"^13.7.0","acorn":"^7.1.0","ava":"^2.4.0","coveralls":"^3.0.4","nyc":"^15.0.0","typedoc":"^0.15.0","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.5.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"6e39f762bf451dafd2eea37bc533753e5f703e73","_id":"ts-nats@1.2.7-1","_nodeVersion":"12.15.0","_npmVersion":"6.13.4","dist":{"integrity":"sha512-Jcg76DXOUuqjI7rpkYddBhfTXTxR/eIVVu8wneagaSSgYcG38etQv5ukxxietsUtMvGCDUE2r9AYJwq93idIgQ==","shasum":"d4f69662879ad6fd568f8ffc8b9195d6f8cb6162","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.7-1.tgz","fileCount":45,"unpackedSize":212882,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJePIUhCRA9TVsSAnZWagAAa4UP/1KQscer+PxlfCW7b980\n4f8fGUPIfpFqB4KkrnqZlOyY9fYurxUmKNrjvXll8cy2prQ+nJT983n1yWaq\nT96Z54iOofZOHIbWYYIQvkAgzI1cRjuCOMK5YZcbM4slFG+mOSbw/YtGdxzr\nuHYWEsjN/WJc3CUXS+7REQPjC1c3CECRAotKQd9U9yw4rTkBXHamuqFnzwk6\nwS0x+tVZ4aiEitvTOwCKuOHxk8cEqc75TB+UNtsc43Zea2RGiF3Lf+sPWlig\nOFb/cl0LxEzoMXy3/dPpt2Lh7GgReq2dWreGksisT4Urs0OKBzZKlrSCHNgm\n1pIptoyD+YAr7TcFCJkaIrH0ZkBSLkrHB7q5KFl/TwPfGsomBMCDLSd7fuUa\nooD9C0GA2vZ8KHWsE4Q7+Wsxs7hsboMfef4iOglBzgGYoM/VrGjW3bSmd08g\nClHNLj+CXT7IdEX2kTK3DsWW21Q3/zT4sttNNk+jcpwbZg9BQeOgTpVg3ath\nOSLayVDkI7VyqYi2jlmaEjXmtg5IOvjLR1V7G9Sv7gCyYMLvZ1boB+/bA2lu\nbElQTicagUhSOZzo0QCDd5qLFSgLxkhyUIoMx1zom1WC5cRqyQy40GmluHSQ\nsZekpH8qU7Jft+thY52IiWgwPryOaMiYNMgKxb4cMT+U2r2Z/38dpPrZ5Fvh\nxu85\r\n=0TEU\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCICalIQNrGO3pp8up8vWZppYk3WktD1Ra9XuIRMhW4nJdAiAGU535bymU5+XHbz8bvs9tOZX/rSLFXA5GFHcKDqBadQ=="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.7-1_1581024544843_0.48194127146934895"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.7-3":{"name":"ts-nats","version":"1.2.7-3","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm ./*.d.ts || true && rm -Rf coverage/","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib && mv lib/*.d.ts ./","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.0","ts-nkeys":"^1.0.14"},"devDependencies":{"@types/node":"^13.7.0","acorn":"^7.1.0","ava":"^2.4.0","coveralls":"^3.0.4","nyc":"^15.0.0","typedoc":"^0.15.0","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.5.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"fab83e28c3e5b4d7c18f8433696a82781675cb99","_id":"ts-nats@1.2.7-3","_nodeVersion":"12.15.0","_npmVersion":"6.13.4","dist":{"integrity":"sha512-L0BaXKyezxd2i+G4dNOD7H7ieTlhqssYVVQeWZ+WwMcTSSx7/2zOLW4pI61C7rMrTRXz1qy5zrG1MJimkOm7WA==","shasum":"a4690ee3ce5bcb758750c784c5faf5d4e1923a20","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.7-3.tgz","fileCount":106,"unpackedSize":7719315,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJePIm1CRA9TVsSAnZWagAAjugP/igx2+BX99235itJRRQf\niPyyxCFftOFzNXAZRj31AI3Y34ETYhc/slP8VEwBI+BcnZzKP1tS07XMNn9o\nUHTXnCHAVygOPCdP7Xzs7BUfPFUdhXspa2WvCbq2eLniAY63XEkGcRo59lKT\nmLel4Yn+aNTdkY14d3yLNoOf3YkmwR2hstb0dHCZZSvMSRmv5zvk0ePrysGm\nNhKkztqBlTrqXmtCRH6bzbn07hpZOnuBIid7SZe/lmxsvv7NwS/K9sP/m5EN\njKOSyXH9e47wW9oST3bUI+VTYBdUvIGHXXoi8Q7qEURWCpIlCwCCjnS3GB9k\n/Ycm2eVq69sXnn3Kwc6zrZ/mRDJOqHZMwmOBFNCZ+lckf8JZHa0UTgtVQqnu\nSl5Cb3MMl996UXSvvNHSJuMd4TpZh/xlXxDQji1B3eiP9x9ofa+MSZGP2mQr\n4TV2O/znZQ1VWHnVzDi92FSnQ/Af94V/Cp79CVlfKBrCD0wf8D8J/SyGxOmi\nrsu+KkCEO+ophfmaTHBg6VwIAx3bKAGNxXgq4CxsFOfSUGW5zgR8MN4qdE8/\n4vAulIxRJ/lHAMXvwCl+TVHZF62+5weZE1yKOV4RI3Xjskd+kYoVxCzMHpDL\nOnd9SZOHMasoAVIyIl7T5qiZ7AkB1Lpw5QWgPtHRndkH/06VYyzAoxKwCcmH\nqFLU\r\n=qR0J\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQD4kLtu00Lb44gtf0ufYBrfzePixEMxWZlwN530ET9jCQIgaepBbQkx3Q2YYEoD7hhZPVpbIeDxYfHHUh/q7p/9Hzk="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.7-3_1581025717312_0.2872383480084899"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.7-4":{"name":"ts-nats","version":"1.2.7-4","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm ./*.d.ts || true && rm -Rf coverage/","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib && mv lib/*.d.ts ./","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node $NODE_DEBUG_OPTION node_modules/.bin/ava --verbose -T 6500000 -m","test":"tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.0","ts-nkeys":"^1.0.14"},"devDependencies":{"@types/node":"^13.7.0","acorn":"^7.1.0","ava":"^2.4.0","coveralls":"^3.0.4","nyc":"^15.0.0","typedoc":"^0.15.0","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.5.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"313d4d08cfaef0c01a8a0cebaf5860f84ddd176f","_id":"ts-nats@1.2.7-4","_nodeVersion":"12.15.0","_npmVersion":"6.13.4","dist":{"integrity":"sha512-3SlZ2P0WltKzhJoyD1vFtmauz3X0kWiJG4s8D4MUEPaiUa2Xs4ES+cq8fz3m2NcHl974zr/H0ZEPWmi2qYIw8w==","shasum":"d64b2467efea348dd4b117ae82596526c5c89764","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.7-4.tgz","fileCount":67,"unpackedSize":7542730,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJePIuPCRA9TVsSAnZWagAAN3EP/Rkecc1n04cxjEstwHC1\nynzO/Y2+NDj1TErMdLucAG2CDLCynNwOYzbSeBxeqkf9J4IjA9nBPHT7tPEF\nuRoz386XM8KInvupgOtbDfV2hYeTfBVRtkzdFONVx1lOrkZJYfCe/ky9YEMc\nfGZKEmT5FL9T3qtf+QvrlIRv0MMFTvd7fbGSi3Iw59kIHK6pD1GpoPQbd/IP\nuHKZrBGHdoLlCs3FymU/RXyQbmSTX1HUnGToVt6VmCnqlGEM824a9atmihSh\nZhvnJaTShxlx94MQzfe0TcHrWBi3Cpt3tkoygvWOaDs6LBroQ63teX6c3nj6\nKiIcrpOOYsJ2gk0TAlBe1QPpNRBvtQDvEnyELB+Z3lAJlgZfmVqG9HpHQCSu\na8U3qNvLWzKHtNOQEWFHYRKW10jmQxtUkaqw9evI50VH0JplrVUzGOvDuaxu\n+ObAoDjSpwGLhL8QWUncqF4Clb0lcegRrNnzjTidCfAP3hB207AVIwSh3Zsp\n5thyUAFTE6kZCqMDx+9gdZQNMY1vEIqNGQogziquQ1p7UxkDMncMYQEjLoVO\noNvUvPaV3H3LNeAnOaee3WRJxAkLDeiEawy9bgMfyAqOfPVXIzQqTWP6KN9n\nRpEJtL4u6eKAw+qFDPUxKSm2IaAjjsalO2lkGn/gxDh64aRJOrwfUjBsnexx\nU/AA\r\n=VO4p\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIAi63sHZ0L1LTG+lvKIkV7MxCW8Dfcz2laWkPhF0BmRvAiBCt+AfuGZLcCxSGB7NTUZ5WUjHttffxxgY3aXCuktFVQ=="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.7-4_1581026190514_0.40419733845854755"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.7-6":{"name":"ts-nats","version":"1.2.7-6","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm ./*.d.ts || true && rm -Rf coverage/","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib && mv lib/*.d.ts ./","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.0","ts-nkeys":"^1.0.14"},"devDependencies":{"@types/node":"^13.7.0","acorn":"^7.1.0","ava":"^2.4.0","coveralls":"^3.0.4","nyc":"^15.0.0","typedoc":"^0.15.0","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.5.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"4286b70f0561b05238cd8165cfb1732bac491030","_id":"ts-nats@1.2.7-6","_nodeVersion":"12.15.0","_npmVersion":"6.13.4","dist":{"integrity":"sha512-2I5Cm5KoFOJZEIbnNdUaXV18nk3NdDaVxKXJOCPwyzAWcHmUNV4YMkKt+yrzP4RDfCsY2uyPLnL3LQXexxtN+w==","shasum":"16b0f2f71e9055d4592595737146dfc5dedff327","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.7-6.tgz","fileCount":45,"unpackedSize":220416,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeRqDQCRA9TVsSAnZWagAAWL8P/2R/MpU8gMF3qCNNclim\n7ko1umGnBTHi1ucFKdwOIK+K8u+MPf/2hJC7NuNcJU06Ppg8XGbPiiIEsmel\nOg/Om1uZzxzeE1cX6ssJovLDW4K14bhzGwT864b0NwZmEBTAv7RiVWpv2nP3\n+NicylziAhR5fuDnplHEJlHg49j25td/ECoOsogVynpBy6i53MAolncnrHOA\n72k00oFCPf8lf/BkG4gm74CEtjRrwPYJ5Z0b7PFbF1oON+pJ8DwALgEqz8Oy\n72KEcPkZT6yLosxlv5i19rTF4iR6rM7g6XsNjOc9roRQvWUw18l3zYmu7Lxh\nCpHf27rOjGQBAdXuYxCEtSDxHe+HOUe+UgYraf39bIoY+W/kELTVPxZmEq/e\n6UvjqxmH2nnohQVqjK1C5ivUYfdSyUpdRp7GegYlzbLhcO1cK6kehhjoDIKy\nVWyd2M3FrhGC+YmBRnhAAS6pyenARzlijQboSz9T9VbK9qynjET53U3dChkz\nTpNG3mgNOMWb2VOQ8J4noqiTY0BKQv7d0gvyW345MiEOnlT1yqOovWiKivrC\n866YjRGZsQk5amggqSoS83b2odhEFBS2H7u8nvgUaBzgeLicqEgtA6jLfmHd\neSbFhEXMCs/pDzcJGrHiTnEiDBG65d5/EwrkLXIfa2P2ABeEc7vYPgUIiXa5\nDyMz\r\n=VE8N\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIHYNyPEjohHyJc2YA4DhwVVwC/00XvZm9q3r0heTLOE+AiBpfaIFjPPoPm7+T6lHekPSPFsfFs1pRhrykTyfJKSa0w=="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.7-6_1581686991499_0.4973998662214394"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.7-7":{"name":"ts-nats","version":"1.2.7-7","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm ./*.d.ts || true && rm -Rf coverage/","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib && mv lib/*.d.ts ./","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.0","ts-nkeys":"^1.0.14"},"devDependencies":{"@types/node":"^13.7.0","acorn":"^7.1.0","ava":"^2.4.0","coveralls":"^3.0.4","nyc":"^15.0.0","typedoc":"^0.15.0","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.5.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"9ca3ab4fd20fc11a613b785a2a95f7586c842101","_id":"ts-nats@1.2.7-7","_nodeVersion":"12.15.0","_npmVersion":"6.13.7","dist":{"integrity":"sha512-15xdEQsYexHMZwOnbw4JEV40+j8Ylq5RykAL6B5R0HQwTzRMnYVYgQQolji03Uw2Kn8aT1sRFswSlboJihw/FA==","shasum":"ddb3b6a97004544d60dfab3fd534a7ff90562fd7","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.7-7.tgz","fileCount":45,"unpackedSize":220106,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeYQJDCRA9TVsSAnZWagAA+3wQAJOOIenhPPZSCAOg0CFJ\n6CxC60EhiOsbsFfnf4LP34VAWJnLmgDFL47rHvgCf/UVsUeJSE5XPvxshPJR\nc8NuatCQ5LJy4MNVOIengUTljp76hz4rPdbM6/JX7uPq/3YPbh9Y6Nz+E7T0\nsUGkxzafCYX8n9fNP0xY8W3mjJLdL6A1AcWfqnLz+XyuKbfYruO4mFQJrER0\nuGt+HOprtBn/fqDCUSfhYHQEL2DKFrzx+UrpucjQ3Y/YH0ksegNBuWjbW3OU\nB3DcUr1MFPMY64oJtM71wKVjyNddFDdArDDqIyu74+4m+NY91I4UJ3pOuYc/\nk4T/m2eByTsXsg8sRyRVAngfkXu0377H5Ip4Gpwbp9Vkg6VIjEbAsmbRTHLt\nfmk+5aDnc/f7Xs1En3+rxcO/xQ8V5lp1RoLcb6IWLCLjcXTd/+bIEivqbsrZ\n2lZedY92xMXQn+td1P1/wjC09Hkc0JzZ0gVPA/CfVhENPU+BgSQUW/QapU5v\nmYUfxmRHBmuuQJmjaaAkg5w35FbgXtyaGph4c753jQMd7wvp2qMZV9KXVtDL\nctON/dIsDaacrhsBBr3y78N6s1S8Jq+Qq5MwEMJEJhrsvwIYvK/Q8yNIkKeW\nM6xw4SzjWeNh+m4paD5r8n8POzKA3f3lJtMxKqtUDxSqcMP7q1vwGH/1rj5C\n9xUE\r\n=1FIZ\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDQnjwCgDo+MXjjyfq4X5c6fgXFoZPrDufzHU+3M5SPJgIgdUlShm/zqKftiPEAckatJ+lw68G9RZVJkEZ4Qfjqt8U="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.7-7_1583415874288_0.5349375021722509"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.8":{"name":"ts-nats","version":"1.2.8","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm ./*.d.ts || true && rm -Rf coverage/","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib && mv lib/*.d.ts ./","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.2","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.7.7","acorn":"^7.1.1","ava":"^2.4.0","coveralls":"^3.0.9","nyc":"^15.0.0","typedoc":"^0.15.8","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"gitHead":"737464a9faefe31a85666fa07df4b96ced714133","_id":"ts-nats@1.2.8","_nodeVersion":"12.15.0","_npmVersion":"6.13.7","dist":{"integrity":"sha512-LnQcjye/8y0t7Fat5PfeQ7FJGP02d6tuZw8em4m3Xk57as/PgaTzGT7VsXFEBkP0UhTC96/AZAAYymbnuqOTCw==","shasum":"375d307dbb43688ec3722286a44ccb96e707d87b","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.8.tgz","fileCount":106,"unpackedSize":8017535,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeYREzCRA9TVsSAnZWagAA2oQP/2BmSTN2wcHrvlW8y2wm\nnWO4nwSlCEVF+kiKtzknejlDJWLX5FQ3w/2j8H4jJUJ+DPUkUN/qbMlIgQv2\ndqreBNJ/3Rp0rTnCAuoeUNIZjSlnr/mswAowW9aPiXoL9WGPDpYgPnxlNXXg\n/ZT8AiZDLaLEgeRh4/FplyYYpMJ5v9Ec1zbgxHnTVOm4hGYQLrmZeDDCJCfk\nFtPwRF3x75AcIBWYwbXJBq1da+xKrypfA94B/pStpmIzOWQ4ouG0SgVJWRjr\nV0ngTfmBecHHrxjt0C2e83GINM5UFTleEWcsvlnThjnXJFsSwOK11Grq0axc\nhwINI2CnHeKltX4lmDPCVFvjOjNx3xWITZWOw8gAIyyRF/tooCLPgMTzU3Fm\nhFMrJCmYMCa+FXPLy6BNbx9bEESxUr26JYw3H/3OfSXIO6llrdQx6XpKoTz9\niaGrNf5myyv8W1/irUEamLzmYoMwyi5HHOxn7Jm7oglj6/yBEfUXRlL1Ed5U\nruUZ2k/47s+8BkPpifcczuPtjpgu4ALCoCPlCuk7EW5rIJq3dH3omZHRp2jL\nh8/gqMU3HFMC8L/Z3JUv+tNdoArxIbi9Eubj3jGiYqAwD/zkf+Za4N/nEiWh\nd/kTVhztTWjPm2sMxDy9T/za/GJ/NVs5x2kjJcDAFZbCgafxPCAuVEl+zaEV\nYXy9\r\n=qOqS\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQD0IONxpZt16P6q+c5qpCp2Rr3XxbSz0dLkR9uNTXwFcAIgHwT0fZe+eEyPrYRnIXg82P8zBKnneWX/kr5b+Vol/2E="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.8_1583419698643_0.6138816430185614"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.10-0":{"name":"ts-nats","version":"1.2.10-0","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.2","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.7.7","acorn":"^7.1.1","ava":"^2.4.0","coveralls":"^3.0.9","nyc":"^15.0.0","typedoc":"^0.15.8","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n\n# to install current dev version\nnpm install ts-nats@next\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"6cba5b5977c5e875e846be392ecf93b6aed3f5c9","_id":"ts-nats@1.2.10-0","_nodeVersion":"12.15.0","_npmVersion":"6.13.7","dist":{"integrity":"sha512-5XxfyXOP73NZRP2HXszz6GadvrIZX1KH5ISKgCDQ2Vw3MfjCV5xuqg6wvx8iblQ4OB5rHruzRCgRg5mXOC7PYQ==","shasum":"725b0f24c9fb160185c7c476eda6e2ffd4e9fbd8","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.10-0.tgz","fileCount":106,"unpackedSize":8017549,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeYR3ZCRA9TVsSAnZWagAAe1MP/0zgKvRMmFvX/68O9jR+\n1tbejIjyy3vwGNMVeixM6kEaHKgLqhacGnywX5SKuo+X5DF13K5E0gpueEuq\nd8XpOsQzPQ472lO1ZB2BYFOTGXMtSQH8ah7gS8c6bfHkSiccNwbTIJ6v2PHe\nAMvMtR1h7aRuiKs2X3A1R1QrFi7TYfUTRe5pryF1RIWYmzqxNzWbxeYUQy4N\nE56eJXJ7jJSt+zeobZ+ycLUvrAT3rqzwNnDCcXwWnrrEVjFaJ4hQcxFO1tVM\nu+450NtTTvlGDIf17mnm0aebIU73wzXw/J5JdrZG4gI+i32CyfzHse7n5cUm\nrkiarA53JFIodzgbZVc4Dm78SdLmU6o6CXXTeZTqoBin4YorTpy3CQBIGDYt\nqin9R+2HygU9b6b9HTYwl/88Gsy+Najk6ljvNR2PPQOfGIiMiIbQKVKdQfjV\n2QkRVPjtXjpysteV6upvU9MUlfT1axEwbtD2b1dczGeWdWDvUndAbAbDm+rm\nMCmkIcyOv/SbkSWge00g66OXHOiErd1UHDj74d2xaSptFvaMmyWADjI4iQ38\nf2RLHPEoMMtRNWWsJqViYDS9Dbhg/UZVPTrVD+2uyY2hZbEAslFR1rGbHo3+\n0DhpzTJBR09CThkdztLgK7nw8r+ypw2BB8Oyvd4pOKSbhCkyEjlx7xdSoWN2\n+U8A\r\n=1gsU\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDnseJ1/N5yPaydqPnk0i2rC+YvEnvQkGwLXil+qxiFmgIhAM3XLpb4As1gReYdVAfMufb9XnmgUnahhuoOiEnSzlKe"}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.10-0_1583422936907_0.347485994725683"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.10-1":{"name":"ts-nats","version":"1.2.10-1","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.2","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.7.7","acorn":"^7.1.1","ava":"^2.4.0","coveralls":"^3.0.9","nyc":"^15.0.0","typedoc":"^0.15.8","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n\n# to install current dev version\nnpm install ts-nats@next\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"31f9897247cfaa5b34bc83f2d20e66e9a824b646","_id":"ts-nats@1.2.10-1","_nodeVersion":"12.15.0","_npmVersion":"6.13.7","dist":{"integrity":"sha512-N3BZdBMEyazAbz/+82IUZDlzBoVNfiR2ms3V8ojnLBlqxrl/uV0UjlMMaAPPg+jneJKiR/4aEsNdmQJ+k27o8A==","shasum":"7c3307726b5ad1967c697989c98bcbdd0446b163","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.10-1.tgz","fileCount":106,"unpackedSize":8017450,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeYSG1CRA9TVsSAnZWagAAI2QP/RlS6hCq2rIC/gY3ikC6\nKu8/8J8Pc6QkbslJ0xa8aTSf1FUEDjjAc05hW8rjUF4DqM6Q25qnU7T1tOwy\nnwcg5TezbJ/0OUKhImg7WoYXOCMsj5YRnXyYe2QpHfnf+WhgXi12nyqAjDnx\nMK0HaNuu0KzuBdV67wCyH23KKus9E+djuim3DC5HE+q2d1lJ2N4G/8RvMZUK\nxpEIWd5MpwCjqYPyKa8KzZZiTa8cIaH6ExTfPK7pCFNZ8RW1twKy6S7p57vt\njl22PzIWmTMrPP2H0Yrn1FRMg5trvG08ZTVEvhcd2SDy0ZxmSyuilppkw9dy\n8F+++hwJDcQhvBgOeFXoFrLdRhjx0XnUtZAaxUOi4fIhxtfQcWM4b3aC4k5T\nEpkIG2XNEO6SerF/mTrsYC/CEHKvwqRoKHPIseJkQp/k/QjD1Ig8tMnkbynb\nDYFZ+Fiiy2mol2IYcHFqGxR6VKFtKZLvwB2dsnEn0aVeFGIDpBPpSUvdbaJ/\nUniGksDNooWH50lo9KEsZ4JBme8kM6SPjTRzI1McAdgPw1/zmJYSJmQ27WEl\ndNOPlB8q/44rhdlprfcKUx6PZw9T9p4h1Lnxb+FewXkKnlv1ycqRNsGe3hug\nL1P3Jqv3OpmJrDvQruJZHd2GOFWl6X5lTPahSF6S8/LQy5XtyWMWtM3ZZnCk\nlpS5\r\n=ZyKk\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDhqWZ35e0VRbMuYoAlFDuIBub6uOjuCxPHdctMmrW8ogIhAPpT2tUaxzX+jvOADeARKwm3+xKegTfLKA6tBQFDBJp5"}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.10-1_1583423925106_0.5655541195022258"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.10":{"name":"ts-nats","version":"1.2.10","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.2","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.7.7","acorn":"^7.1.1","ava":"^2.4.0","coveralls":"^3.0.9","nyc":"^15.0.0","typedoc":"^0.15.8","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n\n# to install current dev version\nnpm install ts-nats@next\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"cff12075ca17d22cfd8f0af123eca3f4d115185e","_id":"ts-nats@1.2.10","_nodeVersion":"12.15.0","_npmVersion":"6.13.7","dist":{"integrity":"sha512-XNv7i15x8cBuF8lsVMHFaYqmq3S2d9Y1XttivS5bEfRxWo4XDmMNkvbw0IEWVoIKXqIprHEF6OnXC9sEzUTjmA==","shasum":"01eaa3f3bd9e99603e08ff02d796123e1866673e","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.10.tgz","fileCount":106,"unpackedSize":8017448,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeYSLKCRA9TVsSAnZWagAAJ0UQAJLguOKqSHd6qGz7ffSr\nLc9HDGkoAv9g7q0mA+no4Cwr3/bbmwDvj0yN8GboSt7Cl3QAyQEsPvYAzngC\n5cIBPJSkoCv2EzvRN5fq/4KgRx0orgNpDW1kj/Qbc7sdP6xo+08bc0lMFmAx\nMSGjzUKZ6S4FWQTgaR2Ynw5aotrmyXEI8BS5AcHW2G92YdY+VgzR+2XijrR8\nvUZLMpHjlsPpEdwmK8tX8zzR2FDcOPWBQZHurJH7UfBxAxQfgsakbI6cCM4F\nmnj9yGd9SFYgEbXdVwdMLRxrUsg1T9UZkMT2IThOaypGKpA1YfC1bmV7ENTv\nz8fIUgIHg1pSk5hV/VvZI4CcdCvvUHCP3uLNlGRd204CGX1g4YOWD1NClG45\nD3IoLtfAoCc0JLpQpw1DBnGvqAjXWKexXqNM24a/ANjzAYhKt3cI2bKSlIzS\n0Y+L8NvZn1TXPRwrRQ08o5vHJxAbOykTwTPV2PwWb0mY6iadMHbQoNIoI26F\nUsZuFx+x8EsgJSefRpnsIl9TYbWQxSX7ATP26tnz7PHv58ruZE2OAZ3/pHIL\nwOW3VIlVnRMR94TU6ghp4OKboI8R+ZEIeAExs86VgDnt/s69uy8Dkc1f7HJ8\nHMN6Fya8eI06EkPg1QMZQARsQE68YpkT33QuiEfp2pl7lsk1a9RZb8rwIRg/\nNMDX\r\n=hJsn\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFKxq28vL2QERhfRzH3hE5lM8wEYdP4pWR0ZTMCH6OWxAiAyvVobCKaH2PfQ5WS5+tAZ3PHPlxo1L4iLO/EA55ZJHQ=="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.10_1583424201744_0.2898548382122337"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.12-0":{"name":"ts-nats","version":"1.2.12-0","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.2","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.7.7","acorn":"^7.1.1","ava":"^2.4.0","coveralls":"^3.0.9","nyc":"^15.0.0","typedoc":"^0.15.8","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n\n# to install current dev version\nnpm install ts-nats@next\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","gitHead":"4a3b0910c1abcd87dafd9ec4e37406713fda25be","_id":"ts-nats@1.2.12-0","_nodeVersion":"12.15.0","_npmVersion":"6.13.7","dist":{"integrity":"sha512-wauxgn7bagqdYMtAPIWc40JYqkXVjcjom0ccgJxEHI7v80eunsIGRiWsheDulNPZygqzxBW//z2cxbFob0dPNQ==","shasum":"c66d04bfa8e0eff78757e5973e6c10157fe77fd0","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.12-0.tgz","fileCount":106,"unpackedSize":8017402,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeYSQPCRA9TVsSAnZWagAAKFAP/2jzRDBPGd5yaCysGlL8\naeZ6oK66jn1XW+YyATDy962uYwqdui7NGINKOLg8q1wl8TSRsaxYwiandUU6\ndaOMT/2kleFdaBVbRdhpBY7vBReLRR2YQ/QvhztYrOXcbEE2D7FYOc9CBLOv\nPd+A1wy/pPIcxfa5IDzH0BWLKzrorY+Bch0zK7NQbNiU4Zd9wS3b4+GEkzgB\nznIStm6BrsLUdtWm4t7aoNfuZ9204PPA9CnHAckSjdv0YgggbTZF9oaj1ifk\nC4Bt4OcrGN879aEEX8vl1roqqeiW39Hd3eLMgsmLtQPAOcZrYgR0GzF1AmVa\ngNtsGLImGl7SCG1sWnqJjh6WtlkQlGk8dGpZWozX2uD/ahAXhclYUuD5E3C9\nNRKZk/XC4PVkQKrAJEZ19OwQoG7RRJbDhSKkkKH/owcMq/xyu0sVx4lBig7D\nYLOW3nA5Sg8p7+KCeutWR6OsEyDY/B03CYmn35x5xX0mqPcRqjHELHpyukbl\nwV2eqXX0DfjUvnmBNCBRRGeKTsmNcZwojGXe+2+cWw0jZxYDsaE1O6KhNYmd\nCyuzXW2tJhg2RLtQQlsxYA861VgVAR18XT0FQiBVVbUslR0/px7QheEPQXPW\njTH5IszepD0NOdnKx+NksGh4SjjEiWxbwJc1ODhCtwpMguGdl5LQDNCWmUSM\nPgJi\r\n=dzNj\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDX+Zfjj2z5fvGc0cj0WCBXTRQO+7yyYo3nzsQ05QxxGAIhAKyoyDWQ2dGfSUi5gQ0hITBg4cG95rLpkBydtjGybiZ7"}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.12-0_1583424527301_0.5624003410170952"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.12":{"name":"ts-nats","version":"1.2.12","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.2","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.7.7","acorn":"^7.1.1","ava":"^2.4.0","coveralls":"^3.0.9","nyc":"^15.0.0","typedoc":"^0.15.8","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"gitHead":"57989ad5e1245c258c47489b591e35b10b5f3806","_id":"ts-nats@1.2.12","_nodeVersion":"12.15.0","_npmVersion":"6.13.7","dist":{"integrity":"sha512-pYVUoXjQYtiYA3ShOFqt+9SEo2fpGNyX7TNMEDugU3E7H1HrGsgzc8J4I2fJDMkjPOMDd5K/OXdQg1Yefe1J4Q==","shasum":"7de7a191177a0bf49939e3114d60fed4ad0cafa3","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.12.tgz","fileCount":45,"unpackedSize":220127,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeYSXfCRA9TVsSAnZWagAA1coP/jXA4RQPoMFNx6wA+79b\nLOi/rrMzLLLv9lnJdKMSKZX5fWUWHtGQflLUEOUEwDrzS5keeyru47IEfLx/\nbpLgNq8m1GVGQxTorwlz+JNN3VoFVRhfm8d54dMz6xoSh/Ux3IG2dYVb+gg0\natKQ+jtVxP1i9cxQWZ63ImrY5a1GrMy4HLPI1p0uR5uQAe+8Fk4x7c8nj4fJ\nrOkno8Me6wzrioZfmlc0OSyHzqMRZXWnQYn8nymYgFwh6ddILhkacLf4WRbh\niyhJhLBgRrzus98IrWqA+YKde6LjcqaxO4XgACfKe1AxxUlucNuSV+vENr+j\naT3pxcKHLz94ioe1NzdgUHJ9W2cdHCCAXk+NVrN5B7siiVviWulsYiY85Hj5\nBUhHoikdusZyd0yUzeJOvk7b1lpKHg1871fCCIhuLoBKNXid7/gprOXCxuiW\nhNNxTB3U0GmHIqqJr4nvRcxr960o896yAD7soGY2uLTfzq1RQwRtpug5hxFf\nyHcFiC9eWjgf8bge3pdqtn0MWbgEiqypMOpHJHNmOAGAMeWGCYcnelhUJDTi\nQYGqZchAe4yJU8OBuVzRMSyZLcJqxoO1P1DwLsdVbeAQtMm1W8tWeoIDSxXX\nrfnusc0RQGFnHcUorp+yLMN3YoeOJFvFqGtcagh5Kvr4D4rIkLAd6y59Axot\nKDR9\r\n=DyJ1\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCIlF/0T2ReT7WVPh+aZOkEHmoGPH/lFa29aL0WAfNxpwIhAKZEJfv+epqQXgE21UHP7tddI8hqBzsjk+eYby/QX87f"}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.12_1583424990714_0.753443868065087"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"2.0.0-0":{"name":"ts-nats","version":"2.0.0-0","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"npm run lint && tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll","lint":"tslint -c tslint.json 'src/**/*.ts' 'test/**/*.ts' 'examples/**/*.ts'","fixlint":"tslint -c tslint.json --fix 'src/**/*.ts' 'test/**/*.ts' 'examples/**/*.ts' -t verbose"},"engines":{"node":">= 8.17.0"},"dependencies":{"nats":"^2.0.0-21","nuid":"^1.1.4","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.7.7","acorn":"^7.1.1","ava":"^3.5.1","coveralls":"^3.0.9","nyc":"^15.0.0","tslint":"^6.1.0","typedoc":"^0.15.8","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"gitHead":"4142cae1fbe2d44e298abc40876e2c0e55cf1b8a","readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n\n# to install current dev version\nnpm install ts-nats@next\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `credsFile`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `noMuxRequests`        | `false`                   | If set to `true` calls to `request()`  will create an inbox subscription per call.\n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `tokenHandler`         |                           | A function returning a `token` used for authentication.\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `user`                 |                           | Sets the username for a connection\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","_id":"ts-nats@2.0.0-0","_nodeVersion":"11.4.0","_npmVersion":"6.14.3","dist":{"integrity":"sha512-77jD+9HQbf31iuusxjQo7lckiswqi+OMgV6pqydvIqVtZBLULK8b32M1yN7CzgI2Qf3s4XPlkRFoNqzwXzOa4A==","shasum":"3d313c2b8d9e679c2248c19a6f5bf486e2e598f7","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-2.0.0-0.tgz","fileCount":64,"unpackedSize":846296,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeelPzCRA9TVsSAnZWagAArmAP/1eD4ZAkypGRv7rIMS7c\nG5KH/F6OUjI4qOCfHdZ+PwxUVfT1lz/mlpKf1JG5XZSQrAX9T2Avmcpv99cQ\nE6ZojY2kBCbiR4h0UeHThgznM9XZXkHl3pBOItngHFzieP/JFEf1YSYEDTda\n0Y4EMOpPRyPdlG5MaoWqWGQpmqhxNuKZ2dwn2cOfEZI4vN1RHMs4KPt22e4q\npO2qbpzfShJJ2Mzn6eVgVzuvSfeKa5T5jvXlToTyNPcJm4aCC9IXxAPf/K/G\nlkDG5z6LwcSjtehVFlRh9tK2KOnhRecg92RpByK4j/syjZpXYePwcLq6jHlW\nsEXahr7c0knJJUfkfcPFj8x2YetdbiJO/hsN0RoUQ0LvZV0ufG2ptQWTPaLn\nsMG3gz7DliKWI9OyxgXPCGjAtCe4bXiLmI+3S+D5N0HS76BUQelCwYPRsTQo\nPxBaZGiRMY8sSGJssbKulzbwPkWHR+U8EwNTLz4mHIGmGPQjZ5AiIG7/RXfK\nRYVtQaXYh+TyPrmE784CrbRw0KtfEfHPUP2RsSkPickIsTVXgWdOzVnQHsvH\npSf/ciXVSpKUj26qvgcsqo9dgNsXhAjzN7aYnP9E52uv+q5gBq+Be1on8xlk\noct5YQLsS9/D/0TAohSEl8vCGXpvSfFVJ8UbGX99ouhC+JKWr3Vg+i1wZ581\nRJ91\r\n=3SOg\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIE89zeC0GvBfioz9hanxrPJhYbJeZr2ORcQfl6rCAU5fAiEAoxKKjBei9bn27wHYds7OJ0LUzjY9kP8BjN1xIGNs5e8="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_2.0.0-0_1585075186680_0.3776344091766204"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"2.0.0-1":{"name":"ts-nats","version":"2.0.0-1","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"prepare":"npm run build","build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"npm run lint && tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll","lint":"tslint -c tslint.json 'src/**/*.ts' 'test/**/*.ts' 'examples/**/*.ts'","fixlint":"tslint -c tslint.json --fix 'src/**/*.ts' 'test/**/*.ts' 'examples/**/*.ts' -t verbose"},"engines":{"node":">= 8.17.0"},"dependencies":{"nats":"^2.0.0-21","nuid":"^1.1.4","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.7.7","acorn":"^7.1.1","ava":"^3.5.1","coveralls":"^3.0.9","nyc":"^15.0.0","tslint":"^6.1.0","typedoc":"^0.15.8","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"gitHead":"740ed8efb45d275382b3dd4a2076938540007ebc","readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n\n# to install current dev version\nnpm install ts-nats@next\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `credsFile`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `noMuxRequests`        | `false`                   | If set to `true` calls to `request()`  will create an inbox subscription per call.\n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `tokenHandler`         |                           | A function returning a `token` used for authentication.\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `user`                 |                           | Sets the username for a connection\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","_id":"ts-nats@2.0.0-1","_nodeVersion":"11.4.0","_npmVersion":"6.14.3","dist":{"integrity":"sha512-pILJsl+UemnxiahZNBqcWx/rGb3FWREVnfyLszQ5pKRyFDZw9nyPz/GjXJdQ7zAVeR7uH7CFd6dOylTOEFqYzQ==","shasum":"21b891c6bd0cd9b44f48ed0708ea4cde5c6aef53","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-2.0.0-1.tgz","fileCount":16,"unpackedSize":67641,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeggnBCRA9TVsSAnZWagAALZgP/AqeXOmJr/frcfy5URCN\nNMF5MGWe/cmWE9cN1s8x2GpNdop3wWeI0QDGJS3Dhlh+cUpMLFX/ztgOEgLw\nUGmrb2ebm3FY+eYyIhzVb8x4tBdrnxGTPl5gPdb06+1K/FLd0y7A3mT8IRcS\nX5ATr9CepXIfnnnCsbqp4jtKld+7s77/qFyYB65FrfSYyTFik1XyENYZ1E2+\nTVjj4Hz7VBRS7Ta1Jnd9VEBsM/9eaTJslNTkoKF5lgDrqBlT2dBgMAqJSeb0\num9ZluWuS/O0U9/A/RFwDR18CK9Oo5LFwAmkX9vDK8ufwEoSEUkPDnuwpjnL\n1TKwkEKfz75Ewbwi5DZAr35yfZJRsWWaJbbrKDQrTTAF2jHG85xv13Oy+aiG\npFFByQBDnD+4tp+oFRhVbd+LsGsHkAksaYEwHC/yx6PZ2SPKbDgTDhlgq1zs\nNLuMAMOpC1bAXy7xA9E513HYTTb+gn22ss3ecoC3MWdnFHJpi9QPcvP/HflB\nO18KJgkuHL/geisKSMfeEqzvAvQAjPDKNg07OnBaQSowVlAzfZ3oqargQ8n0\nRCl+RrKasriy8PYzwYxvP/TC2TK18GVxtYN6MUecuPTOk4bRYvSIKM1EJFA6\nAp4I/unbHHkrRhWWFqVZR14uVVxWldYgS/QQCryAIIfvOG24YI3s/9mXf57k\nP/nP\r\n=pwFK\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQC1KpP1QDrRdG158wK0Zt9YbVAXzdNcmnv/KWzxcdw9xQIhANLqwwn9DYR3IwrwQ7YcWYI7C4Hzo/Bms9oCRQnJaBLi"}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_2.0.0-1_1585580481160_0.9528732433235587"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.14-1":{"name":"ts-nats","version":"1.2.14-1","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && cp package.json lib/package.json && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && cp package.json lib/package.json && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.2","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.7.7","acorn":"^7.1.1","ava":"^2.4.0","coveralls":"^3.0.9","nyc":"^15.0.0","typedoc":"^0.15.8","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"gitHead":"5078818f67bfc941315808ae27e37022dbc3c574","readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n\n# to install current dev version\nnpm install ts-nats@next\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","_id":"ts-nats@1.2.14-1","_nodeVersion":"11.4.0","_npmVersion":"6.14.3","dist":{"integrity":"sha512-JHhQqxeKKOG9Bl6YiJ3QkyDQVSKNITbVoGsXp00xeBUU8FaQnpzBAhiT27oIe4A9pgymIxutSCKdhuEna5lWdQ==","shasum":"2a3d328f16da95712960f640cf87628095a18f28","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.14-1.tgz","fileCount":73,"unpackedSize":857666,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJenwHOCRA9TVsSAnZWagAAmecP/j7BpNBHIPui+ksCzl58\nsP7HkmBRYEc5MqluOR8tSViWlULI0jJV8IXYZZraRmE/dZorsmiSZQWMQ5Rg\nGZuF56S+o+7c/9eENdLPX6fn0AmsQvnobGwfR5JW3PugvnASvPHXQbAgIeHy\nCDQThUA/dZ9xbUaCmPUCd3e3voCE6NibfGqqjwLRlIJ1HrWv79SpY0B7vlg6\nlW4848MQ1hRVDOLeeCYJ/2NImqMsgcrlX7j1Y0iVlv8hsbVPGyi4Xfn7P5XR\nCjH+JQSxldorwlPteThJ8Ltkxd9aNeHAA9cCK/GAQSJ45xQC/OQCo4qFnc0p\nTgP8GUUzstxn94z0FXJ+T3GS6Ln/kRUogBVjWmrOMfIQ/lDdkTiAkw58ChyV\n0bjoK4uvXxhStaP0liHbQLppFSkRfaLfe0LLKcONPZZ9eJkJSWaZZU+wIglo\n3NZi3VwAJL7YJrExhG8zDeU5ROwxmj99uiXFxmjeop8UuQTzd/nSKT64UwPQ\nks/Bastp1EkwiNJZr0tS7H84OzeNjOsN40KwehLkAwIDb/nW/BSdRlVZTHAT\npuGJi1RaZEijY+RusHZHjr6EQ+0r36wX8NDomlRL6/rLiXWFc8NhEEkS92UL\ntF2o4BzPIoRm6ENlDWj5Fn8g5I1Rbz2EUMbwnqVXcKXlD9kioefhPmR009uY\nNAAT\r\n=PL/0\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCSGeKOkHUul55ay9WTJWYnHkmGZJwEZrkw7/792KoeOwIgW94oBWmavfZMpdqCh8nFgEGM+hYitP4/ibZ3by8CKJ4="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.14-1_1587478986891_0.8256569062300207"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.14-2":{"name":"ts-nats","version":"1.2.14-2","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"prepare":"npm run build","build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && cp package.json lib/package.json && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && cp package.json lib/package.json && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.2","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.7.7","acorn":"^7.1.1","ava":"^2.4.0","coveralls":"^3.0.9","nyc":"^15.0.0","typedoc":"^0.15.8","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"],"sources":["**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"gitHead":"29f2d5fd7e2bfe24720c3f687a0b0bbaf3de000e","readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n\n# to install current dev version\nnpm install ts-nats@next\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","_id":"ts-nats@1.2.14-2","_nodeVersion":"11.4.0","_npmVersion":"6.14.3","dist":{"integrity":"sha512-b0nPczfd8Z4+LQ5C7xWW391qiPsWNidhZRB9yrumQ0hfRHAos4NVwodPIZd78e/so3zBW5LRifejaAJE/UzNXA==","shasum":"4edfa5a99cb983b727b4e03d3280e9f851929b37","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.14-2.tgz","fileCount":45,"unpackedSize":219863,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJenwODCRA9TVsSAnZWagAAKQ8QAJkEpM/6s+vQPBHRLXNx\n60kML0AgsXtj7Ajlw5ITPMTqv9wt+a0kdAmS6Jnxzqw3M4PdQkTTudEngxkZ\npTCr51WY09UkdX6Xf5r5zJRYE75PnysZvZSOJ31+Ju5MjH8eB0BfZ//NF2n0\nAFPEmx4TY5926xYn93HJFTYVLmSSxXJIwOtx3KEu8iflqjXl7Tq4h7Zrx7KD\n+qK+SopqPTpPNrE8YA9gmMZaSFqfyECHgS3EUj55uJttUs/31PBXp0YxNbyv\noY2tCxlsHAkxOmvOuCq9qPn/hBdL8SBSvpQQ5MOyT/0DZXh3XC/TTRbPGC1U\nckZ0dDZobHtpuCQpN+SIXlc1C/r7mfHbPkTCUJUTEp1AAPB12kJt9Sg63bnI\nACDjZZbyz7seqJ7kl8uK2IWkOy5xUg65iOtlaYlPFmMS2aYpFlp7akgXakNH\nSa21DLlOV76pGiOVZ32Xn7i03TBKkpYlGXzq/1uXrxipULv2oXdzfTdslqS5\nfXjoVjk0gFwVIrqAzn5QApolps4SwstH6mVoUeqeUNW1EO5re8ZN9s9ZsZut\nMLvEH7ihEfBwsThUN1y0BcreLLAoVRlFn9t6n4TxspWDbybX0mlpz+2XKWd6\nnARQOJCjZf5AdTxXvTyJwPUlxAeKgEBzE8pKoB/0hoW46L1aShYxgaLUT3Pd\ngOwU\r\n=coPI\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDSIsqXHYvS07WGcAkWNPynjhQG2IhAsRCg4cNwwcIccwIhAPFiyHeehE3yHEb4Xhwvmy4Yt0LTNV18wZGpPt2YW4Y4"}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.14-2_1587479426859_0.9107303443892198"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"2.0.0-2":{"name":"ts-nats","version":"2.0.0-2","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"prepare":"npm run build","build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && cp package.json lib/ && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"npm run lint && cp package.json lib/ && tsc && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedocconfig.ts && touch ./docs/.nojekyll","lint":"tslint -c tslint.json 'src/**/*.ts' 'test/**/*.ts' 'examples/**/*.ts'","fixlint":"tslint -c tslint.json --fix 'src/**/*.ts' 'test/**/*.ts' 'examples/**/*.ts' -t verbose"},"engines":{"node":">= 8.17.0"},"dependencies":{"nats":"^2.0.0-24","nuid":"^1.1.4","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.7.7","acorn":"^7.1.1","ava":"^3.5.1","coveralls":"^3.0.9","nyc":"^15.0.0","tslint":"^6.1.0","typedoc":"^0.15.8","typedoc-plugin-markdown":"^1.2.1","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"bin":{"tsnats-pub":"examples/tsnats-pub.ts","tsnats-sub":"examples/tsnats-sub.ts","tsnats-req":"examples/tsnats-req.ts","tsnats-rply":"examples/tsnats-rply.ts"},"gitHead":"0015affedc128477014907f66ccb97e6fba12f90","readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n\n# to install current dev version\nnpm install ts-nats@next\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `credsFile`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `noMuxRequests`        | `false`                   | If set to `true` calls to `request()`  will create an inbox subscription per call.\n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `tokenHandler`         |                           | A function returning a `token` used for authentication.\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `user`                 |                           | Sets the username for a connection\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","_id":"ts-nats@2.0.0-2","_nodeVersion":"11.4.0","_npmVersion":"6.14.4","dist":{"integrity":"sha512-917cQYathDaPyIj6m7tzmLXplQ2Lp4wz8mB0kfqhn0crZN2NRh4jeFVilngZDy7R9OaKSNZ+Lv9nfoXUhHzL+A==","shasum":"21372edbdde38ce823cbe51872942d9e39413ccb","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-2.0.0-2.tgz","fileCount":20,"unpackedSize":74348,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJen2oJCRA9TVsSAnZWagAA7rMQAI6OfAaKYPIFB2tfeNSm\nzY8sY46NzgN41jI5PeK0FuWaM3WOwObIMm1q7Puc/rtXUufXDSrjTh8WPGaX\nu4HOkJOE3B++XL7F4CocVsVpfesigKhcxc7pO3E2beuRRGu7Q4hXBApfpuyG\njBUD/VZeGJzZXdGkXzXing3NFnPqrDfjQUj6c8CG49NDmNfl+w917s3+DFem\nCAoyGyofFS3Tx2Dr90Vt/pIyZibA7wEF/R2L2V2KvjEH4S8QrnfmIrOqevLJ\n5vmi62x1Uv1jZFfz+yIvFEosMxv4sZDMBIDL1SZ3oHWI7eOdwxUSob1f2a5s\nzvr5rPlFHdpCAtEKvZPtkCNezSn97WD7jMdjL5wT82unMilf2ZLSixL0DLwF\nngfJiAjV8vtwA4J1bNSJr+N8SMZ1poTKU8s6N97M5p17NgcnJJiQ4dtbR6SY\n8trZ7YoZvD0OLis8NmTL+29EVfqlPdLHZORSJ5UF82fERCJr6SmwgbnMrlLA\nTLXtVp//wMJKp12G7l5zLUy+d7tFgRJnupzimoVijPpkE968iGlMJGT74esW\n8Y29TMde/qQicAPhuW6nLm3rwu7NYQQempwOTVI07C+XiKTvrctpCi2wlg9e\nCrcDgwfR/z/E9VHsqHZfJS8xTz0yBOHpiW36KOta+kEMFZEkPQ9xs5OEOrEe\n0xZf\r\n=zqlE\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCZKDVbvjpJpCLxqCMCtjYarrwB9hNyBPqZ8lwb5MvspQIhAPFtkviYuAJVRE0wnFUxC8GOp4l8SXyYDC/ovQ+rwXSo"}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_2.0.0-2_1587505669907_0.1873058334876614"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.14":{"name":"ts-nats","version":"1.2.14","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"prepare":"npm run build","build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && cp package.json lib/package.json && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && cp package.json lib/package.json && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedoc.json && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.4","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.13.4","acorn":"^7.1.1","ava":"^3.8.1","coveralls":"^3.1.0","nyc":"^15.0.1","typedoc":"^0.17.6","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"gitHead":"21128750825afd2dceec75ebf4d821e680d4235c","_id":"ts-nats@1.2.14","_nodeVersion":"11.4.0","_npmVersion":"6.14.4","dist":{"integrity":"sha512-RGxZcm3rygj4DfbnzdVJtDu6PgKFuf/LALrQ4rKrFCowNgDGWZjg62kCvUNIXimHXDuhMYXz021tysa4jeHyMg==","shasum":"0fec63d7bda7f571ca045a46e6d23d2ad245edaf","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.14.tgz","fileCount":47,"unpackedSize":225618,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeqeVwCRA9TVsSAnZWagAA6ykP/AmIEqSQWBCpAA7rRMGB\nNPqDmS6erVPt8KsTHUaX6G4I62YdQ93DC0p9LjgX8o5pL/6O56kdO2feZGAH\n+Z488O5pWV/usbG+PQGBSpFiaRs6gaojfKAVLGHEut3ar4e0nVG395Y+szaA\ndEhP9eKe5027nHfPMo0JT41NoyfBHlZtxAFhlyb5VreNt98pCTgbXNInTACH\nxA/Ue+nc1rFWbFNYRoBexPAzOgZ3dnp0NJi3F3k/vOBI24EVIQ48KG7m2HwS\nn+L7J0EhSZLscjNxKU/2s16585oz5ALiTFdGuSLVvBMKXdk81nLYhOxPsGnX\na42IE7BNT4rRU2k4sqrI+4RSFSoaM8nYB8Zt/AuH0qTgxKuRRFa8/heUK593\nOz9ilYMk8h1t4PuTlbc3EExLE8mN3I0T350u3UaNMV6J97KmC8aZrFRW+TX0\n6KzH7t+PfcQ47GkIw+GdV8o73zsM/kJ6MAHH1HNGsP3v5XRMZed1/bWpNgIN\n0qK/1Pyw9yEbLpAa5EvHnfvFulRdOqZQbyXM4zl2g4T+nxnGgie0HbHEevNO\nqGskbx8rHDOrTWuPZdLbG3Sd1ostfpyn+uyTloctoU6B/51aH00GrMX/1yEf\n5nndcwYu2o0BQmv33d3/vtZTOfRGERWotpYFB/oAil5h2c+JQZyDK1igBXdw\ngOJj\r\n=9ubb\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIHOYsMmQ6/RlbnIly48puV7JnOev2Ew6R0EMb+0yL2b2AiEAws18gmmFYaFyf34E4thv3h4r7Iee5LPY5R05Wu8SqF8="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.14_1588192624044_0.6160278277961597"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.15-0":{"name":"ts-nats","version":"1.2.15-0","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"prepare":"npm run build","build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && cp package.json lib/package.json && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && cp package.json lib/package.json && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedoc.json && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.4","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.13.4","acorn":"^7.1.1","ava":"^3.8.1","coveralls":"^3.1.0","nyc":"^15.0.1","typedoc":"^0.17.6","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"gitHead":"3ce9d00d273e63fea3865eae8737a36fea64ba59","readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n\n# to install current dev version\nnpm install ts-nats@next\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectJitter`      | `100`                     | Number of millis to randomize after `reconnectTimeWait`. See [jitter](#jitter).\n| `reconnectJitterTLS`   | `1000`                    | Number of millis to randomize after `reconnectTimeWait` when TLS options are specified. See [jitter](#jitter).\n| `reconnectDelayHandler`| Generated function        | A function that returns the number of millis to wait before the next connection to a server it connected to. See [jitter](#jitter).\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n### Jitter \n\nThe settings `reconnectTimeWait`, `reconnectJitter`, `reconnectJitterTLS`, `reconnectDelayHandler` are all related.\nThey control how long before the NATS client attempts to reconnect to a server it has previously connected.\n\nThe intention of the settings is to spread out the number of clients attempting to reconnect to a server over a period of time, \nand thus preventing a [\"Thundering Herd\"](https://docs.nats.io/developing-with-nats/reconnect/random).\n\nThe relationship between these is:\n\n- If `reconnectDelayHandler` is specified, the client will wait the value returned by this function. No other value will be taken into account.\n- If the client specified TLS options, the client will generate a number between 0 and `reconnectJitterTLS` and add it to\n`reconnectTimeWait`.\n- If the client didn't specify TLS options, the client will generate a number between 0 and `reconnectJitter` and add it to `reconnectTimeWait`.\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md","_id":"ts-nats@1.2.15-0","_nodeVersion":"10.20.1","_npmVersion":"6.14.5","dist":{"integrity":"sha512-GuhdRRGWq+Qeza/yuRZ9uKnfFWkHlWeIyQ5HPTOEKTazzJZdRlcAHoCsGWlZhZnbZEo/QIft30QQWnhs5cDleg==","shasum":"3b111ffbbc5e47812825eab26c0efbd6732c3596","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.15-0.tgz","fileCount":47,"unpackedSize":229278,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeyGr2CRA9TVsSAnZWagAADrgP/R2Nc3SgGSekuy7hp+SB\nQNFNm5peJUheuTwAHBb7J0hkN/SRqlpRYuoCyfIRQ4md5li87wKwKfjBxRiH\n0JHuviZCuLOu/qkdv4i3pJZx6RLHFdfbug0t2lg8WXyTSRWAg2CF/xBn/sWg\nbyCGsWL2VEh8wYbljXENGyteAu5DV3cDahd2p6na+S2CkU3zSh9xC3L1kGaL\ncLvd2IT1yDFJyrJFac294+z9arFvU5gzEUD6xZ5/C7ce0I+Iqx9REb98zIAs\naeiyu9aFNY59NDLDQbnhFEc47sNx5V4SGEuUK+6X57ic60mZWwaPK8vIfU+v\nZpMuBswAjK8NBgaQVn4NoMGvfdCRR/+hCfrUNuaSeis1qJh8RuBXR7xkkFTd\ncNl6d6t3SFmMF7yNGR3GhxFzYJvltZe+QZkZ0gMZBvVlUk3wR5712vWxyRj3\nbZ3RKk2lYhNG64Cz/7ePeqtX/8y5QO4fDsG9RpdL6YIh8ERao80RZo2L/W2z\nwfd2fo/zVSS963IaUTVv99birE2AwaeZTcEySkAA0MZrYfIEM4nU0CtP9SpC\nRBIjb753FNOcDMJ6NvqWa2Mh9cNKm1dZ+Ju64i5Vlh7KflW4YGSMgPvrbHxN\njTsTYFb9shRiYR0AcEnYfjo2/f6QVODbcDWH3YDZDZAYeQHcJ6kV5xSt79H+\nTBZ/\r\n=ckuq\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCp9xuflFk+ldCYLPWxtfeHqZzgscpi9e0kq4amr1kc2gIgcbenJcQ1fy+1IpozIMCTQeg72dS1jHdqWejrXYqv2IY="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.15-0_1590192886206_0.5862024592395407"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"},"1.2.15":{"name":"ts-nats","version":"1.2.15","description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"homepage":"https://nats.io","repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","private":false,"author":{"name":"The NATS Authors"},"contributors":[],"main":"./index.js","types":"./","scripts":{"prepare":"npm run build","build":"npm run clean && tsc && npm run copy","clean":"rm -Rf lib/ || true && rm -Rf .nyc_output/ || true && rm -Rf coverage/ || true","copy":"cp -R ./lib/src ./dist && rm -Rf lib/ && mv dist lib","cover:html":"nyc report --reporter=html && open coverage/index.html","cover:coveralls":"nyc report --reporter=lcovonly && cat ./coverage/lcov.info | coveralls","pack":"npm run build && npm pack","debugtest":"tsc && cp package.json lib/package.json && node node_modules/.bin/ava --verbose -T 6500000 --match","test":"tsc && cp package.json lib/package.json && nyc ava --verbose -T 15000","doc":"typedoc --options ./typedoc.json && touch ./docs/.nojekyll"},"engines":{"node":">= 8.17.0"},"dependencies":{"nuid":"^1.1.4","ts-nkeys":"^1.0.16"},"devDependencies":{"@types/node":"^13.13.4","acorn":"^7.1.1","ava":"^3.8.1","coveralls":"^3.1.0","nyc":"^15.0.1","typedoc":"^0.17.6","typescript":"^3.8.3"},"typings":"./lib/nats.d.ts","ava":{"failFast":false,"require":["./lib/test/helpers/ava_fix.js"],"files":["./lib/test/**/*.js","!./lib/test/helpers/**/*.js"]},"nyc":{"extension":[".ts",".js"],"include":["src/**/*.ts","lib/src/**/*.js"],"exclude":["lib/test/**","examples/**","benchmark/**"],"sourceMap":true,"all":true},"gitHead":"77cd1cf0ad1d992ca1fc3dd4d545228d8a349a3b","_id":"ts-nats@1.2.15","_nodeVersion":"10.20.1","_npmVersion":"6.14.5","dist":{"integrity":"sha512-5dNokE+DpCcxfmfzDEid1P9awOUo7EfIzYnL175jCi/L8NpFFjgTdwqR/DsqYBPC4dk7MrOkwrZK8tM8z+i3rw==","shasum":"cfcf25d77687c96cf563264265fa0faf99a89c80","tarball":"https://registry.npmjs.org/ts-nats/-/ts-nats-1.2.15.tgz","fileCount":47,"unpackedSize":229276,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeyGt/CRA9TVsSAnZWagAAd9IQAJdzSdckFXp/4X+W9IFv\nvCaqTfnrROYqwy4tGs4TtKaHgADd0zZ47GRv4Yf6XQ2/vyzFJH4nFwiZBMWM\nkcfgQ/sFmD22bpObd5YidnTHrXVh+o9INwN0UIHf1YEmORJi9GqbXxaUWcVV\nSGACc7KSWj/OiqpQWdnAZBNhwVMzxOLv/oW7D+Ix3SSK2Sl61ovCyMalfHhU\nx+9CuHx/Jnc7UM/ff6nAFuHPLFCeqzLXkPgmi5bRl/33z2OXP3eyDaZ1Go/E\nB/T338sgxPGT/tB2SSXiZ8Yf1RuAJkK0q8GLXfqlRh1Odla02EeHe4Fq5S0K\n+JsNYHOUw58iPBRCXvO7bxejbvtcoXCaFkFTTYFwSupnTHZ32O9VeICtIe4D\nAIJdEOOavXMyWHlxtCssvRAJQgihZRIhhqLKJbTgm74UyOP96Spw3K7RFcxH\nutGz9D3pwussOITUqtwfRutGQr3duU8FAA5U0/4LbaxBdNozrAx643J202aI\nkkL70CaJ/qFM6Gl3UVm1H0Ad9lAvMJRtOjR+iiYq6J7V/NQga7ivW74FFxtS\nu4OZDWoy1SSrsi58vf/zIMi1hiHx6tBbzEgspzTRd9kkt6VjxDah1Ed8Y4JI\nabWeAXOlbh+TpHrIGNQjW7I2Zc/EuiprQXRtwzvIfXd0rc8y1+cm4gpLYL+C\n7YPP\r\n=kE4E\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIGYeguWbIFHmDLvb5UDof2YQwATaQLPnj67h9Qvt7/xqAiAIu4Eb0Qvr7UMW1PPSZslqnWEcouMyg7OguB/PhNGazQ=="}]},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"_npmUser":{"name":"aricart","email":"alberto@synadia.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-nats_1.2.15_1590193022435_0.9628783521449014"},"_hasShrinkwrap":false,"deprecated":"nats now offers the async functionality directly"}},"time":{"created":"2018-07-26T20:57:24.416Z","0.0.9":"2018-07-26T20:57:24.549Z","modified":"2022-05-22T07:30:58.361Z","0.0.10":"2018-07-26T21:11:10.082Z","1.0.0":"2018-07-30T22:46:16.927Z","1.0.1":"2018-07-30T23:05:20.204Z","1.0.2":"2018-08-09T21:27:15.630Z","1.0.3":"2018-08-17T21:32:41.466Z","1.0.4":"2018-08-27T21:12:16.550Z","1.1.0":"2019-01-22T16:23:15.370Z","1.1.2":"2019-02-08T21:33:23.119Z","1.1.3":"2019-03-20T15:05:54.523Z","1.1.4":"2019-03-20T15:22:48.792Z","1.2.0":"2019-03-22T15:39:04.020Z","1.2.2":"2019-03-29T16:56:46.228Z","1.2.4":"2019-04-10T23:15:16.542Z","1.2.7-1":"2020-02-06T21:29:04.972Z","1.2.7-3":"2020-02-06T21:48:37.601Z","1.2.7-4":"2020-02-06T21:56:30.678Z","1.2.7-6":"2020-02-14T13:29:51.702Z","1.2.7-7":"2020-03-05T13:44:34.491Z","1.2.8":"2020-03-05T14:48:19.120Z","1.2.10-0":"2020-03-05T15:42:17.180Z","1.2.10-1":"2020-03-05T15:58:45.325Z","1.2.10":"2020-03-05T16:03:22.035Z","1.2.12-0":"2020-03-05T16:08:47.532Z","1.2.12":"2020-03-05T16:16:30.847Z","2.0.0-0":"2020-03-24T18:39:46.862Z","2.0.0-1":"2020-03-30T15:01:21.291Z","1.2.14-1":"2020-04-21T14:23:07.011Z","1.2.14-2":"2020-04-21T14:30:27.012Z","2.0.0-2":"2020-04-21T21:47:50.069Z","1.2.14":"2020-04-29T20:37:04.134Z","1.2.15-0":"2020-05-23T00:14:46.330Z","1.2.15":"2020-05-23T00:17:02.600Z"},"maintainers":[{"name":"aricart","email":"alberto@synadia.com"}],"description":"Typescript Node.js client for NATS, a lightweight, high-performance cloud native messaging system","homepage":"https://nats.io","keywords":["nats","messaging","pubsub","publish","subscribe","queue","distributed","queueing"],"repository":{"type":"git","url":"git+ssh://git@github.com/nats-io/nats.ts.git"},"contributors":[],"author":{"name":"The NATS Authors"},"bugs":{"url":"https://github.com/nats-io/nats.ts/issues"},"license":"Apache-2.0","readme":"# NATS.ts - Node.js Client\n\nA TypeScript [Node.js](http://nodejs.org/) client for the [NATS messaging system](https://nats.io).\n\n[![license](https://img.shields.io/github/license/nats-io/nats.ts.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Travis branch](https://img.shields.io/travis/nats-io/nats.ts/master.svg)]()\n[![Coverage Status](https://coveralls.io/repos/github/nats-io/nats.ts/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nats.ts?branch=master)\n[![npm](https://img.shields.io/npm/v/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n[![npm](https://img.shields.io/npm/dm/ts-nats.svg)](https://www.npmjs.com/package/ts-nats)\n\nts-nats is a typescript nats library for node that supports Promises and async/await patterns.\n[Full documentation](https://nats-io.github.io/nats.ts/).\n\n## Installation\n\n```bash\nnpm install ts-nats\n\n# to install current dev version\nnpm install ts-nats@next\n```\n\n## Basic Usage\n\nThe starting point is the `connect()` function. You can give no arguments, a port, an URL or a\n[`NatsConnectionOption`](https://nats-io.github.io/nats.ts/interfaces/_nats_.natsconnectionoptions.html) \nspecifying detailed behaviour. Inside an async function, you can use async/await to wait for the\npromise to resolve or reject.\n\n```typescript\nimport {connect, NatsConnectionOptions, Payload} from 'ts-nats';\n\n// ...\ntry {\n    let nc = await connect({servers: ['nats://demo.nats.io:4222', 'tls://demo.nats.io:4443']});\n    // Do something with the connection\n} catch(ex) {\n    // handle the error\n}\n// ...\n```\n\n\nSince `connect()` returns a Promise, the promise patterns are supported. With no arguments, it will attempt to connect to `nats://localhost:4222`\n```typescript\nconnect()\n    .then((nc) => {\n        // Do something with the connection\n    })\n    .catch((ex) => {\n        // handle the error\n    });\n    \n```\n\nOnce you have a connection, you can publish data:\n```typescript\nnc.publish('greeting', 'hello world!');\n```\n\nSubscribing allows you to receive messages published on a subject:\n```typescript\n// simple subscription - subscribe returns a promise to a subscription object\nlet sub = await nc.subscribe('greeting', (err, msg) => {\n    if(err) {\n        // do something\n    } else {\n        // do something with msg.data\n    }\n});\n```\n\nSubscription can respond to the publisher if the publisher sets a reply subject:\n```typescript\nlet service = await nc.subscribe('greeter', (err, msg) => {\n    if(err) {\n        // handle the error\n    } else if (msg.reply) {\n        nc.publish(msg.reply, `hello there ${msg.data}`);\n    }\n});\n\n// create an unique subject just to receive a response message\nlet inbox = nc.createInbox();\nlet sub2 = await nc.subscribe(inbox, (err, msg) => {\n    if(err) {\n        // handle the error\n    } else {\n        console.log(msg.data);\n    }\n}, {max: 1});\n\n// publish a 'request' message\nnc.publish('greeter', \"NATS\", inbox)\n\n// stop getting messages on the service subscription\nservice.unsubscribe();\n\n// didn't have to specify unsubscribe for sub2, the `{max: 1}` auto unsubscribes\n// when the first message is received.\n```\n\nThe above pattern is called Request/Reply - because it is so pervasive, ts-nats makes\nit very easy to make a request and handle a single response. The request API returns\na Promise to a response message. All the bookkeeping, creating an inbox subject,\ncreating a subscription to manage the response, and publishing details are handled.  Since requests are expected to have a response, they require a timeout. \nIf the request does not receive a response within the specified timeout, the promise rejects.\n\nSubscriptions to handle request responses are very efficient since they utilize a shared\nsubscription on the server. The client multiplexes the response without having to create\nand destroy subscriptions server-side.\n\n```typescript\nlet msg = await nc.request('greeter', 1000, 'me');\n```\n\nWhen done using a connection, closing it releases all resources, and cancels all\nsubscriptions.\n```typescript\nnc.close();\n```\n\n\n## Wildcard Subscriptions\n\nA single subscription can process related messages. When the subject\nspecifies wildcards tokens, those parts of the subject can match different things.\nOne of the wildcards is the `*` (asterisk). The asterisk in `foo.*.baz` matches all values in that token's position (`foo.bar.baz`, f`oo.a.baz`, ...). \n\nTo work as a wildcard, the wildcard character must be the only character in the token.\n Asterisks that are part of a token value are interpreted as string literals,\n`foo.a*.bar` and will only match the literal value of `foo.a*.bar`.\n\n```typescript\nlet sub1 = await nc.subscribe('foo.*.baz', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n```\n\nAnother wildcard is the `>` (greater than symbol). `>` tokens can only appear\nas the last token in a subject. `foo.>` will match `foo.bar`, `foo.bar.baz`,\n`foo.foo.bar.bax.22`. When part of a token it is interpreted as a string \nliteral `foo.bar.a>` will only match `foo.bar.a>`. Subscribing to `>` will \nmatch all subjects.\n\n```typescript\nlet sub2 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n});\n\n```\n## Queue Groups\n\nAll subscriptions with the same queue name will form a queue group.\nEach message will be delivered to only a single subscriber in the queue group.\nYou can have as many queue groups as you wish. Normal subscribers and different\nqueue groups are independent.\n```typescript\nlet sub3 = await nc.subscribe('foo.baz.>', (err, msg) => {\n    console.log('message received on', msg.subject, \":\", msg.data);\n}, {queue: 'A'});\n\n```\n## Clustered Usage\n\nA NATS connection can specify several servers. When the NATS client connects to one of the\nservers, the server may gossip additional known cluster members. If the NATS client\ndisconnects, it will attempt to connect to one of them.\n\n```typescript\nlet servers = ['nats://demo.nats.io:4222', 'nats://127.0.0.1:5222', 'nats://127.0.0.1:6222'];\n// Randomly connect to a server in the cluster group.\nlet nc2 = await connect({servers: servers});\n```\n\nThe client will randomize the list of servers that it manages to prevent a __thundering herd__\nof clients all at the same time trying to reconnect to the same server. To prevent randomization,\nspecify the `noRandomize` option.\n\n```typescript\n// Preserve order when connecting to servers.\nlet nc3 = await connect({servers: servers, noRandomize: true});\n```\n## TLS\n\nUsing a TLS connection encrypts all traffic to the client. Secure connections are easy with NATS.\nServers using TLS typically specify the `tls` protocol instead of `nats`. Strict tls requirements or options\nare specified by the `tls` option.\n\n```typescript\n// Simple TLS connect\nlet ncs = await connect({url: 'tls://demo.nats.io:4443'});\n\n// Client can explicitly request that the server be using tls\nlet ncs1 = await connect({url: 'tls://demo.nats.io:4443', tls: true});\n\n// if CA is self signed:\nimport {readFileSync} from \"fs\";\n\nlet caCert = readFileSync('/path/to/cacert');\nlet ncs2 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert\n}});\n\n// client can verify server certificate:\nlet ncs3 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    ca: caCert,\n    rejectUnauthorized: true\n}});\n\n// client can request to not validate server cert:\nlet ncs4 = await connect({url: 'tls://demo.nats.io:4443', tls: {\n    rejectUnauthorized: false\n}});\n\n// if server requires client certificates\nimport {readFileSync} from \"fs\";\nlet caCert = readFileSync('/path/to/cacert');\nlet clientCert = readFileSync('/path/to/clientCert');\nlet clientKey = readFileSync('/path/to/clientKey');\n\nlet ncs5 = await connect({url: 'tls://someserver:4443', tls: {\n    ca: caCert,\n    key: clientKey,\n    cert: clientCert\n}});\n\n```\n## Authentication\n\nUser credentials can be specified in the URL or as NatsConnectionOptions:\n\n```typescript\n// Connect with username and password in the url\nlet nc6 = await connect({url: 'nats://me:secret@127.0.0.1:4222'});\n// Connect with username and password in the options\nlet nc7 = await connect({url: 'nats://127.0.0.1:4222', user: 'me', pass: 'secret'});\n// Connect with token in url\nlet nc8 = await connect({url: 'nats://token@127.0.0.1:4222'});\n// or token inside the options:\nlet nc9 = await connect({url: 'nats://127.0.0.1:4222', token: 'token'});\n```\n\n### NKey Authentication\n\nNKey authentication sends to the server a public nkey from the user, \nand signs a challenge. Server matches the public key with those allowed\nto connect and cryptographically verifies that the challenge was signed\nthe user owning having the presented public key.\n\n\n```typescript\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAEL6GG2L2HIF7DUGZJGMRUFKXELGGYFMHF76UO2AYBG3K4YLWR3FKC2Q\";\nconst uPub = \"UD6OU4D3CIOGIDZVL4ANXU3NWXOW5DCDE2YPZDBHPBXCVKHSODUA4FKI\";\nlet nc11 = await connect({url: 'tls://localhost:4222', \n    nkey: uPub, \n    nonceSigner: function(nonce:string): Buffer {\n        // fromSeed is from ts-nkeys\n        let sk = fromSeed(Buffer.from(uSeed));\n        return sk.sign(Buffer.from(nonce));\n    }\n });\n\n// Or much simpler if the seed nkey is in a file\nlet nc12 = await connect({url: 'tls://localhost:4222', nkeyCreds: \"/tmp/seed.txt\" });\n```\n\n### JWT Authentication\n\nJWT Authentication returns a JWT to the server and signs a challenge. The JWT\nincludes the user's public key and permissions. The server resolves the issuer\nof the JWT (an account). If the server trusts account issuer, the user is\nauthenticated. The server itself doesn't have a direct knowledge of the user \nor the account.\n\n```typescript\n// Simples way to connect to a server using JWT and NKeys\nlet nc13 = await connect({url: 'tls://connect.ngs.global', userCreds: \"/path/to/file.creds\"});\n\n// Setting nkeys and nonceSigner callbacks directly\n// Seed Keys should be treated as secrets\nconst uSeed = \"SUAIBDPBAUTWCWBKIO6XHQNINK5FWJW4OHLXC3HQ2KFE4PEJUA44CNHTC4\";\nconst uJWT = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJFU1VQS1NSNFhGR0pLN0FHUk5ZRjc0STVQNTZHMkFGWERYQ01CUUdHSklKUEVNUVhMSDJBIiwiaWF0IjoxNTQ0MjE3NzU3LCJpc3MiOiJBQ1pTV0JKNFNZSUxLN1FWREVMTzY0VlgzRUZXQjZDWENQTUVCVUtBMzZNSkpRUlBYR0VFUTJXSiIsInN1YiI6IlVBSDQyVUc2UFY1NTJQNVNXTFdUQlAzSDNTNUJIQVZDTzJJRUtFWFVBTkpYUjc1SjYzUlE1V002IiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ.kCR9Erm9zzux4G6M-V2bp7wKMKgnSNqMBACX05nwePRWQa37aO_yObbhcJWFGYjo1Ix-oepOkoyVLxOJeuD8Bw\";\n\n// the nonceSigner function takes a seed key and returns the signed nonce\nlet nc14 = await connect({url: 'tls://connect.ngs.global',\n    userJWT: uJWT, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n// the user JWT can also be provided dynamically\nlet nc15 = await connect({url: 'tls://connect.ngs.global', \n    userJWT: function():string {\n        return uJWT;\n    }, \n    nonceSigner: function(nonce:string): Buffer {\n       // fromSeed is from ts-nkeys\n       let sk = fromSeed(Buffer.from(uSeed));\n       return sk.sign(Buffer.from(nonce));\n    }\n});\n\n```\n\n## Advanced Usage\n\nNATS typically buffers messages sent to the server to reduce the number of kernel calls.\nThis yields greater performance. The NATS client automatically buffers commands from the\nclient and sends them. This buffering behaviour allows a NATS client to disconnect and continue to publish messages and create subscriptions briefly. On reconnect,\nthe client sends all buffered messages and subscriptions to the server.\n\nSometimes a client wants to make sure that the NATS\nserver has processed outgoing messages. The `flush()` will call a user-provided callback when the round trip\nto the server is done.\n\n```typescript\n// Flush the connection and get notified when the server has finished processing\nlet ok = await nc.flush();\n\n// or\nnc.flush(() => {\n    console.log('done');\n});\n```\n\nA client can ensure that when the processing of incoming messages takes longer\nthan some threshold, that time is given to other waiting IO tasks.\nIn the example below, when processing takes longer than 10ms, the client\nwill yield.\n\n```typescript\nlet nc16 = await connect({port: PORT, yieldTime: 10});\n```\n\nSubscriptions can auto cancel after it has received a specified\nnumber of messages:\n\n```typescript\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10});\n```\n\nOr if the expected message count is not received to timeout:\n```typescript\n// Timeout if 10 messages are not received in specified time:\nnc.subscribe('foo', (err, msg) => {\n    // do something\n}, {max: 10, timeout: 1000});\n```\n\nTimeouts and expected message counts can be specified via the\nsubscription after it the subscription resolves:\n\n```typescript\nlet sub2 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\nsub2.unsubscribe(10);\nsub2.setTimeout(1000);\n```\n\n\nNormally unsubscribe will cancel a subscription by sending a command to the server\nand then cancelling the message handler for the subscription. In such cases it is\npossible for messages waiting to be processed to be dropped.\n\nTo orderly unsubscribe, `drain()` sends the unsubscribe to the server and\nflushes with a handler that cancels the subscription. Because the cancel\nhappens when the flush completes, drain ensures that the server will not send\nany additional messages to the subscription and that all sent messages have\nbeen processed by the client. \n\nThis functionality is particularly useful to queue subscribers.\n\n```typescript\nlet sub3 = await nc.subscribe('foo', (err, msg) => {\n    // do something\n});\n// sometime in the future drain the subscription. Drain returns a promise\n// when the drain promise resolves, the subscription finished processing \n// all pending inbound messages for the subscription.\nlet p = await sub3.drain();\n```\n\nSimilarly to subscription `drain()`, an entire connection can be drained.\n\n```typescript\nlet nc17 = await connect();\n\n// create subscriptions etc\n...\n\n// When drain is called:\n// - no additional subscriptions or requests can be made.\n// - all open subscriptions drain (including the global request/reply)\n// When all drain requests resolve:\n// - a flush is sent to the server to drain outbound messages\n// - client closes\nawait nc17.drain();\n```\n\nMessage payloads can be strings, binary, or JSON.\nPayloads determine the type of `msg.data` on subscriptions\n`string`, `Buffer`, or `javascript object`.\n\n```typescript\nlet nc18 = await connect({payload: Payload.STRING});\nlet nc19 = await connect({payload: Payload.JSON});\nlet nc20 = await connect({payload: Payload.BINARY});\n```\n\nString encodings can be set to node supported string encodings.\nThe default encoding is `utf-8`, it only affects string payloads.\n\n```typescript\nlet nc21 = await connect({payload: Payload.STRING, encoding: \"ascii\"});\n```\n\nConnect and reconnect behaviours can be configured. You can specify the number\nof attempts and the interval between attempts on reconnects. By default a NATS connection will try to reconnect to a server ten times, waiting 2 seconds between reconnect attempts.\nIf the maximum number of retries is reached, the client will `close()` the connection.\n\n```typescript\n// Keep trying to reconnect forever, and attempt to reconnect every 250ms\nlet nc22 = await connect({maxReconnectAttempts: -1, reconnectTimeWait: 250});\n\n```\n\n## Notifications\n\nThe nats client is an `EventEmitter`, and thus emits various notifications:\n\n| Event                  | Argument               | Description\n|--------                |---------               |------------\n| `close`                |                        | Emitted when the client closes. A closed client is finished, and cannot be reused.\n| `connect`              | `Client`, url (string), `ServerInfo` | Emitted when the client first connects to a NATS server. Only happens once.\n| `disconnect`           | url                    | Emitted when the client disconnects from a server.\n| `error`                | `NatsError`            | Emitted when the client receives an error. If an error handler is not set, the node process will exit.\n| `permissionError`      | `NatsError`            | Emitted when the server emits a permission error when subscribing or publishing to a subject that the client is not allowed to.\n| `reconnect`            | `Client`, url (string) | Emitted when the server connects to a different server\n| `reconnecting`         | url (string)           | Emitted when the server attempts to reconnect to a different server\n| `serversChanged`       | `ServersChangedEvent`  | Emitted when the server gossips a list of other servers in the cluster. Only servers not specified in a connect list are deleted if they disapear.\n| `subscribe`            | `SubEvent`             | Emitted when a subscription is created on the client\n| `unsubscribe`          | `SubEvent`             | Emitted when a subscription is auto-unsubscribed\n| `yield`                |                        | Emitted when the client's processing took longer than the specified yield option, and the client yielded.\n\n\n\nSee examples for more information.   \n\n## Connect Options\n\nThe following is the list of connection options and default values.\n\n| Option                 | Default                   | Description\n|--------                |---------                  |------------\n| `encoding`             | `\"utf8\"`                  | Encoding specified by the client to encode/decode data\n| `maxPingOut`           | `2`                       | Max number of pings the client will allow unanswered before rasing a stale connection error\n| `maxReconnectAttempts` | `10`                      | Sets the maximum number of reconnect attempts. The value of `-1` specifies no limit\n| `name`                 |                           | Optional client name (useful for debugging a client on the server output `-DV`)\n| `nkey`                 |                           | The public NKey identifying the client\n| `nkeyCreds`            |                           | Path to a file containing seed nkey for the client. This property sets a `nonceSigner` and `nkey` automatically.\n| `noEcho`               | `false`                   | If set, the client's matching subscriptions won't receive messages published by the client. Requires server support 1.2.0+.\n| `nonceSigner`          |                           | A `NonceSigner` function that signs the server challenge. \n| `noRandomize`          | `false`                   | If set, the order of user-specified servers is randomized.\n| `pass`                 |                           | Sets the password for a connection\n| `payload`              | `Payload.STRING`          | Sets the payload type [`Payload.STRING`, `Payload.BINARY`, or `Payload.JSON`].\n| `pedantic`             | `false`                   | Turns on strict subject format checks\n| `pingInterval`         | `120000`                  | Number of milliseconds between client-sent pings\n| `reconnect`            | `true`                    | If false server will not attempt reconnecting\n| `reconnectJitter`      | `100`                     | Number of millis to randomize after `reconnectTimeWait`. See [jitter](#jitter).\n| `reconnectJitterTLS`   | `1000`                    | Number of millis to randomize after `reconnectTimeWait` when TLS options are specified. See [jitter](#jitter).\n| `reconnectDelayHandler`| Generated function        | A function that returns the number of millis to wait before the next connection to a server it connected to. See [jitter](#jitter).\n| `reconnectTimeWait`    | `2000`                    | If disconnected, the client will wait the specified number of milliseconds between reconnect attempts\n| `servers`              |                           | Array of connection `url`s\n| `timeout`              | `0`                       | Number of milliseconds to wait before timing out the initial connection. Must be greater than `0`. Note that `waitOnFirst` must be specified, and `reconnectTimeWait` and `maxReconnectAttempts` must have sensible values supporting the desired timeout.\n| `tls`                  | `undefined`               | This property can be a boolean or an Object. If `true` the client requires a TLS connection. If `false` a non-tls connection is required. `undefined` allows connecting to either secure or non-secured.  The value can also be an object specifying TLS certificate data, which will implicitly require a secured connection. The properties `ca`, `key`, `cert` should contain the certificate file data. `ca` should be provided for self-signed certificates. `key` and `cert` are required for client provided certificates. `rejectUnauthorized` if `true` validates server's credentials\n| `token`                |                           | Sets a authorization token for a connection\n| `url`                  | `\"nats://localhost:4222\"` | Connection url\n| `user`                 |                           | Sets the username for a connection\n| `userCreds`            |                           | Path to a properly formatted user credentials file containing the client's JWT and seed key for the client. This property sets a `nonceSigner` automatically.\n| `userJWT`              |                           | A string or a `JWTProvider` function which provides a JWT specifying the client's permissions\n| `verbose`              | `false`                   | Turns on `+OK` protocol acknowledgements\n| `waitOnFirstConnect`   | `false`                   | If `true` the server will fall back to a reconnect mode if it fails its first connection attempt.\n| `yieldTime`            |                           | If set and processing exceeds yieldTime, client will yield to IO callbacks before processing additional inbound messages \n\n\n### Jitter \n\nThe settings `reconnectTimeWait`, `reconnectJitter`, `reconnectJitterTLS`, `reconnectDelayHandler` are all related.\nThey control how long before the NATS client attempts to reconnect to a server it has previously connected.\n\nThe intention of the settings is to spread out the number of clients attempting to reconnect to a server over a period of time, \nand thus preventing a [\"Thundering Herd\"](https://docs.nats.io/developing-with-nats/reconnect/random).\n\nThe relationship between these is:\n\n- If `reconnectDelayHandler` is specified, the client will wait the value returned by this function. No other value will be taken into account.\n- If the client specified TLS options, the client will generate a number between 0 and `reconnectJitterTLS` and add it to\n`reconnectTimeWait`.\n- If the client didn't specify TLS options, the client will generate a number between 0 and `reconnectJitter` and add it to `reconnectTimeWait`.\n\n\n## Supported Node Versions    \n\nSupport policy for Nodejs versions follows \n[Nodejs release support]( https://github.com/nodejs/Release).\nWe will support and build ts-nats on even Nodejs versions that are current \nor in maintenance.\n\n\n## License\n\nUnless otherwise noted, the NATS source files are distributed under the Apache Version 2.0 license found in the LICENSE file.\n","readmeFilename":"README.md"}