@chatwise/node 0.0.0-stage → 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 +19 -0
- package/LICENSE +202 -0
- package/README.md +592 -2
- package/dist/cjs/client.d.ts +20 -0
- package/dist/cjs/client.js +32 -0
- package/dist/cjs/core/errors.d.ts +101 -0
- package/dist/cjs/core/errors.js +143 -0
- package/dist/cjs/core/http.d.ts +87 -0
- package/dist/cjs/core/http.js +360 -0
- package/dist/cjs/core/pagination.d.ts +35 -0
- package/dist/cjs/core/pagination.js +101 -0
- package/dist/cjs/generated/types.d.ts +1017 -0
- package/dist/cjs/generated/types.js +3 -0
- package/dist/cjs/index.d.ts +15 -0
- package/dist/cjs/index.js +26 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/resources/conversations.d.ts +20 -0
- package/dist/cjs/resources/conversations.js +32 -0
- package/dist/cjs/resources/messages.d.ts +104 -0
- package/dist/cjs/resources/messages.js +112 -0
- package/dist/cjs/resources/webhook-deliveries.d.ts +27 -0
- package/dist/cjs/resources/webhook-deliveries.js +42 -0
- package/dist/cjs/resources/webhook-endpoints.d.ts +54 -0
- package/dist/cjs/resources/webhook-endpoints.js +82 -0
- package/dist/cjs/resources/webhook-event-types.d.ts +13 -0
- package/dist/cjs/resources/webhook-event-types.js +22 -0
- package/dist/cjs/resources/whatsapp-templates.d.ts +48 -0
- package/dist/cjs/resources/whatsapp-templates.js +71 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +74 -0
- package/dist/cjs/webhooks.js +123 -0
- package/dist/esm/client.d.ts +20 -0
- package/dist/esm/client.js +28 -0
- package/dist/esm/core/errors.d.ts +101 -0
- package/dist/esm/core/errors.js +124 -0
- package/dist/esm/core/http.d.ts +87 -0
- package/dist/esm/core/http.js +356 -0
- package/dist/esm/core/pagination.d.ts +35 -0
- package/dist/esm/core/pagination.js +95 -0
- package/dist/esm/generated/types.d.ts +1017 -0
- package/dist/esm/generated/types.js +2 -0
- package/dist/esm/index.d.ts +15 -0
- package/dist/esm/index.js +4 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/resources/conversations.d.ts +20 -0
- package/dist/esm/resources/conversations.js +28 -0
- package/dist/esm/resources/messages.d.ts +104 -0
- package/dist/esm/resources/messages.js +108 -0
- package/dist/esm/resources/webhook-deliveries.d.ts +27 -0
- package/dist/esm/resources/webhook-deliveries.js +38 -0
- package/dist/esm/resources/webhook-endpoints.d.ts +54 -0
- package/dist/esm/resources/webhook-endpoints.js +78 -0
- package/dist/esm/resources/webhook-event-types.d.ts +13 -0
- package/dist/esm/resources/webhook-event-types.js +18 -0
- package/dist/esm/resources/whatsapp-templates.d.ts +48 -0
- package/dist/esm/resources/whatsapp-templates.js +67 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +74 -0
- package/dist/esm/webhooks.js +118 -0
- package/package.json +79 -4
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WhatsappTemplates = void 0;
|
|
4
|
+
const errors_js_1 = require("../core/errors.js");
|
|
5
|
+
const http_js_1 = require("../core/http.js");
|
|
6
|
+
const pagination_js_1 = require("../core/pagination.js");
|
|
7
|
+
/** WhatsApp message templates. */
|
|
8
|
+
class WhatsappTemplates {
|
|
9
|
+
#request;
|
|
10
|
+
/** @internal */
|
|
11
|
+
constructor(request) {
|
|
12
|
+
this.#request = request;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Lists the workspace's WhatsApp templates, newest first, with the variables and buttons each takes.
|
|
16
|
+
*
|
|
17
|
+
* Scope: `templates:read`.
|
|
18
|
+
*/
|
|
19
|
+
list(params = {}, options) {
|
|
20
|
+
return (0, pagination_js_1.list)(this.#request, () => '/v1/whatsapp/templates', params, options);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Reads one WhatsApp template. After creating one, poll it until `status` is no longer `PENDING`.
|
|
24
|
+
* `sendable` then says whether it can be sent.
|
|
25
|
+
*
|
|
26
|
+
* Scope: `templates:read`.
|
|
27
|
+
*/
|
|
28
|
+
async get(templateId, options) {
|
|
29
|
+
const { data } = await this.#request({ method: 'GET', path: (0, http_js_1.path) `/v1/whatsapp/templates/${templateId}` }, options);
|
|
30
|
+
return data;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Creates a WhatsApp template and submits it to Meta for review. The route recognizes a repeat, by
|
|
34
|
+
* `idempotencyKey` or by the template itself, so this is retried like a read. Only an answer with a
|
|
35
|
+
* `code` isn't. `TEMPLATE_SUBMISSION_IN_PROGRESS`, which a retry can end with, and
|
|
36
|
+
* `TEMPLATE_SUBMISSION_UNCONFIRMED` mean to repeat the call later, with the same key and template.
|
|
37
|
+
*
|
|
38
|
+
* Scope: `templates:write`.
|
|
39
|
+
*/
|
|
40
|
+
async create(params, options) {
|
|
41
|
+
const { idempotencyKey, ...rest } = options ?? {};
|
|
42
|
+
if (idempotencyKey !== undefined && !/^[\x21-\x7e]+$/.test(idempotencyKey)) {
|
|
43
|
+
throw new errors_js_1.ChatwiseError('idempotencyKey must be 1 to 128 letters, digits, dots, underscores, hyphens or colons.');
|
|
44
|
+
}
|
|
45
|
+
const { data } = await this.#request({
|
|
46
|
+
method: 'POST',
|
|
47
|
+
path: '/v1/whatsapp/templates',
|
|
48
|
+
body: params,
|
|
49
|
+
headers: idempotencyKey === undefined ? undefined : { 'Idempotency-Key': idempotencyKey },
|
|
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,
|
|
53
|
+
}, rest);
|
|
54
|
+
return data;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Sends an approved WhatsApp template by its name. The answer means WhatsApp accepted the message,
|
|
58
|
+
* not that it was delivered. To send one by its id, use `messages.send`.
|
|
59
|
+
*
|
|
60
|
+
* Sending twice sends two messages, so this is retried only after a 429. After anything but a 4xx
|
|
61
|
+
* (a timeout, a connection error, an abort, a 5xx) it may have been sent, even if the conversation
|
|
62
|
+
* doesn't show it, so check before you send again.
|
|
63
|
+
*
|
|
64
|
+
* Scope: `messages:send`.
|
|
65
|
+
*/
|
|
66
|
+
async send(params, options) {
|
|
67
|
+
const { data } = await this.#request({ method: 'POST', path: '/v1/template/whatsapp', body: params }, options);
|
|
68
|
+
return data;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
exports.WhatsappTemplates = WhatsappTemplates;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { ChatwiseError } from './core/errors.js';
|
|
2
|
+
import type { KnownWebhookEvent } from './generated/types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Not a value that is ever sent: it stands for every type this version doesn't know. It is exported so that
|
|
5
|
+
* TypeScript can name it in the declarations of code that uses an event's `type`.
|
|
6
|
+
*/
|
|
7
|
+
export declare enum UnknownWebhookEventType {
|
|
8
|
+
Unknown = "a type this version does not know"
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* An event this version doesn't know, as it was sent. Its `type` is the one that was sent. TypeScript
|
|
12
|
+
* can't compare it with one, so write `(event.type as string) === 'the.type'` until you update.
|
|
13
|
+
*/
|
|
14
|
+
export interface UnknownWebhookEvent {
|
|
15
|
+
id: string;
|
|
16
|
+
type: UnknownWebhookEventType;
|
|
17
|
+
timestamp: string;
|
|
18
|
+
apiVersion: string;
|
|
19
|
+
workspaceId: string;
|
|
20
|
+
data: unknown;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* An event, told apart by its `type`. Handle the types you want and ignore the rest: Chatwise adds
|
|
24
|
+
* events, and they reach you as `UnknownWebhookEvent` until you update.
|
|
25
|
+
*/
|
|
26
|
+
export type WebhookEvent = KnownWebhookEvent | UnknownWebhookEvent;
|
|
27
|
+
/** Request headers: a `Headers` object, or Node's `request.headers`. */
|
|
28
|
+
export type WebhookHeaders = {
|
|
29
|
+
get(name: string): string | null;
|
|
30
|
+
} | Readonly<Record<string, string | readonly string[] | undefined>>;
|
|
31
|
+
export interface VerifyWebhookOptions {
|
|
32
|
+
/** The request body exactly as received, not parsed: its text or its bytes. */
|
|
33
|
+
payload: string | Uint8Array;
|
|
34
|
+
/** The request's headers. */
|
|
35
|
+
headers: WebhookHeaders;
|
|
36
|
+
/** The endpoint's signing secret (`whsec_…`), or several to accept any of them. */
|
|
37
|
+
secret: string | readonly string[] | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* How far the time of the request may be from this machine's, in seconds, so that a captured request
|
|
40
|
+
* can't be sent again later.
|
|
41
|
+
* @defaultValue 300
|
|
42
|
+
*/
|
|
43
|
+
toleranceSeconds?: number | undefined;
|
|
44
|
+
/** The time to compare with instead of now, to test with a recorded request. */
|
|
45
|
+
now?: Date | undefined;
|
|
46
|
+
}
|
|
47
|
+
/** Why a request is refused. */
|
|
48
|
+
export type WebhookVerificationErrorCode =
|
|
49
|
+
/** `webhook-id`, `webhook-timestamp` or `webhook-signature` is missing. */
|
|
50
|
+
'missing_header'
|
|
51
|
+
/** `webhook-timestamp` or `webhook-signature` isn't written the way Standard Webhooks writes it. */
|
|
52
|
+
| 'malformed_header'
|
|
53
|
+
/** The request is older than the tolerance, or this machine's clock is fast. */
|
|
54
|
+
| 'timestamp_too_old'
|
|
55
|
+
/** The request is from the future, or this machine's clock is slow. */
|
|
56
|
+
| 'timestamp_too_new'
|
|
57
|
+
/** No signature matches: another secret, a body that was changed or parsed, or not from Chatwise. */
|
|
58
|
+
| 'signature_mismatch'
|
|
59
|
+
/** The signature matches, but the body isn't an event. */
|
|
60
|
+
| 'invalid_payload';
|
|
61
|
+
/** The request isn't a valid webhook from Chatwise. Answer 400. */
|
|
62
|
+
export declare class WebhookVerificationError extends ChatwiseError {
|
|
63
|
+
name: string;
|
|
64
|
+
readonly code: WebhookVerificationErrorCode;
|
|
65
|
+
constructor(code: WebhookVerificationErrorCode, message: string);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Checks that a request really comes from Chatwise and returns its event. Throws a
|
|
69
|
+
* `WebhookVerificationError` if it doesn't: answer 400 then. It checks the signature in constant time
|
|
70
|
+
* and that the request isn't old, as Standard Webhooks says to.
|
|
71
|
+
*
|
|
72
|
+
* Pass the body exactly as received. The same event can arrive more than once, with the same `id`.
|
|
73
|
+
*/
|
|
74
|
+
export declare function verifyWebhook(options: VerifyWebhookOptions): WebhookEvent;
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WebhookVerificationError = void 0;
|
|
4
|
+
exports.verifyWebhook = verifyWebhook;
|
|
5
|
+
const node_crypto_1 = require("node:crypto");
|
|
6
|
+
const node_util_1 = require("node:util");
|
|
7
|
+
const errors_js_1 = require("./core/errors.js");
|
|
8
|
+
/** The request isn't a valid webhook from Chatwise. Answer 400. */
|
|
9
|
+
class WebhookVerificationError extends errors_js_1.ChatwiseError {
|
|
10
|
+
name = 'WebhookVerificationError';
|
|
11
|
+
code;
|
|
12
|
+
constructor(code, message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.code = code;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
exports.WebhookVerificationError = WebhookVerificationError;
|
|
18
|
+
const SECRET_PREFIX = 'whsec_';
|
|
19
|
+
const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
20
|
+
// Mistakes on the receiver's side are plain ChatwiseErrors: answering 400 to them would make Chatwise
|
|
21
|
+
// give up on deliveries that are fine, while an unhandled error's 500 makes it try again.
|
|
22
|
+
function readSecrets(secret) {
|
|
23
|
+
const secrets = Array.isArray(secret) ? secret : [secret];
|
|
24
|
+
if (!secrets.length)
|
|
25
|
+
throw new errors_js_1.ChatwiseError('No webhook signing secret. Pass the endpoint\'s as `secret`.');
|
|
26
|
+
return secrets.map((value) => {
|
|
27
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
28
|
+
if (!text)
|
|
29
|
+
throw new errors_js_1.ChatwiseError('No webhook signing secret. Pass the endpoint\'s as `secret`.');
|
|
30
|
+
const encoded = text.slice(SECRET_PREFIX.length);
|
|
31
|
+
const key = text.startsWith(SECRET_PREFIX) && BASE64.test(encoded) ? Buffer.from(encoded, 'base64') : undefined;
|
|
32
|
+
if (!key || key.length < 24 || key.length > 64) {
|
|
33
|
+
throw new errors_js_1.ChatwiseError('The webhook signing secret is not valid: it starts with `whsec_`, followed by base64.');
|
|
34
|
+
}
|
|
35
|
+
return key;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
function readHeader(headers, name) {
|
|
39
|
+
let value;
|
|
40
|
+
if (typeof headers.get === 'function') {
|
|
41
|
+
value = headers.get(name);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
for (const [key, found] of Object.entries(headers)) {
|
|
45
|
+
if (key.toLowerCase() === name)
|
|
46
|
+
value = Array.isArray(found) && found.length === 1 ? found[0] : found;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (Array.isArray(value))
|
|
50
|
+
throw new WebhookVerificationError('malformed_header', `The ${name} header was sent more than once.`);
|
|
51
|
+
if (typeof value !== 'string' || !value)
|
|
52
|
+
throw new WebhookVerificationError('missing_header', `The ${name} header is missing.`);
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Checks that a request really comes from Chatwise and returns its event. Throws a
|
|
57
|
+
* `WebhookVerificationError` if it doesn't: answer 400 then. It checks the signature in constant time
|
|
58
|
+
* and that the request isn't old, as Standard Webhooks says to.
|
|
59
|
+
*
|
|
60
|
+
* Pass the body exactly as received. The same event can arrive more than once, with the same `id`.
|
|
61
|
+
*/
|
|
62
|
+
function verifyWebhook(options) {
|
|
63
|
+
if (typeof options !== 'object' || options === null) {
|
|
64
|
+
throw new errors_js_1.ChatwiseError('Pass verifyWebhook an object with the request\'s payload and headers, and the secret.');
|
|
65
|
+
}
|
|
66
|
+
const { payload, headers, secret, toleranceSeconds = 300, now } = options;
|
|
67
|
+
const keys = readSecrets(secret);
|
|
68
|
+
// Not instanceof, which refuses bytes from another realm, as tests and sandboxes have them.
|
|
69
|
+
if (typeof payload !== 'string' && !node_util_1.types.isUint8Array(payload)) {
|
|
70
|
+
if (node_util_1.types.isAnyArrayBuffer(payload)) {
|
|
71
|
+
throw new errors_js_1.ChatwiseError('payload must be the raw request body, as a string or bytes. Of an ArrayBuffer, pass `new Uint8Array(payload)`.');
|
|
72
|
+
}
|
|
73
|
+
throw new errors_js_1.ChatwiseError('payload must be the raw request body, as a string or bytes. It looks parsed: verify the request before anything parses its body.');
|
|
74
|
+
}
|
|
75
|
+
if (typeof headers !== 'object' || headers === null)
|
|
76
|
+
throw new errors_js_1.ChatwiseError('headers must be the request\'s headers.');
|
|
77
|
+
if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0)
|
|
78
|
+
throw new errors_js_1.ChatwiseError('toleranceSeconds must be a number of seconds.');
|
|
79
|
+
const currentTime = now === undefined ? Date.now() : now instanceof Date && now.getTime();
|
|
80
|
+
if (typeof currentTime !== 'number' || Number.isNaN(currentTime))
|
|
81
|
+
throw new errors_js_1.ChatwiseError('now must be a valid Date.');
|
|
82
|
+
const id = readHeader(headers, 'webhook-id');
|
|
83
|
+
const timestamp = readHeader(headers, 'webhook-timestamp');
|
|
84
|
+
const signatures = readHeader(headers, 'webhook-signature');
|
|
85
|
+
if (!/^\d{1,12}$/.test(timestamp)) {
|
|
86
|
+
throw new WebhookVerificationError('malformed_header', 'The webhook-timestamp header is not a time in Unix seconds.');
|
|
87
|
+
}
|
|
88
|
+
const age = currentTime / 1000 - Number(timestamp);
|
|
89
|
+
if (age > toleranceSeconds)
|
|
90
|
+
throw new WebhookVerificationError('timestamp_too_old', `The request is ${Math.round(age)} seconds old.`);
|
|
91
|
+
if (age < -toleranceSeconds)
|
|
92
|
+
throw new WebhookVerificationError('timestamp_too_new', `The request is from ${Math.round(-age)} seconds in the future.`);
|
|
93
|
+
// `v1,<base64>`, one or more with spaces between. Other versions may be added, so they are skipped.
|
|
94
|
+
const candidates = signatures.split(' ').flatMap((entry) => {
|
|
95
|
+
const match = /^v1,([A-Za-z0-9+/]{43}=)$/.exec(entry);
|
|
96
|
+
return match ? [Buffer.from(match[1])] : [];
|
|
97
|
+
});
|
|
98
|
+
if (!candidates.length) {
|
|
99
|
+
throw new WebhookVerificationError('malformed_header', 'The webhook-signature header has no v1 signature.');
|
|
100
|
+
}
|
|
101
|
+
let matches = false;
|
|
102
|
+
for (const key of keys) {
|
|
103
|
+
const expected = Buffer.from((0, node_crypto_1.createHmac)('sha256', key).update(`${id}.${timestamp}.`).update(payload).digest('base64'));
|
|
104
|
+
// Every candidate is 44 characters, as long as `expected`. No early exit, so that the time tells nothing.
|
|
105
|
+
for (const candidate of candidates)
|
|
106
|
+
matches = (0, node_crypto_1.timingSafeEqual)(candidate, expected) || matches;
|
|
107
|
+
}
|
|
108
|
+
if (!matches) {
|
|
109
|
+
throw new WebhookVerificationError('signature_mismatch', 'No signature matches. Check that the secret is this endpoint\'s and that the body is exactly as received, before any parsing.');
|
|
110
|
+
}
|
|
111
|
+
let event;
|
|
112
|
+
try {
|
|
113
|
+
event = JSON.parse(typeof payload === 'string' ? payload : Buffer.from(payload).toString('utf8'));
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
throw new WebhookVerificationError('invalid_payload', 'The body is not JSON.');
|
|
117
|
+
}
|
|
118
|
+
const { id: eventId, type } = (event ?? {});
|
|
119
|
+
if (typeof eventId !== 'string' || typeof type !== 'string') {
|
|
120
|
+
throw new WebhookVerificationError('invalid_payload', 'The body is not an event.');
|
|
121
|
+
}
|
|
122
|
+
return event;
|
|
123
|
+
}
|
|
@@ -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,28 @@
|
|
|
1
|
+
import { createRequester } 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 class Chatwise {
|
|
13
|
+
conversations;
|
|
14
|
+
messages;
|
|
15
|
+
whatsappTemplates;
|
|
16
|
+
webhookEndpoints;
|
|
17
|
+
webhookDeliveries;
|
|
18
|
+
webhookEventTypes;
|
|
19
|
+
constructor(options = {}) {
|
|
20
|
+
const request = createRequester(options);
|
|
21
|
+
this.conversations = new Conversations(request);
|
|
22
|
+
this.messages = new Messages(request);
|
|
23
|
+
this.whatsappTemplates = new WhatsappTemplates(request);
|
|
24
|
+
this.webhookEndpoints = new WebhookEndpoints(request);
|
|
25
|
+
this.webhookDeliveries = new WebhookDeliveries(request);
|
|
26
|
+
this.webhookEventTypes = new WebhookEventTypes(request);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
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, or its subscription needs attention. */
|
|
52
|
+
export declare class PaymentRequiredError extends APIError {
|
|
53
|
+
name: string;
|
|
54
|
+
}
|
|
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
|
+
*/
|
|
59
|
+
export declare class PermissionDeniedError extends APIError {
|
|
60
|
+
name: string;
|
|
61
|
+
}
|
|
62
|
+
/** 404: it doesn't exist in the key's workspace. */
|
|
63
|
+
export declare class NotFoundError extends APIError {
|
|
64
|
+
name: string;
|
|
65
|
+
}
|
|
66
|
+
/** 409: it conflicts with an earlier request, or with how things are now. `code` says how, such as `REPLY_WINDOW_CLOSED`. */
|
|
67
|
+
export declare class ConflictError extends APIError {
|
|
68
|
+
name: string;
|
|
69
|
+
}
|
|
70
|
+
/** 413: the request body is larger than 100 KB. */
|
|
71
|
+
export declare class PayloadTooLargeError extends APIError {
|
|
72
|
+
name: string;
|
|
73
|
+
}
|
|
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`. */
|
|
79
|
+
export declare class RateLimitError extends APIError {
|
|
80
|
+
name: string;
|
|
81
|
+
}
|
|
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
|
+
*/
|
|
86
|
+
export declare class ServerError extends APIError {
|
|
87
|
+
name: string;
|
|
88
|
+
}
|
|
89
|
+
/** There was no complete answer: the network failed, or the answer was cut off. The request may have been carried out. */
|
|
90
|
+
export declare class ConnectionError extends ChatwiseError {
|
|
91
|
+
name: string;
|
|
92
|
+
}
|
|
93
|
+
/** An attempt took longer than `timeoutMs`. The request may have been carried out. */
|
|
94
|
+
export declare class RequestTimeoutError extends ConnectionError {
|
|
95
|
+
name: string;
|
|
96
|
+
}
|
|
97
|
+
/** Your `signal` aborted the request. The request may have been carried out. `cause` is the signal's reason. */
|
|
98
|
+
export declare class RequestAbortedError extends ChatwiseError {
|
|
99
|
+
name: string;
|
|
100
|
+
}
|
|
101
|
+
export declare function apiError(details: APIErrorDetails): APIError;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/** The base of every error this package throws. */
|
|
2
|
+
export class ChatwiseError extends Error {
|
|
3
|
+
// Written out in each class, because minifiers rename classes.
|
|
4
|
+
name = 'ChatwiseError';
|
|
5
|
+
}
|
|
6
|
+
const text = (value) => (typeof value === 'string' && value ? value : undefined);
|
|
7
|
+
function readFieldErrors(body) {
|
|
8
|
+
if (Array.isArray(body.errors)) {
|
|
9
|
+
return body.errors.flatMap((entry) => typeof entry?.path === 'string' && typeof entry.message === 'string' ? [{ path: entry.path, message: entry.message }] : []);
|
|
10
|
+
}
|
|
11
|
+
const field = text(body.field);
|
|
12
|
+
return field ? [{ path: field, message: text(body.message) ?? '' }] : [];
|
|
13
|
+
}
|
|
14
|
+
/** Chatwise answered with an error. Each status has a subclass. */
|
|
15
|
+
export class APIError extends ChatwiseError {
|
|
16
|
+
name = 'APIError';
|
|
17
|
+
/** The HTTP status. */
|
|
18
|
+
status;
|
|
19
|
+
/** A code to check in your program, such as `TEMPLATE_EXISTS`, when the error has one. */
|
|
20
|
+
code;
|
|
21
|
+
/** What was wrong with which field, when the API says so. */
|
|
22
|
+
fieldErrors;
|
|
23
|
+
/** Quote it when you contact support. Only some 500s have one. */
|
|
24
|
+
errorId;
|
|
25
|
+
/** How long the API asks to wait before another request, in milliseconds. From `Retry-After`. */
|
|
26
|
+
retryAfterMs;
|
|
27
|
+
method;
|
|
28
|
+
/** The path of the request, without its query. */
|
|
29
|
+
path;
|
|
30
|
+
/** The parsed body of the response, or its text when it wasn't JSON. */
|
|
31
|
+
body;
|
|
32
|
+
constructor({ status, method, path, body, retryAfterMs }) {
|
|
33
|
+
const fields = typeof body === 'object' && body !== null ? body : {};
|
|
34
|
+
const fieldErrors = readFieldErrors(fields);
|
|
35
|
+
let message = text(fields.message) ?? `Chatwise answered ${status} to ${method} ${path}`;
|
|
36
|
+
if (Array.isArray(fields.errors) && fieldErrors.length) {
|
|
37
|
+
message += ` (${fieldErrors.map((error) => `${error.path}: ${error.message}`).join('; ')})`;
|
|
38
|
+
}
|
|
39
|
+
super(message);
|
|
40
|
+
this.status = status;
|
|
41
|
+
this.code = text(fields.code);
|
|
42
|
+
this.fieldErrors = fieldErrors;
|
|
43
|
+
this.errorId = text(fields.errorId);
|
|
44
|
+
this.retryAfterMs = retryAfterMs;
|
|
45
|
+
this.method = method;
|
|
46
|
+
this.path = path;
|
|
47
|
+
this.body = body;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** 400: a parameter, field, cursor or id is invalid. `fieldErrors` says which. */
|
|
51
|
+
export class BadRequestError extends APIError {
|
|
52
|
+
name = 'BadRequestError';
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 401: the API key is missing, invalid, expired or revoked. With the message `Invalid API key`, Chatwise
|
|
56
|
+
* couldn't check the key: try again.
|
|
57
|
+
*/
|
|
58
|
+
export class AuthenticationError extends APIError {
|
|
59
|
+
name = 'AuthenticationError';
|
|
60
|
+
}
|
|
61
|
+
/** 402: sending is paused for the workspace, or its subscription needs attention. */
|
|
62
|
+
export class PaymentRequiredError extends APIError {
|
|
63
|
+
name = 'PaymentRequiredError';
|
|
64
|
+
}
|
|
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
|
+
*/
|
|
69
|
+
export class PermissionDeniedError extends APIError {
|
|
70
|
+
name = 'PermissionDeniedError';
|
|
71
|
+
}
|
|
72
|
+
/** 404: it doesn't exist in the key's workspace. */
|
|
73
|
+
export class NotFoundError extends APIError {
|
|
74
|
+
name = 'NotFoundError';
|
|
75
|
+
}
|
|
76
|
+
/** 409: it conflicts with an earlier request, or with how things are now. `code` says how, such as `REPLY_WINDOW_CLOSED`. */
|
|
77
|
+
export class ConflictError extends APIError {
|
|
78
|
+
name = 'ConflictError';
|
|
79
|
+
}
|
|
80
|
+
/** 413: the request body is larger than 100 KB. */
|
|
81
|
+
export class PayloadTooLargeError extends APIError {
|
|
82
|
+
name = 'PayloadTooLargeError';
|
|
83
|
+
}
|
|
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`. */
|
|
89
|
+
export class RateLimitError extends APIError {
|
|
90
|
+
name = 'RateLimitError';
|
|
91
|
+
}
|
|
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
|
+
*/
|
|
96
|
+
export class ServerError extends APIError {
|
|
97
|
+
name = 'ServerError';
|
|
98
|
+
}
|
|
99
|
+
/** There was no complete answer: the network failed, or the answer was cut off. The request may have been carried out. */
|
|
100
|
+
export class ConnectionError extends ChatwiseError {
|
|
101
|
+
name = 'ConnectionError';
|
|
102
|
+
}
|
|
103
|
+
/** An attempt took longer than `timeoutMs`. The request may have been carried out. */
|
|
104
|
+
export class RequestTimeoutError extends ConnectionError {
|
|
105
|
+
name = 'RequestTimeoutError';
|
|
106
|
+
}
|
|
107
|
+
/** Your `signal` aborted the request. The request may have been carried out. `cause` is the signal's reason. */
|
|
108
|
+
export class RequestAbortedError extends ChatwiseError {
|
|
109
|
+
name = 'RequestAbortedError';
|
|
110
|
+
}
|
|
111
|
+
export function apiError(details) {
|
|
112
|
+
switch (details.status) {
|
|
113
|
+
case 400: return new BadRequestError(details);
|
|
114
|
+
case 401: return new AuthenticationError(details);
|
|
115
|
+
case 402: return new PaymentRequiredError(details);
|
|
116
|
+
case 403: return new PermissionDeniedError(details);
|
|
117
|
+
case 404: return new NotFoundError(details);
|
|
118
|
+
case 409: return new ConflictError(details);
|
|
119
|
+
case 413: return new PayloadTooLargeError(details);
|
|
120
|
+
case 422: return new UnprocessableEntityError(details);
|
|
121
|
+
case 429: return new RateLimitError(details);
|
|
122
|
+
default: return details.status >= 500 ? new ServerError(details) : new APIError(details);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { APIError } from './errors.js';
|
|
2
|
+
/** An `AbortSignal`. */
|
|
3
|
+
export interface AbortSignalLike {
|
|
4
|
+
readonly aborted: boolean;
|
|
5
|
+
readonly reason?: unknown;
|
|
6
|
+
addEventListener(type: 'abort', listener: () => void): void;
|
|
7
|
+
removeEventListener(type: 'abort', listener: () => void): void;
|
|
8
|
+
}
|
|
9
|
+
/** A `fetch` response. */
|
|
10
|
+
export interface ResponseLike {
|
|
11
|
+
readonly status: number;
|
|
12
|
+
readonly headers: {
|
|
13
|
+
get(name: string): string | null;
|
|
14
|
+
};
|
|
15
|
+
/** A `ReadableStream`. An answer without one is read with `text()`, however long it is. */
|
|
16
|
+
readonly body?: unknown;
|
|
17
|
+
text(): Promise<string>;
|
|
18
|
+
}
|
|
19
|
+
/** A `fetch` function, such as the global one. It receives the API key, in the `Authorization` header. */
|
|
20
|
+
export type FetchLike = (url: string, init: {
|
|
21
|
+
method: string;
|
|
22
|
+
headers: Record<string, string>;
|
|
23
|
+
body?: string;
|
|
24
|
+
redirect: 'manual';
|
|
25
|
+
signal: any;
|
|
26
|
+
}) => Promise<ResponseLike>;
|
|
27
|
+
export interface ChatwiseOptions {
|
|
28
|
+
/** The API key. Without it, the `CHATWISE_API_KEY` environment variable. */
|
|
29
|
+
apiKey?: string | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Where the API is. It must be https, except on this machine.
|
|
32
|
+
* @defaultValue 'https://api.chatwise.so'
|
|
33
|
+
*/
|
|
34
|
+
baseUrl?: string | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* How long one attempt may take, in milliseconds. Waits between attempts don't count.
|
|
37
|
+
* @defaultValue 60000
|
|
38
|
+
*/
|
|
39
|
+
timeoutMs?: number | undefined;
|
|
40
|
+
/**
|
|
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.
|
|
43
|
+
* @defaultValue 2
|
|
44
|
+
*/
|
|
45
|
+
maxRetries?: number | undefined;
|
|
46
|
+
/** A `fetch` to use instead of the global one. */
|
|
47
|
+
fetch?: FetchLike | undefined;
|
|
48
|
+
}
|
|
49
|
+
/** Options of a single call. */
|
|
50
|
+
export interface RequestOptions {
|
|
51
|
+
/** Aborts the call, including its waits between attempts. */
|
|
52
|
+
signal?: AbortSignalLike | undefined;
|
|
53
|
+
/** How long one attempt may take, in milliseconds. Overrides the client's. */
|
|
54
|
+
timeoutMs?: number | undefined;
|
|
55
|
+
/** How many times to retry what is safe to retry. Overrides the client's. */
|
|
56
|
+
maxRetries?: number | undefined;
|
|
57
|
+
}
|
|
58
|
+
export interface Operation {
|
|
59
|
+
method: 'GET' | 'POST' | 'PATCH' | 'DELETE';
|
|
60
|
+
path: string;
|
|
61
|
+
query?: object | undefined;
|
|
62
|
+
body?: object | undefined;
|
|
63
|
+
headers?: Record<string, string> | undefined;
|
|
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
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** Makes a request and returns the body of its answer. */
|
|
80
|
+
export type Requester = (operation: Operation, options?: RequestOptions) => Promise<Record<string, unknown>>;
|
|
81
|
+
/** A path with its ids. An id that would change the path, such as `..`, is refused. */
|
|
82
|
+
export declare function path(strings: TemplateStringsArray, ...ids: string[]): string;
|
|
83
|
+
/**
|
|
84
|
+
* The function every resource makes its requests with. The key stays in this closure: it is on no
|
|
85
|
+
* object, so printing a client can't show it.
|
|
86
|
+
*/
|
|
87
|
+
export declare function createRequester(options: ChatwiseOptions): Requester;
|