@vzaps/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1046 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ AuthResource: () => AuthResource,
34
+ ChatsResource: () => ChatsResource,
35
+ ChatwootResource: () => ChatwootResource,
36
+ ContactsResource: () => ContactsResource,
37
+ EventSubscription: () => EventSubscription,
38
+ EventsResource: () => EventsResource,
39
+ GroupsResource: () => GroupsResource,
40
+ InstancesResource: () => InstancesResource,
41
+ MessagesResource: () => MessagesResource,
42
+ QueuesResource: () => QueuesResource,
43
+ SessionsResource: () => SessionsResource,
44
+ TypebotsResource: () => TypebotsResource,
45
+ UsersResource: () => UsersResource,
46
+ VZapsAuthenticationError: () => VZapsAuthenticationError,
47
+ VZapsClient: () => VZapsClient,
48
+ VZapsError: () => VZapsError,
49
+ VZapsTimeoutError: () => VZapsTimeoutError,
50
+ WebhooksResource: () => WebhooksResource
51
+ });
52
+ module.exports = __toCommonJS(index_exports);
53
+
54
+ // src/events.ts
55
+ var import_ws = __toESM(require("ws"), 1);
56
+ var EventsResource = class {
57
+ constructor(http, webSocketFactory) {
58
+ this.http = http;
59
+ this.webSocketFactory = webSocketFactory;
60
+ }
61
+ http;
62
+ webSocketFactory;
63
+ async subscribe(request) {
64
+ const subscription = new EventSubscription(this.http, request, this.webSocketFactory);
65
+ await subscription.open();
66
+ return subscription;
67
+ }
68
+ };
69
+ var EventSubscription = class {
70
+ constructor(http, request, webSocketFactory) {
71
+ this.http = http;
72
+ this.request = request;
73
+ this.webSocketFactory = webSocketFactory;
74
+ }
75
+ http;
76
+ request;
77
+ webSocketFactory;
78
+ handlers = /* @__PURE__ */ new Map();
79
+ errorHandlers = /* @__PURE__ */ new Set();
80
+ lifecycleHandlers = /* @__PURE__ */ new Map();
81
+ socket;
82
+ closed = false;
83
+ retryCount = 0;
84
+ async open() {
85
+ const token = await this.http.getAccessToken(this.request.signal);
86
+ const url = this.http.buildRealtimeUrl("/events/ws", {
87
+ instance_id: this.request.instanceId,
88
+ events: this.request.events?.join(","),
89
+ access_token: token,
90
+ client_token: this.http.clientToken,
91
+ instance_token: this.request.instanceToken,
92
+ last_event_id: this.request.lastEventId
93
+ });
94
+ const headers = {
95
+ Authorization: `Bearer ${token}`,
96
+ "X-Client-Token": this.http.clientToken
97
+ };
98
+ headers["X-Instance-Token"] = this.request.instanceToken;
99
+ this.socket = this.createSocket(url, headers);
100
+ this.bindSocket(this.socket);
101
+ }
102
+ on(event, handler) {
103
+ if (event === "error") {
104
+ this.errorHandlers.add(handler);
105
+ return this;
106
+ }
107
+ if (event === "open" || event === "close") {
108
+ this.addLifecycleHandler(event, handler);
109
+ return this;
110
+ }
111
+ const handlers = this.handlers.get(event) ?? /* @__PURE__ */ new Set();
112
+ handlers.add(handler);
113
+ this.handlers.set(event, handlers);
114
+ return this;
115
+ }
116
+ off(event, handler) {
117
+ if (event === "error") {
118
+ this.errorHandlers.delete(handler);
119
+ return this;
120
+ }
121
+ if (event === "open" || event === "close") {
122
+ this.lifecycleHandlers.get(event)?.delete(handler);
123
+ return this;
124
+ }
125
+ this.handlers.get(event)?.delete(handler);
126
+ return this;
127
+ }
128
+ async close(code = 1e3, reason = "Client closed subscription") {
129
+ this.closed = true;
130
+ this.socket?.close(code, reason);
131
+ }
132
+ createSocket(url, headers) {
133
+ if (this.webSocketFactory) {
134
+ return this.webSocketFactory(url, headers);
135
+ }
136
+ if (typeof globalThis.WebSocket !== "undefined") {
137
+ return new globalThis.WebSocket(url);
138
+ }
139
+ return new import_ws.default(url, { headers });
140
+ }
141
+ bindSocket(socket) {
142
+ listen(socket, "open", () => {
143
+ this.retryCount = 0;
144
+ this.emitLifecycle("open");
145
+ });
146
+ listen(socket, "message", (eventOrData) => {
147
+ const raw = readMessageData(eventOrData);
148
+ if (raw !== void 0) {
149
+ void this.dispatch(raw);
150
+ }
151
+ });
152
+ listen(socket, "error", (error) => {
153
+ this.emitError(error);
154
+ });
155
+ listen(socket, "close", () => {
156
+ this.emitLifecycle("close");
157
+ void this.reconnectIfNeeded();
158
+ });
159
+ this.request.signal?.addEventListener("abort", () => {
160
+ void this.close(1e3, "Subscription aborted");
161
+ }, { once: true });
162
+ }
163
+ async dispatch(raw) {
164
+ try {
165
+ const event = parseEvent(raw);
166
+ const handlers = /* @__PURE__ */ new Set([
167
+ ...this.handlers.get(event.type) ?? [],
168
+ ...this.handlers.get("All") ?? []
169
+ ]);
170
+ await Promise.all([...handlers].map((handler) => handler(event)));
171
+ this.ack(event.id);
172
+ } catch (error) {
173
+ this.emitError(error);
174
+ }
175
+ }
176
+ ack(eventId) {
177
+ if (!eventId || !this.socket) {
178
+ return;
179
+ }
180
+ this.socket.send(JSON.stringify({ type: "ack", event_id: eventId }));
181
+ }
182
+ async reconnectIfNeeded() {
183
+ if (this.closed || this.request.reconnect === false) {
184
+ return;
185
+ }
186
+ const maxRetries = this.request.maxRetries ?? Number.POSITIVE_INFINITY;
187
+ if (this.retryCount >= maxRetries) {
188
+ return;
189
+ }
190
+ this.retryCount += 1;
191
+ await delay(this.request.retryDelayMs ?? Math.min(3e4, 1e3 * this.retryCount));
192
+ await this.open();
193
+ }
194
+ addLifecycleHandler(event, handler) {
195
+ const handlers = this.lifecycleHandlers.get(event) ?? /* @__PURE__ */ new Set();
196
+ handlers.add(handler);
197
+ this.lifecycleHandlers.set(event, handlers);
198
+ }
199
+ emitLifecycle(event, ...args) {
200
+ for (const handler of this.lifecycleHandlers.get(event) ?? []) {
201
+ handler(...args);
202
+ }
203
+ }
204
+ emitError(error) {
205
+ if (this.errorHandlers.size === 0) {
206
+ return;
207
+ }
208
+ for (const handler of this.errorHandlers) {
209
+ handler(error);
210
+ }
211
+ }
212
+ };
213
+ function listen(socket, type, listener) {
214
+ if (socket.addEventListener) {
215
+ socket.addEventListener(type, listener);
216
+ return;
217
+ }
218
+ socket.on?.(type, listener);
219
+ }
220
+ function readMessageData(eventOrData) {
221
+ if (isRecord(eventOrData) && "data" in eventOrData) {
222
+ return eventOrData.data;
223
+ }
224
+ return eventOrData;
225
+ }
226
+ function parseEvent(raw) {
227
+ const text = typeof raw === "string" ? raw : Buffer.isBuffer(raw) ? raw.toString("utf8") : String(raw);
228
+ return JSON.parse(text);
229
+ }
230
+ function delay(ms) {
231
+ return new Promise((resolve) => setTimeout(resolve, ms));
232
+ }
233
+ function isRecord(value) {
234
+ return typeof value === "object" && value !== null;
235
+ }
236
+
237
+ // src/errors.ts
238
+ var VZapsError = class extends Error {
239
+ status;
240
+ code;
241
+ details;
242
+ constructor(message, options = {}) {
243
+ super(message);
244
+ this.name = "VZapsError";
245
+ this.status = options.status;
246
+ this.code = options.code;
247
+ this.details = options.details;
248
+ }
249
+ };
250
+ var VZapsAuthenticationError = class extends VZapsError {
251
+ constructor(message = "Invalid VZaps client credentials", details) {
252
+ super(message, { status: 401, code: "AUTHENTICATION_FAILED", details });
253
+ this.name = "VZapsAuthenticationError";
254
+ }
255
+ };
256
+ var VZapsTimeoutError = class extends VZapsError {
257
+ constructor(message = "VZaps request timed out") {
258
+ super(message, { code: "REQUEST_TIMEOUT" });
259
+ this.name = "VZapsTimeoutError";
260
+ }
261
+ };
262
+
263
+ // src/casing.ts
264
+ function isPlainObject(value) {
265
+ return typeof value === "object" && value !== null && !Array.isArray(value);
266
+ }
267
+ function toSnakeCaseKey(key) {
268
+ return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase();
269
+ }
270
+ function toCamelCaseKey(key) {
271
+ return key.replace(/_([a-z0-9])/g, (_, char) => char.toUpperCase());
272
+ }
273
+ function keysToSnakeCase(value) {
274
+ return transformKeys(value, toSnakeCaseKey);
275
+ }
276
+ function keysToCamelCase(value) {
277
+ return transformKeys(value, toCamelCaseKey);
278
+ }
279
+ function transformKeys(value, transformKey) {
280
+ if (Array.isArray(value)) {
281
+ return value.map((item) => transformKeys(item, transformKey));
282
+ }
283
+ if (!isPlainObject(value)) {
284
+ return value;
285
+ }
286
+ const result = {};
287
+ for (const [key, nested] of Object.entries(value)) {
288
+ result[transformKey(key)] = transformKeys(nested, transformKey);
289
+ }
290
+ return result;
291
+ }
292
+
293
+ // src/http.ts
294
+ var DEFAULT_BASE_URL = "https://api.vzaps.com";
295
+ var DEFAULT_REALTIME_URL = "wss://realtime.vzaps.com";
296
+ var DEFAULT_TIMEOUT_MS = 3e4;
297
+ var DEFAULT_TOKEN_SKEW_MS = 6e4;
298
+ var HttpClient = class {
299
+ baseUrl;
300
+ realtimeUrl;
301
+ clientToken;
302
+ clientSecret;
303
+ fetchImpl;
304
+ timeoutMs;
305
+ tokenSkewMs;
306
+ userAgent;
307
+ cachedToken;
308
+ pendingToken;
309
+ constructor(options) {
310
+ this.clientToken = requireNonEmpty(options.clientToken, "clientToken");
311
+ this.clientSecret = requireNonEmpty(options.clientSecret, "clientSecret");
312
+ this.baseUrl = normalizeBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL);
313
+ this.realtimeUrl = normalizeBaseUrl(options.realtimeUrl ?? DEFAULT_REALTIME_URL);
314
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
315
+ this.tokenSkewMs = options.tokenSkewMs ?? DEFAULT_TOKEN_SKEW_MS;
316
+ this.userAgent = options.userAgent;
317
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
318
+ if (!this.fetchImpl) {
319
+ throw new VZapsError("No fetch implementation available. Use Node.js 18+ or pass options.fetch.");
320
+ }
321
+ }
322
+ async getAccessToken(signal) {
323
+ if (this.cachedToken && this.cachedToken.expiresAt > Date.now()) {
324
+ return this.cachedToken.accessToken;
325
+ }
326
+ this.pendingToken ??= this.requestToken(signal).finally(() => {
327
+ this.pendingToken = void 0;
328
+ });
329
+ return this.pendingToken;
330
+ }
331
+ async request(method, path, options = {}) {
332
+ const url = this.buildUrl(path, options.query);
333
+ const headers = new Headers();
334
+ headers.set("Accept", "application/json");
335
+ if (options.body !== void 0) {
336
+ headers.set("Content-Type", "application/json");
337
+ }
338
+ if (this.userAgent) {
339
+ headers.set("User-Agent", this.userAgent);
340
+ }
341
+ for (const [key, value] of Object.entries(options.headers ?? {})) {
342
+ if (value !== void 0) {
343
+ headers.set(key, value);
344
+ }
345
+ }
346
+ if (options.auth !== false) {
347
+ headers.set("Authorization", `Bearer ${await this.getAccessToken(options.signal)}`);
348
+ headers.set("X-Client-Token", this.clientToken);
349
+ }
350
+ if (options.instanceToken) {
351
+ headers.set("X-Instance-Token", options.instanceToken);
352
+ }
353
+ const body = options.body === void 0 ? void 0 : JSON.stringify(keysToSnakeCase(options.body));
354
+ const response = await this.fetchWithTimeout(url, {
355
+ method,
356
+ headers,
357
+ body,
358
+ signal: options.signal
359
+ });
360
+ return parseResponse(response);
361
+ }
362
+ buildRealtimeUrl(path, query) {
363
+ return buildUrl(this.realtimeUrl, path, query);
364
+ }
365
+ async requestToken(signal) {
366
+ const response = await this.request("POST", "/token", {
367
+ auth: false,
368
+ signal,
369
+ body: {
370
+ clientToken: this.clientToken,
371
+ clientSecret: this.clientSecret
372
+ }
373
+ });
374
+ if (!response.accessToken || !response.expiresIn) {
375
+ throw new VZapsAuthenticationError("VZaps token response is missing accessToken or expiresIn", response);
376
+ }
377
+ this.cachedToken = {
378
+ accessToken: response.accessToken,
379
+ expiresAt: Date.now() + response.expiresIn * 1e3 - this.tokenSkewMs
380
+ };
381
+ return response.accessToken;
382
+ }
383
+ buildUrl(path, query) {
384
+ return buildUrl(this.baseUrl, path, query);
385
+ }
386
+ async fetchWithTimeout(url, init) {
387
+ const controller = new AbortController();
388
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
389
+ const signal = mergeSignals(controller.signal, init.signal ?? void 0);
390
+ try {
391
+ return await this.fetchImpl(url, { ...init, signal });
392
+ } catch (error) {
393
+ if (controller.signal.aborted) {
394
+ throw new VZapsTimeoutError();
395
+ }
396
+ throw error;
397
+ } finally {
398
+ clearTimeout(timeout);
399
+ }
400
+ }
401
+ };
402
+ function requireNonEmpty(value, name) {
403
+ if (!value || value.trim() === "") {
404
+ throw new VZapsError(`VZaps ${name} is required`);
405
+ }
406
+ return value;
407
+ }
408
+ function normalizeBaseUrl(value) {
409
+ return value.replace(/\/+$/, "");
410
+ }
411
+ function buildUrl(baseUrl, path, query) {
412
+ const cleanPath = path.startsWith("/") ? path : `/${path}`;
413
+ const url = new URL(`${normalizeBaseUrl(baseUrl)}${cleanPath}`);
414
+ for (const [key, value] of Object.entries(query ?? {})) {
415
+ if (value !== void 0) {
416
+ url.searchParams.set(toSnakeCaseKey(key), String(value));
417
+ }
418
+ }
419
+ return url.toString();
420
+ }
421
+ async function parseResponse(response) {
422
+ const text = await response.text();
423
+ const data = text ? safeJsonParse(text) : void 0;
424
+ if (!response.ok) {
425
+ if (response.status === 401) {
426
+ throw new VZapsAuthenticationError(readErrorMessage(data, response.statusText), data);
427
+ }
428
+ throw new VZapsError(readErrorMessage(data, response.statusText), {
429
+ status: response.status,
430
+ details: data
431
+ });
432
+ }
433
+ return keysToCamelCase(data);
434
+ }
435
+ function safeJsonParse(text) {
436
+ try {
437
+ return JSON.parse(text);
438
+ } catch {
439
+ return text;
440
+ }
441
+ }
442
+ function readErrorMessage(data, fallback) {
443
+ if (isRecord2(data)) {
444
+ if (typeof data.error === "string") return data.error;
445
+ if (typeof data.message === "string") return data.message;
446
+ }
447
+ return fallback || "VZaps request failed";
448
+ }
449
+ function isRecord2(value) {
450
+ return typeof value === "object" && value !== null;
451
+ }
452
+ function mergeSignals(primary, secondary) {
453
+ if (!secondary) {
454
+ return primary;
455
+ }
456
+ if (secondary.aborted) {
457
+ return secondary;
458
+ }
459
+ const controller = new AbortController();
460
+ const abort = () => controller.abort();
461
+ primary.addEventListener("abort", abort, { once: true });
462
+ secondary.addEventListener("abort", abort, { once: true });
463
+ return controller.signal;
464
+ }
465
+
466
+ // src/resources.ts
467
+ var AuthResource = class {
468
+ constructor(http) {
469
+ this.http = http;
470
+ }
471
+ http;
472
+ getAccessToken(signal) {
473
+ return this.http.getAccessToken(signal);
474
+ }
475
+ };
476
+ var InstancesResource = class {
477
+ constructor(http) {
478
+ this.http = http;
479
+ }
480
+ http;
481
+ create(data, options = {}) {
482
+ return this.http.request("PUT", "/instances/create", {
483
+ body: data,
484
+ signal: options.signal
485
+ });
486
+ }
487
+ list(data = {}, options = {}) {
488
+ return this.http.request("POST", "/instances/list", {
489
+ body: data,
490
+ signal: options.signal
491
+ });
492
+ }
493
+ get(instanceId, options = {}) {
494
+ return this.http.request("GET", `/instances/${encodeURIComponent(instanceId)}`, {
495
+ signal: options.signal,
496
+ instanceToken: options.instanceToken
497
+ });
498
+ }
499
+ update(instanceId, data, options = {}) {
500
+ return this.http.request("PATCH", `/instances/${encodeURIComponent(instanceId)}`, {
501
+ body: data,
502
+ signal: options.signal,
503
+ instanceToken: options.instanceToken
504
+ });
505
+ }
506
+ restart(instanceId, options = {}) {
507
+ return this.http.request("POST", `/instances/${encodeURIComponent(instanceId)}/restart`, {
508
+ signal: options.signal,
509
+ instanceToken: options.instanceToken
510
+ });
511
+ }
512
+ delete(instanceId, options = {}) {
513
+ return this.http.request("DELETE", `/instances/${encodeURIComponent(instanceId)}`, {
514
+ signal: options.signal,
515
+ instanceToken: options.instanceToken
516
+ });
517
+ }
518
+ provision(data, options = {}) {
519
+ return this.http.request("PUT", "/instances/provision", {
520
+ body: data,
521
+ signal: options.signal
522
+ });
523
+ }
524
+ search(data, options = {}) {
525
+ return this.http.request("POST", "/instances/search", {
526
+ body: data,
527
+ signal: options.signal
528
+ });
529
+ }
530
+ subscribe(instanceId, data = {}, options = {}) {
531
+ return this.http.request("POST", `/instances/${encodeURIComponent(instanceId)}/subscribe`, {
532
+ body: data,
533
+ signal: options.signal,
534
+ instanceToken: options.instanceToken
535
+ });
536
+ }
537
+ resumeSubscription(instanceId, options = {}) {
538
+ return this.http.request("POST", `/instances/${encodeURIComponent(instanceId)}/resume-subscription`, {
539
+ signal: options.signal,
540
+ instanceToken: options.instanceToken
541
+ });
542
+ }
543
+ cancel(instanceId, options = {}) {
544
+ return this.http.request("PUT", `/instances/${encodeURIComponent(instanceId)}/cancel`, {
545
+ signal: options.signal,
546
+ instanceToken: options.instanceToken
547
+ });
548
+ }
549
+ };
550
+ var MessagesResource = class {
551
+ constructor(http) {
552
+ this.http = http;
553
+ }
554
+ http;
555
+ sendText(request, options = {}) {
556
+ return this.post("/chat/send/text", request, options);
557
+ }
558
+ sendImage(request, options = {}) {
559
+ return this.post("/chat/send/image", request, options);
560
+ }
561
+ sendAudio(request, options = {}) {
562
+ return this.post("/chat/send/audio", request, options);
563
+ }
564
+ sendDocument(request, options = {}) {
565
+ return this.post("/chat/send/document", request, options);
566
+ }
567
+ sendVideo(request, options = {}) {
568
+ return this.post("/chat/send/video", request, options);
569
+ }
570
+ sendSticker(request, options = {}) {
571
+ return this.post("/chat/send/sticker", request, options);
572
+ }
573
+ sendGif(request, options = {}) {
574
+ return this.post("/chat/send/gif", request, options);
575
+ }
576
+ sendLocation(request, options = {}) {
577
+ return this.post("/chat/send/location", request, options);
578
+ }
579
+ sendContact(request, options = {}) {
580
+ return this.post("/chat/send/contact", request, options);
581
+ }
582
+ sendButtons(request, options = {}) {
583
+ return this.post("/chat/send/buttons", request, options);
584
+ }
585
+ sendList(request, options = {}) {
586
+ return this.post("/chat/send/list", request, options);
587
+ }
588
+ sendLink(request, options = {}) {
589
+ return this.post("/chat/send/link", request, options);
590
+ }
591
+ sendPoll(request, options = {}) {
592
+ return this.post("/chat/send/poll", request, options);
593
+ }
594
+ pollVote(request, options = {}) {
595
+ return this.post("/chat/poll/vote", request, options);
596
+ }
597
+ react(request, options = {}) {
598
+ return this.post("/chat/react", request, options);
599
+ }
600
+ removeReaction(request, options = {}) {
601
+ return this.sendRequest("DELETE", "/chat/react", request, options);
602
+ }
603
+ presence(request, options = {}) {
604
+ return this.post("/chat/presence", request, options);
605
+ }
606
+ markRead(request, options = {}) {
607
+ return this.post("/chat/markread", request, options);
608
+ }
609
+ downloadImage(request, options = {}) {
610
+ return this.post("/chat/downloadimage", request, options);
611
+ }
612
+ downloadVideo(request, options = {}) {
613
+ return this.post("/chat/downloadvideo", request, options);
614
+ }
615
+ downloadAudio(request, options = {}) {
616
+ return this.post("/chat/downloadaudio", request, options);
617
+ }
618
+ downloadDocument(request, options = {}) {
619
+ return this.post("/chat/downloaddocument", request, options);
620
+ }
621
+ edit(request, options = {}) {
622
+ const { messageId, ...rest } = request;
623
+ return this.sendRequest("PATCH", `/chat/messages/${encodeURIComponent(messageId)}`, rest, options);
624
+ }
625
+ delete(request, options = {}) {
626
+ const { messageId, ...rest } = request;
627
+ return this.sendRequest("DELETE", `/chat/messages/${encodeURIComponent(messageId)}`, rest, options);
628
+ }
629
+ send(instanceId, path, body, options = {}) {
630
+ return this.http.request("POST", `/instances/${encodeURIComponent(instanceId)}/chat/${path.replace(/^\/+/, "")}`, {
631
+ body,
632
+ signal: options.signal,
633
+ instanceToken: options.instanceToken
634
+ });
635
+ }
636
+ post(path, request, options) {
637
+ return this.sendRequest("POST", path, request, options);
638
+ }
639
+ sendRequest(method, path, request, options) {
640
+ const { instanceId, instanceToken, ...body } = request;
641
+ return this.http.request(method, `/instances/${encodeURIComponent(instanceId)}${path}`, {
642
+ body,
643
+ signal: options.signal,
644
+ instanceToken
645
+ });
646
+ }
647
+ };
648
+ var WebhooksResource = class {
649
+ constructor(http) {
650
+ this.http = http;
651
+ }
652
+ http;
653
+ get(instanceId, options = {}) {
654
+ return this.http.request("GET", `/instances/${encodeURIComponent(instanceId)}/webhook`, {
655
+ signal: options.signal,
656
+ instanceToken: options.instanceToken
657
+ });
658
+ }
659
+ set(request, options = {}) {
660
+ const { instanceId, instanceToken, ...body } = request;
661
+ return this.http.request("POST", `/instances/${encodeURIComponent(instanceId)}/webhook`, {
662
+ body,
663
+ signal: options.signal,
664
+ instanceToken
665
+ });
666
+ }
667
+ searchLogs(request, options = {}) {
668
+ const { instanceId, instanceToken, ...body } = request;
669
+ return this.http.request("POST", `/instances/${encodeURIComponent(instanceId)}/webhook/logs/search`, {
670
+ body,
671
+ signal: options.signal,
672
+ instanceToken
673
+ });
674
+ }
675
+ getLog(request, options = {}) {
676
+ return this.http.request(
677
+ "GET",
678
+ `/instances/${encodeURIComponent(request.instanceId)}/webhook/logs/${encodeURIComponent(request.logId)}`,
679
+ {
680
+ signal: options.signal,
681
+ instanceToken: request.instanceToken
682
+ }
683
+ );
684
+ }
685
+ retryLog(request, options = {}) {
686
+ return this.http.request(
687
+ "POST",
688
+ `/instances/${encodeURIComponent(request.instanceId)}/webhook/logs/${encodeURIComponent(request.logId)}/retry`,
689
+ {
690
+ signal: options.signal,
691
+ instanceToken: request.instanceToken
692
+ }
693
+ );
694
+ }
695
+ };
696
+ var ContactsResource = class {
697
+ constructor(http) {
698
+ this.http = http;
699
+ }
700
+ http;
701
+ list(instanceId, options = {}) {
702
+ return this.http.request("GET", `/instances/${encodeURIComponent(instanceId)}/contact/list`, {
703
+ signal: options.signal,
704
+ instanceToken: options.instanceToken
705
+ });
706
+ }
707
+ add(request, options = {}) {
708
+ const { instanceId, instanceToken, ...body } = request;
709
+ return this.http.request("POST", `/instances/${encodeURIComponent(instanceId)}/contact/add`, {
710
+ body,
711
+ signal: options.signal,
712
+ instanceToken
713
+ });
714
+ }
715
+ };
716
+ var GroupsResource = class {
717
+ constructor(http) {
718
+ this.http = http;
719
+ }
720
+ http;
721
+ list(request, options = {}) {
722
+ const { instanceId, instanceToken, page, pageSize } = request;
723
+ return this.http.request("GET", `/instances/${encodeURIComponent(instanceId)}/group/list`, {
724
+ query: { page, pageSize },
725
+ signal: options.signal,
726
+ instanceToken
727
+ });
728
+ }
729
+ get(request, options = {}) {
730
+ return this.http.request("GET", `/instances/${encodeURIComponent(request.instanceId)}/group/info`, {
731
+ query: { groupId: request.groupId },
732
+ signal: options.signal,
733
+ instanceToken: request.instanceToken
734
+ });
735
+ }
736
+ inviteLink(request, options = {}) {
737
+ return this.http.request("GET", `/instances/${encodeURIComponent(request.instanceId)}/group/invitelink`, {
738
+ query: { groupId: request.groupId, reset: request.reset },
739
+ signal: options.signal,
740
+ instanceToken: request.instanceToken
741
+ });
742
+ }
743
+ setPhoto(request, options = {}) {
744
+ return postInstancePath(this.http, request, "/group/photo", options);
745
+ }
746
+ setName(request, options = {}) {
747
+ return postInstancePath(this.http, request, "/group/name", options);
748
+ }
749
+ setDescription(request, options = {}) {
750
+ return postInstancePath(this.http, request, "/group/description", options);
751
+ }
752
+ setSettings(request, options = {}) {
753
+ return postInstancePath(this.http, request, "/group/settings", options);
754
+ }
755
+ create(request, options = {}) {
756
+ return postInstancePath(this.http, request, "/group/create", options);
757
+ }
758
+ addAdmin(request, options = {}) {
759
+ return postInstancePath(this.http, request, "/group/add-admin", options);
760
+ }
761
+ removeAdmin(request, options = {}) {
762
+ return postInstancePath(this.http, request, "/group/remove-admin", options);
763
+ }
764
+ };
765
+ var SessionsResource = class {
766
+ constructor(http) {
767
+ this.http = http;
768
+ }
769
+ http;
770
+ status(instanceId, options = {}) {
771
+ return this.http.request("GET", `/instances/${encodeURIComponent(instanceId)}/session/status`, {
772
+ signal: options.signal,
773
+ instanceToken: options.instanceToken
774
+ });
775
+ }
776
+ qr(instanceId, options = {}) {
777
+ return this.http.request("GET", `/instances/${encodeURIComponent(instanceId)}/session/qr`, {
778
+ signal: options.signal,
779
+ instanceToken: options.instanceToken
780
+ });
781
+ }
782
+ pairCode(instanceId, phone, options = {}) {
783
+ return this.http.request(
784
+ "GET",
785
+ `/instances/${encodeURIComponent(instanceId)}/session/paircode/${encodeURIComponent(phone)}`,
786
+ {
787
+ signal: options.signal,
788
+ instanceToken: options.instanceToken
789
+ }
790
+ );
791
+ }
792
+ disconnect(instanceId, options = {}) {
793
+ return this.http.request("POST", `/instances/${encodeURIComponent(instanceId)}/session/disconnect`, {
794
+ signal: options.signal,
795
+ instanceToken: options.instanceToken
796
+ });
797
+ }
798
+ };
799
+ var UsersResource = class {
800
+ constructor(http) {
801
+ this.http = http;
802
+ }
803
+ http;
804
+ info(request, options = {}) {
805
+ return postInstancePath(this.http, request, "/user/info", options);
806
+ }
807
+ check(request, options = {}) {
808
+ return postInstancePath(this.http, request, "/user/check", options);
809
+ }
810
+ avatar(request, options = {}) {
811
+ return postInstancePath(this.http, request, "/user/avatar", options);
812
+ }
813
+ contacts(instanceId, options = {}) {
814
+ return this.http.request("GET", `/instances/${encodeURIComponent(instanceId)}/user/contacts`, {
815
+ signal: options.signal,
816
+ instanceToken: options.instanceToken
817
+ });
818
+ }
819
+ };
820
+ var QueuesResource = class {
821
+ constructor(http) {
822
+ this.http = http;
823
+ }
824
+ http;
825
+ listMessages(request, options = {}) {
826
+ return getInstancePath(this.http, request, "/queue/messages", options);
827
+ }
828
+ purgeMessages(request, options = {}) {
829
+ return deleteInstancePath(this.http, request, "/queue/messages", options);
830
+ }
831
+ removeMessage(request, options = {}) {
832
+ const { messageId, ...rest } = request;
833
+ return deleteInstancePath(this.http, rest, `/queue/messages/${encodeURIComponent(messageId)}`, options);
834
+ }
835
+ listOperations(request, options = {}) {
836
+ return getInstancePath(this.http, request, "/queue/operations", options);
837
+ }
838
+ purgeOperations(request, options = {}) {
839
+ return deleteInstancePath(this.http, request, "/queue/operations", options);
840
+ }
841
+ removeOperation(request, options = {}) {
842
+ const { messageId, ...rest } = request;
843
+ return deleteInstancePath(this.http, rest, `/queue/operations/${encodeURIComponent(messageId)}`, options);
844
+ }
845
+ };
846
+ var TypebotsResource = class {
847
+ constructor(http) {
848
+ this.http = http;
849
+ }
850
+ http;
851
+ list(instanceId, options = {}) {
852
+ return this.http.request("GET", `/instances/${encodeURIComponent(instanceId)}/typebots`, {
853
+ signal: options.signal,
854
+ instanceToken: options.instanceToken
855
+ });
856
+ }
857
+ create(request, options = {}) {
858
+ return postInstancePath(this.http, request, "/typebots", options);
859
+ }
860
+ update(request, options = {}) {
861
+ const { typebotId, ...rest } = request;
862
+ return requestInstancePath(this.http, "PATCH", rest, `/typebots/${encodeURIComponent(typebotId)}`, options);
863
+ }
864
+ delete(request, options = {}) {
865
+ const { typebotId, ...rest } = request;
866
+ return deleteInstancePath(this.http, rest, `/typebots/${encodeURIComponent(typebotId)}`, options);
867
+ }
868
+ listSessions(instanceId, options = {}) {
869
+ return this.http.request("GET", `/instances/${encodeURIComponent(instanceId)}/typebots/sessions`, {
870
+ signal: options.signal,
871
+ instanceToken: options.instanceToken
872
+ });
873
+ }
874
+ startSession(request, options = {}) {
875
+ const { typebotId, ...rest } = request;
876
+ const path = typebotId ? `/typebots/${encodeURIComponent(typebotId)}/sessions/start` : "/typebots/sessions/start";
877
+ return postInstancePath(this.http, rest, path, options);
878
+ }
879
+ closeSession(request, options = {}) {
880
+ const { session, ...rest } = request;
881
+ return postInstancePath(this.http, rest, `/typebots/sessions/${encodeURIComponent(session)}/close`, options);
882
+ }
883
+ pauseSession(request, options = {}) {
884
+ const { session, ...rest } = request;
885
+ return postInstancePath(this.http, rest, `/typebots/sessions/${encodeURIComponent(session)}/pause`, options);
886
+ }
887
+ };
888
+ var ChatwootResource = class {
889
+ constructor(http) {
890
+ this.http = http;
891
+ }
892
+ http;
893
+ get(instanceId, options = {}) {
894
+ return this.http.request("GET", `/instances/${encodeURIComponent(instanceId)}/chatwoot`, {
895
+ signal: options.signal,
896
+ instanceToken: options.instanceToken
897
+ });
898
+ }
899
+ set(request, options = {}) {
900
+ return postInstancePath(this.http, request, "/chatwoot", options);
901
+ }
902
+ delete(instanceId, options = {}) {
903
+ return this.http.request("DELETE", `/instances/${encodeURIComponent(instanceId)}/chatwoot`, {
904
+ signal: options.signal,
905
+ instanceToken: options.instanceToken
906
+ });
907
+ }
908
+ triggerImport(request, options = {}) {
909
+ const { what, ...rest } = request;
910
+ return postInstancePath(this.http, rest, `/chatwoot/import/${encodeURIComponent(what)}`, options);
911
+ }
912
+ };
913
+ var ChatsResource = class {
914
+ constructor(http) {
915
+ this.http = http;
916
+ }
917
+ http;
918
+ list(request, options = {}) {
919
+ const { instanceId, instanceToken, page, pageSize } = request;
920
+ return this.http.request("GET", `/instances/${encodeURIComponent(instanceId)}/chats`, {
921
+ query: { page, pageSize },
922
+ signal: options.signal,
923
+ instanceToken
924
+ });
925
+ }
926
+ get(request, options = {}) {
927
+ return this.chatAction("GET", request, "", options);
928
+ }
929
+ archive(request, options = {}) {
930
+ return this.chatAction("POST", request, "/archive", options);
931
+ }
932
+ unarchive(request, options = {}) {
933
+ return this.chatAction("POST", request, "/unarchive", options);
934
+ }
935
+ mute(request, options = {}) {
936
+ return this.chatAction("POST", request, "/mute", options);
937
+ }
938
+ unmute(request, options = {}) {
939
+ return this.chatAction("POST", request, "/unmute", options);
940
+ }
941
+ pin(request, options = {}) {
942
+ return this.chatAction("POST", request, "/pin", options);
943
+ }
944
+ unpin(request, options = {}) {
945
+ return this.chatAction("POST", request, "/unpin", options);
946
+ }
947
+ read(request, options = {}) {
948
+ return this.chatAction("POST", request, "/read", options);
949
+ }
950
+ unread(request, options = {}) {
951
+ return this.chatAction("POST", request, "/unread", options);
952
+ }
953
+ clear(request, options = {}) {
954
+ return this.chatAction("POST", request, "/clear", options);
955
+ }
956
+ delete(request, options = {}) {
957
+ return this.chatAction("DELETE", request, "", options);
958
+ }
959
+ setExpiration(request, options = {}) {
960
+ return this.chatAction("PUT", request, "/expiration", options);
961
+ }
962
+ chatAction(method, request, suffix, options) {
963
+ const { instanceId, instanceToken, phone, ...body } = request;
964
+ return this.http.request(method, `/instances/${encodeURIComponent(instanceId)}/chats/${encodeURIComponent(phone)}${suffix}`, {
965
+ body: Object.keys(body).length > 0 ? body : void 0,
966
+ signal: options.signal,
967
+ instanceToken
968
+ });
969
+ }
970
+ };
971
+ function getInstancePath(http, request, path, options) {
972
+ return requestInstancePath(http, "GET", request, path, options);
973
+ }
974
+ function postInstancePath(http, request, path, options) {
975
+ return requestInstancePath(http, "POST", request, path, options);
976
+ }
977
+ function deleteInstancePath(http, request, path, options) {
978
+ return requestInstancePath(http, "DELETE", request, path, options);
979
+ }
980
+ function requestInstancePath(http, method, request, path, options) {
981
+ const { instanceId, instanceToken, ...body } = request;
982
+ return http.request(method, `/instances/${encodeURIComponent(instanceId)}${path}`, {
983
+ body: Object.keys(body).length > 0 ? body : void 0,
984
+ signal: options.signal,
985
+ instanceToken
986
+ });
987
+ }
988
+
989
+ // src/client.ts
990
+ var VZapsClient = class {
991
+ auth;
992
+ instances;
993
+ sessions;
994
+ messages;
995
+ webhooks;
996
+ contacts;
997
+ groups;
998
+ users;
999
+ queues;
1000
+ typebots;
1001
+ chatwoot;
1002
+ chats;
1003
+ events;
1004
+ http;
1005
+ constructor(options) {
1006
+ this.http = new HttpClient(options);
1007
+ this.auth = new AuthResource(this.http);
1008
+ this.instances = new InstancesResource(this.http);
1009
+ this.sessions = new SessionsResource(this.http);
1010
+ this.messages = new MessagesResource(this.http);
1011
+ this.webhooks = new WebhooksResource(this.http);
1012
+ this.contacts = new ContactsResource(this.http);
1013
+ this.groups = new GroupsResource(this.http);
1014
+ this.users = new UsersResource(this.http);
1015
+ this.queues = new QueuesResource(this.http);
1016
+ this.typebots = new TypebotsResource(this.http);
1017
+ this.chatwoot = new ChatwootResource(this.http);
1018
+ this.chats = new ChatsResource(this.http);
1019
+ this.events = new EventsResource(this.http, options.webSocketFactory);
1020
+ }
1021
+ request(method, path, options = {}) {
1022
+ return this.http.request(method, path, options);
1023
+ }
1024
+ };
1025
+ // Annotate the CommonJS export names for ESM import in node:
1026
+ 0 && (module.exports = {
1027
+ AuthResource,
1028
+ ChatsResource,
1029
+ ChatwootResource,
1030
+ ContactsResource,
1031
+ EventSubscription,
1032
+ EventsResource,
1033
+ GroupsResource,
1034
+ InstancesResource,
1035
+ MessagesResource,
1036
+ QueuesResource,
1037
+ SessionsResource,
1038
+ TypebotsResource,
1039
+ UsersResource,
1040
+ VZapsAuthenticationError,
1041
+ VZapsClient,
1042
+ VZapsError,
1043
+ VZapsTimeoutError,
1044
+ WebhooksResource
1045
+ });
1046
+ //# sourceMappingURL=index.cjs.map