@chatwise/node 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/LICENSE +202 -0
  3. package/README.md +506 -2
  4. package/dist/cjs/client.d.ts +20 -0
  5. package/dist/cjs/client.js +32 -0
  6. package/dist/cjs/core/errors.d.ts +91 -0
  7. package/dist/cjs/core/errors.js +131 -0
  8. package/dist/cjs/core/http.d.ts +74 -0
  9. package/dist/cjs/core/http.js +336 -0
  10. package/dist/cjs/core/pagination.d.ts +35 -0
  11. package/dist/cjs/core/pagination.js +101 -0
  12. package/dist/cjs/generated/types.d.ts +969 -0
  13. package/dist/cjs/generated/types.js +3 -0
  14. package/dist/cjs/index.d.ts +15 -0
  15. package/dist/cjs/index.js +25 -0
  16. package/dist/cjs/package.json +1 -0
  17. package/dist/cjs/resources/conversations.d.ts +20 -0
  18. package/dist/cjs/resources/conversations.js +32 -0
  19. package/dist/cjs/resources/messages.d.ts +46 -0
  20. package/dist/cjs/resources/messages.js +60 -0
  21. package/dist/cjs/resources/webhook-deliveries.d.ts +27 -0
  22. package/dist/cjs/resources/webhook-deliveries.js +42 -0
  23. package/dist/cjs/resources/webhook-endpoints.d.ts +54 -0
  24. package/dist/cjs/resources/webhook-endpoints.js +82 -0
  25. package/dist/cjs/resources/webhook-event-types.d.ts +13 -0
  26. package/dist/cjs/resources/webhook-event-types.js +22 -0
  27. package/dist/cjs/resources/whatsapp-templates.d.ts +48 -0
  28. package/dist/cjs/resources/whatsapp-templates.js +69 -0
  29. package/dist/cjs/version.d.ts +2 -0
  30. package/dist/cjs/version.js +5 -0
  31. package/dist/cjs/webhooks.d.ts +74 -0
  32. package/dist/cjs/webhooks.js +123 -0
  33. package/dist/esm/client.d.ts +20 -0
  34. package/dist/esm/client.js +28 -0
  35. package/dist/esm/core/errors.d.ts +91 -0
  36. package/dist/esm/core/errors.js +113 -0
  37. package/dist/esm/core/http.d.ts +74 -0
  38. package/dist/esm/core/http.js +332 -0
  39. package/dist/esm/core/pagination.d.ts +35 -0
  40. package/dist/esm/core/pagination.js +95 -0
  41. package/dist/esm/generated/types.d.ts +969 -0
  42. package/dist/esm/generated/types.js +2 -0
  43. package/dist/esm/index.d.ts +15 -0
  44. package/dist/esm/index.js +4 -0
  45. package/dist/esm/package.json +1 -0
  46. package/dist/esm/resources/conversations.d.ts +20 -0
  47. package/dist/esm/resources/conversations.js +28 -0
  48. package/dist/esm/resources/messages.d.ts +46 -0
  49. package/dist/esm/resources/messages.js +56 -0
  50. package/dist/esm/resources/webhook-deliveries.d.ts +27 -0
  51. package/dist/esm/resources/webhook-deliveries.js +38 -0
  52. package/dist/esm/resources/webhook-endpoints.d.ts +54 -0
  53. package/dist/esm/resources/webhook-endpoints.js +78 -0
  54. package/dist/esm/resources/webhook-event-types.d.ts +13 -0
  55. package/dist/esm/resources/webhook-event-types.js +18 -0
  56. package/dist/esm/resources/whatsapp-templates.d.ts +48 -0
  57. package/dist/esm/resources/whatsapp-templates.js +65 -0
  58. package/dist/esm/version.d.ts +2 -0
  59. package/dist/esm/version.js +2 -0
  60. package/dist/esm/webhooks.d.ts +74 -0
  61. package/dist/esm/webhooks.js +118 -0
  62. package/package.json +79 -4
package/README.md CHANGED
@@ -1,3 +1,507 @@
1
- # Temporary Holding Version
1
+ # Chatwise for Node.js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official Node.js SDK for the [Chatwise API](https://chatwise.so/docs): read your WhatsApp, Instagram, Messenger and Website Chat inbox, send WhatsApp templates, and receive signed webhooks.
4
+
5
+ - **Small.** No dependencies, and ES modules and CommonJS with types for both.
6
+ - **Typed.** Requests, responses and webhook events, generated from the API's own specification.
7
+ - **Careful.** It retries only what is safe to repeat, so a retry never sends a message twice.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @chatwise/node
13
+ ```
14
+
15
+ It needs Node.js 20 or later. Use it on a server only: anyone who has your API key can use it.
16
+
17
+ ## Quick start
18
+
19
+ Create an API key in the dashboard under **Settings → Developer → API Keys**, with the **Read conversations** permission, and set it as `CHATWISE_API_KEY`.
20
+
21
+ ```ts
22
+ import { Chatwise } from '@chatwise/node';
23
+
24
+ const chatwise = new Chatwise(); // Reads CHATWISE_API_KEY.
25
+
26
+ const { data: conversations } = await chatwise.conversations.list({ status: 'open', limit: 5 });
27
+
28
+ for (const { id, channel, participant } of conversations) {
29
+ console.log(id, channel, participant.name);
30
+ }
31
+ ```
32
+
33
+ ## Read the inbox
34
+
35
+ A list can be iterated over, and reads its pages as it goes:
36
+
37
+ ```ts
38
+ import { Chatwise } from '@chatwise/node';
39
+
40
+ const chatwise = new Chatwise();
41
+
42
+ for await (const message of chatwise.messages.list({ channel: 'WHATSAPP', q: 'refund' })) {
43
+ console.log(message.sentAt, message.direction, message.text);
44
+ }
45
+ ```
46
+
47
+ Or read page by page. Keep `nextCursor` to go on later, with the same filters:
48
+
49
+ ```ts
50
+ import { Chatwise } from '@chatwise/node';
51
+
52
+ const chatwise = new Chatwise();
53
+
54
+ let page = await chatwise.conversations.list({ channel: 'INSTAGRAM', limit: 100 });
55
+ console.log(page.data.length, page.nextCursor);
56
+
57
+ while (page.hasNextPage()) {
58
+ page = (await page.getNextPage())!;
59
+ console.log(page.data.length);
60
+ }
61
+ ```
62
+
63
+ One conversation, its messages of a day, and one message:
64
+
65
+ ```ts
66
+ import { Chatwise } from '@chatwise/node';
67
+
68
+ const chatwise = new Chatwise();
69
+
70
+ const conversation = await chatwise.conversations.get('1234');
71
+
72
+ const messages = chatwise.messages.listInConversation(conversation.id, {
73
+ from: new Date('2026-11-12T00:00:00Z'),
74
+ to: new Date('2026-11-13T00:00:00Z'),
75
+ order: 'asc',
76
+ });
77
+ for await (const message of messages) console.log(message.text);
78
+
79
+ const message = await chatwise.messages.get('1234', '5678');
80
+ console.log(message.attachments);
81
+ ```
82
+
83
+ Ids are strings. They can be larger than a JavaScript number can hold, so don't convert them.
84
+
85
+ To copy new messages on a schedule, see [examples/copy-messages.ts](https://github.com/vectorscalelabs/chatwise-node/blob/main/examples/copy-messages.ts). To get them as they arrive, use [webhooks](#receive-webhooks).
86
+
87
+ ## Send a WhatsApp template
88
+
89
+ By its name:
90
+
91
+ ```ts
92
+ import { Chatwise } from '@chatwise/node';
93
+
94
+ const chatwise = new Chatwise();
95
+
96
+ const { from } = await chatwise.whatsappTemplates.send({
97
+ phoneNumber: '12025550147',
98
+ templateName: 'order_ready',
99
+ templateLanguage: 'en_US',
100
+ templateParams: [{ parameter_name: 'order_number', text: 'A-1042' }],
101
+ });
102
+ console.log(`Sent from ${from}`);
103
+ ```
104
+
105
+ Or by its id, which also works for templates that share a name:
106
+
107
+ ```ts
108
+ import { Chatwise } from '@chatwise/node';
109
+
110
+ const chatwise = new Chatwise();
111
+
112
+ for await (const template of chatwise.whatsappTemplates.list({ sendable: true, language: 'en_US' })) {
113
+ console.log(template.id, template.name, template.components.body.variables);
114
+ }
115
+
116
+ await chatwise.messages.send({
117
+ to: '12025550147',
118
+ templateId: '123456789012345',
119
+ templateParams: [{ parameter_name: 'order_number', text: 'A-1042' }],
120
+ });
121
+ ```
122
+
123
+ The answer means WhatsApp accepted the message, not that it was delivered. Sending twice sends two messages: see [retries](#retries-and-timeouts).
124
+
125
+ ## Create a WhatsApp template
126
+
127
+ ```ts
128
+ import { Chatwise } from '@chatwise/node';
129
+
130
+ const chatwise = new Chatwise();
131
+
132
+ const created = await chatwise.whatsappTemplates.create(
133
+ {
134
+ name: 'order_ready',
135
+ language: 'en_US',
136
+ category: 'UTILITY',
137
+ components: {
138
+ body: { text: 'Your order {{order_number}} is ready to collect.', examples: { order_number: 'A-1042' } },
139
+ },
140
+ },
141
+ { idempotencyKey: 'order-ready-en-us-v1' },
142
+ );
143
+
144
+ // Meta reviews it. Once `status` isn't PENDING any more, `sendable` says whether it can be sent.
145
+ const { status, sendable } = await chatwise.whatsappTemplates.get(created.id);
146
+ console.log(status, sendable);
147
+ ```
148
+
149
+ Call it again with the same `idempotencyKey` and template, and you get the same template back.
150
+
151
+ ## Receive webhooks
152
+
153
+ Chatwise sends events to your server as signed HTTPS requests. Create an endpoint, and store its secret:
154
+
155
+ ```ts
156
+ import { Chatwise } from '@chatwise/node';
157
+
158
+ const chatwise = new Chatwise();
159
+
160
+ const endpoint = await chatwise.webhookEndpoints.create({
161
+ name: 'Order support',
162
+ url: 'https://example.com/webhooks/chatwise',
163
+ events: ['message.received'],
164
+ });
165
+ console.log(endpoint.signingSecret); // The only time it is returned.
166
+ ```
167
+
168
+ Then check each request with `verifyWebhook`. It needs the body **exactly as received**, so get it before anything parses it. Each of these does:
169
+
170
+ ### Express
171
+
172
+ ```ts
173
+ import express from 'express';
174
+ import { verifyWebhook, WebhookVerificationError, type WebhookEvent } from '@chatwise/node';
175
+
176
+ const app = express();
177
+
178
+ // express.raw keeps the body as it was received, whatever its type. Put this route before any
179
+ // app.use(express.json()), which would parse it. Chatwise sends up to 256 KB, more than Express's own limit.
180
+ app.post('/webhooks/chatwise', express.raw({ type: () => true, limit: '300kb' }), (request, response) => {
181
+ let event: WebhookEvent;
182
+ try {
183
+ event = verifyWebhook({ payload: request.body ?? '', headers: request.headers, secret: process.env.CHATWISE_WEBHOOK_SECRET });
184
+ } catch (error) {
185
+ if (!(error instanceof WebhookVerificationError)) throw error; // A 500, so Chatwise tries again.
186
+ console.error(error.message); // After a 400 it doesn't, so watch for these.
187
+ response.status(400).send(error.code);
188
+ return;
189
+ }
190
+
191
+ // Answer within 10 seconds. An event that was answered isn't sent again, so first put work that must not
192
+ // be lost in a queue.
193
+ response.sendStatus(204);
194
+
195
+ if (event.type === 'message.received') {
196
+ console.log(`New message in conversation ${event.data.message.conversationId}`);
197
+ }
198
+ });
199
+
200
+ app.listen(3000);
201
+ ```
202
+
203
+ ### Next.js
204
+
205
+ ```ts
206
+ // app/webhooks/chatwise/route.ts
207
+ import { verifyWebhook, WebhookVerificationError, type WebhookEvent } from '@chatwise/node';
208
+
209
+ // verifyWebhook uses Node's crypto, which the Edge runtime doesn't have.
210
+ export const runtime = 'nodejs';
211
+
212
+ export async function POST(request: Request): Promise<Response> {
213
+ // Anyone can send a request, and Next.js has no limit. Chatwise sends up to 256 KB. A request without a
214
+ // Content-Length has to be limited by your host or proxy.
215
+ if (Number(request.headers.get('content-length')) > 300 * 1024) return new Response(null, { status: 413 });
216
+
217
+ let event: WebhookEvent;
218
+ try {
219
+ // text(), not json(): the signature is of the body as it was received.
220
+ event = verifyWebhook({ payload: await request.text(), headers: request.headers, secret: process.env.CHATWISE_WEBHOOK_SECRET });
221
+ } catch (error) {
222
+ if (!(error instanceof WebhookVerificationError)) throw error; // A 500, so Chatwise tries again.
223
+ console.error(error.message); // After a 400 it doesn't, so watch for these.
224
+ return new Response(error.code, { status: 400 });
225
+ }
226
+
227
+ // Answer within 10 seconds. Put longer work in a queue, or in Next.js's after().
228
+ if (event.type === 'message.received') {
229
+ console.log(`New message in conversation ${event.data.message.conversationId}`);
230
+ }
231
+ return new Response(null, { status: 204 });
232
+ }
233
+ ```
234
+
235
+ ### Hono
236
+
237
+ ```ts
238
+ import { serve } from '@hono/node-server';
239
+ import { Hono } from 'hono';
240
+ import { bodyLimit } from 'hono/body-limit';
241
+ import { verifyWebhook, WebhookVerificationError, type WebhookEvent } from '@chatwise/node';
242
+
243
+ const app = new Hono();
244
+
245
+ // Anyone can send a request, so limit what is read. Chatwise sends up to 256 KB. The connection is closed,
246
+ // so that what wasn't read can't get in the way of another request.
247
+ const limit = bodyLimit({ maxSize: 300 * 1024, onError: (c) => c.body(null, 413, { Connection: 'close' }) });
248
+
249
+ app.post('/webhooks/chatwise', limit, async (c) => {
250
+ let event: WebhookEvent;
251
+ try {
252
+ // text(), not json(): the signature is of the body as it was received.
253
+ event = verifyWebhook({ payload: await c.req.text(), headers: c.req.raw.headers, secret: process.env.CHATWISE_WEBHOOK_SECRET });
254
+ } catch (error) {
255
+ if (!(error instanceof WebhookVerificationError)) throw error; // A 500, so Chatwise tries again.
256
+ console.error(error.message); // After a 400 it doesn't, so watch for these.
257
+ return c.text(error.code, 400);
258
+ }
259
+
260
+ // Answer within 10 seconds. Put longer work in a queue.
261
+ if (event.type === 'message.received') {
262
+ console.log(`New message in conversation ${event.data.message.conversationId}`);
263
+ }
264
+ return c.body(null, 204);
265
+ });
266
+
267
+ serve({ fetch: app.fetch, port: 3000 });
268
+ ```
269
+
270
+ `verifyWebhook` checks the signature in constant time and that the request is at most five minutes old (`toleranceSeconds` changes that). It throws:
271
+
272
+ - a `WebhookVerificationError` if the request isn't a valid webhook. Answer 400. Its `code` is `missing_header`, `malformed_header`, `timestamp_too_old`, `timestamp_too_new`, `signature_mismatch` or `invalid_payload`;
273
+ - another `ChatwiseError` if your own code has to change: no secret, or a body that was already parsed. Let it become a 500, and Chatwise tries again once you fixed it.
274
+
275
+ **A delivery you answer with a 400 is not sent again.** Chatwise retries after no answer, a 408, 425, 429 or 5xx. Anything else that isn't a 2xx, a 400, 401 or 413 too, fails the delivery at once. So a wrong secret, or a clock that is off by more than five minutes, loses deliveries until you notice: log these errors, and watch `health` of the endpoint. Once it is fixed, send the failed deliveries of the last 30 days again, as [redeliver-failed.ts](https://github.com/vectorscalelabs/chatwise-node/blob/main/examples/redeliver-failed.ts) does.
276
+
277
+ **The same event can arrive more than once**, with the same `event.id`. Remember the ids you handled.
278
+
279
+ ### Events
280
+
281
+ `event.type` tells events apart, and TypeScript then knows their `data`:
282
+
283
+ ```ts
284
+ import type { WebhookEvent } from '@chatwise/node';
285
+
286
+ export function handle(event: WebhookEvent): string {
287
+ switch (event.type) {
288
+ case 'message.received': {
289
+ const { message, conversation } = event.data;
290
+ return `${conversation.participant.name ?? 'Someone'} on ${message.channel}: ${message.text ?? message.type}`;
291
+ }
292
+ case 'message.failed': {
293
+ const { message, error } = event.data;
294
+ return `${message.id} wasn't delivered: ${error?.title ?? error?.code ?? 'no reason given'}`;
295
+ }
296
+ case 'comment.received': {
297
+ const { comment, post } = event.data;
298
+ return `${comment.author.username ?? 'Someone'} commented on ${post.id}: ${comment.text}`;
299
+ }
300
+ case 'webhook.test':
301
+ return event.data.message;
302
+ default:
303
+ // Always have a default: Chatwise adds events, and they reach you before you update this package.
304
+ return `Ignored ${event.type}`;
305
+ }
306
+ }
307
+
308
+ console.log(handle({
309
+ id: 'evt_01JE2Z3QK4T8M6N2R5S7V9W1X3',
310
+ type: 'webhook.test',
311
+ timestamp: '2026-11-30T10:00:00.000Z',
312
+ apiVersion: '2026-12-01',
313
+ workspaceId: '42',
314
+ data: { endpointId: 'we_01JE2Z3K8Q9V7W5X4Y3Z2A1B0C', message: 'This is a test event from Chatwise.' },
315
+ }));
316
+ ```
317
+
318
+ | Event | When it is sent | `data` |
319
+ | --- | --- | --- |
320
+ | `message.received` | A customer sent a message, on any channel. | `message`, `conversation`, `account` |
321
+ | `message.sent` | The workspace sent a message, and the channel accepted it. | `message`, `conversation`, `account` |
322
+ | `message.delivered` | The channel says that a message from the workspace was delivered. | `message`, `conversation`, `account` |
323
+ | `message.read` | The channel says that the customer read it. | `message`, `conversation`, `account` |
324
+ | `message.failed` | The channel says that it couldn't be delivered. | `message`, `conversation`, `account`, `error` |
325
+ | `comment.received` | Someone commented on a post of a connected Instagram account. | `comment`, `post`, `account` |
326
+ | `webhook.test` | You sent a test event. | `endpointId`, `message` |
327
+
328
+ Each [event's page](https://chatwise.so/docs/webhooks/events) says when exactly it is sent, and when not. **Don't rely on the order.** A message's events can arrive in any order, and some never do: `message.read` can come before `message.delivered`, or not at all, when the customer turned read receipts off.
329
+
330
+ ### Test, rotate and redeliver
331
+
332
+ ```ts
333
+ import { Chatwise } from '@chatwise/node';
334
+
335
+ const chatwise = new Chatwise();
336
+ const endpointId = 'we_01JE2Z3K8Q9V7W5X4Y3Z2A1B0C';
337
+
338
+ // Sends a webhook.test event now, and says what your endpoint answered.
339
+ const { delivered, statusCode, error } = await chatwise.webhookEndpoints.test(endpointId);
340
+ console.log(delivered, statusCode, error);
341
+
342
+ // For 24 hours deliveries are signed with both secrets, so you can switch without missing any.
343
+ const { signingSecret, previousSecretExpiresAt } = await chatwise.webhookEndpoints.rotateSecret(endpointId);
344
+ console.log(signingSecret.length, previousSecretExpiresAt);
345
+
346
+ // What was sent in the last 30 days, and sending it again.
347
+ for await (const delivery of chatwise.webhookDeliveries.list(endpointId, { status: 'FAILED' })) {
348
+ const { attemptLog } = await chatwise.webhookDeliveries.get(delivery.id);
349
+ console.log(delivery.eventType, delivery.lastError, attemptLog.length);
350
+ await chatwise.webhookDeliveries.redeliver(delivery.id);
351
+ }
352
+
353
+ // How its deliveries are going. Chatwise leaves an endpoint that is unavailable alone for a while: until
354
+ // backoffUntil, which is null when it isn't waiting. A test that succeeds ends the wait.
355
+ const { status, health } = await chatwise.webhookEndpoints.get(endpointId);
356
+ console.log(status, health.consecutiveFailures, health.lastSuccessAt, health.backoffUntil);
357
+
358
+ // Pause it, and delete it.
359
+ await chatwise.webhookEndpoints.update(endpointId, { status: 'PAUSED' });
360
+ await chatwise.webhookEndpoints.delete(endpointId);
361
+ ```
362
+
363
+ ## Errors
364
+
365
+ Everything the SDK throws is a `ChatwiseError`. An answer that isn't a success is an `APIError`, with a class for each status:
366
+
367
+ ```ts
368
+ import { APIError, BadRequestError, Chatwise, ConflictError, NotFoundError, RateLimitError } from '@chatwise/node';
369
+
370
+ const chatwise = new Chatwise();
371
+
372
+ try {
373
+ await chatwise.conversations.get('404');
374
+ } catch (error) {
375
+ if (error instanceof NotFoundError) {
376
+ console.log('There is no such conversation.');
377
+ } else if (error instanceof BadRequestError) {
378
+ for (const { path, message } of error.fieldErrors) console.log(path, message);
379
+ } else if (error instanceof ConflictError) {
380
+ console.log(error.code); // Such as TEMPLATE_EXISTS.
381
+ } else if (error instanceof RateLimitError) {
382
+ console.log(`Wait ${error.retryAfterMs} ms.`);
383
+ } else if (error instanceof APIError) {
384
+ console.log(error.status, error.message, error.errorId); // Quote errorId to support.
385
+ } else {
386
+ throw error;
387
+ }
388
+ }
389
+ ```
390
+
391
+ | Class | When |
392
+ | --- | --- |
393
+ | `BadRequestError` | 400: something in the request is invalid. `fieldErrors` says what. |
394
+ | `AuthenticationError` | 401: the key is missing, invalid, expired or revoked. With the message `Invalid API key`, Chatwise couldn't check it: try again. |
395
+ | `PaymentRequiredError` | 402: sending is paused for the workspace. |
396
+ | `PermissionDeniedError` | 403: the key lacks a scope, or WhatsApp has to be reconnected. |
397
+ | `NotFoundError` | 404: it doesn't exist in the key's workspace. |
398
+ | `ConflictError` | 409: a template submission conflicts with an earlier one. `code` says how. |
399
+ | `PayloadTooLargeError` | 413: the request is larger than 100 KB. |
400
+ | `RateLimitError` | 429: more than 120 requests in a minute with this key, the default limit. |
401
+ | `ServerError` | 5xx: something failed in Chatwise, or WhatsApp refused the message. |
402
+ | `ConnectionError` | There was no complete answer. `RequestTimeoutError` is one, when it took too long. |
403
+ | `RequestAbortedError` | Your `signal` aborted the request. |
404
+ | `WebhookVerificationError` | `verifyWebhook` refused the request. |
405
+
406
+ An answer far larger than the API's isn't read to its end: an error then has an empty `body`, and a success is a `ConnectionError`.
407
+
408
+ Every `APIError` has `status`, `message`, `code`, `fieldErrors`, `errorId`, `retryAfterMs`, `method`, `path` and `body`. No error contains your API key.
409
+
410
+ ## Retries and timeouts
411
+
412
+ A failed call is retried up to twice, if that is safe:
413
+
414
+ | | After a 429 | After a 5xx, a network error or a timeout |
415
+ | --- | --- | --- |
416
+ | Reads | Retried | Retried |
417
+ | Creating a template | Retried | Retried: the route recognizes a repeat. Not if the answer has a `code`, which says what to do. `TEMPLATE_SUBMISSION_IN_PROGRESS` means to call again later |
418
+ | Sends and every other change | Retried: it wasn't carried out | **Not retried**: it may have been carried out |
419
+
420
+ It waits longer each time, and as long as `Retry-After` says: 60 seconds when you are over the rate limit. A wait of more than 90 seconds isn't waited out: the call fails with the error. Where a call can't take that long, pass `maxRetries: 0`. **After a send fails with anything but an `APIError` with a 4xx status, it may have been sent,** even if the conversation doesn't show it. Check before you send again.
421
+
422
+ Each attempt may take 60 seconds. Change that for every call, or for one, or pass a signal:
423
+
424
+ ```ts
425
+ import { Chatwise } from '@chatwise/node';
426
+
427
+ const chatwise = new Chatwise({ timeoutMs: 20_000, maxRetries: 4 });
428
+
429
+ const controller = new AbortController();
430
+ process.once('SIGTERM', () => controller.abort());
431
+
432
+ const page = await chatwise.messages.list({ limit: 100 }, {
433
+ signal: controller.signal, // Also ends the waits between attempts.
434
+ timeoutMs: 5000,
435
+ maxRetries: 0,
436
+ });
437
+ console.log(page.data.length);
438
+ ```
439
+
440
+ ## Methods and scopes
441
+
442
+ A key can do only what its scopes allow, and no scope includes another.
443
+
444
+ | Method | Scopes |
445
+ | --- | --- |
446
+ | `conversations.list(params?)` | `conversations:read` |
447
+ | `conversations.get(conversationId)` | `conversations:read` |
448
+ | `messages.list(params?)` | `messages:read` |
449
+ | `messages.listInConversation(conversationId, params?)` | `messages:read` |
450
+ | `messages.get(conversationId, messageId)` | `messages:read` |
451
+ | `messages.send(params)` | `messages:send` |
452
+ | `whatsappTemplates.list(params?)` | `templates:read` |
453
+ | `whatsappTemplates.get(templateId)` | `templates:read` |
454
+ | `whatsappTemplates.create(params, { idempotencyKey }?)` | `templates:write` |
455
+ | `whatsappTemplates.send(params)` | `messages:send` |
456
+ | `webhookEndpoints.list()` | `webhooks:read` |
457
+ | `webhookEndpoints.create(params)` | `webhooks:write`, and `messages:read` to subscribe to `message.*` events |
458
+ | `webhookEndpoints.get(endpointId)` | `webhooks:read` |
459
+ | `webhookEndpoints.update(endpointId, params)` | `webhooks:write`, and `messages:read` if it has `message.*` events before or after the change |
460
+ | `webhookEndpoints.delete(endpointId)` | `webhooks:write` |
461
+ | `webhookEndpoints.test(endpointId)` | `webhooks:write` |
462
+ | `webhookEndpoints.rotateSecret(endpointId)` | `webhooks:write`, and `messages:read` if it has `message.*` events |
463
+ | `webhookDeliveries.list(endpointId, params?)` | `webhooks:read` |
464
+ | `webhookDeliveries.get(deliveryId)` | `webhooks:read`, and `messages:read` if it is for a `message.*` event |
465
+ | `webhookDeliveries.redeliver(deliveryId)` | `webhooks:write`, and `messages:read` if it is for a `message.*` event |
466
+ | `webhookEventTypes.list()` | `webhooks:read` |
467
+
468
+ Every method takes `{ signal, timeoutMs, maxRetries }` as its last argument. Lists with pages return a page when awaited, and their items when iterated over. `webhookEndpoints.list()` and `webhookEventTypes.list()` are short, and return an array.
469
+
470
+ ## Options
471
+
472
+ ```ts
473
+ import { Chatwise } from '@chatwise/node';
474
+
475
+ const chatwise = new Chatwise({
476
+ apiKey: process.env.CHATWISE_API_KEY, // The default.
477
+ baseUrl: 'https://api.chatwise.so', // The default.
478
+ timeoutMs: 60_000, // The default, for each attempt.
479
+ maxRetries: 2, // The default.
480
+ // Your own fetch, for a proxy or for tests. It receives the key, in the Authorization header.
481
+ fetch: (url, init) => fetch(url, init),
482
+ });
483
+
484
+ console.log(await chatwise.webhookEventTypes.list());
485
+ ```
486
+
487
+ The key isn't on the client, so logging a client doesn't show it. Redirects aren't followed, and `baseUrl` must be `https` unless it is this machine, so the key isn't sent anywhere else.
488
+
489
+ ## TypeScript and CommonJS
490
+
491
+ The types need TypeScript 5.0 or later, and neither the DOM's nor Node's types. In CommonJS:
492
+
493
+ ```js
494
+ const { Chatwise } = require('@chatwise/node');
495
+
496
+ const chatwise = new Chatwise();
497
+ chatwise.webhookEndpoints.list().then((endpoints) => console.log(endpoints.length));
498
+ ```
499
+
500
+ Values and fields the API adds later reach you as they are, and the types allow for them: a channel or a status you don't know is a string. New events and fields can arrive in any version of the API, so ignore what you don't know.
501
+
502
+ ## Help
503
+
504
+ - [API documentation](https://chatwise.so/docs), [webhooks](https://chatwise.so/docs/webhooks) and the [changelog](https://github.com/vectorscalelabs/chatwise-node/blob/main/CHANGELOG.md).
505
+ - [Report a problem](https://github.com/vectorscalelabs/chatwise-node/issues) with this package. Leave out API keys, signing secrets and customers' messages. To report a security problem, see [SECURITY.md](https://github.com/vectorscalelabs/chatwise-node/blob/main/SECURITY.md).
506
+
507
+ Copyright 2026 VectorScale Labs Private Limited. [Apache License 2.0](https://github.com/vectorscalelabs/chatwise-node/blob/main/LICENSE).
@@ -0,0 +1,20 @@
1
+ import { type ChatwiseOptions } from './core/http.js';
2
+ import { Conversations } from './resources/conversations.js';
3
+ import { Messages } from './resources/messages.js';
4
+ import { WebhookDeliveries } from './resources/webhook-deliveries.js';
5
+ import { WebhookEndpoints } from './resources/webhook-endpoints.js';
6
+ import { WebhookEventTypes } from './resources/webhook-event-types.js';
7
+ import { WhatsappTemplates } from './resources/whatsapp-templates.js';
8
+ /**
9
+ * A client of the Chatwise API, for one workspace: the API key's. Use it on a server only, because
10
+ * anyone who has the key can use it.
11
+ */
12
+ export declare class Chatwise {
13
+ readonly conversations: Conversations;
14
+ readonly messages: Messages;
15
+ readonly whatsappTemplates: WhatsappTemplates;
16
+ readonly webhookEndpoints: WebhookEndpoints;
17
+ readonly webhookDeliveries: WebhookDeliveries;
18
+ readonly webhookEventTypes: WebhookEventTypes;
19
+ constructor(options?: ChatwiseOptions);
20
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Chatwise = void 0;
4
+ const http_js_1 = require("./core/http.js");
5
+ const conversations_js_1 = require("./resources/conversations.js");
6
+ const messages_js_1 = require("./resources/messages.js");
7
+ const webhook_deliveries_js_1 = require("./resources/webhook-deliveries.js");
8
+ const webhook_endpoints_js_1 = require("./resources/webhook-endpoints.js");
9
+ const webhook_event_types_js_1 = require("./resources/webhook-event-types.js");
10
+ const whatsapp_templates_js_1 = require("./resources/whatsapp-templates.js");
11
+ /**
12
+ * A client of the Chatwise API, for one workspace: the API key's. Use it on a server only, because
13
+ * anyone who has the key can use it.
14
+ */
15
+ class Chatwise {
16
+ conversations;
17
+ messages;
18
+ whatsappTemplates;
19
+ webhookEndpoints;
20
+ webhookDeliveries;
21
+ webhookEventTypes;
22
+ constructor(options = {}) {
23
+ const request = (0, http_js_1.createRequester)(options);
24
+ this.conversations = new conversations_js_1.Conversations(request);
25
+ this.messages = new messages_js_1.Messages(request);
26
+ this.whatsappTemplates = new whatsapp_templates_js_1.WhatsappTemplates(request);
27
+ this.webhookEndpoints = new webhook_endpoints_js_1.WebhookEndpoints(request);
28
+ this.webhookDeliveries = new webhook_deliveries_js_1.WebhookDeliveries(request);
29
+ this.webhookEventTypes = new webhook_event_types_js_1.WebhookEventTypes(request);
30
+ }
31
+ }
32
+ exports.Chatwise = Chatwise;
@@ -0,0 +1,91 @@
1
+ /** The base of every error this package throws. */
2
+ export declare class ChatwiseError extends Error {
3
+ name: string;
4
+ }
5
+ /** What was wrong with one field of a request. */
6
+ export interface FieldError {
7
+ /** The field, such as `body.name` or `query.limit`, or the name of the value that was refused, such as `url`. */
8
+ path: string;
9
+ message: string;
10
+ }
11
+ /** What an `APIError` is made of. */
12
+ export interface APIErrorDetails {
13
+ status: number;
14
+ method: string;
15
+ path: string;
16
+ /** The parsed body, or its text when it isn't JSON. */
17
+ body: unknown;
18
+ retryAfterMs?: number | undefined;
19
+ }
20
+ /** Chatwise answered with an error. Each status has a subclass. */
21
+ export declare class APIError extends ChatwiseError {
22
+ name: string;
23
+ /** The HTTP status. */
24
+ readonly status: number;
25
+ /** A code to check in your program, such as `TEMPLATE_EXISTS`, when the error has one. */
26
+ readonly code: string | undefined;
27
+ /** What was wrong with which field, when the API says so. */
28
+ readonly fieldErrors: readonly FieldError[];
29
+ /** Quote it when you contact support. Only some 500s have one. */
30
+ readonly errorId: string | undefined;
31
+ /** How long the API asks to wait before another request, in milliseconds. From `Retry-After`. */
32
+ readonly retryAfterMs: number | undefined;
33
+ readonly method: string;
34
+ /** The path of the request, without its query. */
35
+ readonly path: string;
36
+ /** The parsed body of the response, or its text when it wasn't JSON. */
37
+ readonly body: unknown;
38
+ constructor({ status, method, path, body, retryAfterMs }: APIErrorDetails);
39
+ }
40
+ /** 400: a parameter, field, cursor or id is invalid. `fieldErrors` says which. */
41
+ export declare class BadRequestError extends APIError {
42
+ name: string;
43
+ }
44
+ /**
45
+ * 401: the API key is missing, invalid, expired or revoked. With the message `Invalid API key`, Chatwise
46
+ * couldn't check the key: try again.
47
+ */
48
+ export declare class AuthenticationError extends APIError {
49
+ name: string;
50
+ }
51
+ /** 402: sending is paused for the workspace. */
52
+ export declare class PaymentRequiredError extends APIError {
53
+ name: string;
54
+ }
55
+ /** 403: the key lacks a scope, or WhatsApp has to be reconnected (`code` is `WHATSAPP_REAUTH_REQUIRED`). */
56
+ export declare class PermissionDeniedError extends APIError {
57
+ name: string;
58
+ }
59
+ /** 404: it doesn't exist in the key's workspace. */
60
+ export declare class NotFoundError extends APIError {
61
+ name: string;
62
+ }
63
+ /** 409: a template submission conflicts with an earlier one. `code` says how. */
64
+ export declare class ConflictError extends APIError {
65
+ name: string;
66
+ }
67
+ /** 413: the request body is larger than 100 KB. */
68
+ export declare class PayloadTooLargeError extends APIError {
69
+ name: string;
70
+ }
71
+ /** 429: too many requests with this key. Wait `retryAfterMs`. */
72
+ export declare class RateLimitError extends APIError {
73
+ name: string;
74
+ }
75
+ /** 5xx: something failed in Chatwise, or WhatsApp refused a message. The request may have been carried out. */
76
+ export declare class ServerError extends APIError {
77
+ name: string;
78
+ }
79
+ /** There was no complete answer: the network failed, or the answer was cut off. The request may have been carried out. */
80
+ export declare class ConnectionError extends ChatwiseError {
81
+ name: string;
82
+ }
83
+ /** An attempt took longer than `timeoutMs`. The request may have been carried out. */
84
+ export declare class RequestTimeoutError extends ConnectionError {
85
+ name: string;
86
+ }
87
+ /** Your `signal` aborted the request. The request may have been carried out. `cause` is the signal's reason. */
88
+ export declare class RequestAbortedError extends ChatwiseError {
89
+ name: string;
90
+ }
91
+ export declare function apiError(details: APIErrorDetails): APIError;