@chatwise/node 0.1.0 → 0.1.1

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  What changed in each version of `@chatwise/node`. Versions follow [semantic versioning](https://semver.org): before 1.0.0 a minor version can change what your code has to do, and says so here.
4
4
 
5
+ ## 0.1.1
6
+
7
+ - `messages.reply` answers a customer in a WhatsApp, Instagram or Messenger conversation, with a text or a file. It takes an `idempotencyKey`, which makes it safe to repeat, so it is retried like a read. It waits for a file that takes longer to prepare, for as long as `mediaTimeoutMs` says.
8
+ - `messages.listFiles` lists a message's files, with links to download them.
9
+ - The types' comments and the README cover files on Messenger, which the API sends and lists since December 2026.
10
+ - `UnprocessableEntityError` for a 422. It is an `APIError`, as a 422 was before.
11
+
5
12
  ## 0.1.0
6
13
 
7
14
  The first version.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Chatwise for Node.js
2
2
 
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.
3
+ The official Node.js SDK for the [Chatwise API](https://chatwise.so/docs): read your WhatsApp, Instagram, Messenger and Website Chat inbox, reply to customers, send WhatsApp templates, and receive signed webhooks.
4
4
 
5
5
  - **Small.** No dependencies, and ES modules and CommonJS with types for both.
6
6
  - **Typed.** Requests, responses and webhook events, generated from the API's own specification.
@@ -84,6 +84,82 @@ Ids are strings. They can be larger than a JavaScript number can hold, so don't
84
84
 
85
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
86
 
87
+ ## Reply to a customer
88
+
89
+ With a text, in a WhatsApp, Instagram or Messenger conversation:
90
+
91
+ ```ts
92
+ import { Chatwise } from '@chatwise/node';
93
+
94
+ const chatwise = new Chatwise();
95
+
96
+ const { id, channel } = await chatwise.messages.reply(
97
+ '1234',
98
+ { text: 'Yes, it is available in blue.' },
99
+ { idempotencyKey: 'reply-evt_01JE2Z3QK4T8M6N2R5S7V9W1X3' },
100
+ );
101
+ console.log(`${channel} accepted message ${id}`);
102
+ ```
103
+
104
+ Or with a file, on WhatsApp, Instagram and Messenger. Chatwise downloads it from its address, which must be public and `https`, and [converts it](https://chatwise.so/docs/replies#what-can-be-sent) to what the channel takes:
105
+
106
+ ```ts
107
+ import { Chatwise } from '@chatwise/node';
108
+
109
+ const chatwise = new Chatwise();
110
+
111
+ const { type } = await chatwise.messages.reply(
112
+ '1234',
113
+ {
114
+ media: {
115
+ url: 'https://example.com/files/invoice-1042.pdf',
116
+ fileName: 'Invoice 1042.pdf',
117
+ caption: 'Here is your invoice.', // Only on WhatsApp, and not with audio.
118
+ },
119
+ },
120
+ { idempotencyKey: 'invoice-1042' },
121
+ );
122
+ console.log(`Sent as ${type}`);
123
+ ```
124
+
125
+ The answer means the channel accepted the message, not that it was delivered. A customer can be answered for 24 hours after their latest message. Later the code is `REPLY_WINDOW_CLOSED`: on WhatsApp, [send a template](#send-a-whatsapp-template) then.
126
+
127
+ **One `idempotencyKey` stands for one message.** Make it from what you answer, such as the event's id. A call that is repeated with the same key, content and API key doesn't send the message again, for 30 days. With another `idempotencyKey` or another API key it sends another message. What to do when a reply throws:
128
+
129
+ | It throws | What to do |
130
+ | --- | --- |
131
+ | `SEND_OUTCOME_UNKNOWN` | Let a person decide. The message [may have been sent](https://chatwise.so/docs/replies#when-it-isnt-clear), even if the conversation doesn't show it, and a repeat sends nothing. Send it again with a new key only if it is better that the customer gets it twice than not at all. |
132
+ | A `ConnectionError`, a `RequestAbortedError`, any other 5xx, a 429, `SEND_IN_PROGRESS`, `MEDIA_PROCESSING`, or a 401 with the message `Invalid API key` | Call it again later, with the same key, content and API key. It may have been sent, and then the repeat returns that message. |
133
+ | `MEDIA_DOWNLOAD_FAILED` | Call it again after a minute, and the file is downloaded again. For another address, use a new key. |
134
+ | Any other 4xx | Fix what it names first: until then it fails again. Other content, such as another file, needs a new key. |
135
+
136
+ **An error is about the last request of the call.** If an earlier one got no answer, a 401, 403, 404 or 429 doesn't say that nothing was sent, so don't go on with another `idempotencyKey`. With a file no error says so while the earlier request is still running, because that one can send the file later: wait a minute and make the call once more first. The same goes for a new API key, such as after `SEND_NOT_PERMITTED`: first make sure that it wasn't sent.
137
+
138
+ A file can take minutes to prepare. The call waits for it, for ten minutes unless `mediaTimeoutMs` says otherwise: see [retries](#retries-and-timeouts). [examples/reply.ts](https://github.com/vectorscalelabs/chatwise-node/blob/main/examples/reply.ts) answers a message and handles what can go wrong.
139
+
140
+ **When you answer webhooks, answer `message.received` only.** Each reply makes a `message.sent` event, as every message from the workspace does: a program that answers those answers itself.
141
+
142
+ ## Download a message's files
143
+
144
+ ```ts
145
+ import { Chatwise } from '@chatwise/node';
146
+
147
+ const chatwise = new Chatwise();
148
+
149
+ for (const file of await chatwise.messages.listFiles('1234', '5678')) {
150
+ if (file.url === null) {
151
+ console.log(file.type, file.status); // It is still being copied (pending), or it is gone (unavailable).
152
+ continue;
153
+ }
154
+ // A plain fetch: whoever has the link has the file, so it needs no API key. Don't send yours.
155
+ const response = await fetch(file.url);
156
+ if (!response.ok) throw new Error(`The file answered ${response.status}`);
157
+ console.log(file.name, file.mimeType, (await response.arrayBuffer()).byteLength);
158
+ }
159
+ ```
160
+
161
+ A link works for five minutes, until `urlExpiresAt`. Don't store it: list the files again for a new one. `name` is what the sender called the file, so don't use it as a path. [Read the files](https://chatwise.so/docs/replies#4-read-the-files) says which files there are on which channel. [examples/download-files.ts](https://github.com/vectorscalelabs/chatwise-node/blob/main/examples/download-files.ts) waits for those that are still being copied.
162
+
87
163
  ## Send a WhatsApp template
88
164
 
89
165
  By its name:
@@ -392,13 +468,14 @@ try {
392
468
  | --- | --- |
393
469
  | `BadRequestError` | 400: something in the request is invalid. `fieldErrors` says what. |
394
470
  | `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. |
471
+ | `PaymentRequiredError` | 402: sending is paused for the workspace, or its subscription needs attention. |
472
+ | `PermissionDeniedError` | 403: the key lacks a scope, WhatsApp has to be reconnected, or the key's creator may not send replies any more. |
397
473
  | `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. |
474
+ | `ConflictError` | 409: it conflicts with an earlier request, or with how things are now. `code` says how, such as `REPLY_WINDOW_CLOSED` or `TEMPLATE_EXISTS`. |
399
475
  | `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. |
476
+ | `UnprocessableEntityError` | 422: the channel refused a reply, or its file can't be downloaded or sent. `code` says which. |
477
+ | `RateLimitError` | 429: more than 120 requests in a minute with this key, the default limit, or too many [replies or files](https://chatwise.so/docs/rate-limits#replies). |
478
+ | `ServerError` | 5xx: something failed or is busy in Chatwise or at the channel, or WhatsApp refused a template. With the code `SEND_OUTCOME_UNKNOWN`, a reply [may have been sent](#reply-to-a-customer). |
402
479
  | `ConnectionError` | There was no complete answer. `RequestTimeoutError` is one, when it took too long. |
403
480
  | `RequestAbortedError` | Your `signal` aborted the request. |
404
481
  | `WebhookVerificationError` | `verifyWebhook` refused the request. |
@@ -409,15 +486,22 @@ Every `APIError` has `status`, `message`, `code`, `fieldErrors`, `errorId`, `ret
409
486
 
410
487
  ## Retries and timeouts
411
488
 
412
- A failed call is retried up to twice, if that is safe:
489
+ A failed call is retried up to twice, if that is safe. A 401 never is, also for a reply:
413
490
 
414
491
  | | After a 429 | After a 5xx, a network error or a timeout |
415
492
  | --- | --- | --- |
416
493
  | Reads | Retried | Retried |
494
+ | Replies | Retried | Retried, with the same `idempotencyKey`: the route recognizes a repeat. So is a 409 with the code `SEND_IN_PROGRESS`. Not if the code is `SEND_OUTCOME_UNKNOWN` |
417
495
  | 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 |
496
+ | Sending a template, and every other change | Retried: it wasn't carried out | **Not retried**: it may have been carried out |
497
+
498
+ 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 sending a template 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.
499
+
500
+ **A reply is different,** because it can be repeated: [call it again](#reply-to-a-customer), with the same key.
501
+
502
+ **A file isn't always ready at once.** `MEDIA_PROCESSING` and `MEDIA_BUSY` say to repeat the request until it is. `messages.reply` does, as `Retry-After` says, as long as the next request begins within `mediaTimeoutMs` of the call. That is ten minutes by default, and 0 with `maxRetries: 0`, which makes one request. These repeats don't count as retries, and the count of retries starts again after each. Leave `timeoutMs` at a minute for a file: a request waits up to 25 seconds for it, and then sends it.
419
503
 
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.
504
+ **A video on Messenger can take longer to send than the retries last.** Facebook fetches it, and if that takes [more than 30 seconds](https://chatwise.so/docs/replies#when-messenger-takes-long), the request answers `SEND_IN_PROGRESS` and Chatwise goes on sending it. The call throws that when its retries are used up. Make it again within a minute, with the same `idempotencyKey`: if Facebook refused the video, only the repeats of the next minute are told, and a later one sends it again. Or pass a higher `maxRetries`, up to 10.
421
505
 
422
506
  Each attempt may take 60 seconds. Change that for every call, or for one, or pass a signal:
423
507
 
@@ -448,6 +532,8 @@ A key can do only what its scopes allow, and no scope includes another.
448
532
  | `messages.list(params?)` | `messages:read` |
449
533
  | `messages.listInConversation(conversationId, params?)` | `messages:read` |
450
534
  | `messages.get(conversationId, messageId)` | `messages:read` |
535
+ | `messages.listFiles(conversationId, messageId)` | `messages:read` |
536
+ | `messages.reply(conversationId, params, { idempotencyKey })` | `messages:reply` |
451
537
  | `messages.send(params)` | `messages:send` |
452
538
  | `whatsappTemplates.list(params?)` | `templates:read` |
453
539
  | `whatsappTemplates.get(templateId)` | `templates:read` |
@@ -48,11 +48,14 @@ export declare class BadRequestError extends APIError {
48
48
  export declare class AuthenticationError extends APIError {
49
49
  name: string;
50
50
  }
51
- /** 402: sending is paused for the workspace. */
51
+ /** 402: sending is paused for the workspace, or its subscription needs attention. */
52
52
  export declare class PaymentRequiredError extends APIError {
53
53
  name: string;
54
54
  }
55
- /** 403: the key lacks a scope, or WhatsApp has to be reconnected (`code` is `WHATSAPP_REAUTH_REQUIRED`). */
55
+ /**
56
+ * 403: the key lacks a scope, WhatsApp has to be reconnected (`code` is `WHATSAPP_REAUTH_REQUIRED`), or the
57
+ * person who created the key may not send replies any more (`SEND_NOT_PERMITTED`).
58
+ */
56
59
  export declare class PermissionDeniedError extends APIError {
57
60
  name: string;
58
61
  }
@@ -60,7 +63,7 @@ export declare class PermissionDeniedError extends APIError {
60
63
  export declare class NotFoundError extends APIError {
61
64
  name: string;
62
65
  }
63
- /** 409: a template submission conflicts with an earlier one. `code` says how. */
66
+ /** 409: it conflicts with an earlier request, or with how things are now. `code` says how, such as `REPLY_WINDOW_CLOSED`. */
64
67
  export declare class ConflictError extends APIError {
65
68
  name: string;
66
69
  }
@@ -68,11 +71,18 @@ export declare class ConflictError extends APIError {
68
71
  export declare class PayloadTooLargeError extends APIError {
69
72
  name: string;
70
73
  }
71
- /** 429: too many requests with this key. Wait `retryAfterMs`. */
74
+ /** 422: the channel refused a reply, or its file can't be downloaded or sent. `code` says which. This request sent nothing. */
75
+ export declare class UnprocessableEntityError extends APIError {
76
+ name: string;
77
+ }
78
+ /** 429: too many requests with this key, or too many replies or files. Wait `retryAfterMs`. */
72
79
  export declare class RateLimitError extends APIError {
73
80
  name: string;
74
81
  }
75
- /** 5xx: something failed in Chatwise, or WhatsApp refused a message. The request may have been carried out. */
82
+ /**
83
+ * 5xx: something failed or is busy in Chatwise or at the channel, or WhatsApp refused a template. The request
84
+ * may have been carried out. `SEND_OUTCOME_UNKNOWN` is one, and it must not be sent again with a new key by itself.
85
+ */
76
86
  export declare class ServerError extends APIError {
77
87
  name: string;
78
88
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RequestAbortedError = exports.RequestTimeoutError = exports.ConnectionError = exports.ServerError = exports.RateLimitError = exports.PayloadTooLargeError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.PaymentRequiredError = exports.AuthenticationError = exports.BadRequestError = exports.APIError = exports.ChatwiseError = void 0;
3
+ exports.RequestAbortedError = exports.RequestTimeoutError = exports.ConnectionError = exports.ServerError = exports.RateLimitError = exports.UnprocessableEntityError = exports.PayloadTooLargeError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.PaymentRequiredError = exports.AuthenticationError = exports.BadRequestError = exports.APIError = exports.ChatwiseError = void 0;
4
4
  exports.apiError = apiError;
5
5
  /** The base of every error this package throws. */
6
6
  class ChatwiseError extends Error {
@@ -66,12 +66,15 @@ class AuthenticationError extends APIError {
66
66
  name = 'AuthenticationError';
67
67
  }
68
68
  exports.AuthenticationError = AuthenticationError;
69
- /** 402: sending is paused for the workspace. */
69
+ /** 402: sending is paused for the workspace, or its subscription needs attention. */
70
70
  class PaymentRequiredError extends APIError {
71
71
  name = 'PaymentRequiredError';
72
72
  }
73
73
  exports.PaymentRequiredError = PaymentRequiredError;
74
- /** 403: the key lacks a scope, or WhatsApp has to be reconnected (`code` is `WHATSAPP_REAUTH_REQUIRED`). */
74
+ /**
75
+ * 403: the key lacks a scope, WhatsApp has to be reconnected (`code` is `WHATSAPP_REAUTH_REQUIRED`), or the
76
+ * person who created the key may not send replies any more (`SEND_NOT_PERMITTED`).
77
+ */
75
78
  class PermissionDeniedError extends APIError {
76
79
  name = 'PermissionDeniedError';
77
80
  }
@@ -81,7 +84,7 @@ class NotFoundError extends APIError {
81
84
  name = 'NotFoundError';
82
85
  }
83
86
  exports.NotFoundError = NotFoundError;
84
- /** 409: a template submission conflicts with an earlier one. `code` says how. */
87
+ /** 409: it conflicts with an earlier request, or with how things are now. `code` says how, such as `REPLY_WINDOW_CLOSED`. */
85
88
  class ConflictError extends APIError {
86
89
  name = 'ConflictError';
87
90
  }
@@ -91,12 +94,20 @@ class PayloadTooLargeError extends APIError {
91
94
  name = 'PayloadTooLargeError';
92
95
  }
93
96
  exports.PayloadTooLargeError = PayloadTooLargeError;
94
- /** 429: too many requests with this key. Wait `retryAfterMs`. */
97
+ /** 422: the channel refused a reply, or its file can't be downloaded or sent. `code` says which. This request sent nothing. */
98
+ class UnprocessableEntityError extends APIError {
99
+ name = 'UnprocessableEntityError';
100
+ }
101
+ exports.UnprocessableEntityError = UnprocessableEntityError;
102
+ /** 429: too many requests with this key, or too many replies or files. Wait `retryAfterMs`. */
95
103
  class RateLimitError extends APIError {
96
104
  name = 'RateLimitError';
97
105
  }
98
106
  exports.RateLimitError = RateLimitError;
99
- /** 5xx: something failed in Chatwise, or WhatsApp refused a message. The request may have been carried out. */
107
+ /**
108
+ * 5xx: something failed or is busy in Chatwise or at the channel, or WhatsApp refused a template. The request
109
+ * may have been carried out. `SEND_OUTCOME_UNKNOWN` is one, and it must not be sent again with a new key by itself.
110
+ */
100
111
  class ServerError extends APIError {
101
112
  name = 'ServerError';
102
113
  }
@@ -125,6 +136,7 @@ function apiError(details) {
125
136
  case 404: return new NotFoundError(details);
126
137
  case 409: return new ConflictError(details);
127
138
  case 413: return new PayloadTooLargeError(details);
139
+ case 422: return new UnprocessableEntityError(details);
128
140
  case 429: return new RateLimitError(details);
129
141
  default: return details.status >= 500 ? new ServerError(details) : new APIError(details);
130
142
  }
@@ -1,3 +1,4 @@
1
+ import { APIError } from './errors.js';
1
2
  /** An `AbortSignal`. */
2
3
  export interface AbortSignalLike {
3
4
  readonly aborted: boolean;
@@ -37,8 +38,8 @@ export interface ChatwiseOptions {
37
38
  */
38
39
  timeoutMs?: number | undefined;
39
40
  /**
40
- * How many times to retry what is safe to retry: reads, and creating a template, after a 429, a 5xx or
41
- * a network error; anything else only after a 429, because such a request wasn't carried out.
41
+ * How many times to retry what is safe to retry: reads, replies and creating a template after a 429, a
42
+ * 5xx or a network error; anything else only after a 429, because such a request wasn't carried out.
42
43
  * @defaultValue 2
43
44
  */
44
45
  maxRetries?: number | undefined;
@@ -60,8 +61,20 @@ export interface Operation {
60
61
  query?: object | undefined;
61
62
  body?: object | undefined;
62
63
  headers?: Record<string, string> | undefined;
63
- /** The route takes an idempotency key, so repeating it can't do it twice. */
64
- idempotent?: boolean;
64
+ /**
65
+ * The route recognizes a repeat, so a request that may have been carried out can be repeated. Says which
66
+ * answers it is repeated after, besides a 429.
67
+ */
68
+ repeatAfter?: (answer: APIError) => boolean;
69
+ /**
70
+ * Codes of answers that say to repeat the request until something is ready, and for how long to. These
71
+ * don't count as retries, and the count starts again after each. Without a time it is a default, or none if
72
+ * the call has no retries.
73
+ */
74
+ pending?: {
75
+ codes: readonly string[];
76
+ timeoutMs: number | undefined;
77
+ };
65
78
  }
66
79
  /** Makes a request and returns the body of its answer. */
67
80
  export type Requester = (operation: Operation, options?: RequestOptions) => Promise<Record<string, unknown>>;
@@ -7,6 +7,10 @@ const errors_js_1 = require("./errors.js");
7
7
  const DEFAULT_BASE_URL = 'https://api.chatwise.so';
8
8
  const DEFAULT_TIMEOUT_MS = 60_000;
9
9
  const DEFAULT_MAX_RETRIES = 2;
10
+ const DEFAULT_PENDING_TIMEOUT_MS = 600_000;
11
+ /** How long to wait before asking again for what isn't ready, if the answer doesn't say, and at least. */
12
+ const PENDING_RETRY_MS = 10_000;
13
+ const MIN_PENDING_RETRY_MS = 1000;
10
14
  /** The longest wait setTimeout can hold. A longer one would end at once. */
11
15
  const MAX_TIMEOUT_MS = 2_147_483_647;
12
16
  /** Chatwise asks for 60 seconds. A call doesn't wait for much longer than that: it fails instead. */
@@ -21,6 +25,12 @@ function checkTimeout(value) {
21
25
  }
22
26
  return value;
23
27
  }
28
+ function checkPendingTimeout(value) {
29
+ if (!Number.isInteger(value) || value < 0 || value > MAX_TIMEOUT_MS) {
30
+ throw new errors_js_1.ChatwiseError(`mediaTimeoutMs must be a whole number of milliseconds from 0 to ${MAX_TIMEOUT_MS}.`);
31
+ }
32
+ return value;
33
+ }
24
34
  function checkRetries(value) {
25
35
  if (!Number.isInteger(value) || value < 0 || value > 10) {
26
36
  throw new errors_js_1.ChatwiseError('maxRetries must be a whole number from 0 to 10.');
@@ -129,21 +139,22 @@ function parseRetryAfter(value) {
129
139
  const date = /\bGMT$/.test(text) ? Date.parse(text) : NaN;
130
140
  return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
131
141
  }
142
+ /** The wait an answer asks for, or undefined if it is too long to wait for. */
143
+ function askedDelay(retryAfterMs) {
144
+ // Up to a second more, so that callers limited together don't come back together.
145
+ return retryAfterMs > MAX_RETRY_AFTER_MS ? undefined : Math.ceil(retryAfterMs + Math.random() * 1000);
146
+ }
132
147
  /** How long to wait before retrying after `error`, or undefined not to retry. `attempt` counts from 0. */
133
- function retryDelay(error, attempt, { method, idempotent = false }) {
134
- const limited = error instanceof errors_js_1.APIError && error.status === 429;
135
- const failed = error instanceof errors_js_1.ConnectionError || (error instanceof errors_js_1.APIError && error.status >= 500);
136
- // An answer with a code says what to do about a template that was submitted, such as to wait for
137
- // Meta. Asking again right away would only replace it with "already in progress".
138
- const safe = method === 'GET' || (idempotent && !(error instanceof errors_js_1.APIError && error.code !== undefined));
139
- if (!limited && !(safe && failed))
140
- return undefined;
141
- const retryAfter = error instanceof errors_js_1.APIError ? error.retryAfterMs : undefined;
142
- if (retryAfter !== undefined) {
143
- if (retryAfter > MAX_RETRY_AFTER_MS)
148
+ function retryDelay(error, attempt, { method, repeatAfter }) {
149
+ if (error instanceof errors_js_1.APIError) {
150
+ const again = error.status === 429 || (repeatAfter ? repeatAfter(error) : method === 'GET' && error.status >= 500);
151
+ if (!again)
144
152
  return undefined;
145
- // Up to a second more, so that callers limited together don't come back together.
146
- return Math.ceil(retryAfter + Math.random() * 1000);
153
+ if (error.retryAfterMs !== undefined)
154
+ return askedDelay(error.retryAfterMs);
155
+ }
156
+ else if (!(error instanceof errors_js_1.ConnectionError && (method === 'GET' || repeatAfter))) {
157
+ return undefined;
147
158
  }
148
159
  const backoff = Math.min(8000, 500 * 2 ** attempt);
149
160
  return Math.ceil(backoff * (0.75 + Math.random() * 0.25));
@@ -302,14 +313,17 @@ function createRequester(options) {
302
313
  return async function request(operation, options) {
303
314
  const { signal, timeoutMs, maxRetries } = options ?? {};
304
315
  checkSignal(signal);
305
- const { method } = operation;
316
+ const { method, pending } = operation;
306
317
  // For errors, which can show it.
307
318
  const requestPath = redact(operation.path);
308
319
  const timeout = timeoutMs === undefined ? defaultTimeoutMs : checkTimeout(timeoutMs);
309
320
  const retries = maxRetries === undefined ? defaultMaxRetries : checkRetries(maxRetries);
321
+ const patience = pending?.timeoutMs === undefined ? retries && DEFAULT_PENDING_TIMEOUT_MS : checkPendingTimeout(pending.timeoutMs);
310
322
  const url = baseUrl + operation.path + queryString(operation.query);
311
323
  const requestBody = operation.body && serialize(operation.body);
312
- for (let count = 0;; count++) {
324
+ // Not the time of day, which can be set back.
325
+ const until = performance.now() + patience;
326
+ for (let failures = 0;;) {
313
327
  try {
314
328
  const { status, retryAfter, text } = await attempt(operation, requestPath, url, requestBody, timeout, signal);
315
329
  if (status >= 200 && status < 300) {
@@ -326,7 +340,17 @@ function createRequester(options) {
326
340
  throw (0, errors_js_1.apiError)({ status, method, path: requestPath, body: redactBody(body), retryAfterMs: parseRetryAfter(retryAfter) });
327
341
  }
328
342
  catch (error) {
329
- const delay = count < retries ? retryDelay(error, count, operation) : undefined;
343
+ let delay;
344
+ if (error instanceof errors_js_1.APIError && error.code !== undefined && pending?.codes.includes(error.code)) {
345
+ delay = askedDelay(Math.max(error.retryAfterMs ?? PENDING_RETRY_MS, MIN_PENDING_RETRY_MS));
346
+ if (delay !== undefined && performance.now() + delay > until)
347
+ delay = undefined;
348
+ failures = 0;
349
+ }
350
+ else if (failures < retries) {
351
+ delay = retryDelay(error, failures, operation);
352
+ failures += 1;
353
+ }
330
354
  if (delay === undefined)
331
355
  throw error;
332
356
  await sleep(delay, signal);
@@ -53,7 +53,7 @@ export interface Message {
53
53
  direction: Open<MessageDirection>;
54
54
  /** The message's type, such as `text`, `image`, `audio`, `interactive` or `whatsapp_template`. */
55
55
  type: string;
56
- /** The text or caption. For other types, text that Chatwise makes of the message, such as JSON for a location or contacts. Null for WhatsApp authentication templates, so a one-time code is never returned. */
56
+ /** The text or caption. For other types, text that Chatwise makes of the message, such as JSON for a location or contacts. On Messenger, a message without a text has the title and address of what is shared in it, such as a link, also when it has a file. With neither, it has words of Chatwise's such as `Attachment sent in Messenger`. Null for WhatsApp authentication templates, so a one-time code is never returned. */
57
57
  text: string | null;
58
58
  /** When the message was sent. ISO 8601, in UTC. */
59
59
  sentAt: string;
@@ -61,7 +61,7 @@ export interface Message {
61
61
  ingestedAt: string;
62
62
  /** The message this one replies to, if any and still visible. */
63
63
  replyToMessageId: string | null;
64
- /** The message's attachments, at most 10. Always empty on Messenger and Website Chat, and for WhatsApp authentication templates. */
64
+ /** The message's attachments, at most 10. Always empty on Website Chat, for WhatsApp authentication templates, and for Messenger messages from before Chatwise kept their attachments, in December 2026. */
65
65
  attachments: {
66
66
  /** The attachment's type, such as `image`, `video`, `audio` or `document`. */
67
67
  type: string;
@@ -389,6 +389,15 @@ export type WhatsappTemplateComponent = {
389
389
  couponCode: string;
390
390
  }[];
391
391
  };
392
+ /** A file to send instead of a text. */
393
+ export interface ReplyMedia {
394
+ /** The https address of the file, which must answer without a redirect or a sign-in. */
395
+ url: string;
396
+ /** The name a document is shown with on WhatsApp, up to 120 characters. On Messenger the customer sees the letters A to Z and the digits of it, with some of Chatwise's own after them. Its ending is the document's own. Without it, the one the file's server gives. Word, Excel and PowerPoint files from before 2007 look the same inside, so their name, or the type their server gives, has to say which they are. Can't contain NUL characters or unpaired surrogates. */
397
+ fileName?: string | undefined;
398
+ /** A text shown with the file: on WhatsApp, for an image, a video or a document. At most 1,024 characters. It is refused elsewhere; send the text as a message of its own there. Can't be blank, or contain NUL characters or unpaired surrogates. */
399
+ caption?: string | undefined;
400
+ }
392
401
  /** The filters of "List conversations". */
393
402
  export interface ListConversationsParams {
394
403
  /**
@@ -435,6 +444,45 @@ export interface ListConversationMessagesParams {
435
444
  */
436
445
  order?: 'asc' | 'desc' | undefined;
437
446
  }
447
+ /** The body of "Reply in a conversation". */
448
+ export interface SendReplyParams {
449
+ /** The message. At most 4,096 characters on WhatsApp, 2,000 on Messenger, and 1,000 bytes of UTF-8 on Instagram. Send either this or `media`. Can't be blank, or contain NUL characters or unpaired surrogates. */
450
+ text?: string | undefined;
451
+ /** A file to send instead of a text. */
452
+ media?: ReplyMedia | undefined;
453
+ }
454
+ /** What "Reply in a conversation" answers. */
455
+ export interface SendReplyResult {
456
+ /** The message's id. */
457
+ id: string;
458
+ /** The conversation's id. */
459
+ conversationId: string;
460
+ /** The conversation's channel. */
461
+ channel: Open<'WHATSAPP' | 'INSTAGRAM' | 'MESSENGER'>;
462
+ /** What kind of message it is, such as `text`. */
463
+ type: string;
464
+ /** When the channel accepted it. ISO 8601, in UTC. */
465
+ sentAt: string;
466
+ }
467
+ /** What "List a message's files" answers. */
468
+ export interface MessageFile {
469
+ /** The file's id, the same each time you list it. Only when one of several Instagram files is lost before it is copied can another take its id. */
470
+ id: string;
471
+ /** What kind of file it is. */
472
+ type: Open<'image' | 'video' | 'audio' | 'document'>;
473
+ /** `available`, `pending` while Chatwise is still copying it, or `unavailable` when it couldn't be copied, isn't copied after 15 minutes, or is gone. */
474
+ status: Open<'available' | 'pending' | 'unavailable'>;
475
+ /** The name it was sent with, if Chatwise has it. */
476
+ name: string | null;
477
+ /** Its MIME type. Types a browser could run, such as HTML and SVG, are downloaded as `application/octet-stream`. Null unless it is available. */
478
+ mimeType: string | null;
479
+ /** Its size in bytes. Null unless it is available. */
480
+ size: number | null;
481
+ /** Where to download it, without an API key, until `urlExpiresAt`. Null unless it is available. */
482
+ url: string | null;
483
+ /** When the link stops working. ISO 8601, in UTC. Null unless it is available. */
484
+ urlExpiresAt: string | null;
485
+ }
438
486
  /** The filters of "List or search messages". */
439
487
  export interface ListMessagesParams {
440
488
  /**
@@ -1,15 +1,15 @@
1
1
  export { Chatwise } from './client.js';
2
2
  export type { AbortSignalLike, ChatwiseOptions, FetchLike, RequestOptions, ResponseLike } from './core/http.js';
3
3
  export type { Page, PagePromise } from './core/pagination.js';
4
- export { APIError, AuthenticationError, BadRequestError, ChatwiseError, ConflictError, ConnectionError, NotFoundError, PayloadTooLargeError, PaymentRequiredError, PermissionDeniedError, RateLimitError, RequestAbortedError, RequestTimeoutError, ServerError, } from './core/errors.js';
4
+ export { APIError, AuthenticationError, BadRequestError, ChatwiseError, ConflictError, ConnectionError, NotFoundError, PayloadTooLargeError, PaymentRequiredError, PermissionDeniedError, RateLimitError, RequestAbortedError, RequestTimeoutError, ServerError, UnprocessableEntityError, } from './core/errors.js';
5
5
  export type { APIErrorDetails, FieldError } from './core/errors.js';
6
6
  export { verifyWebhook, WebhookVerificationError } from './webhooks.js';
7
7
  export type { UnknownWebhookEvent, UnknownWebhookEventType, VerifyWebhookOptions, WebhookEvent, WebhookHeaders, WebhookVerificationErrorCode } from './webhooks.js';
8
8
  export { VERSION } from './version.js';
9
9
  export type { Conversations } from './resources/conversations.js';
10
- export type { Messages, SendMessageParams } from './resources/messages.js';
10
+ export type { Messages, SendMessageParams, SendReplyOptions, SendReplyParams } from './resources/messages.js';
11
11
  export type { WebhookDeliveries } from './resources/webhook-deliveries.js';
12
12
  export type { WebhookEndpoints } from './resources/webhook-endpoints.js';
13
13
  export type { WebhookEventTypes } from './resources/webhook-event-types.js';
14
14
  export type { CreateWhatsappTemplateOptions, WhatsappTemplates } from './resources/whatsapp-templates.js';
15
- export type { Channel, CommentReceivedEvent, CommentReceivedEventData, Conversation, ConversationStatus, CreateWebhookEndpointParams, CreateWhatsappTemplateParams, DeleteWebhookEndpointResult, KnownWebhookEvent, KnownWebhookEventType, ListConversationMessagesParams, ListConversationsParams, ListMessagesParams, ListWebhookDeliveriesParams, ListWhatsappTemplatesParams, Message, MessageDeliveredEvent, MessageDirection, MessageEventData, MessageFailedEvent, MessageFailedEventData, MessageReadEvent, MessageReceivedEvent, MessageSentEvent, Open, RotateWebhookSecretResult, SendMessageResult, SendWhatsappTemplateParams, SendWhatsappTemplateResult, TestWebhookEndpointResult, UpdateWebhookEndpointParams, WebhookDelivery, WebhookDeliveryDetails, WebhookDeliveryStatus, WebhookEndpoint, WebhookEndpointStatus, WebhookEndpointWithSecret, WebhookEventType, WebhookEventTypeInfo, WebhookTestEvent, WebhookTestEventData, WhatsappTemplate, WhatsappTemplateCategory, WhatsappTemplateComponent, WhatsappTemplateParam, } from './generated/types.js';
15
+ export type { Channel, CommentReceivedEvent, CommentReceivedEventData, Conversation, ConversationStatus, CreateWebhookEndpointParams, CreateWhatsappTemplateParams, DeleteWebhookEndpointResult, KnownWebhookEvent, KnownWebhookEventType, ListConversationMessagesParams, ListConversationsParams, ListMessagesParams, ListWebhookDeliveriesParams, ListWhatsappTemplatesParams, Message, MessageDeliveredEvent, MessageDirection, MessageEventData, MessageFailedEvent, MessageFailedEventData, MessageFile, MessageReadEvent, MessageReceivedEvent, MessageSentEvent, Open, ReplyMedia, RotateWebhookSecretResult, SendMessageResult, SendReplyResult, SendWhatsappTemplateParams, SendWhatsappTemplateResult, TestWebhookEndpointResult, UpdateWebhookEndpointParams, WebhookDelivery, WebhookDeliveryDetails, WebhookDeliveryStatus, WebhookEndpoint, WebhookEndpointStatus, WebhookEndpointWithSecret, WebhookEventType, WebhookEventTypeInfo, WebhookTestEvent, WebhookTestEventData, WhatsappTemplate, WhatsappTemplateCategory, WhatsappTemplateComponent, WhatsappTemplateParam, } from './generated/types.js';
package/dist/cjs/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.VERSION = exports.WebhookVerificationError = exports.verifyWebhook = exports.ServerError = exports.RequestTimeoutError = exports.RequestAbortedError = exports.RateLimitError = exports.PermissionDeniedError = exports.PaymentRequiredError = exports.PayloadTooLargeError = exports.NotFoundError = exports.ConnectionError = exports.ConflictError = exports.ChatwiseError = exports.BadRequestError = exports.AuthenticationError = exports.APIError = exports.Chatwise = void 0;
3
+ exports.VERSION = exports.WebhookVerificationError = exports.verifyWebhook = exports.UnprocessableEntityError = exports.ServerError = exports.RequestTimeoutError = exports.RequestAbortedError = exports.RateLimitError = exports.PermissionDeniedError = exports.PaymentRequiredError = exports.PayloadTooLargeError = exports.NotFoundError = exports.ConnectionError = exports.ConflictError = exports.ChatwiseError = exports.BadRequestError = exports.AuthenticationError = exports.APIError = exports.Chatwise = void 0;
4
4
  var client_js_1 = require("./client.js");
5
5
  Object.defineProperty(exports, "Chatwise", { enumerable: true, get: function () { return client_js_1.Chatwise; } });
6
6
  var errors_js_1 = require("./core/errors.js");
@@ -18,6 +18,7 @@ Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: functi
18
18
  Object.defineProperty(exports, "RequestAbortedError", { enumerable: true, get: function () { return errors_js_1.RequestAbortedError; } });
19
19
  Object.defineProperty(exports, "RequestTimeoutError", { enumerable: true, get: function () { return errors_js_1.RequestTimeoutError; } });
20
20
  Object.defineProperty(exports, "ServerError", { enumerable: true, get: function () { return errors_js_1.ServerError; } });
21
+ Object.defineProperty(exports, "UnprocessableEntityError", { enumerable: true, get: function () { return errors_js_1.UnprocessableEntityError; } });
21
22
  var webhooks_js_1 = require("./webhooks.js");
22
23
  Object.defineProperty(exports, "verifyWebhook", { enumerable: true, get: function () { return webhooks_js_1.verifyWebhook; } });
23
24
  Object.defineProperty(exports, "WebhookVerificationError", { enumerable: true, get: function () { return webhooks_js_1.WebhookVerificationError; } });
@@ -1,6 +1,6 @@
1
1
  import { type RequestOptions } from '../core/http.js';
2
2
  import { type PagePromise } from '../core/pagination.js';
3
- import type { ListConversationMessagesParams, ListMessagesParams, Message, SendMessageParams as SendMessageBody, SendMessageResult } from '../generated/types.js';
3
+ import type { ListConversationMessagesParams, ListMessagesParams, Message, MessageFile, ReplyMedia, SendMessageParams as SendMessageBody, SendMessageResult, SendReplyParams as SendReplyBody, SendReplyResult } from '../generated/types.js';
4
4
  /** A template to send by id, and its values. */
5
5
  export type SendMessageParams = Omit<SendMessageBody, 'channel' | 'templateId'> & {
6
6
  /** The template's `id`. */
@@ -11,6 +11,32 @@ export type SendMessageParams = Omit<SendMessageBody, 'channel' | 'templateId'>
11
11
  */
12
12
  channel?: 'WHATSAPP' | undefined;
13
13
  };
14
+ /** What to reply: a text, or a file. Not both, because a reply is one message. */
15
+ export type SendReplyParams = Omit<SendReplyBody, 'text' | 'media'> & ({
16
+ /** The message. At most 4,096 characters on WhatsApp, 2,000 on Messenger, and 1,000 bytes of UTF-8 on Instagram. */
17
+ text: string;
18
+ media?: undefined;
19
+ } | {
20
+ /** A file to send, which Chatwise downloads from its address. On WhatsApp, Instagram and Messenger. */
21
+ media: ReplyMedia;
22
+ text?: undefined;
23
+ });
24
+ export interface SendReplyOptions extends RequestOptions {
25
+ /**
26
+ * A key you choose for this message, 8 to 128 letters, digits, dots, underscores, hyphens or colons. A new
27
+ * one for each message, and the same one, with the same conversation, content and API key, when you repeat
28
+ * the call: for 30 days a repeat doesn't send the message again. Make it from what you answer, such as an
29
+ * event's id. With another API key the same call sends another message.
30
+ */
31
+ idempotencyKey: string;
32
+ /**
33
+ * How long to wait for a file that takes longer to prepare, in milliseconds. A request answered
34
+ * `MEDIA_PROCESSING` or `MEDIA_BUSY` is repeated as `Retry-After` says, if that is within this time after
35
+ * the call began. These don't count as retries, which start again from 0 after each.
36
+ * @defaultValue 600000, or 0 with `maxRetries: 0`
37
+ */
38
+ mediaTimeoutMs?: number | undefined;
39
+ }
14
40
  /** Messages on every channel. */
15
41
  export declare class Messages {
16
42
  #private;
@@ -32,6 +58,38 @@ export declare class Messages {
32
58
  * Scope: `messages:read`.
33
59
  */
34
60
  get(conversationId: string, messageId: string, options?: RequestOptions): Promise<Message>;
61
+ /**
62
+ * Lists a message's files, at most 20. One that is `available` has a `url` that works for 5 minutes,
63
+ * without an API key: don't send yours with it. List the files again for a new one.
64
+ *
65
+ * On WhatsApp, Instagram and Messenger. A file on Instagram or Messenger can be `pending` for a moment
66
+ * after the message arrives, and a story that a message replies to or mentions the account in isn't
67
+ * listed until it is copied.
68
+ *
69
+ * Scope: `messages:read`.
70
+ */
71
+ listFiles(conversationId: string, messageId: string, options?: RequestOptions): Promise<MessageFile[]>;
72
+ /**
73
+ * Replies in a WhatsApp, Instagram or Messenger conversation, with a text or a file. The answer means the
74
+ * channel accepted the message, not that it was delivered.
75
+ *
76
+ * The route recognizes a repeat by `idempotencyKey`, so this is retried like a read, and after
77
+ * `SEND_IN_PROGRESS`. If it still fails with one of these, with no answer, or with `MEDIA_PROCESSING`,
78
+ * `MEDIA_DOWNLOAD_FAILED` or `Invalid API key`, call it again later, with the same key, content and API
79
+ * key. Any other 4xx comes back until you fix what it names. A video on Messenger can take longer to send
80
+ * than the retries last: after `SEND_IN_PROGRESS`, call again within a minute, or you can miss that it was
81
+ * refused, and send it again.
82
+ *
83
+ * After `SEND_OUTCOME_UNKNOWN` a repeat sends nothing. The message may have been sent, also if the
84
+ * conversation doesn't show it, so let a person decide whether to send it again with a new key.
85
+ *
86
+ * An error is about the last request. If an earlier one got no answer, 401, 403, 404 and 429 don't say
87
+ * that nothing was sent, and with a file no error does while that one is still running. So don't go on with
88
+ * another `idempotencyKey` or API key.
89
+ *
90
+ * Scope: `messages:reply`.
91
+ */
92
+ reply(conversationId: string, params: SendReplyParams, options: SendReplyOptions): Promise<SendReplyResult>;
35
93
  /**
36
94
  * Sends an approved WhatsApp template by its id. The answer means WhatsApp accepted the message, not
37
95
  * that it was delivered. To send one by its name, use `whatsappTemplates.send`.
@@ -36,6 +36,58 @@ class Messages {
36
36
  const { data } = await this.#request({ method: 'GET', path: (0, http_js_1.path) `/v1/conversations/${conversationId}/messages/${messageId}` }, options);
37
37
  return data;
38
38
  }
39
+ /**
40
+ * Lists a message's files, at most 20. One that is `available` has a `url` that works for 5 minutes,
41
+ * without an API key: don't send yours with it. List the files again for a new one.
42
+ *
43
+ * On WhatsApp, Instagram and Messenger. A file on Instagram or Messenger can be `pending` for a moment
44
+ * after the message arrives, and a story that a message replies to or mentions the account in isn't
45
+ * listed until it is copied.
46
+ *
47
+ * Scope: `messages:read`.
48
+ */
49
+ async listFiles(conversationId, messageId, options) {
50
+ const { data } = await this.#request({ method: 'GET', path: (0, http_js_1.path) `/v1/conversations/${conversationId}/messages/${messageId}/files` }, options);
51
+ return data;
52
+ }
53
+ /**
54
+ * Replies in a WhatsApp, Instagram or Messenger conversation, with a text or a file. The answer means the
55
+ * channel accepted the message, not that it was delivered.
56
+ *
57
+ * The route recognizes a repeat by `idempotencyKey`, so this is retried like a read, and after
58
+ * `SEND_IN_PROGRESS`. If it still fails with one of these, with no answer, or with `MEDIA_PROCESSING`,
59
+ * `MEDIA_DOWNLOAD_FAILED` or `Invalid API key`, call it again later, with the same key, content and API
60
+ * key. Any other 4xx comes back until you fix what it names. A video on Messenger can take longer to send
61
+ * than the retries last: after `SEND_IN_PROGRESS`, call again within a minute, or you can miss that it was
62
+ * refused, and send it again.
63
+ *
64
+ * After `SEND_OUTCOME_UNKNOWN` a repeat sends nothing. The message may have been sent, also if the
65
+ * conversation doesn't show it, so let a person decide whether to send it again with a new key.
66
+ *
67
+ * An error is about the last request. If an earlier one got no answer, 401, 403, 404 and 429 don't say
68
+ * that nothing was sent, and with a file no error does while that one is still running. So don't go on with
69
+ * another `idempotencyKey` or API key.
70
+ *
71
+ * Scope: `messages:reply`.
72
+ */
73
+ async reply(conversationId, params, options) {
74
+ const { idempotencyKey, mediaTimeoutMs, ...rest } = options ?? {};
75
+ // Without one the header would be "undefined", which is a key the API takes, and the same for every reply.
76
+ // Other characters can't be in a header. The rest is for the API to check.
77
+ if (typeof idempotencyKey !== 'string' || !/^[\x21-\x7e]+$/.test(idempotencyKey)) {
78
+ throw new errors_js_1.ChatwiseError('messages.reply needs an idempotencyKey: 8 to 128 letters, digits, dots, underscores, hyphens or colons.');
79
+ }
80
+ const { data } = await this.#request({
81
+ method: 'POST',
82
+ path: (0, http_js_1.path) `/v1/conversations/${conversationId}/messages`,
83
+ body: params,
84
+ headers: { 'Idempotency-Key': idempotencyKey },
85
+ // Not after SEND_OUTCOME_UNKNOWN, which a repeat only answers again.
86
+ repeatAfter: ({ status, code }) => (status >= 500 ? code !== 'SEND_OUTCOME_UNKNOWN' : status === 409 && code === 'SEND_IN_PROGRESS'),
87
+ pending: { codes: ['MEDIA_PROCESSING', 'MEDIA_BUSY'], timeoutMs: mediaTimeoutMs },
88
+ }, rest);
89
+ return data;
90
+ }
39
91
  /**
40
92
  * Sends an approved WhatsApp template by its id. The answer means WhatsApp accepted the message, not
41
93
  * that it was delivered. To send one by its name, use `whatsappTemplates.send`.
@@ -47,7 +47,9 @@ class WhatsappTemplates {
47
47
  path: '/v1/whatsapp/templates',
48
48
  body: params,
49
49
  headers: idempotencyKey === undefined ? undefined : { 'Idempotency-Key': idempotencyKey },
50
- idempotent: true,
50
+ // An answer with a code says what to do about a template that was submitted, such as to wait for
51
+ // Meta. Asking again right away would only replace it with "already in progress".
52
+ repeatAfter: ({ status, code }) => status >= 500 && code === undefined,
51
53
  }, rest);
52
54
  return data;
53
55
  }
@@ -1,2 +1,2 @@
1
1
  /** The version of this package. A test keeps it equal to package.json's. */
2
- export declare const VERSION = "0.1.0";
2
+ export declare const VERSION = "0.1.1";
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
4
  /** The version of this package. A test keeps it equal to package.json's. */
5
- exports.VERSION = '0.1.0';
5
+ exports.VERSION = '0.1.1';
@@ -48,11 +48,14 @@ export declare class BadRequestError extends APIError {
48
48
  export declare class AuthenticationError extends APIError {
49
49
  name: string;
50
50
  }
51
- /** 402: sending is paused for the workspace. */
51
+ /** 402: sending is paused for the workspace, or its subscription needs attention. */
52
52
  export declare class PaymentRequiredError extends APIError {
53
53
  name: string;
54
54
  }
55
- /** 403: the key lacks a scope, or WhatsApp has to be reconnected (`code` is `WHATSAPP_REAUTH_REQUIRED`). */
55
+ /**
56
+ * 403: the key lacks a scope, WhatsApp has to be reconnected (`code` is `WHATSAPP_REAUTH_REQUIRED`), or the
57
+ * person who created the key may not send replies any more (`SEND_NOT_PERMITTED`).
58
+ */
56
59
  export declare class PermissionDeniedError extends APIError {
57
60
  name: string;
58
61
  }
@@ -60,7 +63,7 @@ export declare class PermissionDeniedError extends APIError {
60
63
  export declare class NotFoundError extends APIError {
61
64
  name: string;
62
65
  }
63
- /** 409: a template submission conflicts with an earlier one. `code` says how. */
66
+ /** 409: it conflicts with an earlier request, or with how things are now. `code` says how, such as `REPLY_WINDOW_CLOSED`. */
64
67
  export declare class ConflictError extends APIError {
65
68
  name: string;
66
69
  }
@@ -68,11 +71,18 @@ export declare class ConflictError extends APIError {
68
71
  export declare class PayloadTooLargeError extends APIError {
69
72
  name: string;
70
73
  }
71
- /** 429: too many requests with this key. Wait `retryAfterMs`. */
74
+ /** 422: the channel refused a reply, or its file can't be downloaded or sent. `code` says which. This request sent nothing. */
75
+ export declare class UnprocessableEntityError extends APIError {
76
+ name: string;
77
+ }
78
+ /** 429: too many requests with this key, or too many replies or files. Wait `retryAfterMs`. */
72
79
  export declare class RateLimitError extends APIError {
73
80
  name: string;
74
81
  }
75
- /** 5xx: something failed in Chatwise, or WhatsApp refused a message. The request may have been carried out. */
82
+ /**
83
+ * 5xx: something failed or is busy in Chatwise or at the channel, or WhatsApp refused a template. The request
84
+ * may have been carried out. `SEND_OUTCOME_UNKNOWN` is one, and it must not be sent again with a new key by itself.
85
+ */
76
86
  export declare class ServerError extends APIError {
77
87
  name: string;
78
88
  }
@@ -58,11 +58,14 @@ export class BadRequestError extends APIError {
58
58
  export class AuthenticationError extends APIError {
59
59
  name = 'AuthenticationError';
60
60
  }
61
- /** 402: sending is paused for the workspace. */
61
+ /** 402: sending is paused for the workspace, or its subscription needs attention. */
62
62
  export class PaymentRequiredError extends APIError {
63
63
  name = 'PaymentRequiredError';
64
64
  }
65
- /** 403: the key lacks a scope, or WhatsApp has to be reconnected (`code` is `WHATSAPP_REAUTH_REQUIRED`). */
65
+ /**
66
+ * 403: the key lacks a scope, WhatsApp has to be reconnected (`code` is `WHATSAPP_REAUTH_REQUIRED`), or the
67
+ * person who created the key may not send replies any more (`SEND_NOT_PERMITTED`).
68
+ */
66
69
  export class PermissionDeniedError extends APIError {
67
70
  name = 'PermissionDeniedError';
68
71
  }
@@ -70,7 +73,7 @@ export class PermissionDeniedError extends APIError {
70
73
  export class NotFoundError extends APIError {
71
74
  name = 'NotFoundError';
72
75
  }
73
- /** 409: a template submission conflicts with an earlier one. `code` says how. */
76
+ /** 409: it conflicts with an earlier request, or with how things are now. `code` says how, such as `REPLY_WINDOW_CLOSED`. */
74
77
  export class ConflictError extends APIError {
75
78
  name = 'ConflictError';
76
79
  }
@@ -78,11 +81,18 @@ export class ConflictError extends APIError {
78
81
  export class PayloadTooLargeError extends APIError {
79
82
  name = 'PayloadTooLargeError';
80
83
  }
81
- /** 429: too many requests with this key. Wait `retryAfterMs`. */
84
+ /** 422: the channel refused a reply, or its file can't be downloaded or sent. `code` says which. This request sent nothing. */
85
+ export class UnprocessableEntityError extends APIError {
86
+ name = 'UnprocessableEntityError';
87
+ }
88
+ /** 429: too many requests with this key, or too many replies or files. Wait `retryAfterMs`. */
82
89
  export class RateLimitError extends APIError {
83
90
  name = 'RateLimitError';
84
91
  }
85
- /** 5xx: something failed in Chatwise, or WhatsApp refused a message. The request may have been carried out. */
92
+ /**
93
+ * 5xx: something failed or is busy in Chatwise or at the channel, or WhatsApp refused a template. The request
94
+ * may have been carried out. `SEND_OUTCOME_UNKNOWN` is one, and it must not be sent again with a new key by itself.
95
+ */
86
96
  export class ServerError extends APIError {
87
97
  name = 'ServerError';
88
98
  }
@@ -107,6 +117,7 @@ export function apiError(details) {
107
117
  case 404: return new NotFoundError(details);
108
118
  case 409: return new ConflictError(details);
109
119
  case 413: return new PayloadTooLargeError(details);
120
+ case 422: return new UnprocessableEntityError(details);
110
121
  case 429: return new RateLimitError(details);
111
122
  default: return details.status >= 500 ? new ServerError(details) : new APIError(details);
112
123
  }
@@ -1,3 +1,4 @@
1
+ import { APIError } from './errors.js';
1
2
  /** An `AbortSignal`. */
2
3
  export interface AbortSignalLike {
3
4
  readonly aborted: boolean;
@@ -37,8 +38,8 @@ export interface ChatwiseOptions {
37
38
  */
38
39
  timeoutMs?: number | undefined;
39
40
  /**
40
- * How many times to retry what is safe to retry: reads, and creating a template, after a 429, a 5xx or
41
- * a network error; anything else only after a 429, because such a request wasn't carried out.
41
+ * How many times to retry what is safe to retry: reads, replies and creating a template after a 429, a
42
+ * 5xx or a network error; anything else only after a 429, because such a request wasn't carried out.
42
43
  * @defaultValue 2
43
44
  */
44
45
  maxRetries?: number | undefined;
@@ -60,8 +61,20 @@ export interface Operation {
60
61
  query?: object | undefined;
61
62
  body?: object | undefined;
62
63
  headers?: Record<string, string> | undefined;
63
- /** The route takes an idempotency key, so repeating it can't do it twice. */
64
- idempotent?: boolean;
64
+ /**
65
+ * The route recognizes a repeat, so a request that may have been carried out can be repeated. Says which
66
+ * answers it is repeated after, besides a 429.
67
+ */
68
+ repeatAfter?: (answer: APIError) => boolean;
69
+ /**
70
+ * Codes of answers that say to repeat the request until something is ready, and for how long to. These
71
+ * don't count as retries, and the count starts again after each. Without a time it is a default, or none if
72
+ * the call has no retries.
73
+ */
74
+ pending?: {
75
+ codes: readonly string[];
76
+ timeoutMs: number | undefined;
77
+ };
65
78
  }
66
79
  /** Makes a request and returns the body of its answer. */
67
80
  export type Requester = (operation: Operation, options?: RequestOptions) => Promise<Record<string, unknown>>;
@@ -3,6 +3,10 @@ import { apiError, APIError, ChatwiseError, ConnectionError, RequestAbortedError
3
3
  const DEFAULT_BASE_URL = 'https://api.chatwise.so';
4
4
  const DEFAULT_TIMEOUT_MS = 60_000;
5
5
  const DEFAULT_MAX_RETRIES = 2;
6
+ const DEFAULT_PENDING_TIMEOUT_MS = 600_000;
7
+ /** How long to wait before asking again for what isn't ready, if the answer doesn't say, and at least. */
8
+ const PENDING_RETRY_MS = 10_000;
9
+ const MIN_PENDING_RETRY_MS = 1000;
6
10
  /** The longest wait setTimeout can hold. A longer one would end at once. */
7
11
  const MAX_TIMEOUT_MS = 2_147_483_647;
8
12
  /** Chatwise asks for 60 seconds. A call doesn't wait for much longer than that: it fails instead. */
@@ -17,6 +21,12 @@ function checkTimeout(value) {
17
21
  }
18
22
  return value;
19
23
  }
24
+ function checkPendingTimeout(value) {
25
+ if (!Number.isInteger(value) || value < 0 || value > MAX_TIMEOUT_MS) {
26
+ throw new ChatwiseError(`mediaTimeoutMs must be a whole number of milliseconds from 0 to ${MAX_TIMEOUT_MS}.`);
27
+ }
28
+ return value;
29
+ }
20
30
  function checkRetries(value) {
21
31
  if (!Number.isInteger(value) || value < 0 || value > 10) {
22
32
  throw new ChatwiseError('maxRetries must be a whole number from 0 to 10.');
@@ -125,21 +135,22 @@ function parseRetryAfter(value) {
125
135
  const date = /\bGMT$/.test(text) ? Date.parse(text) : NaN;
126
136
  return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
127
137
  }
138
+ /** The wait an answer asks for, or undefined if it is too long to wait for. */
139
+ function askedDelay(retryAfterMs) {
140
+ // Up to a second more, so that callers limited together don't come back together.
141
+ return retryAfterMs > MAX_RETRY_AFTER_MS ? undefined : Math.ceil(retryAfterMs + Math.random() * 1000);
142
+ }
128
143
  /** How long to wait before retrying after `error`, or undefined not to retry. `attempt` counts from 0. */
129
- function retryDelay(error, attempt, { method, idempotent = false }) {
130
- const limited = error instanceof APIError && error.status === 429;
131
- const failed = error instanceof ConnectionError || (error instanceof APIError && error.status >= 500);
132
- // An answer with a code says what to do about a template that was submitted, such as to wait for
133
- // Meta. Asking again right away would only replace it with "already in progress".
134
- const safe = method === 'GET' || (idempotent && !(error instanceof APIError && error.code !== undefined));
135
- if (!limited && !(safe && failed))
136
- return undefined;
137
- const retryAfter = error instanceof APIError ? error.retryAfterMs : undefined;
138
- if (retryAfter !== undefined) {
139
- if (retryAfter > MAX_RETRY_AFTER_MS)
144
+ function retryDelay(error, attempt, { method, repeatAfter }) {
145
+ if (error instanceof APIError) {
146
+ const again = error.status === 429 || (repeatAfter ? repeatAfter(error) : method === 'GET' && error.status >= 500);
147
+ if (!again)
140
148
  return undefined;
141
- // Up to a second more, so that callers limited together don't come back together.
142
- return Math.ceil(retryAfter + Math.random() * 1000);
149
+ if (error.retryAfterMs !== undefined)
150
+ return askedDelay(error.retryAfterMs);
151
+ }
152
+ else if (!(error instanceof ConnectionError && (method === 'GET' || repeatAfter))) {
153
+ return undefined;
143
154
  }
144
155
  const backoff = Math.min(8000, 500 * 2 ** attempt);
145
156
  return Math.ceil(backoff * (0.75 + Math.random() * 0.25));
@@ -298,14 +309,17 @@ export function createRequester(options) {
298
309
  return async function request(operation, options) {
299
310
  const { signal, timeoutMs, maxRetries } = options ?? {};
300
311
  checkSignal(signal);
301
- const { method } = operation;
312
+ const { method, pending } = operation;
302
313
  // For errors, which can show it.
303
314
  const requestPath = redact(operation.path);
304
315
  const timeout = timeoutMs === undefined ? defaultTimeoutMs : checkTimeout(timeoutMs);
305
316
  const retries = maxRetries === undefined ? defaultMaxRetries : checkRetries(maxRetries);
317
+ const patience = pending?.timeoutMs === undefined ? retries && DEFAULT_PENDING_TIMEOUT_MS : checkPendingTimeout(pending.timeoutMs);
306
318
  const url = baseUrl + operation.path + queryString(operation.query);
307
319
  const requestBody = operation.body && serialize(operation.body);
308
- for (let count = 0;; count++) {
320
+ // Not the time of day, which can be set back.
321
+ const until = performance.now() + patience;
322
+ for (let failures = 0;;) {
309
323
  try {
310
324
  const { status, retryAfter, text } = await attempt(operation, requestPath, url, requestBody, timeout, signal);
311
325
  if (status >= 200 && status < 300) {
@@ -322,7 +336,17 @@ export function createRequester(options) {
322
336
  throw apiError({ status, method, path: requestPath, body: redactBody(body), retryAfterMs: parseRetryAfter(retryAfter) });
323
337
  }
324
338
  catch (error) {
325
- const delay = count < retries ? retryDelay(error, count, operation) : undefined;
339
+ let delay;
340
+ if (error instanceof APIError && error.code !== undefined && pending?.codes.includes(error.code)) {
341
+ delay = askedDelay(Math.max(error.retryAfterMs ?? PENDING_RETRY_MS, MIN_PENDING_RETRY_MS));
342
+ if (delay !== undefined && performance.now() + delay > until)
343
+ delay = undefined;
344
+ failures = 0;
345
+ }
346
+ else if (failures < retries) {
347
+ delay = retryDelay(error, failures, operation);
348
+ failures += 1;
349
+ }
326
350
  if (delay === undefined)
327
351
  throw error;
328
352
  await sleep(delay, signal);
@@ -53,7 +53,7 @@ export interface Message {
53
53
  direction: Open<MessageDirection>;
54
54
  /** The message's type, such as `text`, `image`, `audio`, `interactive` or `whatsapp_template`. */
55
55
  type: string;
56
- /** The text or caption. For other types, text that Chatwise makes of the message, such as JSON for a location or contacts. Null for WhatsApp authentication templates, so a one-time code is never returned. */
56
+ /** The text or caption. For other types, text that Chatwise makes of the message, such as JSON for a location or contacts. On Messenger, a message without a text has the title and address of what is shared in it, such as a link, also when it has a file. With neither, it has words of Chatwise's such as `Attachment sent in Messenger`. Null for WhatsApp authentication templates, so a one-time code is never returned. */
57
57
  text: string | null;
58
58
  /** When the message was sent. ISO 8601, in UTC. */
59
59
  sentAt: string;
@@ -61,7 +61,7 @@ export interface Message {
61
61
  ingestedAt: string;
62
62
  /** The message this one replies to, if any and still visible. */
63
63
  replyToMessageId: string | null;
64
- /** The message's attachments, at most 10. Always empty on Messenger and Website Chat, and for WhatsApp authentication templates. */
64
+ /** The message's attachments, at most 10. Always empty on Website Chat, for WhatsApp authentication templates, and for Messenger messages from before Chatwise kept their attachments, in December 2026. */
65
65
  attachments: {
66
66
  /** The attachment's type, such as `image`, `video`, `audio` or `document`. */
67
67
  type: string;
@@ -389,6 +389,15 @@ export type WhatsappTemplateComponent = {
389
389
  couponCode: string;
390
390
  }[];
391
391
  };
392
+ /** A file to send instead of a text. */
393
+ export interface ReplyMedia {
394
+ /** The https address of the file, which must answer without a redirect or a sign-in. */
395
+ url: string;
396
+ /** The name a document is shown with on WhatsApp, up to 120 characters. On Messenger the customer sees the letters A to Z and the digits of it, with some of Chatwise's own after them. Its ending is the document's own. Without it, the one the file's server gives. Word, Excel and PowerPoint files from before 2007 look the same inside, so their name, or the type their server gives, has to say which they are. Can't contain NUL characters or unpaired surrogates. */
397
+ fileName?: string | undefined;
398
+ /** A text shown with the file: on WhatsApp, for an image, a video or a document. At most 1,024 characters. It is refused elsewhere; send the text as a message of its own there. Can't be blank, or contain NUL characters or unpaired surrogates. */
399
+ caption?: string | undefined;
400
+ }
392
401
  /** The filters of "List conversations". */
393
402
  export interface ListConversationsParams {
394
403
  /**
@@ -435,6 +444,45 @@ export interface ListConversationMessagesParams {
435
444
  */
436
445
  order?: 'asc' | 'desc' | undefined;
437
446
  }
447
+ /** The body of "Reply in a conversation". */
448
+ export interface SendReplyParams {
449
+ /** The message. At most 4,096 characters on WhatsApp, 2,000 on Messenger, and 1,000 bytes of UTF-8 on Instagram. Send either this or `media`. Can't be blank, or contain NUL characters or unpaired surrogates. */
450
+ text?: string | undefined;
451
+ /** A file to send instead of a text. */
452
+ media?: ReplyMedia | undefined;
453
+ }
454
+ /** What "Reply in a conversation" answers. */
455
+ export interface SendReplyResult {
456
+ /** The message's id. */
457
+ id: string;
458
+ /** The conversation's id. */
459
+ conversationId: string;
460
+ /** The conversation's channel. */
461
+ channel: Open<'WHATSAPP' | 'INSTAGRAM' | 'MESSENGER'>;
462
+ /** What kind of message it is, such as `text`. */
463
+ type: string;
464
+ /** When the channel accepted it. ISO 8601, in UTC. */
465
+ sentAt: string;
466
+ }
467
+ /** What "List a message's files" answers. */
468
+ export interface MessageFile {
469
+ /** The file's id, the same each time you list it. Only when one of several Instagram files is lost before it is copied can another take its id. */
470
+ id: string;
471
+ /** What kind of file it is. */
472
+ type: Open<'image' | 'video' | 'audio' | 'document'>;
473
+ /** `available`, `pending` while Chatwise is still copying it, or `unavailable` when it couldn't be copied, isn't copied after 15 minutes, or is gone. */
474
+ status: Open<'available' | 'pending' | 'unavailable'>;
475
+ /** The name it was sent with, if Chatwise has it. */
476
+ name: string | null;
477
+ /** Its MIME type. Types a browser could run, such as HTML and SVG, are downloaded as `application/octet-stream`. Null unless it is available. */
478
+ mimeType: string | null;
479
+ /** Its size in bytes. Null unless it is available. */
480
+ size: number | null;
481
+ /** Where to download it, without an API key, until `urlExpiresAt`. Null unless it is available. */
482
+ url: string | null;
483
+ /** When the link stops working. ISO 8601, in UTC. Null unless it is available. */
484
+ urlExpiresAt: string | null;
485
+ }
438
486
  /** The filters of "List or search messages". */
439
487
  export interface ListMessagesParams {
440
488
  /**
@@ -1,15 +1,15 @@
1
1
  export { Chatwise } from './client.js';
2
2
  export type { AbortSignalLike, ChatwiseOptions, FetchLike, RequestOptions, ResponseLike } from './core/http.js';
3
3
  export type { Page, PagePromise } from './core/pagination.js';
4
- export { APIError, AuthenticationError, BadRequestError, ChatwiseError, ConflictError, ConnectionError, NotFoundError, PayloadTooLargeError, PaymentRequiredError, PermissionDeniedError, RateLimitError, RequestAbortedError, RequestTimeoutError, ServerError, } from './core/errors.js';
4
+ export { APIError, AuthenticationError, BadRequestError, ChatwiseError, ConflictError, ConnectionError, NotFoundError, PayloadTooLargeError, PaymentRequiredError, PermissionDeniedError, RateLimitError, RequestAbortedError, RequestTimeoutError, ServerError, UnprocessableEntityError, } from './core/errors.js';
5
5
  export type { APIErrorDetails, FieldError } from './core/errors.js';
6
6
  export { verifyWebhook, WebhookVerificationError } from './webhooks.js';
7
7
  export type { UnknownWebhookEvent, UnknownWebhookEventType, VerifyWebhookOptions, WebhookEvent, WebhookHeaders, WebhookVerificationErrorCode } from './webhooks.js';
8
8
  export { VERSION } from './version.js';
9
9
  export type { Conversations } from './resources/conversations.js';
10
- export type { Messages, SendMessageParams } from './resources/messages.js';
10
+ export type { Messages, SendMessageParams, SendReplyOptions, SendReplyParams } from './resources/messages.js';
11
11
  export type { WebhookDeliveries } from './resources/webhook-deliveries.js';
12
12
  export type { WebhookEndpoints } from './resources/webhook-endpoints.js';
13
13
  export type { WebhookEventTypes } from './resources/webhook-event-types.js';
14
14
  export type { CreateWhatsappTemplateOptions, WhatsappTemplates } from './resources/whatsapp-templates.js';
15
- export type { Channel, CommentReceivedEvent, CommentReceivedEventData, Conversation, ConversationStatus, CreateWebhookEndpointParams, CreateWhatsappTemplateParams, DeleteWebhookEndpointResult, KnownWebhookEvent, KnownWebhookEventType, ListConversationMessagesParams, ListConversationsParams, ListMessagesParams, ListWebhookDeliveriesParams, ListWhatsappTemplatesParams, Message, MessageDeliveredEvent, MessageDirection, MessageEventData, MessageFailedEvent, MessageFailedEventData, MessageReadEvent, MessageReceivedEvent, MessageSentEvent, Open, RotateWebhookSecretResult, SendMessageResult, SendWhatsappTemplateParams, SendWhatsappTemplateResult, TestWebhookEndpointResult, UpdateWebhookEndpointParams, WebhookDelivery, WebhookDeliveryDetails, WebhookDeliveryStatus, WebhookEndpoint, WebhookEndpointStatus, WebhookEndpointWithSecret, WebhookEventType, WebhookEventTypeInfo, WebhookTestEvent, WebhookTestEventData, WhatsappTemplate, WhatsappTemplateCategory, WhatsappTemplateComponent, WhatsappTemplateParam, } from './generated/types.js';
15
+ export type { Channel, CommentReceivedEvent, CommentReceivedEventData, Conversation, ConversationStatus, CreateWebhookEndpointParams, CreateWhatsappTemplateParams, DeleteWebhookEndpointResult, KnownWebhookEvent, KnownWebhookEventType, ListConversationMessagesParams, ListConversationsParams, ListMessagesParams, ListWebhookDeliveriesParams, ListWhatsappTemplatesParams, Message, MessageDeliveredEvent, MessageDirection, MessageEventData, MessageFailedEvent, MessageFailedEventData, MessageFile, MessageReadEvent, MessageReceivedEvent, MessageSentEvent, Open, ReplyMedia, RotateWebhookSecretResult, SendMessageResult, SendReplyResult, SendWhatsappTemplateParams, SendWhatsappTemplateResult, TestWebhookEndpointResult, UpdateWebhookEndpointParams, WebhookDelivery, WebhookDeliveryDetails, WebhookDeliveryStatus, WebhookEndpoint, WebhookEndpointStatus, WebhookEndpointWithSecret, WebhookEventType, WebhookEventTypeInfo, WebhookTestEvent, WebhookTestEventData, WhatsappTemplate, WhatsappTemplateCategory, WhatsappTemplateComponent, WhatsappTemplateParam, } from './generated/types.js';
package/dist/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  export { Chatwise } from './client.js';
2
- export { APIError, AuthenticationError, BadRequestError, ChatwiseError, ConflictError, ConnectionError, NotFoundError, PayloadTooLargeError, PaymentRequiredError, PermissionDeniedError, RateLimitError, RequestAbortedError, RequestTimeoutError, ServerError, } from './core/errors.js';
2
+ export { APIError, AuthenticationError, BadRequestError, ChatwiseError, ConflictError, ConnectionError, NotFoundError, PayloadTooLargeError, PaymentRequiredError, PermissionDeniedError, RateLimitError, RequestAbortedError, RequestTimeoutError, ServerError, UnprocessableEntityError, } from './core/errors.js';
3
3
  export { verifyWebhook, WebhookVerificationError } from './webhooks.js';
4
4
  export { VERSION } from './version.js';
@@ -1,6 +1,6 @@
1
1
  import { type RequestOptions } from '../core/http.js';
2
2
  import { type PagePromise } from '../core/pagination.js';
3
- import type { ListConversationMessagesParams, ListMessagesParams, Message, SendMessageParams as SendMessageBody, SendMessageResult } from '../generated/types.js';
3
+ import type { ListConversationMessagesParams, ListMessagesParams, Message, MessageFile, ReplyMedia, SendMessageParams as SendMessageBody, SendMessageResult, SendReplyParams as SendReplyBody, SendReplyResult } from '../generated/types.js';
4
4
  /** A template to send by id, and its values. */
5
5
  export type SendMessageParams = Omit<SendMessageBody, 'channel' | 'templateId'> & {
6
6
  /** The template's `id`. */
@@ -11,6 +11,32 @@ export type SendMessageParams = Omit<SendMessageBody, 'channel' | 'templateId'>
11
11
  */
12
12
  channel?: 'WHATSAPP' | undefined;
13
13
  };
14
+ /** What to reply: a text, or a file. Not both, because a reply is one message. */
15
+ export type SendReplyParams = Omit<SendReplyBody, 'text' | 'media'> & ({
16
+ /** The message. At most 4,096 characters on WhatsApp, 2,000 on Messenger, and 1,000 bytes of UTF-8 on Instagram. */
17
+ text: string;
18
+ media?: undefined;
19
+ } | {
20
+ /** A file to send, which Chatwise downloads from its address. On WhatsApp, Instagram and Messenger. */
21
+ media: ReplyMedia;
22
+ text?: undefined;
23
+ });
24
+ export interface SendReplyOptions extends RequestOptions {
25
+ /**
26
+ * A key you choose for this message, 8 to 128 letters, digits, dots, underscores, hyphens or colons. A new
27
+ * one for each message, and the same one, with the same conversation, content and API key, when you repeat
28
+ * the call: for 30 days a repeat doesn't send the message again. Make it from what you answer, such as an
29
+ * event's id. With another API key the same call sends another message.
30
+ */
31
+ idempotencyKey: string;
32
+ /**
33
+ * How long to wait for a file that takes longer to prepare, in milliseconds. A request answered
34
+ * `MEDIA_PROCESSING` or `MEDIA_BUSY` is repeated as `Retry-After` says, if that is within this time after
35
+ * the call began. These don't count as retries, which start again from 0 after each.
36
+ * @defaultValue 600000, or 0 with `maxRetries: 0`
37
+ */
38
+ mediaTimeoutMs?: number | undefined;
39
+ }
14
40
  /** Messages on every channel. */
15
41
  export declare class Messages {
16
42
  #private;
@@ -32,6 +58,38 @@ export declare class Messages {
32
58
  * Scope: `messages:read`.
33
59
  */
34
60
  get(conversationId: string, messageId: string, options?: RequestOptions): Promise<Message>;
61
+ /**
62
+ * Lists a message's files, at most 20. One that is `available` has a `url` that works for 5 minutes,
63
+ * without an API key: don't send yours with it. List the files again for a new one.
64
+ *
65
+ * On WhatsApp, Instagram and Messenger. A file on Instagram or Messenger can be `pending` for a moment
66
+ * after the message arrives, and a story that a message replies to or mentions the account in isn't
67
+ * listed until it is copied.
68
+ *
69
+ * Scope: `messages:read`.
70
+ */
71
+ listFiles(conversationId: string, messageId: string, options?: RequestOptions): Promise<MessageFile[]>;
72
+ /**
73
+ * Replies in a WhatsApp, Instagram or Messenger conversation, with a text or a file. The answer means the
74
+ * channel accepted the message, not that it was delivered.
75
+ *
76
+ * The route recognizes a repeat by `idempotencyKey`, so this is retried like a read, and after
77
+ * `SEND_IN_PROGRESS`. If it still fails with one of these, with no answer, or with `MEDIA_PROCESSING`,
78
+ * `MEDIA_DOWNLOAD_FAILED` or `Invalid API key`, call it again later, with the same key, content and API
79
+ * key. Any other 4xx comes back until you fix what it names. A video on Messenger can take longer to send
80
+ * than the retries last: after `SEND_IN_PROGRESS`, call again within a minute, or you can miss that it was
81
+ * refused, and send it again.
82
+ *
83
+ * After `SEND_OUTCOME_UNKNOWN` a repeat sends nothing. The message may have been sent, also if the
84
+ * conversation doesn't show it, so let a person decide whether to send it again with a new key.
85
+ *
86
+ * An error is about the last request. If an earlier one got no answer, 401, 403, 404 and 429 don't say
87
+ * that nothing was sent, and with a file no error does while that one is still running. So don't go on with
88
+ * another `idempotencyKey` or API key.
89
+ *
90
+ * Scope: `messages:reply`.
91
+ */
92
+ reply(conversationId: string, params: SendReplyParams, options: SendReplyOptions): Promise<SendReplyResult>;
35
93
  /**
36
94
  * Sends an approved WhatsApp template by its id. The answer means WhatsApp accepted the message, not
37
95
  * that it was delivered. To send one by its name, use `whatsappTemplates.send`.
@@ -33,6 +33,58 @@ export class Messages {
33
33
  const { data } = await this.#request({ method: 'GET', path: path `/v1/conversations/${conversationId}/messages/${messageId}` }, options);
34
34
  return data;
35
35
  }
36
+ /**
37
+ * Lists a message's files, at most 20. One that is `available` has a `url` that works for 5 minutes,
38
+ * without an API key: don't send yours with it. List the files again for a new one.
39
+ *
40
+ * On WhatsApp, Instagram and Messenger. A file on Instagram or Messenger can be `pending` for a moment
41
+ * after the message arrives, and a story that a message replies to or mentions the account in isn't
42
+ * listed until it is copied.
43
+ *
44
+ * Scope: `messages:read`.
45
+ */
46
+ async listFiles(conversationId, messageId, options) {
47
+ const { data } = await this.#request({ method: 'GET', path: path `/v1/conversations/${conversationId}/messages/${messageId}/files` }, options);
48
+ return data;
49
+ }
50
+ /**
51
+ * Replies in a WhatsApp, Instagram or Messenger conversation, with a text or a file. The answer means the
52
+ * channel accepted the message, not that it was delivered.
53
+ *
54
+ * The route recognizes a repeat by `idempotencyKey`, so this is retried like a read, and after
55
+ * `SEND_IN_PROGRESS`. If it still fails with one of these, with no answer, or with `MEDIA_PROCESSING`,
56
+ * `MEDIA_DOWNLOAD_FAILED` or `Invalid API key`, call it again later, with the same key, content and API
57
+ * key. Any other 4xx comes back until you fix what it names. A video on Messenger can take longer to send
58
+ * than the retries last: after `SEND_IN_PROGRESS`, call again within a minute, or you can miss that it was
59
+ * refused, and send it again.
60
+ *
61
+ * After `SEND_OUTCOME_UNKNOWN` a repeat sends nothing. The message may have been sent, also if the
62
+ * conversation doesn't show it, so let a person decide whether to send it again with a new key.
63
+ *
64
+ * An error is about the last request. If an earlier one got no answer, 401, 403, 404 and 429 don't say
65
+ * that nothing was sent, and with a file no error does while that one is still running. So don't go on with
66
+ * another `idempotencyKey` or API key.
67
+ *
68
+ * Scope: `messages:reply`.
69
+ */
70
+ async reply(conversationId, params, options) {
71
+ const { idempotencyKey, mediaTimeoutMs, ...rest } = options ?? {};
72
+ // Without one the header would be "undefined", which is a key the API takes, and the same for every reply.
73
+ // Other characters can't be in a header. The rest is for the API to check.
74
+ if (typeof idempotencyKey !== 'string' || !/^[\x21-\x7e]+$/.test(idempotencyKey)) {
75
+ throw new ChatwiseError('messages.reply needs an idempotencyKey: 8 to 128 letters, digits, dots, underscores, hyphens or colons.');
76
+ }
77
+ const { data } = await this.#request({
78
+ method: 'POST',
79
+ path: path `/v1/conversations/${conversationId}/messages`,
80
+ body: params,
81
+ headers: { 'Idempotency-Key': idempotencyKey },
82
+ // Not after SEND_OUTCOME_UNKNOWN, which a repeat only answers again.
83
+ repeatAfter: ({ status, code }) => (status >= 500 ? code !== 'SEND_OUTCOME_UNKNOWN' : status === 409 && code === 'SEND_IN_PROGRESS'),
84
+ pending: { codes: ['MEDIA_PROCESSING', 'MEDIA_BUSY'], timeoutMs: mediaTimeoutMs },
85
+ }, rest);
86
+ return data;
87
+ }
36
88
  /**
37
89
  * Sends an approved WhatsApp template by its id. The answer means WhatsApp accepted the message, not
38
90
  * that it was delivered. To send one by its name, use `whatsappTemplates.send`.
@@ -44,7 +44,9 @@ export class WhatsappTemplates {
44
44
  path: '/v1/whatsapp/templates',
45
45
  body: params,
46
46
  headers: idempotencyKey === undefined ? undefined : { 'Idempotency-Key': idempotencyKey },
47
- idempotent: true,
47
+ // An answer with a code says what to do about a template that was submitted, such as to wait for
48
+ // Meta. Asking again right away would only replace it with "already in progress".
49
+ repeatAfter: ({ status, code }) => status >= 500 && code === undefined,
48
50
  }, rest);
49
51
  return data;
50
52
  }
@@ -1,2 +1,2 @@
1
1
  /** The version of this package. A test keeps it equal to package.json's. */
2
- export declare const VERSION = "0.1.0";
2
+ export declare const VERSION = "0.1.1";
@@ -1,2 +1,2 @@
1
1
  /** The version of this package. A test keeps it equal to package.json's. */
2
- export const VERSION = '0.1.0';
2
+ export const VERSION = '0.1.1';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@chatwise/node",
3
- "version": "0.1.0",
4
- "description": "Official Node.js SDK for the Chatwise API: read your WhatsApp, Instagram, Messenger and Website Chat inbox, send WhatsApp templates and verify webhooks.",
3
+ "version": "0.1.1",
4
+ "description": "Official Node.js SDK for the Chatwise API: read your WhatsApp, Instagram, Messenger and Website Chat inbox, reply to customers, send WhatsApp templates and verify webhooks.",
5
5
  "keywords": [
6
6
  "chatwise",
7
7
  "whatsapp",