{"id":13408184,"url":"https://github.com/camunda-community-hub/zeebe-client-node-js","last_synced_at":"2025-03-14T12:32:13.185Z","repository":{"id":38809587,"uuid":"167303075","full_name":"camunda-community-hub/zeebe-client-node-js","owner":"camunda-community-hub","description":"Node.js client library for Zeebe Microservices Orchestration Engine","archived":true,"fork":false,"pushed_at":"2024-04-08T02:59:16.000Z","size":16343,"stargazers_count":152,"open_issues_count":0,"forks_count":38,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-10-29T16:58:38.580Z","etag":null,"topics":["camunda-8","community-supported","grpc-client","hacktoberfest","job-worker","release-drafter","workflow-instance","zeebe"],"latest_commit_sha":null,"homepage":"https://camunda-community-hub.github.io/zeebe-client-node-js/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/camunda-community-hub.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-01-24T04:29:08.000Z","updated_at":"2024-09-27T12:10:16.000Z","dependencies_parsed_at":"2023-11-06T06:22:32.712Z","dependency_job_id":"75a5dd71-21eb-4c67-a2ee-1935af15ca76","html_url":"https://github.com/camunda-community-hub/zeebe-client-node-js","commit_stats":{"total_commits":543,"total_committers":28,"mean_commits":"19.392857142857142","dds":0.2154696132596685,"last_synced_commit":"5f0a213ae142a2f0964eb2bd408e2237a64d0c16"},"previous_names":["creditsenseau/zeebe-client-node-js"],"tags_count":79,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/camunda-community-hub%2Fzeebe-client-node-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/camunda-community-hub%2Fzeebe-client-node-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/camunda-community-hub%2Fzeebe-client-node-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/camunda-community-hub%2Fzeebe-client-node-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/camunda-community-hub","download_url":"https://codeload.github.com/camunda-community-hub/zeebe-client-node-js/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243307343,"owners_count":20270257,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["camunda-8","community-supported","grpc-client","hacktoberfest","job-worker","release-drafter","workflow-instance","zeebe"],"created_at":"2024-07-30T20:00:51.264Z","updated_at":"2025-03-14T12:32:11.097Z","avatar_url":"https://github.com/camunda-community-hub.png","language":"TypeScript","funding_links":[],"categories":["Clients and Programming Framework Integrations"],"sub_categories":[],"readme":"# Zeebe Node.js Client\n\n\n![Compatible with: Camunda Platform 8](https://img.shields.io/badge/Compatible%20with-Camunda%20Platform%208-0072Ce)\n![Community Extension](https://img.shields.io/badge/Community%20Extension-An%20open%20source%20community%20maintained%20project-FF4700)\n![Lifecycle](https://img.shields.io/badge/Lifecycle-Stable-brightgreen)\n[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\n\n# DEPRECATED\n\nThis package is deprecated. Please use the official SDK package @camunda8/sdk. See: https://github.com/camunda/camunda-8-js-sdk\n---\n\nThis is a Node.js gRPC client for [Zeebe](https://zeebe.io), the workflow engine in [Camunda Platform 8](https://camunda.com/platform/). It is written in TypeScript and transpiled to JavaScript in the `dist` directory.\n\nComprehensive API documentation is available [online](https://camunda-community-hub.github.io/zeebe-client-node-js/).\n\nSee [CHANGELOG.md](https://github.com/camunda-community-hub/zeebe-client-node-js/blob/master/CHANGELOG.md) to see what has changed with each release.\n\nGet a hosted instance of Zeebe on [Camunda Cloud](https://camunda.io).\n\n## Table of Contents\n\n**Quick Start**\n\n-   [ Install ](#install)\n-   [ Get Broker Topology ](#get-topology)\n-   [ Deploy a process ](#deploy-process)\n-   [ Start and service a process](#start-and-service-a-process)\n\n-   [ Versioning ](#versioning)\n-   [ Compatible Node Versions ](#node-versions)\n-   [ Breaking changes in 8.1.0 ](#breaking-8.1.0)\n-   [ Breaking changes in 1.0.0 ](#breaking-1.0.0)\n-   [ gRPC Implementation ](#grpc-implementation)\n-   [ Type difference from other Zeebe clients ](#type-difference)\n-   [ A note on representing timeout durations ](#time-duration)\n\n**Connection Behaviour**\n\n-   [ Client-side gRPC retry in ZBClient ](#client-side-retry)\n-   [ onReady(), onConnectionError(), and connected ](#on-ready)\n-   [ Initial Connection Tolerance ](#initial-connection-tolerance)\n\n**Connecting to a Broker**\n\n-   [ TLS ](#tls)\n-   [ OAuth ](#oauth)\n-   [ Basic Auth ](#basic-auth)\n-   [ Camunda Cloud ](#camunda-cloud)\n-   [ Zero-conf constructor ](#zero-conf)\n\n**Job Workers**\n\n-   [ Job Workers](#job-workers)\n-   [ The `ZBWorker` Job Worker ](#create-zbworker)\n-   [ Unhandled Exceptions in Task Handlers ](#unhandled-exceptions)\n-   [ Completing tasks with success, failure, error, or forwarded ](#complete-tasks)\n-   [ Working with Process Variables and Custom Headers ](#working-with-variables)\n-   [ Constraining the Variables Fetched by the Worker ](#fetch-variable)\n-   [ The \"Decoupled Job Completion\" pattern ](#decoupled-complete)\n-   [ The `ZBBatchWorker` Job Worker ](#zbbatchworker)\n-   [ Long polling ](#long-polling)\n-   [ Poll Interval ](#poll-interval)\n\n**Client Commands**\n\n-   [ Deploy Process Models and DMN Tables ](#deploy-resource)\n-   [ Start a Process Instance ](#start-process)\n-   [ Start a Process Instance of a specific version of a Process definition ](#start-specific-version)\n-   [ Start a process instance and await the process outcome ](#start-await)\n-   [ Publish a Message ](#publish-message)\n-   [ Publish a Start Message ](#publish-start-message)\n-   [ Activate Jobs ](#activate-jobs)\n\n**Other Concerns**\n\n-   [ Graceful Shutdown ](#graceful-shutdown)\n-   [ Logging ](#logging)\n\n**Programming with Safety**\n\n-   [ Generating TypeScript constants for BPMN Models ](#generate-constants)\n-   [ Generating code from a BPM Model file ](#generate-code)\n-   [ Writing Strongly-typed Job Workers ](#strongly-typed)\n-   [ Run-time Type Safety ](#run-time-safety)\n\n**Development of the Library itself**\n\n-   [ Developing Zeebe Node ](#developing)\n    -   [ Tests ](#tests)\n    -   [ Writing Tests ](#writing-tests)\n-   [ Contributors ](#contributors)\n\n## Quick Start\n\n\u003ca name = \"install\"\u003e\u003c/a\u003e\n\n## Install\n\n### Add the Library to your Project\n\n```bash\nnpm i zeebe-node\n```\n\nFor Zeebe broker versions prior to 1.0.0:\n\n```bash\nnpm i zeebe-node@0\n```\n\nRefer to [here](https://github.com/camunda-community-hub/zeebe-client-node-js/blob/v.0.25.0/README.md) for the documentation for the pre-1.0.0 version of the library.\n\n\u003ca name = \"get-topology\"\u003e\u003c/a\u003e\n\n### Get Broker Topology\n\n```javascript\nconst ZB = require('zeebe-node')\n\nvoid (async () =\u003e {\n\tconst zbc = new ZB.ZBClient()\n\tconst topology = await zbc.topology()\n\tconsole.log(JSON.stringify(topology, null, 2))\n})()\n```\n\n\u003ca name = \"deploy-process\"\u003e\u003c/a\u003e\n\n### Deploy a process\n\n```javascript\nconst ZB = require('zeebe-node')\nconst fs = require('fs')\n\nvoid (async () =\u003e {\n\tconst zbc = new ZB.ZBClient() // localhost:26500 || ZEEBE_GATEWAY_ADDRESS\n\n\tconst res = await zbc.deployProcess('./domain-mutation.bpmn')\n\tconsole.log(res)\n\n\t// Deploy multiple with an array of filepaths\n\tawait zbc.deployProcess(['./wf1.bpmn', './wf2.bpmn'])\n\n\tconst buffer = fs.readFileSync('./wf3.bpmn')\n\n\t// Deploy from an in-memory buffer\n\tawait zbc.deployProcess({ definition: buffer, name: 'wf3.bpmn' })\n})()\n```\n\n\u003ca name = \"start-and-service-process\"\u003e\u003c/a\u003e\n\n### Start and service a process\n\nThis code demonstrates how to deploy a Zeebe process, create a process instance, and handle a service task using the Zeebe Node.js client. The 'get-customer-record' service task worker checks for the presence of a customerId variable, simulates fetching a customer record from a database, and completes the task with a customerRecordExists variable.\n\n```javascript\n// Import the Zeebe Node.js client and the 'fs' module\nconst ZB = require('zeebe-node');\nconst fs = require('fs');\n\n// Instantiate a Zeebe client with default localhost settings or environment variables\nconst zbc = new ZB.ZBClient();\n\n// Create a Zeebe worker to handle the 'get-customer-record' service task\nconst worker = zbc.createWorker({\n    // Define the task type that this worker will process\n    taskType: 'get-customer-record',\n    // Define the task handler to process incoming jobs\n    taskHandler: job =\u003e {\n        // Log the job variables for debugging purposes\n        console.log(job.variables);\n\n        // Check if the customerId variable is missing and return an error if so\n        if (!job.variables.customerId) {\n            return job.error('NO_CUSTID', 'Missing customerId in process variables');\n        }\n\n        // Add logic to retrieve the customer record from the database here\n        // ...\n\n        // Complete the job with the 'customerRecordExists' variable set to true\n        return job.complete({\n            customerRecordExists: true\n        });\n    }\n});\n\n// Define an async main function to deploy a process, create a process instance, and log the outcome\nasync function main() {\n    // Deploy the 'new-customer.bpmn' process\n    const res = await zbc.deployProcess('./new-customer.bpmn');\n    // Log the deployment result\n    console.log('Deployed process:', JSON.stringify(res, null, 2));\n\n    // Create a process instance of the 'new-customer-process' process, with a customerId variable set\n    // 'createProcessInstanceWithResult' awaits the outcome\n    const outcome = await zbc.createProcessInstanceWithResult({\n        bpmnProcessId: 'new-customer-process',\n        variables: { customerId: 457 }\n    });\n    // Log the process outcome\n    console.log('Process outcome', JSON.stringify(outcome, null, 2));\n}\n\n// Call the main function to execute the script\nmain();\n```\n\n\u003ca name = \"versioning\"\u003e\u003c/a\u003e\n\n## Versioning\n\nTo enable that the client libraries can be easily supported to the Zeebe server we map the version numbers, so that Major, Minor match the server application. Patches are independent and indicate client updates.\n\nNPM Package version 0.26.x supports Zeebe 0.22.x to 0.26.x.\n\nNPM Package version 1.x supports Zeebe 1.x. It uses the C-based gRPC library by default.\n\nNPM Package version 2.x supports Zeebe 1.x, and requires Node \u003e= 16.6.1, \u003e=14.17.5, or \u003e=12.22.5. It removes the C-based gRPC library and uses the pure JS implementation.\n\n\u003ca name=\"node-versions\"\u003e\u003c/a\u003e\n\n## Compatible Node Versions\n\nVersion 1.x of the package: Node versions \u003c=16.x. Version 1.x uses the C-based gRPC library and does not work with Node 17. The C-based gRPC library is deprecated and no longer being maintained.\n\nVersion 2.x and later of the package: Node versions 12.22.5+, 14.17.5+, or 16.6.1+. Version 2.x uses the pure JS implementation of the gRPC library, and requires a fix to the `nghttp2` library in Node (See [#201](https://github.com/camunda-community-hub/zeebe-client-node-js/issues/201)).\n\n\u003ca name=\"breaking-8.1.0\"\u003e\u003c/a\u003e\n\n## Breaking changes in Zeebe 8.1.0\n\nAll deprecated APIs are removed in the 8.1.0 package version. If your code relies on deprecated methods and method signatures, you need to use a package version prior to 8.1.0 or update your application code.\n\n\u003ca name=\"breaking-1.0.0\"\u003e\u003c/a\u003e\n\n## Breaking changes in Zeebe 1.0.0\n\nFor Zeebe brokers prior to 1.0.0, use the 0.26.z version of `zeebe-node`. This README documents the Zeebe 1.0.0 API. The previous API is documented [here](https://github.com/camunda-community-hub/zeebe-client-node-js/blob/v.0.25.0/README.md).\n\nZeebe 1.0.0 contains a number of breaking changes, including the gRPC protocol and the API surface area. You must use a 1.x.y version of the client library with Zeebe 1.0.0 and later.\n\nThe pre-1.0.0 API of the Node client has been deprecated, but not removed. This means that your pre-1.0.0 applications should still work, just by changing the version of `zeebe-node` in the `package.json`.\n\n\u003ca name=\"grpc-implementation\"\u003e\u003c/a\u003e\n\n## gRPC Implementation\n\nFrom version 2.x, the Zeebe Node client uses the pure JS gRPC client implementation.\n\nFor version 1.x, the Zeebe Node client uses the C gRPC client implementation [grpc-node](https://github.com/grpc/grpc-node) by default. The C-based gRPC implementation is deprecated and is not being maintained.\n\n\u003ca name = \"type-difference\"\u003e\u003c/a\u003e\n\n## Type difference from other Zeebe clients\n\nProtobuf fields of type `int64` are serialised as type string in the Node library. These fields are serialised as numbers (long) in the Go and Java client. See [grpc/#7229](https://github.com/grpc/grpc/issues/7229) for why the Node library serialises them as string. The Process instance key, and other fields that are of type long in other client libraries, are type string in this library. Fields of type `int32` are serialised as type number in the Node library.\n\n\u003ca name = \"time-duration\"\u003e\u003c/a\u003e\n\n## A note on representing timeout durations\n\nAll timeouts are ultimately communicated in _milliseconds_. They can be specified using the primitive type `number`, and this is always a _number of milliseconds_.\n\nAll timeouts in the client library can _also_, optionally, be specified by a time value that encodes the units, using the [typed-durations](https://www.npmjs.com/package/typed-duration) package. You can specify durations for timeouts like this:\n\n```\nconst { Duration } = require('zeebe-node')\n\nconst timeoutS = Duration.seconds.of(30) // 30s timeout\nconst timeoutMs = Duration.milliseconds.of(30000) // 30s timeout in milliseconds\n```\n\nUsing the value types makes your code more semantically specific.\n\nThere are five timeouts to take into account.\n\nThe first is the job `timeout`. This is the amount of time that the broker allocates exclusive responsibility for a job to a worker instance. By default, this is 60 seconds. This is the default value set by this client library. See \"[Job Workers](#job-workers)\".\n\nThe second is the `requestTimeout`. Whenever the client library sends a gRPC command to the broker, it has an explicit or implied `requestTimeout`. This is the amount of time that the gRPC gateway will wait for a response from the broker cluster before returning a `4 DEADLINE` gRPC error response.\n\nIf no `requestTimeout` is specified, then the configured timeout of the broker gateway is used. Out of the box, this is 15 seconds by default.\n\nThe most significant use of the `requestTimeout` is when using the `createProcessInstanceWithResult` command. If your process will take longer than 15 seconds to complete, you should specify a `requestTimeout`. See \"[Start a Process Instance and await the Process Outcome](#start-await)\".\n\nThe third is the `longpoll` duration. This is the amount of time that the job worker holds a long poll request to activate jobs open.\n\nThe fourth is the maximum back-off delay in client-side gRPC command retries. See \"[Client-side gRPC retry in ZBClient](#client-side-retry)\".\n\nFinally, the `connectionTolerance` option for ZBClient can also take a typed duration. This value is used to buffer reporting connection errors while establishing a connection - for example with Camunda SaaS, which requires a token exchange as part of the connection process.\n\n## Connection Behaviour\n\n\u003ca name = \"client-side-retry\"\u003e\u003c/a\u003e\n\n### Client-side gRPC retry in ZBClient\n\nIf a gRPC command method fails in the ZBClient - such as `ZBClient.deployProcess` or `ZBClient.topology()`, the underlying gRPC library will throw an exception.\n\nIf no workers have been started, this can be fatal to the process if it is not handled by the application logic. This is especially an issue when a worker container starts before the Zeebe gRPC gateway is available to service requests, and can be inconsistent as this is a race condition.\n\nTo mitigate against this, the Node client implements some client-side gRPC operation retry logic by default. This can be configured, including disabled, via configuration in the client constructor.\n\n-   Operations retry, but only for [gRPC error codes 8 and 14](https://github.com/grpc/grpc/blob/master/doc/statuscodes.md) - indicating resource exhaustion (8) or transient network failure (14). Resource exhaustion occurs when the broker starts backpressure due to latency because of load. Network failure can be caused by passing in an unresolvable gateway address (`14: DNS Resolution failed`), or by the gateway not being ready yet (`14: UNAVAILABLE: failed to connect to all addresses`).\n-   Operations that fail for other reasons, such as deploying an invalid bpmn file or cancelling a process that does not exist, do not retry.\n-   Retry is enabled by default, and can be disabled by passing { retry: false } to the client constructor.\n-   Values for `retry`, `maxRetries` and `maxRetryTimeout` can be configured via the environment variables `ZEEBE_CLIENT_RETRY`, `ZEEBE_CLIENT_MAX_RETRIES` and `ZEEBE_CLIENT_MAX_RETRY_TIMEOUT` respectively.\n-   `maxRetries` and `maxRetryTimeout` are also configurable through the constructor options, or through environment variables. By default, if not supplied, the values are:\n\n```TypeScript\nconst { ZBClient, Duration } = require('zeebe-node')\n\nconst zbc = new ZBClient(gatewayAddress, {\n    retry: true,\n    maxRetries: -1, // infinite retries\n    maxRetryTimeout: Duration.seconds.of(5)\n})\n```\n\nThe environment variables are:\n\n```\nZEEBE_CLIENT_MAX_RETRIES\nZEEBE_CLIENT_RETRY\nZEEBE_CLIENT_MAX_RETRY_TIMEOUT\n```\n\nRetry is provided by [promise-retry](https://www.npmjs.com/package/promise-retry), and the back-off strategy is simple ^2.\n\nAdditionally, the gRPC Client will continually reconnect when in a failed state, such as when the gateway goes away due to pod rescheduling on Kubernetes.\n\n\u003ca name = \"eager-connection\"\u003e\u003c/a\u003e\n\n### Eager Connection\n\nThe ZBClient eagerly connects to the broker by issuing a topology command in the constructor. This allows you an onReady event to be emitted. You can disable this (for example, for testing without a broker), by either passing `eagerConnection: false` to the client constructor options, or setting the environment variable `ZEEBE_NODE_EAGER_CONNECTION` to `false`.\n\n\u003ca name = \"on-ready\"\u003e\u003c/a\u003e\n\n### onReady(), onConnectionError(), and connected\n\nThe client has a `connected` property that can be examined to determine if it has a gRPC connection to the gateway.\n\nThe client and the worker can take an optional `onReady()` and `onConnectionError()` handler in their constructors, like this:\n\n```TypeScript\nconst { ZBClient, Duration } = require('zeebe-node')\n\nconst zbc = new ZBClient({\n\tonReady: () =\u003e console.log(`Connected!`),\n\tonConnectionError: () =\u003e console.log(`Disconnected!`)\n})\n\nconst zbWorker = zbc.createWorker({\n    taskType: 'demo-service',\n\ttaskHandler: handler,\n    onReady: () =\u003e console.log(`Worker connected!`),\n    onConnectionError: () =\u003e console.log(`Worker disconnected!`)\n})\n```\n\nThese handlers are called whenever the gRPC channel is established or lost. As the grpc channel will often \"jitter\" when it is lost (rapidly emitting READY and ERROR events at the transport layer), there is a `connectionTolerance` property that determines how long the connection must be in a connected or failed state before the handler is called. By default this is 3000ms.\n\nYou can specify another value either in the constructor or via an environment variable.\n\nTo specify it via an environment variable, set `ZEEBE_CONNECTION_TOLERANCE` to a number of milliseconds.\n\nTo set it via the constructor, specify a value for `connectionTolerance` like this:\n\n```TypeScript\nconst { ZBClient, Duration } = require('zeebe-node')\n\nconst zbc = new ZBClient({\n\tonReady: () =\u003e console.log(`Connected!`),\n\tonConnectionError: () =\u003e console.log(`Disconnected!`),\n\tconnectionTolerance: 5000 // milliseconds\n})\n\nconst zbWorker = zbc.createWorker({\n\ttaskType: 'demo-service',\n\ttaskHandler: handler,\n    onReady: () =\u003e console.log(`Worker connected!`),\n    onConnectionError: () =\u003e console.log(`Worker disconnected!`),\n    connectionTolerance: Duration.seconds.of(3.5) // 3500 milliseconds\n})\n```\n\nAs well as the callback handlers, the client and workers extend the [`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter) class, and you can attach listeners to them for the 'ready' and 'connectionError' events:\n\n```TypeScript\nconst { ZBClient, Duration } = require('zeebe-node')\n\nconst zbc = new ZBClient()\n\nconst zbWorker = zbc.createWorker({\n\ttaskType: 'demo-service',\n\ttaskHandler: handler,\n    connectionTolerance: Duration.seconds.of(3.5)\n})\n\nzbWorker.on('ready', () =\u003e console.log(`Worker connected!`))\nzbWorker.on('connectionError', () =\u003e console.log(`Worker disconnected!`))\n```\n\n\u003ca href = \"initial-connection-tolerance\" \u003e\u003c/a\u003e\n\n### Initial Connection Tolerance\n\nSome broker connections can initially emit error messages - for example: when connecting to Camunda SaaS, during TLS negotiation and OAuth authentication, the eager commands used to detect connection status will fail, and the library will report connection errors.\n\nSince this is expected behaviour - a _characteristic of that particular connection_ - the library has a configurable \"_initial connection tolerance_\". This is a number of milliseconds representing the expected window in which these errors will occur on initial connection.\n\nIf the library detects that you are connecting to Camunda SaaS, it sets this window to five seconds (5000 milliseconds). In some environments and under some conditions this may not be sufficient.\n\nYou can set an explicit value for this using the environment variable `ZEEBE_INITIAL_CONNECTION_TOLERANCE`, set to a number of milliseconds.\n\nThe effect of this setting is to suppress connection errors during this window, and only report them if the connection did not succeed by the end of the window.\n\n## Connecting to a Broker\n\n\u003ca name = \"tls\"\u003e\u003c/a\u003e\n\n### TLS\n\nThe Node client does not use TLS by default.\n\nEnable a secure connection by setting `useTLS: true`:\n\n```typescript\nconst { ZBClient } = require('zeebe-node')\n\nconst zbc = new ZBClient(tlsSecuredGatewayAddress, {\n\tuseTLS: true,\n})\n```\n\nVia environment variable:\n\n```bash\nZEEBE_SECURE_CONNECTION=true\n```\n\n### Using a Self-signed Certificate\n\nYou can use a self-signed SSL certificate with the Zeebe client. You need to provide the root certificates, the private key and the SSL cert chain as Buffers. You can pass them into the ZBClient constructor:\n\n```typescript\nconst rootCertsPath = '/path/to/rootCerts'\nconst privateKeyPath = '/path/to/privateKey'\nconst certChainPath = '/path/to/certChain'\n\nconst zbc = new ZBClient({\n    useTLS: true,\n    customSSL: {\n        rootCerts: rootCertsPath,\n        privateKey: privateKeyPath,\n        certChain: certChainPath\n    }\n})\n\nOr you can put the file paths into the environment in the following variables:\n\nZEEBE_CLIENT_SSL_ROOT_CERTS_PATH\nZEEBE_CLIENT_SSL_PRIVATE_KEY_PATH\nZEEBE_CLIENT_SSL_CERT_CHAIN_PATH\n```\n\n# Enable TLS\n\n```\nZEEBE_SECURE_CONNECTION=true\n```\n\nIn this case, they will be passed to the constructor automatically.\n\n\u003ca name = \"oauth\"\u003e\u003c/a\u003e\n\n### OAuth\n\nIn case you need to connect to a secured endpoint with OAuth, you can pass in OAuth credentials. This will enable TLS (unless you explicitly disable it with `useTLS: false`), and handle the OAuth flow to get / renew a JWT:\n\n```typescript\nconst { ZBClient } = require('zeebe-node')\n\nconst zbc = new ZBClient(\"my-secure-broker.io:443\", {\n\toAuth: {\n\t\turl: \"https://your-auth-endpoint/oauth/token\",\n\t\taudience: \"my-secure-broker.io\",\n        scope: \"myScope\",\n\t\tclientId: \"myClientId\",\n\t\tclientSecret: \"randomClientSecret\",\n\t\tcustomRootCert: fs.readFileSync('./my_CA.pem'),\n\t\tcacheOnDisk: true\n\t}\n}\n```\n\nThe `cacheOnDisk` option will cache the token on disk in `$HOME/.camunda`, which can be useful in development if you are restarting the service frequently, or are running in a serverless environment, like AWS Lambda.\n\nIf the cache directory is not writable, the ZBClient constructor will throw an exception. This is considered fatal, as it can lead to denial of service or hefty bills if you think caching is on when it is not.\n\nThe `customRootCert` argument is optional. It can be used to provide a custom TLS certificate as a Buffer, which will be used while obtaining the OAuth token from the specified URL. If not provided, the CAs provided by [Mozilla](https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReport) will be used.\n\n\u003ca name = \"basic-auth\"\u003e\u003c/a\u003e\n\n## Basic Auth\n\nIf you put a proxy in front of the broker with basic auth, you can pass in a username and password:\n\n```typescript\nconst { ZBClient } = require('zeebe-node')\n\nconst zbc = new ZBClient(\"my-broker-with-basic-auth.io:443\", {\n\tbasicAuth: {\n\t\tusername: \"user1\",\n\t\tpassword: \"secret\",\n\t},\n\tuseTLS: true\n}\n```\n\nBasic Auth will also work without TLS.\n\n\u003ca name = \"camunda-cloud\"\u003e\u003c/a\u003e\n\n### Camunda 8 SaaS\n\n[Camunda 8 SaaS](https://camunda.io) is a hosted SaaS instance of Zeebe. The easiest way to connect is to use the [Zero-conf constructor](#zero-conf) with the Client Credentials from the Camunda SaaS console as environment variables.\n\nYou can also connect to Camunda SaaS by using the `camundaCloud` configuration option, using the `clusterId`, `clientSecret`, and `clientId` from the Camunda SaaS Console, like this:\n\n```typescript\nconst { ZBClient } = require('zeebe-node')\n\nconst zbc = new ZBClient({\n\tcamundaCloud: {\n\t\tclientId,\n\t\tclientSecret,\n\t\tclusterId,\n\t\tclusterRegion, // optional, defaults to bru-2\n\t},\n})\n```\n\nThat's it! Under the hood, the client lib will construct the OAuth configuration for Camunda SaaS and set the gateway address and port for you.\n\nWe recommend the [Zero-conf constructor](#zero-conf) with the configuration passed in via environment variables. This allows you to run your application against different environments via configuration.\n\n\u003ca name = \"zero-conf\"\u003e\u003c/a\u003e\n\n## Zero-Conf constructor\n\nThe ZBClient has a 0-parameter constructor that takes the config from the environment. This is useful for injecting secrets into your app via the environment, and switching between development and production environments with no change to code.\n\nTo use the zero-conf constructor, you create the client like this:\n\n```typescript\nconst { ZBClient } = require('zeebe-node')\n\nconst zbc = new ZBClient()\n```\n\nWith no relevant environment variables set, it will default to localhost on the default port with no TLS.\n\nThe following environment variable configurations are possible with the Zero-conf constructor:\n\nFrom 8.3.0, multi-tenancy: \n\n```bash\nZEEBE_TENANT_ID\n```\n\nCamunda SaaS:\n\n```bash\nZEEBE_ADDRESS\nZEEBE_CLIENT_SECRET\nZEEBE_CLIENT_ID\nZEEBE_TOKEN_AUDIENCE\nZEEBE_AUTHORIZATION_SERVER_URL\n```\n\nSelf-hosted or local broker (no TLS or OAuth):\n\n```bash\nZEEBE_ADDRESS\n```\n\nSelf-hosted with self-signed SSL certificate:\n\n```bash\nZEEBE_CLIENT_SSL_ROOT_CERTS_PATH\nZEEBE_CLIENT_SSL_PRIVATE_KEY_PATH\nZEEBE_CLIENT_SSL_CERT_CHAIN_PATH\nZEEBE_SECURE_CONNECTION=true\n```\n\nSelf-hosted or local broker with OAuth + TLS:\n\n```bash\nZEEBE_CLIENT_ID\nZEEBE_CLIENT_SECRET\nZEEBE_TOKEN_AUDIENCE\nZEEBE_TOKEN_SCOPE\nZEEBE_AUTHORIZATION_SERVER_URL\nZEEBE_ADDRESS\n```\n\nMulti-tenant self-hosted or local broker with OAuth and no TLS:\n\n```bash\nZEEBE_TENANT_ID='\u003cdefault\u003e'\nZEEBE_SECURE_CONNECTION=false\nZEEBE_ADDRESS='localhost:26500'\nZEEBE_CLIENT_ID='zeebe'\nZEEBE_CLIENT_SECRET='zecret'\nZEEBE_AUTHORIZATION_SERVER_URL='http://localhost:18080/auth/realms/camunda-platform/protocol/openid-connect/token'\nZEEBE_TOKEN_AUDIENCE='zeebe.camunda.io'\nZEEBE_TOKEN_SCOPE='not needed'\nCAMUNDA_CREDENTIALS_SCOPES='Zeebe'\nCAMUNDA_OAUTH_URL='http://localhost:18080/auth/realms/camunda-platform/protocol/openid-connect/token'\n```\n\nBasic Auth:\n\n```bash\nZEEBE_BASIC_AUTH_PASSWORD\nZEEBE_BASIC_AUTH_USERNAME\n```\n\n\u003ca name =\"job-workers\"\u003e\u003c/a\u003e\n\n## Job Workers\n\n### Types of Job Workers\n\nThere are two different types of job worker provided by the Zeebe Node client:\n\n-   The `ZBWorker` - this worker operates on individual jobs.\n-   The `ZBBatchWorker` - this worker batches jobs on the client, to allow you to batch operations that pool resources. (_This worker was introduced in 0.23.0 of the client_).\n\nMuch of the information in the following [`ZBWorker` section](#create-zbworker) applies also to the `ZBBatchWorker`. The `ZBBatchWorker` section covers the features that differ from the `ZBWorker`.\n\n\u003ca name = \"create-zbworker\"\u003e\u003c/a\u003e\n\n### The `ZBWorker` Job Worker\n\nThe `ZBWorker` takes a _job handler function_ that is invoked for each job. It is invoked as soon as the worker retrieves a job from the broker. The worker can retrieve any number of jobs in a response from the broker, and the handler is invoked for each one, independently.\n\nThe simplest signature for a worker takes a string task type, and a job handler function.\n\nThe job handler receives the job object, which has methods that it can use to complete or fail the job, and a reference to the worker itself, which you can use to log using the worker's configured logger (See [Logging](#logging)).\n\nNote: _The second argument is deprecated, and remains for backward-compatibility - it is a complete function. In the 1.0 version of the API, the complete function methods are available on the `job` object_.\n\n```javascript\nconst ZB = require('zeebe-node')\n\nconst zbc = new ZB.ZBClient()\n\nconst zbWorker = zbc.createWorker({\n\ttaskType: 'demo-service',\n\ttaskHandler: handler,\n})\n\nfunction handler(job) {\n\tzbWorker.log('Task variables', job.variables)\n\n\t// Task worker business logic goes here\n\tconst updateToBrokerVariables = {\n\t\tupdatedProperty: 'newValue',\n\t}\n\n\treturn job.complete(updateToBrokerVariables)\n}\n```\n\nHere is an example job:\n\n```javascript\n\n{ key: '578',\n  type: 'demo-service',\n  jobHeaders:\n   { processInstanceKey: '574',\n     bpmnProcessId: 'test-process',\n     processDefinitionVersion: 1,\n     processKey: '3',\n     elementId: 'ServiceTask_0xdwuw7',\n     elementInstanceKey: '577' },\n  customHeaders: '{}',\n  worker: 'test-worker',\n  retries: 3,\n  deadline: '1546915422636',\n  variables: { testData: 'something' } }\n```\n\nThe worker can be configured with options. To do this, you should use the object parameter constructor.\n\nShown below are the defaults that apply if you don't supply them:\n\n```javascript\nconst { ZBClient, Duration } = require('zeebe-node')\n\nconst zbc = new ZBClient()\n\nconst zbWorker = zbc.createWorker({\n\ttaskType: 'demo-service',\n    taskHandler: handler,\n    // the number of simultaneous tasks this worker can handle\n    maxJobsToActivate: 32,\n    // the amount of time the broker should allow this worker to complete a task\n    timeout: Duration.seconds.of(30),\n    // One of 'DEBUG', 'INFO', 'NONE'\n    loglevel: 'INFO',\n    // Called when the connection to the broker cannot be established, or fails\n    onConnectionError: () =\u003e zbWorker.log('Disconnected')\n    // Called when the connection to the broker is (re-)established\n    onReady: () =\u003e zbWorker.log('Connected.')\n})\n```\n\n\u003ca name = \"unhandled-exceptions\"\u003e\u003c/a\u003e\n\n#### Unhandled Exceptions in Task Handlers\n\n_Note: this behaviour is for the ZBWorker only. The ZBBatchWorker does not manage this._\n\nWhen a task handler throws an unhandled exception, the library will fail the job. Zeebe will then retry the job according to the retry settings of the task. Sometimes you want to halt the entire process so you can investigate. To have the library cancel the process on an unhandled exception, pass in `{failProcessOnException: true}` to the `createWorker` call:\n\n```typescript\nimport { ZBClient } from 'zeebe-node'\n\nconst zbc = new ZBClient()\n\nzbc.createWorker({\n\ttaskType: 'console-log',\n\ttaskHandler: maybeFaultyHandler,\n\tfailProcessOnException: true,\n})\n```\n\n\u003ca name = \"complete-tasks\"\u003e\u003c/a\u003e\n\n### Completing tasks with success, failure, error, or forwarded\n\nTo complete a task, the job object that the task worker handler function receives has `complete`, `fail`, and `error` methods.\n\nCall `job.complete()` passing in a optional plain old JavaScript object (POJO) - a key:value map. These are variable:value pairs that will be used to update the process state in the broker. They will be merged with existing values. You can set an existing key to `null` or `undefined`, but there is no way to delete a key.\n\nCall `job.fail()` to fail the task. You mus t pass in a string message describing the failure. The client library decrements the retry count, and the broker handles the retry logic. If the failure is a hard failure and should cause an incident to be raised in Operate, then pass in `0` for the optional second parameter, `retries`:\n\n```javascript\njob.fail('This is a critical failure and will raise an incident', 0)\n```\n\nFrom version 8.0.0 of the package, used with a 8.0.0 Zeebe broker, you can specify to the broker an optional backoff for the reactivation of the job, like this:\n\n```javascript\njob.fail({\n\terrorMessage: 'Triggering a retry with a two second back-off',\n\tretryBackOff: 2000,\n\tretries: 1,\n})\n```\n\nCall `job.error()` to trigger a BPMN error throw event. You must pass in a string error code for the error code, and you can pass an optional error message as the second parameter. If no BPMN error catch event exists for the error code, an incident will be raised.\n\n```javascript\njob.error('RECORD_NOT_FOUND', 'Could not find the customer in the database')\n```\n\nFrom 8.2.5 of the client, you can update the variables in the workflow when you throw a BPMN error in a worker:\n\n```javascript\njob.error({\n    errorCode: 'RECORD_NOT_FOUND',\n    errorMessage: 'Could not find the customer in the database',\n    variables: {\n        someVariable: 'someValue'\n    }\n})\n```\n\nCall `job.forwarded()` to release worker capacity to handle another job, without completing the job in any way with the Zeebe broker. This method supports the _decoupled job completion_ pattern. In this pattern, the worker forwards the job to another system - a lambda or a RabbitMQ queue. Some other process is ultimately responsible for completing the job.\n\n\u003ca name = \"working-with-variables\"\u003e\u003c/a\u003e\n\n## Working with Process Variables and Custom Headers\n\nProcess variables are available in your worker job handler callback as `job.variables`, and any custom headers are available as `job.customHeaders`.\n\nThese are read-only JavaScript objects in the Zeebe Node client. However, they are not stored that way in the broker.\n\nBoth process variables and custom headers are stored in the broker as a dictionary of named strings. That means that the variables and custom headers are JSON.parsed in the Node client when it fetches the job, and any update passed to the `success()` function is JSON.stringified.\n\nIf you pass in a circular JSON structure to `complete()` - like, for example the response object from an HTTP call - it will throw, as this cannot be serialised to a string.\n\nTo update a key deep in the object structure of a process variable, you can use the [deepmerge utility](https://www.npmjs.com/package/deepmerge):\n\n```TypeScript\nconst merge = require('deepmerge')\nimport { ZBClient } from 'zeebe-node'\n\nconst zbc = new ZBClient()\n\nzbc.createWorker({\n    taskType: 'some-task',\n    taskHandler: job =\u003e {\n        const { people } = job.variables\n        // update bob's age, keeping all his other properties the same\n        job.complete(merge(people, { bob: { age: 23 } }))\n    }\n})\n```\n\nWhen setting custom headers in BPMN tasks, while designing your model, you can put stringified JSON as the value for a custom header, and it will show up in the client as a JavaScript object.\n\nProcess variables and custom headers are untyped in the Zeebe broker, however the Node client in TypeScript mode provides the option to type them to provide safety. You can type your worker as `any` to turn that off:\n\n```TypeScript\n// No type checking - totally dynamic and unchecked\nzbc.createWorker\u003cany\u003e({\n    taskType: 'yolo-jobs',\n    taskHandler: (job) =\u003e {\n        console.log(`Look ma - ${job.variables?.anything?.goes?.toUpperCase()}`)\n        job.complete({what: job.variables.could.possibly.go.wrong})\n    }\n})\n```\n\nSee the section [Writing Strongly-typed Job Workers](#strongly-typed) for more details.\n\n\u003ca name = \"fetch-variables\"\u003e\u003c/a\u003e\n\n## Constraining the Variables Fetched by the Worker\n\nSometimes you only need a few specific process variables to service a job. One way you can achieve constraint on the process variables received by a worker is by using [input variable mappings](https://docs.zeebe.io/reference/variables.html#inputoutput-variable-mappings) on the task in the model.\n\nYou can also use the `fetchVariable` parameter when creating a worker. Pass an array of strings, containing the names of the variables to fetch, to the `fetchVariable` parameter when creating a worker. Here is an example, in JavaScript:\n\n```javascript\nzbc.createWorker({\n\ttaskType: 'process-favorite-albums',\n\ttaskHandler: job =\u003e {\n\t\tconst { name, albums } = job.variables\n\t\tconsole.log(`${name} has the following albums: ${albums.join(', ')}`)\n\t\tjob.complete()\n\t},\n\tfetchVariable: ['name', 'albums'],\n})\n```\n\nIf you are using TypeScript, you can supply an interface describing the process variables, and parameterize the worker:\n\n```TypeScript\ninterface Variables {\n    name: string\n    albums: string[]\n}\n\nzbc.createWorker\u003cVariables\u003e({\n    taskType: 'process-favorite-albums',\n    taskHandler: (job) =\u003e {\n        const { name, albums = [] } = job.variables\n        console.log(`${name} has the following albums: ${albums?.join?.(', ')}`)\n        job.complete()\n    },\n    fetchVariable: ['name', 'albums'],\n})\n```\n\nThis parameterization does two things:\n\n-   It informs the worker about the expected types of the variables. For example, if `albums` is a string, calling `join` on it will fail at runtime. Providing the type allows the compiler to reason about the valid methods that can be applied to the variables.\n-   It allows the type-checker to pick up spelling errors in the strings in `fetchVariable`, by comparing them with the Variables typing.\n\nNote, that this does not protect you against run-time exceptions where your typings are incorrect, or the payload simply does not match the definition that you provided.\n\nSee the section [ Writing Strongly-typed Job Workers ](#strongly-typed) for more details on run-time safety.\n\nYou can turn off the type-safety by typing the worker as `any`:\n\n```TypeScript\nzbc.createWorker\u003cany\u003e({\n    taskType: 'process-favorite-albums',\n    taskHandler: (job) =\u003e {\n        const { name, albums = [] } = job.variables\n        // TS 3.7 safe access to .join _and_ safe call, to prevent run-time exceptions\n        console.log(`${name} has the following albums: ${albums?.join?.(', ')}`)\n        job.complete()\n    },\n    fetchVariable: ['name', 'albums'],\n})\n```\n\n\u003ca name = \"decoupled-complete\"\u003e\u003c/a\u003e\n\n## The \"Decoupled Job Completion\" pattern\n\nThe _Decoupled Job Completion_ pattern uses a Zeebe Job Worker to activate jobs from the broker, and some other asynchronous (remote) system to do the work.\n\nYou might activate jobs and then send them to a RabbitMQ queue, or to an AWS lambda. In this case, there may be no outcome about the job that this worker can report back to the broker about success or failure. That will be the responsibility of another part of your distributed system.\n\nThe first thing you should do is ensure that you activate the job with sufficient time for the complete execution of your system. Your worker will not be completing the job, but it informs the broker how long the expected loop will take to close.\n\nNext, call `job.forward()` in your job worker handler. This has no side-effect with the broker - so nothing is communicated to Zeebe. The job is still out there with your worker as far as Zeebe is concerned. What this call does is release worker capacity to request more jobs.\n\nIf you are using the Zeebe Node library in the remote system, or if the remote system eventually reports back to you (perhaps over a different RabbitMQ queue), you can use the ZBClient methods `completeJob()`, `failJob()`, and `throwError()` to report the outcome back to the broker.\n\nYou need at least the `job.key`, to be able to correlate the result back to Zeebe. Presumably you also want the information from the remote system about the outcome, and any updated variables.\n\nHere is an example:\n\n-   You have a COBOL system that runs a database.\n-   Somebody wrote an adapter for this COBOL database. In executes commands over SSH.\n-   The adapter is accessible via a RabbitMQ \"request\" queue, which takes a command and a correlation id, so that its response can be correlated to this request.\n-   The adapter sends back the COBOL database system response on a RabbitMQ \"response\" queue, with the correlation id.\n-   It typically takes 15 seconds for the round-trip through RabbitMQ to the COBOL database and back.\n\nYou want to put this system into a Zeebe-orchestrated BPMN model as a task.\n\nRather than injecting a RabbitMQ listener into the job handler, you can \"_fire and forget_\" the request using the decoupled job completion pattern.\n\nHere is how you do it:\n\n-   Your worker gets the job from Zeebe.\n-   Your worker makes the command and sends it down the RabbitMQ \"request\" queue, with the `job.jobKey` as the correlation id.\n-   Your worker calls `job.forward()`\n\nHere is what that looks like in code:\n\n```TypeScript\nimport { RabbitMQSender } from './lib/my-awesome-rabbitmq-api'\nimport { ZBClient, Duration } from 'zeebe-node'\n\nconst zbc = new ZBClient()\n\nconst cobolWorker = zbc.createWorker({\n    taskType: 'cobol-insert',\n    timeout: Duration.seconds.of(20), // allow 5s over the expected 15s\n    taskHandler: job =\u003e {\n        const { key, variables } = job\n        const request = {\n            correlationId: key,\n            command: `INSERT ${variables.customer} INTO CUSTOMERS`\n        }\n        RabbitMQSender.send({\n            channel: 'COBOL_REQ',\n            request\n        })\n        // Call forward() to release worker capacity\n        return job.forward()\n    }\n)\n```\n\nNow for the response part:\n\n-   Another part of your system listens to the RabbitMQ response queue.\n-   It gets a response back from the COBOL adapter.\n-   It examines the response, then sends the appropriate outcome to Zeebe, using the jobKey that has been attached as the correlationId\n\n```TypeScript\nimport { RabbitMQListener } from './lib/my-awesome-rabbitmq-api'\nimport { ZBClient } from 'zeebe-node'\n\nconst zbc = new ZBClient()\n\nconst RabbitMQListener.listen({\n    channel: 'COBOL_RES',\n    handler: message =\u003e {\n        const { outcome, correlationId } = message\n        if (outcome.SUCCESS) {\n            zbc.completeJob({\n                jobKey: correlationId,\n                variables: {}\n            })\n        }\n        if (outcome.ERROR) {\n            zbc.throwError({\n                jobKey: correlationId,\n                errorCode: \"5\",\n                errorMessage: \"The COBOL Database reported an error. Boo!\"\n            })\n        }\n    })\n}\n```\n\nSee also the section \"[Publish a Message](#publish-message)\", for a pattern that you can use when it is not possible to attach the job key to the round trip data response.\n\n\u003ca name = \"zbbatchworker\"\u003e\u003c/a\u003e\n\n## The `ZBBatchWorker` Job Worker\n\nThe `ZBBatchWorker` Job Worker batches jobs before calling the job handler. Its fundamental differences from the ZBWorker are:\n\n-   Its job handler receives an _array_ of one or more jobs.\n-   The handler is not invoked immediately, but rather when enough jobs are batched, or a job in the batch is at risk of being timed out by the Zeebe broker.\n\nYou can use the batch worker if you have tasks that _benefit from processing together_, but are _not related in the BPMN model_.\n\nAn example would be a high volume of jobs that require calls to an external system, where you have to pay per call to that system. In that case, you may want to batch up jobs, make one call to the external system, then update all the jobs and send them on their way.\n\nThe batch worker works on a _first-of_ batch size _or_ batch timeout basis.\n\nYou must configure both `jobBatchMinSize` and `jobBatchMaxTime`. Whichever condition is met first will trigger the processing of the jobs:\n\n-   Enough jobs are available to the worker to satisfy the minimum job batch size;\n-   The batch has been building for the maximum amount of time - \"_we're doing this now, before the earliest jobs in the batch time out on the broker_\".\n\nYou should be sure to specify a `timeout` for your worker that is `jobBatchMaxTime` _plus_ the expected latency of the external call _plus_ your processing time and network latency, to avoid the broker timing your batch worker's lock and making the jobs available to another worker. That would defeat the whole purpose.\n\nHere is an example of using the `ZBBatchWorker`:\n\n```TypeScript\nimport { API } from './lib/my-awesome-external-api'\nimport { ZBClient, BatchedJob, Duration } from 'zeebe-node'\n\nconst zbc = new ZBClient()\n\n// Helper function to find a job by its key\nconst findJobByKey = jobs =\u003e key =\u003e jobs.filter(job =\u003e job.jobKey === id)?.[0] ?? []\n\nconst handler = async (jobs: BatchedJob[]) =\u003e {\n    console.log(\"Let's do this!\")\n    const {jobKey, variables} = job\n    // Construct some hypothetical payload with correlation ids and requests\n    const req = jobs.map(job =\u003e ({id: jobKey, data: variables.request}))\n    // An uncaught exception will not be managed by the library\n    try {\n        // Our API wrapper turns that into a request, and returns\n        // an array of results with ids\n        const outcomes = await API.post(req)\n        // Construct a find function for these jobs\n        const getJob = findJobByKey(jobs)\n        // Iterate over the results and call the succeed method on the corresponding job,\n        // passing in the correlated outcome of the API call\n        outcomes.forEach(res =\u003e getJob(res.id)?.complete(res.data))\n    } catch (e) {\n        jobs.forEach(job =\u003e job.fail(e.message))\n    }\n}\n\nconst batchWorker = zbc.createBatchWorker({\n    taskType: 'get-data-from-external-api',\n    taskHandler: handler,\n    jobBatchMinSize: 10, // at least 10 at a time\n    jobBatchMaxTime: 60, // or every 60 seconds, whichever comes first\n    timeout: Duration.seconds.of(80) // 80 second timeout means we have 20 seconds to process at least\n})\n```\n\nSee [this blog post](http://joshwulf.com/blog/2020/03/zb-batch-worker/) for some more details on the implementation.\n\n\u003ca name = \"long-polling\"\u003e\u003c/a\u003e\n\n### Long polling\n\nWith Zeebe 0.21 onward, long polling is supported for clients, and is used by default. Rather than polling continuously for work and getting nothing back, a client can poll once and leave the request open until work appears. This reduces network traffic and CPU utilization in the server. Every JobActivation Request is appended to the event log, so continuous polling can significantly impact broker performance, especially when an exporter is loaded (see [here](https://github.com/zeebe-io/zeebe-client-node-js/issues/64#issuecomment-520233275)).\n\nLong polling sends the `ActivateJobs` command to the broker, and waits for up to the long poll interval for jobs to be available, rather than returning immediately with an empty response if no jobs are available at that moment.\n\nThe default long poll duration is 30s.\n\nTo use a different long polling duration, pass in a long poll timeout in milliseconds to the client. All workers created with that client will use it. Alternatively, set a period per-worker.\n\nLong polling for workers is configured in the ZBClient like this:\n\n```typescript\nconst { ZBClient, Duration } = require('zeebe-node')\n\nconst zbc = new ZBClient('serverAddress', {\n\tlongPoll: Duration.minutes.of(10), // Ten minutes - inherited by workers\n})\n\nconst longPollingWorker = zbc.createWorker({\n\ttaskType: 'task-type',\n\ttaskHandler: handler,\n\tlongPoll: Duration.minutes.of(2), // override client, poll 2m\n})\n```\n\n\u003ca name = \"poll-interval\"\u003e\n\n### Poll Interval\n\nThe poll interval is a timer that fires on the configured interval and sends an `ActivateJobs` command if no pending command is currently active. By default, this is set to 300ms. This guarantees that there will be a minimum of 300ms between `ActivateJobs` commands, which prevents flooding the broker.\n\nToo many `ActivateJobs` requests per period of time can cause broker backpressure to kick in, and the gateway to return a GRPC 8 error code.\n\nYou can configure this with the `pollInterval` option in the client constructor, in which case all workers inherit it as their default. You can also override this by specifying a value in the `createWorker` call:\n\n```typescript\nconst zbc = new ZBClient({\n\tpollInterval: Duration.milliseconds.of(500),\n})\n\nconst worker = zbc.createWorker({\n\ttaskType: 'send-email',\n\ttaskHandler: sendEmailWorkerHandler,\n\tpollInterval: Duration.milliseconds.of(750),\n})\n```\n\n## Client Commands\n\n\u003ca name = \"deploy-resource\"\u003e\u003c/a\u003e\n\n### Deploy Process Models and Decision Tables\n\nFrom version 8 of Zeebe, `deployProcess` in deprecated in favor of `deployResource` which allows you to deploy both process models and DMN tables.\n\nYou can deploy a resource as a buffer, or by passing a filename - in which case the client library will load the file into a buffer for you.\n\n### Deploy Process Model\n\nBy passing a filename, and allowing the client library to load the file into a buffer:\n\n```typescript\nasync function deploy() {\n\tconst zbc = new ZBClient()\n\tconst result = await zbc.deployResource({\n\t\tprocessFilename: `./src/__tests__/testdata/Client-DeployWorkflow.bpmn`,\n\t})\n}\n```\n\nBy passing a buffer, and a name:\n\n```typescript\nasync function deploy() {\n\tconst zbc = new ZBClient()\n\tconst process = fs.readFileSync(\n\t\t`./src/__tests__/testdata/Client-DeployWorkflow.bpmn`\n\t)\n\tconst result = await zbc.deployResource({\n\t\tprocess,\n\t\tname: `Client-DeployWorkflow.bpmn`,\n\t})\n}\n```\n\n### Deploy DMN Table\n\nBy passing a filename, and allowing the client library to load the file into a buffer:\n\n```typescript\nasync function deploy() {\n\tconst zbc = new ZBClient()\n\tconst result = await zbc.deployResource({\n\t\tdecisionFilename: `./src/__tests__/testdata/quarantine-duration.dmn`,\n\t})\n}\n```\n\nBy passing a buffer, and a name:\n\n```typescript\nasync function deploy() {\n\tconst zbc = new ZBClient()\n\tconst decision = fs.readFileSync(\n\t\t`./src/__tests__/testdata/quarantine-duration.dmn`\n\t)\n\tconst result = await zbc.deployResource({\n\t\tdecision,\n\t\tname: `quarantine-duration.dmn`,\n\t})\n}\n```\n\n### Deploy Form\n\nFrom 8.3.1, you can deploy a form to the Zeebe broker:\n\n```javascript\nasync function deploy() {\n    const zbc = new ZBClient()\n    const form = fs.readFileSync(\n\t\t'./src/__tests__/testdata/form_1.form'\n\t)\n\tconst result = await zbc.deployResource({\n\t\tform,\n\t\tname: 'form_1.form',\n\t})\n}\n```\n\n\u003ca name = \"start-process\"\u003e\u003c/a\u003e\n\n### Start a Process Instance\n\n```javascript\nconst ZB = require('zeebe-node')\n\n;(async () =\u003e {\n\tconst zbc = new ZB.ZBClient('localhost:26500')\n\tconst result = await zbc.createProcessInstance({\n        bpmnProcessId: 'test-process',\n\t\tvariables: {\n            testData: 'something'\n        }\n\t})\n\tconsole.log(result)\n})()\n```\n\nExample output:\n\n```javascript\n\n{ processKey: '3',\n  bpmnProcessId: 'test-process',\n  version: 1,\n  processInstanceKey: '569' }\n\n```\n\n\u003ca name = \"start-specific-version\"\u003e\u003c/a\u003e\n\n### Start a Process Instance of a specific version of a Process definition\n\nFrom version 0.22 of the client onward:\n\n```javascript\nconst ZB = require('zeebe-node')\n\n;(async () =\u003e {\n\tconst zbc = new ZB.ZBClient('localhost:26500')\n\tconst result = await zbc.createProcessInstance({\n\t\tbpmnProcessId: 'test-process',\n\t\tvariables: {\n\t\t\ttestData: 'something',\n\t\t},\n\t\tversion: 5,\n\t})\n\tconsole.log(result)\n})()\n```\n\n\u003ca name = \"start-await\"\u003e\u003c/a\u003e\n\n### Start a Process Instance and await the Process Outcome\n\nFrom version 0.22 of the broker and client, you can await the outcome of a process end-to-end execution:\n\n```typescript\nasync function getOutcome() {\n\tconst result = await zbc.createProcessInstanceWithResult({\n        bpmnProcessId: processId,\n        variables: {\n\t\t    sourceValue: 5\n        }\n\t})\n\treturn result\n}\n```\n\nBe aware that by default, **this will throw an exception if the process takes longer than 15 seconds to complete**.\n\nTo override the gateway's default timeout for a process that needs more time to complete:\n\n```typescript\nconst { ZBClient, Duration } = require('zeebe-node')\n\nconst zbc = new ZBClient()\n\nconst result = await zbc.createProcessInstanceWithResult({\n\tbpmnProcessId: processId,\n\tvariables: {\n\t\tsourceValue: 5,\n\t\totherValue: 'rome',\n\t},\n\trequestTimeout: Duration.seconds.of(25),\n\t// also works supplying a number of milliseconds\n\t// requestTimeout: 25000\n})\n```\n\n\u003ca name = \"publish-message\"\u003e\u003c/a\u003e\n\n### Publish a Message\n\nYou can publish a message to the Zeebe broker that will be correlated with a running process instance:\n\n```javascript\nconst { ZBClient, Duration } = require('zeebe-node');\nconst uuid = require('uuid');\n\nconst zbc = new ZBClient()\n\nzbc.publishMessage({\n\tcorrelationKey: 'value-to-correlate-with-process-variable',\n\tmessageId: uuid.v4(),\n\tname: 'message-name',\n\tvariables: { valueToAddToProcessVariables: 'here', status: 'PROCESSED' },\n\ttimeToLive: Duration.seconds.of(10), // seconds\n})\n```\n\nWhen would you do this? Well, the sky is not even the limit when it comes to thinking creatively about building a system with Zeebe - _and_ here's one concrete example to get you thinking:\n\nRecall the example of the _remote COBOL database_ in the section \"[The \"Decoupled Job Completion\" pattern](#decoupled-complete)\". We're writing code to allow that system to be participate in a BPMN-modelling process orchestrated by Zeebe.\n\nBut what happens if the adapter for that system has been written in such a way that there is no opportunity to attach metadata to it? In that case we have no opportunity to attach a job key. Maybe you send the fixed data for the command, and you have to correlate the response based on those fields.\n\nAnother example: think of a system that emits events, and has no knowledge of a running process. An example from one system that I orchestrate with Zeebe is Minecraft. A logged-in user in the game performs some action, and code in the game emits an event. I can catch that event in my Node-based application, but I have no knowledge of which running process to target - _and_ the event was not generated from a BPMN task providing a worker with the complete context of a process.\n\nIn these two cases, I can publish a message to Zeebe, and let the broker figure out which processes are:\n\n-   Sitting at an intermediate message catch event waiting for this message; or\n-   In a sub-process that has a boundary event that will be triggered by this message; or\n-   Would be started by a message start event, on receiving this message.\n\nThe Zeebe broker correlates a message to a running process instance _not on the job key_ - but on _the value of one of the process variables_ (for intermediate message events) and _the message name_ (for all message events, including start messages).\n\nSo the response from your COBOL database system, sans job key, is sent back to Zeebe from the RabbitMQListener not via `completeJob()`, but with `publishMessage()`, and the value of the payload is used to figure out which process it is for.\n\nIn the case of the Minecraft event, a message is published to Zeebe with the Minecraft username, and that is used by Zeebe to determine which processes are running for that user and are interested in that event.\n\nSee the article \"[Zeebe Message Correlation](https://zeebe.io/blog/2019/08/zeebe-message-correlation/)\" for a complete example with code.\n\n\u003ca name=\"publish-start-message\"\u003e\u003c/a\u003e\n\n### Publish a Start Message\n\nYou can also publish a message targeting a [Message Start Event](https://github.com/zeebe-io/zeebe/issues/1858).\nIn this case, the correlation key is optional, and all Message Start events that match the `name` property will receive the message.\n\nYou can use the `publishStartMessage()` method to publish a message with no correlation key (it will be set to a random uuid in the background):\n\n```javascript\nconst { ZBClient, Duration } = require('zeebe-node');\nconst uuid = require('uuid');\n\nconst zbc = new ZBClient('localhost:26500');\nzbc.publishStartMessage({\n  messageId: uuid.v4(),\n  name: 'message-name',\n  variables: { initialProcessVariable: 'here' },\n  timeToLive: Duration.seconds.of(10), // seconds\n});\n\n```\n\nBoth normal messages and start messages can be published idempotently by setting both the `messageId` and the `correlationKey`. They will only ever be correlated once. See: [A message can be published idempotent](https://github.com/zeebe-io/zeebe/issues/1012).\n\n\u003ca name=\"activate-jobs\"\u003e\u003c/a\u003e\n\n### Activate Jobs\n\nIf you have some use case that doesn't fit the existing workers, you can write your own custom workers using the `ZBClient.activateJobs()` method. It takes an `ActivateJobsRequest` object, and returns a stream for that call.\n\nAttach a listener to the stream's 'data' event, and it will be called with an `ActivateJobsResponse` object if there are jobs to work on.\n\nTo complete these jobs, use the `ZBClient` methods `completeJob()`, `failJob()`, and `throwError()`.\n\nFor more details, read the source code of the library, particularly the `ZBWorkerBase` class. This is an advanced use case, and the existing code in the library is the best documentation.\n\n## Other Concerns\n\n\u003ca name = \"graceful-shutdown\"\u003e\u003c/a\u003e\n\n### Graceful Shutdown\n\nTo drain workers, call the `close()` method of the ZBClient. This causes all workers using that client to stop polling for jobs, and returns a Promise that resolves when all active jobs have either finished or timed out.\n\n```javascript\nconsole.log('Closing client...')\nzbc.close().then(() =\u003e console.log('All workers closed'))\n```\n\n\u003ca name = \"logging\"\u003e\u003c/a\u003e\n\n## Logging\n\nControl the log output for the client library by setting the ZBClient log level. Valid log levels are `NONE` (supress all logging), `ERROR` (log only exceptions), `INFO` (general logging), or `DEBUG` (verbose logging). You can set this in the client constructor:\n\n```typescript\nconst zbc = new ZBClient('localhost', { loglevel: 'DEBUG' })\n```\n\nAnd also via the environment:\n\n```bash\nZEEBE_NODE_LOG_LEVEL='ERROR' node start.js\n```\n\nBy default the library uses `console.info` and `console.error` for logging. You can also pass in a custom logger, such as [pino](https://github.com/pinojs/pino):\n\n```typescript\nconst logger = require('pino')()\nconst zbc = new ZBClient({ stdout: logger })\n```\n\nFrom version v0.23.0-alpha.1, the library logs human-readable logs by default, using the `ZBSimpleLogger`. If you want structured logs as stringified JSON, pass in `ZBJSONLogger` to the constructor `stdout` option, like this:\n\n```typescript\nconst { ZBJsonLogger, ZBClient } = require('zeebe-node')\nconst zbc = new ZBClient({ stdout: ZBJsonLogger })\n```\n\nYou can also control this via environment variables:\n\n```bash\nexport ZEEBE_NODE_LOG_TYPE=SIMPLE  # Simple Logger (default)\nexport ZEEBE_NODE_LOG_TYPE=JSON  # JSON Logger\n```\n\n\u003ca name = \"generate-constants\"\u003e\u003c/a\u003e\n\n### Generating TypeScript constants for BPMN Models\n\nMessage names and Task Types are untyped magic strings. You can generate type information to avoid some classes of errors.\n\n#### 0.22.0-alpha.5 and above\n\nInstall the package globally:\n\n```\nnpm i -g zeebe-node\n```\n\nNow you have the command `zeebe-node \u003cfilename\u003e` that parses a BPMN file and emits type definitions.\n\n#### All versions\n\nThe `BpmnParser` class provides a static method `generateConstantsForBpmnFiles()`.\nThis method takes a filepath and returns TypeScript definitions that you can use to avoid typos in your code, and to reason about the completeness of your task worker coverage.\n\n```javascript\nconst ZB = require('zeebe-node')\n;(async () =\u003e {\n\tconsole.log(await ZB.BpmnParser.generateConstantsForBpmnFiles(processFile))\n})()\n```\n\nThis will produce output similar to:\n\n```typescript\n// Autogenerated constants for msg-start.bpmn\n\nexport enum TaskType = {\n    CONSOLE_LOG = \"console-log\"\n};\n\nexport enum MessageName = {\n    MSG_EMIT_FRAME = \"MSG-EMIT_FRAME\",\n    MSG_START_JOB = \"MSG-START_JOB\"\n};\n```\n\n\u003ca name = \"generate-code\"\u003e\u003c/a\u003e\n\n## Generating code from a BPM Model file\n\nYou can scaffold your worker code from a BPMN file with the `zeebe-node` command. To use this command, install the package globally with:\n\n```bash\nnpm i -g zeebe-node\n```\n\nPass in the path to the BPMN file, and it will output a file to implement it:\n\n```bash\nzeebe-node my-model.bpmn\n```\n\n\u003ca name = \"strongly-typed\"\u003e\u003c/a\u003e\n\n### Writing Strongly-typed Job Workers\n\nYou can provide interfaces to get design-time type safety and intellisense on the process variables passed in the a worker job handler, the custom headers that it will receive, and the variables that it will pass back to Zeebe in the `complete.success` call:\n\n```TypeScript\ninterface InputVariables {\n    name: string,\n    age: number,\n    preferences: {\n        beverage: 'Coffee' | 'Tea' | 'Beer' | 'Water',\n        color: string\n    }\n}\n\ninterface OutputVariables {\n    suggestedGift: string\n}\n\ninterface CustomHeaders {\n    occasion: 'Birthday' | 'Christmas' | 'Hannukah' | 'Diwali'\n}\n\nconst giftSuggester = zbc.createWorker\u003c\n    InputVariables,\n    CustomHeaders,\n    OutputVariables\u003e\n    ('get-gift-suggestion', (job) =\u003e {\n        const suggestedGift = `${job.customHeaders.occasion} ${job.variables.preferences.beverage}`\n        job.complete({ suggestedGift })\n})\n```\n\nIf you decouple the declaration of the job handler from the `createWorker` call, you will need to explicitly specify its type, like this:\n\n```TypeScript\nimport { ZBWorkerTaskHandler } from 'zeebe-node'\n\nfunction getGiftSuggestion(job): ZBWorkerTaskHandler\u003cInputVariables, CustomHeaders, OutputVariables\u003e {\n    const suggestedGift = `${job.customHeaders.occasion} ${job.variables.preferences.beverage}`\n    job.complete({ suggestedGift })\n}\n\nconst giftSuggester = zbc.createWorker({\n    taskType: 'get-gift-suggestion',\n    taskHandler: getGiftSuggestion\n})\n```\n\n\u003ca name = \"run-time-safety\"\u003e\u003c/a\u003e\n\n## Run-time Type Safety\n\nThe parameterization of the client and workers helps to catch errors in code, and if your interface definitions are good, can go a long way to making sure that your workers and client emit the correct payloads and have a strong expectation about what they will receive, but it does not give you any _run-time safety_.\n\nYour type definition may be incorrect, or the variables or custom headers may simply not be there at run-time, as there is no type checking in the broker, and other factors are involved, such as tasks with input and output mappings, and data added to the process variables by REST calls and other workers.\n\nYou should consider:\n\n-   Writing interface definitions for your payloads to get design-time assist for protection against spelling errors as you demarshal and update variables.\n-   Testing for the existence of variables and properties on payloads, and writing defensive pathways to deal with missing properties. If you mark _everything_ as optional in your interfaces, the type-checker will force you to write that code.\n-   Surfacing code exceptions operationally to detect and diagnose mismatched expectations.\n-   If you want to validate inputs and outputs to your system at runtime, you can use [io-ts](https://github.com/gcanti/io-ts). Once data goes into that, it either exits through an exception handler, or is guaranteed to have the shape of the defined codec at run-time.\n\nAs with everything, it is a balancing act / trade-off between correctness, safety, and speed. You do not want to lock everything down while you are still exploring.\n\nI recommend the following scale, to match the maturity of your system:\n\n-   Start with `\u003cany\u003e` typing for the workers; then\n-   Develop interfaces to describe the DTOs represented in your process variables;\n-   Use optional types on those interfaces to check your defensive programming structures;\n-   Lock down the run-time behaviour with io-ts as the boundary validator.\n\nYou may choose to start with the DTOs. Anyway, there are options.\n\n\u003ca name = \"developing\"\u003e\u003c/a\u003e\n\n## Developing Zeebe Node\n\nThe source is written in TypeScript in `src`, and compiled to ES6 in the `dist` directory.\n\nTo build:\n\n```bash\nnpm run build\n```\n\nTo start a watcher to build the source and API docs while you are developing:\n\n```bash\nnpm run dev\n```\n\n\u003ca name = \"tests\"\u003e\u003c/a\u003e\n\n### Tests\n\nTests are written in Jest, and live in the `src/__tests__` directory. To run the unit tests:\n\n```bash\nnpm t\n```\n\nIntegration tests are in the `src/__tests__/integration` directory.\n\nThey require a Zeebe broker to run. You can start a dockerised broker:\n\n```bash\ncd docker\ndocker-compose up\n```\n\nAnd then run them manually:\n\n```bash\nnpm run test:integration\n```\n\nFor the failure test, you need to run Operate and manually verify that an incident has been raised.\n\n\u003ca name = \"writing-tests\"\u003e\u003c/a\u003e\n\n### Writing Tests\n\nZeebe is inherently stateful, so integration tests need to be carefully isolated so that workers from one test do not service tasks in another test. Jest runs tests in a random order, so intermittent failures are the outcome of tests that mutate shared state.\n\nThe tests use a templating function to replace the process id, task types and message names in the bpmn model to produce distinct, isolated namespaces for each test and each test run.\n\n\u003ca name = \"contributors\"\u003e\u003c/a\u003e\n\n## Contributors\n\n| Name                                                         |\n| ------------------------------------------------------------ |\n| **[Josh Wulf](https://github.com/jwulf)**                    |\n| **[Colin Raddatz](https://github.com/ColRad)**               |\n| **[Jarred Filmer](https://github.com/BrighTide)**            |\n| **[Timothy Colbert](https://github.com/s3than)**             |\n| **[Olivier Albertini](https://github.com/OlivierAlbertini)** |\n| **[Patrick Dehn](https://github.com/pedesen)**               |\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcamunda-community-hub%2Fzeebe-client-node-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcamunda-community-hub%2Fzeebe-client-node-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcamunda-community-hub%2Fzeebe-client-node-js/lists"}