{"_id":"@besoft-kg/wa-gateway","_rev":"7-25f4388376303c360af7b26707b97796","name":"@besoft-kg/wa-gateway","dist-tags":{"latest":"0.5.0"},"versions":{"0.1.0":{"name":"@besoft-kg/wa-gateway","version":"0.1.0","author":{"name":"Bekbolot Tazhibaev","email":"tabekg@gmail.com"},"license":"MIT","_id":"@besoft-kg/wa-gateway@0.1.0","maintainers":[{"name":"tabekg","email":"tabekg@gmail.com"}],"dist":{"shasum":"2c13d61b9f8529130c47d46c5312e5d4e528199d","tarball":"https://registry.npmjs.org/@besoft-kg/wa-gateway/-/wa-gateway-0.1.0.tgz","fileCount":78,"integrity":"sha512-R/6cHoRd3wCLQp6iboMQPQRSaZZO72U2PW0J4chfgMxhS5eaDjFiraBSK912wXqqvFTSAdl2sgxQFEPKpQJvSg==","signatures":[{"sig":"MEUCIQDMkVkmGppqW92iMg4o6NC58aeUVbyucUvIZdWM3rYB8AIgax5fQiwpT2uM9Q42OTBtOYgYbjoDhu/F5JsJUtnU4AQ=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":185627},"main":"dist/index.js","type":"module","types":"dist/index.d.ts","gitHead":"8412a7048a40729c25e34aa311b75e20c8ab6532","scripts":{"dev":"tsx watch src/index.ts","build":"tsc","start":"node dist/index.js"},"_npmUser":{"name":"tabekg","email":"tabekg@gmail.com"},"_npmVersion":"10.9.2","description":"Universal WhatsApp Gateway — multi-instance manager with pluggable drivers","directories":{},"_nodeVersion":"22.17.0","dependencies":{"pino":"^10.1.0","baileys":"^7.0.0-rc.9","express":"^5.1.0","qrcode-terminal":"^0.12.0"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.21.0","@types/ws":"^8.18.1","typescript":"^5.8.3","@types/node":"^22.0.0","@types/express":"^5.0.1"},"peerDependencies":{"ws":"^8.0.0","ioredis":"^5.0.0"},"peerDependenciesMeta":{"ws":{"optional":true},"ioredis":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/wa-gateway_0.1.0_1774776627164_0.639768646770853","host":"s3://npm-registry-packages-npm-production"}},"0.1.1":{"name":"@besoft-kg/wa-gateway","version":"0.1.1","author":{"name":"Bekbolot Tazhibaev","email":"tabekg@gmail.com"},"license":"MIT","_id":"@besoft-kg/wa-gateway@0.1.1","maintainers":[{"name":"tabekg","email":"tabekg@gmail.com"}],"dist":{"shasum":"3416c609ab93f8440d0fb441ad71ea541248c392","tarball":"https://registry.npmjs.org/@besoft-kg/wa-gateway/-/wa-gateway-0.1.1.tgz","fileCount":78,"integrity":"sha512-/3zsnljMK+vgGKszfJgzbRPkqAwBu9DKgqo/8QOjMGkL5jS9cKB5HTczUduW79AFjfOs1FD7vL/J5eL2Mg8Qcw==","signatures":[{"sig":"MEUCIQDzkFgOIYfLZHBlOePlQ3fzWrqwjh1hwyxixzo73OnFIgIgOPNhM+HuLsGDfIHzYLgvrYzNwdEG36CslOAMiP3kcZQ=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":190923},"main":"dist/index.js","type":"module","types":"dist/index.d.ts","gitHead":"f6c431eab4165ecc78f257e8291cfe90fd589b9b","scripts":{"dev":"tsx watch src/index.ts","build":"tsc","start":"node dist/index.js"},"_npmUser":{"name":"tabekg","email":"tabekg@gmail.com"},"_npmVersion":"10.9.2","description":"Universal WhatsApp Gateway — multi-instance manager with pluggable drivers","directories":{},"_nodeVersion":"22.17.0","dependencies":{"pino":"^10.1.0","baileys":"^7.0.0-rc.9","express":"^5.1.0","qrcode-terminal":"^0.12.0"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.21.0","@types/ws":"^8.18.1","typescript":"^5.8.3","@types/node":"^22.0.0","@types/express":"^5.0.1"},"peerDependencies":{"ws":"^8.0.0","ioredis":"^5.0.0"},"peerDependenciesMeta":{"ws":{"optional":true},"ioredis":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/wa-gateway_0.1.1_1774778109101_0.7472374851298731","host":"s3://npm-registry-packages-npm-production"}},"0.1.2":{"name":"@besoft-kg/wa-gateway","version":"0.1.2","author":{"name":"Bekbolot Tazhibaev","email":"tabekg@gmail.com"},"license":"MIT","_id":"@besoft-kg/wa-gateway@0.1.2","maintainers":[{"name":"tabekg","email":"tabekg@gmail.com"}],"dist":{"shasum":"fa8f55426b6466c820d2d855410f7ab945084289","tarball":"https://registry.npmjs.org/@besoft-kg/wa-gateway/-/wa-gateway-0.1.2.tgz","fileCount":78,"integrity":"sha512-4V0kf6IFGADyrvwkyAMywX1iJA1OfUAABDjOIZUF9aG9nDSNd0ym4FX7d9OfWpK3nRstdqztVk32+OaHiZyB2A==","signatures":[{"sig":"MEUCIQDd23S3u+mfbMeNvj6g8WBxkqKf2kxQGIAIOst+5T/K6wIgemFNjzopDEYeUJxgFqSvI0tSa8IcaazT43LHqGvokyE=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":191798},"main":"dist/index.js","type":"module","types":"dist/index.d.ts","gitHead":"bb17b2b2fa910df344a21ed6bd301a9aa0d64ec6","scripts":{"dev":"tsx watch src/index.ts","build":"tsc","start":"node dist/index.js"},"_npmUser":{"name":"tabekg","email":"tabekg@gmail.com"},"_npmVersion":"10.9.2","description":"Universal WhatsApp Gateway — multi-instance manager with pluggable drivers","directories":{},"_nodeVersion":"22.17.0","dependencies":{"pino":"^10.1.0","baileys":"^7.0.0-rc.9","express":"^5.1.0","qrcode-terminal":"^0.12.0"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.21.0","@types/ws":"^8.18.1","typescript":"^5.8.3","@types/node":"^22.0.0","@types/express":"^5.0.1"},"peerDependencies":{"ws":"^8.0.0","ioredis":"^5.0.0"},"peerDependenciesMeta":{"ws":{"optional":true},"ioredis":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/wa-gateway_0.1.2_1774883267706_0.42054497637953414","host":"s3://npm-registry-packages-npm-production"}},"0.2.0":{"name":"@besoft-kg/wa-gateway","version":"0.2.0","author":{"name":"Bekbolot Tazhibaev","email":"tabekg@gmail.com"},"license":"MIT","_id":"@besoft-kg/wa-gateway@0.2.0","maintainers":[{"name":"tabekg","email":"tabekg@gmail.com"}],"dist":{"shasum":"ab7701cdd73144836337bfa4280e3866164489e6","tarball":"https://registry.npmjs.org/@besoft-kg/wa-gateway/-/wa-gateway-0.2.0.tgz","fileCount":78,"integrity":"sha512-KnY+OOHzYopMObfQnhKIZEhnCJ7WpuWO80FGOpN3PdhIHICql0ZHqR/yYQIVdP9BZK4cydCvFsCS8aiIKBjFWw==","signatures":[{"sig":"MEQCIDRqamdQxuA0HNe66MpsIGuAWOrxpRKVx09HrZ34aeOXAiAi+X6h9AaHCqf42MsqAOVfyWoEGsc0HJ6c0BbW+KGrIQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":195404},"main":"dist/index.js","type":"module","types":"dist/index.d.ts","gitHead":"20d1107e54a39db000cc3f159e6b893de9fd6199","scripts":{"dev":"tsx watch src/index.ts","build":"tsc","start":"node dist/index.js"},"_npmUser":{"name":"tabekg","email":"tabekg@gmail.com"},"_npmVersion":"10.9.2","description":"Universal WhatsApp Gateway — multi-instance manager with pluggable drivers","directories":{},"_nodeVersion":"22.17.0","dependencies":{"pino":"^10.1.0","baileys":"^7.0.0-rc.9","express":"^5.1.0","qrcode-terminal":"^0.12.0"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.21.0","@types/ws":"^8.18.1","typescript":"^5.8.3","@types/node":"^22.0.0","@types/express":"^5.0.1"},"peerDependencies":{"ws":"^8.0.0","ioredis":"^5.0.0"},"peerDependenciesMeta":{"ws":{"optional":true},"ioredis":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/wa-gateway_0.2.0_1777868228900_0.7514365611762246","host":"s3://npm-registry-packages-npm-production"}},"0.3.0":{"name":"@besoft-kg/wa-gateway","version":"0.3.0","author":{"name":"Bekbolot Tazhibaev","email":"tabekg@gmail.com"},"license":"MIT","_id":"@besoft-kg/wa-gateway@0.3.0","maintainers":[{"name":"tabekg","email":"tabekg@gmail.com"}],"dist":{"shasum":"eda1960642d7ea964607d2db26a31d397608dcbe","tarball":"https://registry.npmjs.org/@besoft-kg/wa-gateway/-/wa-gateway-0.3.0.tgz","fileCount":74,"integrity":"sha512-Br5MRyiltzq9BzGpIMV8agsZxjcyOrFMgs5y5lLGrVEAOkr6953FhWZoxDTXKKU76sOGWgzWBdvVasi5juzQpQ==","signatures":[{"sig":"MEUCIAfvNT4DAdaBUpbLVc5J2e5feMTt5g33nYFlIsrMYkz+AiEA6+rjmk9FjlBTaRU2W45X4SaEWQg+LWT5jk1wiUHAq3U=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":163985},"main":"dist/index.js","type":"module","types":"dist/index.d.ts","gitHead":"20d1107e54a39db000cc3f159e6b893de9fd6199","scripts":{"dev":"tsx watch src/index.ts","build":"tsc","start":"node dist/index.js"},"_npmUser":{"name":"tabekg","email":"tabekg@gmail.com"},"_npmVersion":"10.9.7","description":"Universal WhatsApp Gateway — multi-instance manager with pluggable drivers","directories":{},"_nodeVersion":"22.22.2","dependencies":{"pino":"^10.1.0","baileys":"^7.0.0-rc.9","express":"^5.1.0","qrcode-terminal":"^0.12.0"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.21.0","@types/ws":"^8.18.1","typescript":"^5.8.3","@types/node":"^22.0.0","@types/express":"^5.0.1"},"peerDependencies":{"ws":"^8.0.0","ioredis":"^5.0.0"},"peerDependenciesMeta":{"ws":{"optional":true},"ioredis":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/wa-gateway_0.3.0_1780230714821_0.5873792576204706","host":"s3://npm-registry-packages-npm-production"}},"0.4.0":{"name":"@besoft-kg/wa-gateway","version":"0.4.0","author":{"name":"Bekbolot Tazhibaev","email":"tabekg@gmail.com"},"license":"MIT","_id":"@besoft-kg/wa-gateway@0.4.0","maintainers":[{"name":"tabekg","email":"tabekg@gmail.com"}],"dist":{"shasum":"39866c20964aa3ab57e1ed77b7654479e0119d33","tarball":"https://registry.npmjs.org/@besoft-kg/wa-gateway/-/wa-gateway-0.4.0.tgz","fileCount":74,"integrity":"sha512-1zHTWcixQBNAjvuB9PumiNx5iGWkTF1QlAQJ5dv04wH4vhi6EQU6r8ZPvMJehP27vWwq2I+WRdHNNZn7uo8HkA==","signatures":[{"sig":"MEYCIQCGGk0EiDKtAD2PJ0RoWiQUjpTZZJD9FtdNYt2w5l/ucQIhAMmlSgPhUg2Q9sB/6n2uBVtwAMZGvYg9XY/jKGfgrT2+","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":170830},"main":"dist/index.js","type":"module","types":"dist/index.d.ts","gitHead":"4a9221d657709a907719e5a8fea7e5b316fa7e96","scripts":{"dev":"tsx watch src/index.ts","build":"tsc","start":"node dist/index.js"},"_npmUser":{"name":"tabekg","email":"tabekg@gmail.com"},"_npmVersion":"10.9.7","description":"Universal WhatsApp Gateway — multi-instance manager with pluggable drivers","directories":{},"_nodeVersion":"22.22.2","dependencies":{"pino":"^10.1.0","baileys":"^7.0.0-rc.9","express":"^5.1.0","qrcode-terminal":"^0.12.0"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.21.0","@types/ws":"^8.18.1","typescript":"^5.8.3","@types/node":"^22.0.0","@types/express":"^5.0.1"},"peerDependencies":{"ws":"^8.0.0","ioredis":"^5.0.0"},"peerDependenciesMeta":{"ws":{"optional":true},"ioredis":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/wa-gateway_0.4.0_1781857114930_0.02164444072577254","host":"s3://npm-registry-packages-npm-production"}},"0.5.0":{"name":"@besoft-kg/wa-gateway","version":"0.5.0","description":"Universal WhatsApp Gateway — multi-instance manager with pluggable drivers","main":"dist/index.js","types":"dist/index.d.ts","type":"module","scripts":{"dev":"tsx watch src/index.ts","build":"tsc","start":"node dist/index.js"},"author":{"name":"Bekbolot Tazhibaev","email":"tabekg@gmail.com"},"license":"MIT","dependencies":{"baileys":"7.0.0-rc13","express":"^5.1.0","pino":"^10.1.0","qrcode-terminal":"^0.12.0"},"devDependencies":{"@types/express":"^5.0.1","@types/node":"^22.0.0","@types/ws":"^8.18.1","tsx":"^4.21.0","typescript":"^5.8.3"},"peerDependencies":{"ioredis":"^5.0.0","ws":"^8.0.0"},"peerDependenciesMeta":{"ioredis":{"optional":true},"ws":{"optional":true}},"_id":"@besoft-kg/wa-gateway@0.5.0","gitHead":"a58a307a03f5cebf84b8e0e56f876484aeea7d6f","_nodeVersion":"22.22.2","_npmVersion":"10.9.7","dist":{"integrity":"sha512-Ol/toluFyDwVNH6/v9HsJeMQRiXk6DjjK8NqRsYjMbln5asGB2RL//hXTaP1mKEbe2ugiO9AbSuS4nKGWnbH7Q==","shasum":"61991822d8a6bf5f89446780a8ce3b87c227c2ed","tarball":"https://registry.npmjs.org/@besoft-kg/wa-gateway/-/wa-gateway-0.5.0.tgz","fileCount":74,"unpackedSize":171697,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIAO3tzpm8pQeV0WNYrmwqvjklWOUE8a6zLHXOT8Oo73hAiEAn0GYAMP+CeHRvJS6jwPH5d1a3xh9fk4WuIL5pRp2xos="}]},"_npmUser":{"name":"tabekg","email":"tabekg@gmail.com"},"directories":{},"maintainers":[{"name":"tabekg","email":"tabekg@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/wa-gateway_0.5.0_1784006346563_0.7641757746984967"},"_hasShrinkwrap":false}},"time":{"created":"2026-03-29T09:30:27.074Z","modified":"2026-07-14T05:19:06.854Z","0.1.0":"2026-03-29T09:30:27.343Z","0.1.1":"2026-03-29T09:55:09.264Z","0.1.2":"2026-03-30T15:07:47.931Z","0.2.0":"2026-05-04T04:17:09.060Z","0.3.0":"2026-05-31T12:31:54.946Z","0.4.0":"2026-06-19T08:18:35.098Z","0.5.0":"2026-07-14T05:19:06.736Z"},"author":{"name":"Bekbolot Tazhibaev","email":"tabekg@gmail.com"},"license":"MIT","description":"Universal WhatsApp Gateway — multi-instance manager with pluggable drivers","maintainers":[{"name":"tabekg","email":"tabekg@gmail.com"}],"readme":"# WA Gateway\n\nUniversal WhatsApp Gateway — multi-instance manager with pluggable drivers for commands, events, and session storage.\n\n## Features\n\n- **Multi-instance** — manage multiple WhatsApp connections in a single process\n- **Pluggable command drivers** — receive commands via HTTP, Redis, or custom driver\n- **Pluggable event drivers** — emit events via webhook, Redis pub/sub, WebSocket, or custom driver\n- **Pluggable session store** — store sessions on filesystem or implement your own\n- **Programmatic API** — use as a library with `.on()` listeners\n- **Auto-reconnect** — automatic reconnection with exponential backoff\n- **Ban detection** — detects account bans and emits events\n- **Health monitoring** — track instance status in real-time\n- **TypeScript** — full type safety\n\n## Installation\n\n```bash\nnpm install @besoft/wa-gateway\n```\n\nOptional peer dependencies (install only what you need):\n\n```bash\n# For Redis drivers\nnpm install ioredis\n\n# For WebSocket event driver\nnpm install ws\n```\n\n## Quick Start\n\n### As a library\n\n```ts\nimport { createGateway } from '@besoft/wa-gateway'\n\nconst gw = createGateway({ printQr: true })\n\ngw.on('instance.qr', (data) => {\n  console.log('Scan QR code for instance:', data.instanceId)\n})\n\ngw.on('instance.connected', (data) => {\n  console.log('Connected!', data.instanceId, data.phone)\n})\n\ngw.on('message.received', (data) => {\n  console.log(`[${data.instanceId}] ${data.from}: ${data.text}`)\n})\n\nawait gw.start()\nawait gw.createInstance('my-whatsapp')\n```\n\n### As a standalone HTTP service\n\n```ts\nimport { createGateway } from '@besoft/wa-gateway'\n\nconst gw = createGateway({\n  commands: [\n    { driver: 'http', port: 3100, apiKey: 'my-secret-key' },\n  ],\n  events: [\n    { driver: 'webhook', url: 'https://myapp.com/wa-events' },\n  ],\n})\n\nawait gw.start()\n// Gateway is now accepting HTTP commands on port 3100\n// Events will be POSTed to https://myapp.com/wa-events\n```\n\n### With Redis (for microservice architecture)\n\n```ts\nimport { createGateway } from '@besoft/wa-gateway'\n\nconst gw = createGateway({\n  commands: [\n    { driver: 'redis', queue: 'wa:commands', host: 'localhost' },\n  ],\n  events: [\n    { driver: 'redis', channel: 'wa:events', host: 'localhost' },\n  ],\n})\n\nawait gw.start()\n```\n\n### Full configuration\n\n```ts\nimport { createGateway } from '@besoft/wa-gateway'\n\nconst gw = createGateway({\n  // Where to receive commands from\n  commands: [\n    { driver: 'http', port: 3100, apiKey: 'secret' },\n    { driver: 'redis', queue: 'wa:commands', host: 'localhost', port: 6379 },\n  ],\n\n  // Where to send events to\n  events: [\n    { driver: 'webhook', url: 'https://myapp.com/hook', events: ['message.received', 'instance.connected'] },\n    { driver: 'redis', channel: 'wa:events', host: 'localhost' },\n    { driver: 'websocket', port: 3101 },\n  ],\n\n  // Session storage\n  store: { driver: 'file', path: './sessions' },\n\n  // Instance defaults\n  autoReconnect: true,\n  maxReconnectRetries: 5,\n  healthCheckInterval: 30000,\n  printQr: true,\n  logLevel: 'info',\n})\n\nawait gw.start()\n```\n\n## Configuration\n\n### `GatewayConfig`\n\n| Option | Type | Default | Description |\n|---|---|---|---|\n| `commands` | `CommandDriverConfig[]` | `[]` | Command driver configurations |\n| `events` | `EventDriverConfig[]` | `[]` | Event driver configurations |\n| `store` | `StoreConfig` | `{ driver: 'file', path: './sessions' }` | Session store configuration |\n| `autoReconnect` | `boolean` | `true` | Auto-reconnect on disconnect |\n| `maxReconnectRetries` | `number` | `5` | Max reconnect attempts before giving up |\n| `healthCheckInterval` | `number` | `30000` | Health check interval in ms |\n| `printQr` | `boolean` | `true` | Print QR code in terminal |\n| `logLevel` | `string` | `'info'` | Log level: `silent`, `info`, `debug`, `warn`, `error` |\n\n## Programmatic API\n\n### Gateway methods\n\n```ts\nconst gw = createGateway(config)\n\n// Lifecycle\nawait gw.start()\nawait gw.stop()\n\n// Instance management\nawait gw.createInstance('instance-id')\nawait gw.deleteInstance('instance-id')\nawait gw.restartInstance('instance-id')\nawait gw.logoutInstance('instance-id') // Deletes auth state, regenerates QR\nconst instances = gw.listInstances()\n\n// Instance info\nconst status = gw.getStatus('instance-id')\nconst qr = gw.getQr('instance-id')\n\n// Messaging\nawait gw.sendMessage('instance-id', '996555123456', 'text', 'Hello!')\nawait gw.sendMessage('instance-id', '996555123456', 'image', 'https://example.com/photo.jpg', {\n  caption: 'Check this out',\n})\nawait gw.sendMessage('instance-id', '996555123456', 'document', '/path/to/file.pdf', {\n  filename: 'report.pdf',\n  caption: 'Monthly report',\n})\n\n// Number validation\nconst result = await gw.checkNumber('instance-id', '996555123456')\n// { exists: true, jid: '996555123456@s.whatsapp.net' }\n\n// Event listeners\ngw.on('message.received', (data) => { ... })\ngw.off('message.received', handler)\n```\n\n### Send message types\n\n```ts\n// Text\nawait gw.sendMessage(instanceId, to, 'text', 'Hello world')\n\n// Image (URL or file path)\nawait gw.sendMessage(instanceId, to, 'image', 'https://example.com/photo.jpg', {\n  caption: 'Optional caption',\n})\n\n// Video\nawait gw.sendMessage(instanceId, to, 'video', 'https://example.com/video.mp4', {\n  caption: 'Optional caption',\n})\n\n// Audio\nawait gw.sendMessage(instanceId, to, 'audio', 'https://example.com/audio.mp3')\n\n// Document\nawait gw.sendMessage(instanceId, to, 'document', '/path/to/file.pdf', {\n  filename: 'report.pdf',\n  caption: 'Optional caption',\n})\n```\n\n### Instance status\n\n```ts\nconst info = gw.getStatus('instance-id')\n// {\n//   id: 'instance-id',\n//   status: 'connected',     // 'starting' | 'qr_pending' | 'connected' | 'disconnected' | 'banned' | 'destroyed'\n//   phone: '996555123456',\n//   createdAt: Date,\n//   lastConnectedAt: Date\n// }\n```\n\n## Command Drivers\n\nCommand drivers define how the gateway receives instructions (create instance, send message, etc.).\n\n### HTTP Command Driver\n\nExposes a REST API for managing instances and sending messages.\n\n```ts\n{\n  driver: 'http',\n  port: 3100,         // Required\n  apiKey: 'secret',   // Optional, enables X-API-Key header auth\n  host: '0.0.0.0',   // Optional, default: '0.0.0.0'\n}\n```\n\n#### HTTP API Endpoints\n\nAll endpoints require `X-API-Key` header if `apiKey` is configured.\n\n**Instance management:**\n\n```bash\n# Create instance\ncurl -X POST http://localhost:3100/instances \\\n  -H \"Content-Type: application/json\" \\\n  -H \"X-API-Key: secret\" \\\n  -d '{\"id\": \"my-instance\"}'\n\n# List all instances\ncurl http://localhost:3100/instances \\\n  -H \"X-API-Key: secret\"\n\n# Get instance status\ncurl http://localhost:3100/instances/my-instance/status \\\n  -H \"X-API-Key: secret\"\n\n# Get QR code\ncurl http://localhost:3100/instances/my-instance/qr \\\n  -H \"X-API-Key: secret\"\n\n# Restart instance\ncurl -X POST http://localhost:3100/instances/my-instance/restart \\\n  -H \"X-API-Key: secret\"\n\n# Logout instance (deletes auth state and regenerates QR)\ncurl -X POST http://localhost:3100/instances/my-instance/logout \\\n  -H \"X-API-Key: secret\"\n\n# Delete instance\ncurl -X DELETE http://localhost:3100/instances/my-instance \\\n  -H \"X-API-Key: secret\"\n```\n\n**Messaging:**\n\n```bash\n# Send text message\ncurl -X POST http://localhost:3100/instances/my-instance/send \\\n  -H \"Content-Type: application/json\" \\\n  -H \"X-API-Key: secret\" \\\n  -d '{\"to\": \"996555123456\", \"type\": \"text\", \"content\": \"Hello!\"}'\n\n# Send image\ncurl -X POST http://localhost:3100/instances/my-instance/send \\\n  -H \"Content-Type: application/json\" \\\n  -H \"X-API-Key: secret\" \\\n  -d '{\"to\": \"996555123456\", \"type\": \"image\", \"content\": \"https://example.com/photo.jpg\", \"caption\": \"Look!\"}'\n\n# Check if number is on WhatsApp\ncurl \"http://localhost:3100/instances/my-instance/check-number?phone=996555123456\" \\\n  -H \"X-API-Key: secret\"\n```\n\n**Response format:**\n\n```json\n{\n  \"success\": true,\n  \"data\": { ... }\n}\n\n{\n  \"success\": false,\n  \"error\": \"Error message\"\n}\n```\n\n### Redis Command Driver\n\nReceives commands from a Redis pub/sub channel. Useful for microservice architectures.\n\n```ts\n{\n  driver: 'redis',\n  queue: 'wa:commands',          // Optional, default: 'wa:commands'\n  responseChannel: 'wa:responses', // Optional, default: 'wa:responses'\n  host: 'localhost',             // Optional, default: 'localhost'\n  port: 6379,                    // Optional, default: 6379\n  password: '',                  // Optional\n}\n```\n\n#### Redis command format\n\nPublish a JSON message to the `wa:commands` channel:\n\n```json\n{\n  \"id\": \"unique-request-id\",\n  \"command\": \"send_message\",\n  \"params\": {\n    \"instanceId\": \"my-instance\",\n    \"to\": \"996555123456\",\n    \"type\": \"text\",\n    \"content\": \"Hello!\"\n  }\n}\n```\n\nResponse is published to the `wa:responses` channel:\n\n```json\n{\n  \"id\": \"unique-request-id\",\n  \"success\": true,\n  \"data\": {\n    \"messageId\": \"ABCD1234\"\n  }\n}\n```\n\n#### Available commands\n\n| Command | Params |\n|---|---|\n| `create_instance` | `{ id: string }` |\n| `delete_instance` | `{ id: string }` |\n| `restart_instance` | `{ id: string }` |\n| `logout_instance` | `{ id: string }` |\n| `list_instances` | `{}` |\n| `get_status` | `{ instanceId: string }` |\n| `get_qr` | `{ instanceId: string }` |\n| `send_message` | `{ instanceId, to, type, content, caption?, filename? }` |\n| `check_number` | `{ instanceId, phone }` |\n\n### Custom Command Driver\n\nImplement the `CommandDriver` interface:\n\n```ts\nimport type { CommandDriver, CommandHandler } from '@besoft/wa-gateway'\n\nclass MyCommandDriver implements CommandDriver {\n  name = 'my-driver'\n\n  async init(handler: CommandHandler): Promise<void> {\n    // Set up your command source (e.g., gRPC, MQTT, etc.)\n    // Call handler(command, params) when a command is received\n\n    // Example:\n    myMqttClient.on('message', async (topic, msg) => {\n      const { command, params } = JSON.parse(msg)\n      const result = await handler(command, params)\n      // Send result back via your transport\n    })\n  }\n\n  async destroy(): Promise<void> {\n    // Clean up resources\n  }\n}\n\n// Usage\nconst gw = createGateway({\n  commands: [\n    { driver: 'custom', handler: new MyCommandDriver() },\n  ],\n})\n```\n\n## Event Drivers\n\nEvent drivers define where the gateway sends events (new messages, status changes, etc.).\n\n### Webhook Event Driver\n\nSends events as HTTP POST requests with automatic retry.\n\n```ts\n{\n  driver: 'webhook',\n  url: 'https://myapp.com/wa-events',  // Required\n  events: ['message.received', 'instance.connected'],  // Optional, default: ['*'] (all events)\n  headers: { 'Authorization': 'Bearer token' },  // Optional, extra headers\n  retries: 3,        // Optional, default: 3\n  retryDelay: 1000,  // Optional, default: 1000ms (multiplied by attempt number)\n  timeout: 10000,    // Optional, default: 10000ms\n}\n```\n\n#### Webhook payload format\n\n```json\n{\n  \"event\": \"message.received\",\n  \"instanceId\": \"my-instance\",\n  \"payload\": {\n    \"messageId\": \"ABCD1234\",\n    \"from\": \"996555123456@s.whatsapp.net\",\n    \"fromMe\": false,\n    \"text\": \"Hello!\",\n    \"type\": \"text\",\n    \"timestamp\": 1234567890\n  },\n  \"timestamp\": \"2025-01-15T10:30:00.000Z\"\n}\n```\n\n### Redis Event Driver\n\nPublishes events to a Redis pub/sub channel.\n\n```ts\n{\n  driver: 'redis',\n  channel: 'wa:events',   // Optional, default: 'wa:events'\n  host: 'localhost',       // Optional, default: 'localhost'\n  port: 6379,              // Optional, default: 6379\n  password: '',            // Optional\n  events: ['*'],           // Optional, default: ['*']\n}\n```\n\n#### Subscribing to Redis events\n\n```ts\nimport Redis from 'ioredis'\n\nconst sub = new Redis()\nsub.subscribe('wa:events')\n\nsub.on('message', (channel, message) => {\n  const { event, instanceId, payload, timestamp } = JSON.parse(message)\n  console.log(`[${instanceId}] ${event}:`, payload)\n})\n```\n\n### WebSocket Event Driver\n\nStarts a WebSocket server and broadcasts events to all connected clients.\n\n```ts\n{\n  driver: 'websocket',\n  port: 3101,        // Required\n  events: ['*'],     // Optional, default: ['*']\n}\n```\n\n#### Connecting to WebSocket events\n\n```js\nconst ws = new WebSocket('ws://localhost:3101')\n\nws.onmessage = (event) => {\n  const { event: eventName, instanceId, payload } = JSON.parse(event.data)\n  console.log(`[${instanceId}] ${eventName}:`, payload)\n}\n```\n\n### Custom Event Driver\n\nImplement the `EventDriver` interface:\n\n```ts\nimport type { EventDriver } from '@besoft/wa-gateway'\n\nclass TelegramEventDriver implements EventDriver {\n  name = 'telegram'\n\n  async init(): Promise<void> {\n    // Set up Telegram bot\n  }\n\n  async emit(event: string, instanceId: string, payload: any): Promise<void> {\n    // Send event to Telegram chat\n    await telegramBot.sendMessage(chatId, `[${instanceId}] ${event}: ${JSON.stringify(payload)}`)\n  }\n\n  async destroy(): Promise<void> {\n    // Clean up\n  }\n}\n\n// Usage\nconst gw = createGateway({\n  events: [\n    { driver: 'custom', handler: new TelegramEventDriver() },\n  ],\n})\n```\n\n### Event filtering\n\nEach event driver can filter which events it receives:\n\n```ts\nevents: [\n  // This driver only gets message events\n  { driver: 'webhook', url: 'https://messages.myapp.com/hook', events: ['message.received', 'message.sent'] },\n\n  // This driver gets all instance status events\n  { driver: 'webhook', url: 'https://monitoring.myapp.com/hook', events: ['instance.connected', 'instance.disconnected', 'instance.banned'] },\n\n  // This driver gets everything\n  { driver: 'redis', channel: 'wa:all-events', events: ['*'] },\n]\n```\n\n### Available events\n\n| Event | Payload | Description |\n|---|---|---|\n| `instance.qr` | `{ instanceId, qr }` | QR code generated, scan to authenticate |\n| `instance.connected` | `{ instanceId, phone }` | Instance connected to WhatsApp |\n| `instance.disconnected` | `{ instanceId, reason, statusCode? }` | Instance disconnected |\n| `instance.banned` | `{ instanceId, reason }` | Account banned by WhatsApp |\n| `instance.auth_failure` | `{ instanceId, error }` | Authentication failed |\n| `message.received` | `{ instanceId, messageId, from, fromMe, text, type, timestamp, raw }` | New message received |\n| `message.sent` | `{ instanceId, messageId, to, type }` | Message sent successfully |\n| `message.failed` | `{ instanceId, to, type, error }` | Message sending failed |\n| `message.updated` | `{ instanceId, messageId, remoteJid, update }` | Message status updated (delivered, read) |\n\n## Session Store\n\n### File Store (default)\n\nStores Baileys auth sessions on the filesystem.\n\n```ts\n{\n  store: { driver: 'file', path: './sessions' }\n}\n```\n\nDirectory structure:\n\n```\nsessions/\n├── my-instance-1/\n│   ├── creds.json\n│   ├── app-state-sync-key-*.json\n│   └── ...\n├── my-instance-2/\n│   └── ...\n```\n\n### Custom Store\n\nImplement the `SessionStore` interface:\n\n```ts\nimport type { SessionStore } from '@besoft/wa-gateway'\n\nclass RedisSessionStore implements SessionStore {\n  name = 'redis'\n\n  async init(): Promise<void> { ... }\n  async getAuthState(instanceId: string): Promise<any> { ... }\n  async saveAuthState(instanceId: string, state: any): Promise<void> { ... }\n  async deleteSession(instanceId: string): Promise<void> { ... }\n  async listSessions(): Promise<string[]> { ... }\n  async destroy(): Promise<void> { ... }\n}\n\nconst gw = createGateway({\n  store: { driver: 'custom', handler: new RedisSessionStore() },\n})\n```\n\n## Examples\n\n### Bot that auto-replies\n\n```ts\nimport { createGateway } from '@besoft/wa-gateway'\n\nconst gw = createGateway({ printQr: true })\n\ngw.on('instance.connected', (data) => {\n  console.log(`Connected: ${data.phone}`)\n})\n\ngw.on('message.received', async (data) => {\n  if (data.fromMe) return\n\n  const text = data.text.toLowerCase()\n\n  if (text === 'ping') {\n    await gw.sendMessage(data.instanceId, data.from, 'text', 'pong!')\n  }\n\n  if (text === 'help') {\n    await gw.sendMessage(data.instanceId, data.from, 'text',\n      'Available commands:\\n- ping\\n- help\\n- status'\n    )\n  }\n})\n\nawait gw.start()\nawait gw.createInstance('bot')\n```\n\n### OTP service\n\n```ts\nimport { createGateway } from '@besoft/wa-gateway'\n\nconst gw = createGateway({\n  commands: [{ driver: 'http', port: 3100, apiKey: 'otp-service-key' }],\n})\n\nawait gw.start()\nawait gw.createInstance('otp-sender')\n\n// Now your backend can call:\n// POST http://localhost:3100/instances/otp-sender/send\n// { \"to\": \"996555123456\", \"type\": \"text\", \"content\": \"Your code: 1234\" }\n```\n\n### Multi-instance with monitoring\n\n```ts\nimport { createGateway } from '@besoft/wa-gateway'\n\nconst gw = createGateway({\n  commands: [\n    { driver: 'http', port: 3100, apiKey: 'admin-key' },\n  ],\n  events: [\n    { driver: 'webhook', url: 'https://myapp.com/wa-events', events: ['message.received'] },\n    { driver: 'webhook', url: 'https://monitoring.myapp.com/alerts', events: ['instance.banned', 'instance.disconnected'] },\n    { driver: 'websocket', port: 3101 },\n  ],\n})\n\ngw.on('instance.banned', (data) => {\n  console.error(`ALERT: Instance ${data.instanceId} was banned!`)\n})\n\nawait gw.start()\n\n// Create multiple instances\nawait gw.createInstance('company-a')\nawait gw.createInstance('company-b')\nawait gw.createInstance('company-c')\n\nconsole.log('Instances:', gw.listInstances())\n```\n\n### Using with Redis (microservice)\n\n```ts\n// wa-gateway-service.ts\nimport { createGateway } from '@besoft/wa-gateway'\n\nconst gw = createGateway({\n  commands: [\n    { driver: 'redis', queue: 'wa:commands', responseChannel: 'wa:responses' },\n  ],\n  events: [\n    { driver: 'redis', channel: 'wa:events' },\n  ],\n})\n\nawait gw.start()\n```\n\n```python\n# your-flask-api.py\nimport redis\nimport json\nimport uuid\n\nr = redis.Redis()\n\ndef send_whatsapp_message(instance_id, to, text):\n    request_id = str(uuid.uuid4())\n    r.publish('wa:commands', json.dumps({\n        'id': request_id,\n        'command': 'send_message',\n        'params': {\n            'instanceId': instance_id,\n            'to': to,\n            'type': 'text',\n            'content': text,\n        }\n    }))\n    return request_id\n\n# Listen for events\npubsub = r.pubsub()\npubsub.subscribe('wa:events')\n\nfor message in pubsub.listen():\n    if message['type'] == 'message':\n        event = json.loads(message['data'])\n        print(f\"[{event['instanceId']}] {event['event']}: {event['payload']}\")\n```\n\n## Instance Lifecycle\n\n```\ncreateInstance()\n       │\n       ▼\n   [starting]\n       │\n       ▼\n   [qr_pending] ──── QR scanned ────► [connected]\n                                            │\n                                     disconnect/error\n                                            │\n                                            ▼\n                                     [disconnected]\n                                            │\n                              auto-reconnect (exponential backoff)\n                                            │\n                                            ▼\n                                     [starting] ──► ...\n\n                                     if banned:\n                                            │\n                                            ▼\n                                       [banned]\n\n   deleteInstance() ──────────────► [destroyed]\n```\n\n## License\n\nMIT\n","readmeFilename":"README.md"}