@wppconnect-team/wppconnect 2.3.6 → 2.4.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.
@@ -17,7 +17,7 @@ export declare class ProfileLayer extends StatusLayer {
17
17
  * @category Profile
18
18
  * @param status
19
19
  */
20
- setProfileStatus(status: string): Promise<void>;
20
+ setProfileStatus(status: string): Promise<boolean>;
21
21
  /**
22
22
  * Gets current user profile status
23
23
  * @category Profile
@@ -45,9 +45,7 @@ class ProfileLayer extends status_layer_1.StatusLayer {
45
45
  * @param status
46
46
  */
47
47
  async setProfileStatus(status) {
48
- return await (0, helpers_1.evaluateAndReturn)(this.page, ({ status }) => {
49
- WPP.profile.setMyStatus(status);
50
- }, { status });
48
+ return await (0, helpers_1.evaluateAndReturn)(this.page, ({ status }) => WPP.profile.setMyStatus(status), { status });
51
49
  }
52
50
  /**
53
51
  * Gets current user profile status
@@ -334,16 +334,14 @@ export declare class SenderLayer extends ListenerLayer {
334
334
  forwardMessage(toChatId: string, msgId: string | string[], options?: ForwardMessagesOptions): Promise<boolean>;
335
335
  /**
336
336
  * Forwards array of messages (could be ids or message objects)
337
- * What is the difference between forwardMessage and forwardMessagesV2?
338
- * forwardMessage was used to forward a single message
339
- * forwardMessagesV2 is used to forward multiple messages
340
- * Also, it fixes how we pass the arguments to the whatsapp original function
341
- * From positional args to named args (object)
337
+ * Accepts a single message ID or an array and forwards them through the
338
+ * native batch API.
342
339
  * @category Chat
343
340
  * @param to Chat id
344
341
  * @param messages Array of messages ids to be forwarded
345
342
  * @param options
346
- * @returns array of messages ID
343
+ * @returns Messages that could not be forwarded. An empty array means all
344
+ * messages were forwarded.
347
345
  */
348
346
  forwardMessagesV2(toChatId: string, messages: string | string[], options?: ForwardMessagesOptions): Promise<Array<any>>;
349
347
  /**
@@ -611,19 +611,18 @@ class SenderLayer extends listener_layer_1.ListenerLayer {
611
611
  }
612
612
  /**
613
613
  * Forwards array of messages (could be ids or message objects)
614
- * What is the difference between forwardMessage and forwardMessagesV2?
615
- * forwardMessage was used to forward a single message
616
- * forwardMessagesV2 is used to forward multiple messages
617
- * Also, it fixes how we pass the arguments to the whatsapp original function
618
- * From positional args to named args (object)
614
+ * Accepts a single message ID or an array and forwards them through the
615
+ * native batch API.
619
616
  * @category Chat
620
617
  * @param to Chat id
621
618
  * @param messages Array of messages ids to be forwarded
622
619
  * @param options
623
- * @returns array of messages ID
620
+ * @returns Messages that could not be forwarded. An empty array means all
621
+ * messages were forwarded.
624
622
  */
625
623
  async forwardMessagesV2(toChatId, messages, options) {
626
- return (0, helpers_1.evaluateAndReturn)(this.page, ({ toChatId, messages, options }) => WPP.chat.forwardMessages(toChatId, messages, options), { toChatId, messages, options });
624
+ const messageIds = Array.isArray(messages) ? messages : [messages];
625
+ return (0, helpers_1.evaluateAndReturn)(this.page, ({ toChatId, messages, options }) => WPP.chat.forwardMessages(toChatId, messages, options), { toChatId, messages: messageIds, options });
627
626
  }
628
627
  /**
629
628
  * Generates sticker from the provided animated gif image and sends it (Send image as animated sticker)
@@ -23,7 +23,10 @@ export declare class StatusLayer extends LabelsLayer {
23
23
  */
24
24
  sendImageStatus(pathOrBase64: string, options?: SendStatusOptions & {
25
25
  caption?: string;
26
- }): Promise<void>;
26
+ }): Promise<{
27
+ ack: any;
28
+ id: any;
29
+ }>;
27
30
  /**
28
31
  * Send a video message to status stories
29
32
  * @category Status
@@ -41,7 +44,10 @@ export declare class StatusLayer extends LabelsLayer {
41
44
  */
42
45
  sendVideoStatus(pathOrBase64: string, options?: SendStatusOptions & {
43
46
  caption?: string;
44
- }): Promise<void>;
47
+ }): Promise<{
48
+ ack: any;
49
+ id: any;
50
+ }>;
45
51
  /**
46
52
  * Send a text to status stories
47
53
  * @category Status
@@ -55,7 +61,10 @@ export declare class StatusLayer extends LabelsLayer {
55
61
  sendTextStatus(text: string, options: {
56
62
  backgroundColor?: string;
57
63
  font?: number;
58
- }): Promise<void>;
64
+ }): Promise<{
65
+ ack: any;
66
+ id: any;
67
+ }>;
59
68
  /**
60
69
  * Mark status as read/seen
61
70
  * @category Status
@@ -67,5 +76,5 @@ export declare class StatusLayer extends LabelsLayer {
67
76
  * @param chatId Chat ID of contact
68
77
  * @param statusId ID of status msg
69
78
  */
70
- sendReadStatus(chatId: string, statusId: string): Promise<void>;
79
+ sendReadStatus(chatId: string, statusId: string): Promise<any>;
71
80
  }
@@ -76,8 +76,9 @@ class StatusLayer extends labels_layer_1.LabelsLayer {
76
76
  });
77
77
  throw error;
78
78
  }
79
- return await (0, helpers_1.evaluateAndReturn)(this.page, ({ base64, options }) => {
80
- WPP.status.sendImageStatus(base64, options);
79
+ return await (0, helpers_1.evaluateAndReturn)(this.page, async ({ base64, options }) => {
80
+ const result = await WPP.status.sendImageStatus(base64, options);
81
+ return { ack: result?.ack, id: result?.id };
81
82
  }, { base64, options });
82
83
  }
83
84
  /**
@@ -116,8 +117,9 @@ class StatusLayer extends labels_layer_1.LabelsLayer {
116
117
  });
117
118
  throw error;
118
119
  }
119
- return await (0, helpers_1.evaluateAndReturn)(this.page, ({ base64, options }) => {
120
- WPP.status.sendVideoStatus(base64, options);
120
+ return await (0, helpers_1.evaluateAndReturn)(this.page, async ({ base64, options }) => {
121
+ const result = await WPP.status.sendVideoStatus(base64, options);
122
+ return { ack: result?.ack, id: result?.id };
121
123
  }, { base64, options });
122
124
  }
123
125
  /**
@@ -131,8 +133,9 @@ class StatusLayer extends labels_layer_1.LabelsLayer {
131
133
  * @param pathOrBase64 Path or base 64 image
132
134
  */
133
135
  async sendTextStatus(text, options) {
134
- return await (0, helpers_1.evaluateAndReturn)(this.page, ({ text, options }) => {
135
- WPP.status.sendTextStatus(text, options);
136
+ return await (0, helpers_1.evaluateAndReturn)(this.page, async ({ text, options }) => {
137
+ const result = await WPP.status.sendTextStatus(text, options);
138
+ return { ack: result?.ack, id: result?.id };
136
139
  }, { text, options });
137
140
  }
138
141
  /**
@@ -147,9 +150,7 @@ class StatusLayer extends labels_layer_1.LabelsLayer {
147
150
  * @param statusId ID of status msg
148
151
  */
149
152
  async sendReadStatus(chatId, statusId) {
150
- return await (0, helpers_1.evaluateAndReturn)(this.page, ({ chatId, statusId }) => {
151
- WPP.status.sendReadStatus(chatId, statusId);
152
- }, { chatId, statusId });
153
+ return await (0, helpers_1.evaluateAndReturn)(this.page, ({ chatId, statusId }) => WPP.status.sendReadStatus(chatId, statusId), { chatId, statusId });
153
154
  }
154
155
  }
155
156
  exports.StatusLayer = StatusLayer;
@@ -19,3 +19,4 @@ export * from './message-id';
19
19
  export * from './presence-event';
20
20
  export * from './profile-pic-thumb';
21
21
  export * from './wid';
22
+ export * from './label';
@@ -37,3 +37,4 @@ __exportStar(require("./message-id"), exports);
37
37
  __exportStar(require("./presence-event"), exports);
38
38
  __exportStar(require("./profile-pic-thumb"), exports);
39
39
  __exportStar(require("./wid"), exports);
40
+ __exportStar(require("./label"), exports);
@@ -4,4 +4,20 @@ export interface Label {
4
4
  color: number | null;
5
5
  count: number;
6
6
  hexColor: string;
7
+ colorIndex?: number;
8
+ }
9
+ export interface NewLabelOptions {
10
+ labelColor?: string | number;
11
+ }
12
+ export interface EditLabelOptions {
13
+ name?: string;
14
+ labelColor?: string | number;
15
+ }
16
+ export interface AddOrRemoveLabelsOptions {
17
+ labelId: string;
18
+ type: 'add' | 'remove';
19
+ }
20
+ export interface DeleteLabelReturn {
21
+ id: string;
22
+ deleteLabelResult: any;
7
23
  }
@@ -2,6 +2,8 @@ import { Browser, BrowserContext, Page, launch } from 'puppeteer';
2
2
  import { Logger } from 'winston';
3
3
  import { SessionToken, TokenStore } from '../token-store';
4
4
  export interface CreateConfig {
5
+ /** @internal Set by create() for automatic browser cleanup. */
6
+ __browserAcquiredHere?: boolean;
5
7
  /**
6
8
  * Headless chrome
7
9
  * @default true
@@ -55,8 +55,9 @@ export declare function resolveBrowserArgs(requested?: string[], useInsecure?: b
55
55
  */
56
56
  export declare function initBrowser(session: string, options: CreateConfig, logger: Logger): Promise<Browser>;
57
57
  /**
58
- * Closes a browser and, when it was launched by this process, guarantees its
59
- * OS process tree is terminated even if the graceful close fails or hangs.
58
+ * Closes a browser and, when it was launched by this process, attempts to
59
+ * terminate its OS process tree even if graceful close fails or hangs.
60
+ * Failed cleanup can be retried by a later close request.
60
61
  * Remote browsers (`browserWS`) expose no process handle and are only
61
62
  * disconnected. Safe to call when the page/browser was already closed.
62
63
  */
@@ -75,6 +75,7 @@ const puppeteer_config_1 = require("../config/puppeteer.config");
75
75
  const puppeteer_extra_plugin_stealth_1 = __importDefault(require("puppeteer-extra-plugin-stealth"));
76
76
  const WAuserAgente_1 = require("../config/WAuserAgente");
77
77
  const websocket_1 = require("./websocket");
78
+ const logger_1 = require("../utils/logger");
78
79
  const treeKill = require('tree-kill');
79
80
  async function unregisterServiceWorker(page) {
80
81
  await page.evaluateOnNewDocument(() => {
@@ -247,6 +248,8 @@ async function waitForWppReady(page, options = {}) {
247
248
  }, {
248
249
  // 0 would mean no limit to puppeteer
249
250
  timeout: deadline === Infinity ? 0 : Math.max(deadline - Date.now(), 1),
251
+ // Hidden tabs may suspend animation frames while wa-js keeps loading.
252
+ polling: 250,
250
253
  signal: options.signal,
251
254
  });
252
255
  }
@@ -422,29 +425,61 @@ async function initBrowser(session, options, logger) {
422
425
  }
423
426
  return browser;
424
427
  }
428
+ const closingBrowsers = new WeakMap();
425
429
  /**
426
- * Closes a browser and, when it was launched by this process, guarantees its
427
- * OS process tree is terminated even if the graceful close fails or hangs.
430
+ * Closes a browser and, when it was launched by this process, attempts to
431
+ * terminate its OS process tree even if graceful close fails or hangs.
432
+ * Failed cleanup can be retried by a later close request.
428
433
  * Remote browsers (`browserWS`) expose no process handle and are only
429
434
  * disconnected. Safe to call when the page/browser was already closed.
430
435
  */
431
- async function closeBrowser(browser) {
436
+ function closeBrowser(browser) {
437
+ const closing = closingBrowsers.get(browser);
438
+ if (closing)
439
+ return closing;
440
+ // Register before calling close(), which can itself emit targetdestroyed.
441
+ const cleanup = Promise.resolve()
442
+ .then(() => closeBrowserOnce(browser))
443
+ .then((completed) => {
444
+ // Failed cleanup may succeed on a later close request.
445
+ if (!completed)
446
+ closingBrowsers.delete(browser);
447
+ });
448
+ closingBrowsers.set(browser, cleanup);
449
+ void cleanup.catch(() => closingBrowsers.delete(browser));
450
+ return cleanup;
451
+ }
452
+ async function closeBrowserOnce(browser) {
432
453
  // Only browsers launched by this process expose a process handle
433
- const pid = browser.process?.()?.pid;
454
+ const child = browser.process?.();
455
+ const pid = child?.pid;
434
456
  if (!pid) {
435
457
  // Caller-supplied remote connection: detach this client only. Closing it
436
458
  // would terminate the browser shared with every other connected client.
437
459
  // Connections that expose neither a process handle nor a disconnect method
438
460
  // (e.g. test doubles) fall back to close().
439
- if (typeof browser.disconnect === 'function') {
440
- await browser.disconnect().catch(() => null);
461
+ const action = typeof browser.disconnect === 'function' ? 'disconnect' : 'close';
462
+ try {
463
+ if (typeof browser.disconnect === 'function') {
464
+ await browser.disconnect();
465
+ }
466
+ else {
467
+ await browser.close();
468
+ }
469
+ return true;
441
470
  }
442
- else {
443
- await browser.close().catch(() => null);
471
+ catch (error) {
472
+ logger_1.defaultLogger.warn(`Browser ${action} failed`, { error });
473
+ return false;
444
474
  }
445
- return;
446
475
  }
447
- const gracefulClose = browser.close().catch(() => null);
476
+ const gracefulClose = Promise.resolve()
477
+ .then(() => browser.close())
478
+ .catch((error) => {
479
+ logger_1.defaultLogger.warn('Browser close failed; forcing process tree termination', {
480
+ error,
481
+ });
482
+ });
448
483
  // Bound the graceful close so an unresponsive browser cannot hang teardown
449
484
  let timer;
450
485
  const timedOut = new Promise((resolve) => {
@@ -456,9 +491,21 @@ async function closeBrowser(browser) {
456
491
  finally {
457
492
  clearTimeout(timer);
458
493
  }
459
- // Force kill the process tree if the graceful close did not take it down
460
- await new Promise((resolve) => {
461
- treeKill(pid, 'SIGKILL', () => resolve());
494
+ const hasExited = () => child?.exitCode != null || child?.signalCode != null;
495
+ // Never send a termination request for a process handle that has exited:
496
+ // the operating system may have assigned its old pid to another process.
497
+ if (hasExited())
498
+ return true;
499
+ return new Promise((resolve) => {
500
+ treeKill(pid, 'SIGKILL', (error) => {
501
+ if (error) {
502
+ logger_1.defaultLogger.warn('Browser process tree termination failed', {
503
+ pid,
504
+ error,
505
+ });
506
+ }
507
+ resolve(!error || hasExited());
508
+ });
462
509
  });
463
510
  }
464
511
  async function getOrCreatePage(browser) {
@@ -118,7 +118,7 @@ async function create(sessionOrOption, catchQR, statusFind, onLoadingScreen, cat
118
118
  }
119
119
  let browser = mergedOptions.browser;
120
120
  let page = mergedOptions.page;
121
- let browserCreated = false;
121
+ let browserAcquiredHere = false;
122
122
  if (!browser && page) {
123
123
  // Get browser from page
124
124
  browser = page.browser();
@@ -178,7 +178,7 @@ async function create(sessionOrOption, catchQR, statusFind, onLoadingScreen, cat
178
178
  type: 'browser',
179
179
  });
180
180
  }
181
- browserCreated = !mergedOptions.browserWS;
181
+ browserAcquiredHere = true;
182
182
  }
183
183
  if (!mergedOptions.browserWS && browser['_process']) {
184
184
  browser['_process'].once('close', () => {
@@ -186,21 +186,30 @@ async function create(sessionOrOption, catchQR, statusFind, onLoadingScreen, cat
186
186
  });
187
187
  }
188
188
  browser.on('targetdestroyed', async (target) => {
189
- // The handler is registered before the session page is acquired, so ignore
190
- // targets destroyed during startup: there is nothing to auto-close yet.
191
- if (!page) {
192
- return;
193
- }
194
- if (typeof browser.isConnected === 'function' &&
195
- !browser.isConnected()) {
189
+ if (!browserAcquiredHere)
196
190
  return;
191
+ try {
192
+ // The handler is registered before the session page is acquired, so ignore
193
+ // targets destroyed during startup: there is nothing to auto-close yet.
194
+ if (!page || browser.connected === false)
195
+ return;
196
+ const pages = await browser.pages();
197
+ // An `about:blank` tab often remains after the session page is closed, so
198
+ // close only once the session page itself is gone and no real page is left
199
+ // (#2896). A temporarily blank session page must not be mistaken for it.
200
+ // Puppeteer can destroy the target before Page.isClosed() becomes true.
201
+ const sessionTargetDestroyed = typeof page.target === 'function' && target === page.target();
202
+ if ((sessionTargetDestroyed || page.isClosed()) &&
203
+ !(0, browser_1.hasAlivePage)(pages.filter((candidate) => candidate !== page))) {
204
+ await browserModule.closeBrowser(browser);
205
+ }
197
206
  }
198
- const pages = await browser.pages();
199
- // An `about:blank` tab often remains after the session page is closed, so
200
- // close only once the session page itself is gone and no real page is left
201
- // (#2896). A temporarily blank session page must not be mistaken for it.
202
- if (page.isClosed() && !(0, browser_1.hasAlivePage)(pages)) {
203
- browser.close().catch(() => null);
207
+ catch (error) {
208
+ logger.error('Error handling targetdestroyed', {
209
+ session,
210
+ type: 'browser',
211
+ error,
212
+ });
204
213
  }
205
214
  });
206
215
  browser.on('disconnected', () => {
@@ -218,7 +227,10 @@ async function create(sessionOrOption, catchQR, statusFind, onLoadingScreen, cat
218
227
  }
219
228
  if (page) {
220
229
  await page.setBypassCSP(true);
221
- const client = new whatsapp_1.Whatsapp(page, session, mergedOptions);
230
+ const client = new whatsapp_1.Whatsapp(page, session, {
231
+ ...mergedOptions,
232
+ __browserAcquiredHere: browserAcquiredHere,
233
+ });
222
234
  client.catchQR = catchQR;
223
235
  client.statusFind = statusFind;
224
236
  client.onLoadingScreen = onLoadingScreen;
@@ -257,7 +269,7 @@ async function create(sessionOrOption, catchQR, statusFind, onLoadingScreen, cat
257
269
  }
258
270
  catch (error) {
259
271
  // Release a browser launched here; the caller never got a reference
260
- if (browserCreated) {
272
+ if (browserAcquiredHere) {
261
273
  await browserModule.closeBrowser(browser);
262
274
  }
263
275
  throw error;