@wppconnect-team/wppconnect 2.3.5 → 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.
- package/CHANGELOG.md +72 -0
- package/README.md +87 -69
- package/README.pt-BR.md +119 -0
- package/dist/api/helpers/decrypt.js +8 -19
- package/dist/api/helpers/download-file.d.ts +4 -0
- package/dist/api/helpers/download-file.js +12 -0
- package/dist/api/helpers/file-to-base64.d.ts +6 -0
- package/dist/api/helpers/file-to-base64.js +27 -10
- package/dist/api/layers/catalog.layer.d.ts +3 -3
- package/dist/api/layers/catalog.layer.js +2 -2
- package/dist/api/layers/group.layer.js +3 -5
- package/dist/api/layers/host.layer.d.ts +10 -3
- package/dist/api/layers/host.layer.js +56 -25
- package/dist/api/layers/labels.layer.d.ts +34 -12
- package/dist/api/layers/labels.layer.js +36 -18
- package/dist/api/layers/profile.layer.d.ts +1 -1
- package/dist/api/layers/profile.layer.js +1 -3
- package/dist/api/layers/sender.layer.d.ts +4 -6
- package/dist/api/layers/sender.layer.js +6 -7
- package/dist/api/layers/status.layer.d.ts +13 -4
- package/dist/api/layers/status.layer.js +10 -9
- package/dist/api/model/index.d.ts +1 -0
- package/dist/api/model/index.js +1 -0
- package/dist/api/model/label.d.ts +16 -0
- package/dist/api/whatsapp.d.ts +24 -0
- package/dist/api/whatsapp.js +101 -52
- package/dist/config/create-config.d.ts +13 -1
- package/dist/config/create-config.js +2 -2
- package/dist/config/puppeteer.config.d.ts +12 -0
- package/dist/config/puppeteer.config.js +17 -7
- package/dist/controllers/auth.js +3 -1
- package/dist/controllers/browser.d.ts +27 -0
- package/dist/controllers/browser.js +128 -7
- package/dist/controllers/initializer.js +78 -44
- package/dist/lib/wapi/wapi.js +1 -1
- package/documentation/readme-reference.md +118 -0
- package/package.json +19 -19
- package/scripts/docs-redirects.mjs +70 -0
- package/scripts/typedoc-canonical.mjs +49 -0
package/dist/api/whatsapp.js
CHANGED
|
@@ -52,57 +52,125 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
52
52
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
53
53
|
};
|
|
54
54
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
55
|
-
exports.Whatsapp = void 0;
|
|
55
|
+
exports.Whatsapp = exports.DECRYPT_TIMEOUT_MS = void 0;
|
|
56
|
+
exports.getUntilOk = getUntilOk;
|
|
56
57
|
const axios_1 = __importDefault(require("axios"));
|
|
57
58
|
const fs = __importStar(require("fs"));
|
|
58
59
|
const promises_1 = require("stream/promises");
|
|
60
|
+
const browser_1 = require("../controllers/browser");
|
|
59
61
|
const WAuserAgente_1 = require("../config/WAuserAgente");
|
|
60
62
|
const sleep_1 = require("../utils/sleep");
|
|
61
63
|
const helpers_1 = require("./helpers");
|
|
62
64
|
const decrypt_1 = require("./helpers/decrypt");
|
|
63
65
|
const business_layer_1 = require("./layers/business.layer");
|
|
66
|
+
/** Per-request timeout so a single fetch cannot hang a send indefinitely. */
|
|
67
|
+
exports.DECRYPT_TIMEOUT_MS = 30000;
|
|
68
|
+
/**
|
|
69
|
+
* GETs a URL until HTTP 200, retrying transient failures (including a rejected
|
|
70
|
+
* status) with linear backoff. Replaces an unbounded `while` loop that wedged
|
|
71
|
+
* `decryptFile` forever on a persistently failing download. Each attempt is
|
|
72
|
+
* bounded by `timeout` (defaults to {@link DECRYPT_TIMEOUT_MS}) so a stalled
|
|
73
|
+
* response cannot hang either.
|
|
74
|
+
*/
|
|
75
|
+
async function getUntilOk(url, options, maxAttempts = 3) {
|
|
76
|
+
const requestOptions = { timeout: exports.DECRYPT_TIMEOUT_MS, ...options };
|
|
77
|
+
let lastError;
|
|
78
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
79
|
+
try {
|
|
80
|
+
const res = await axios_1.default.get(url, requestOptions);
|
|
81
|
+
if (res.status == 200) {
|
|
82
|
+
return res;
|
|
83
|
+
}
|
|
84
|
+
lastError = new Error(`unexpected status ${res.status}`);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
lastError = error;
|
|
88
|
+
}
|
|
89
|
+
if (attempt < maxAttempts) {
|
|
90
|
+
await (0, decrypt_1.timeout)(2000 * attempt);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
throw new Error(`Error trying to download the file (${(lastError && lastError.message) || lastError}).`);
|
|
94
|
+
}
|
|
64
95
|
class Whatsapp extends business_layer_1.BusinessLayer {
|
|
65
96
|
page;
|
|
97
|
+
/**
|
|
98
|
+
* The page binding exposed by `wireConnectionEvents` can only be registered
|
|
99
|
+
* once per page, but a page may be reused by a later client. This maps each
|
|
100
|
+
* page to the callback of the client that most recently wired it, so the
|
|
101
|
+
* existing binding can be redirected to the current client.
|
|
102
|
+
*/
|
|
103
|
+
static connectionDispatchers = new WeakMap();
|
|
66
104
|
connected = null;
|
|
67
105
|
constructor(page, session, options) {
|
|
68
106
|
super(page, session, options);
|
|
69
107
|
this.page = page;
|
|
70
|
-
let interval = null;
|
|
71
|
-
if (this.page) {
|
|
72
|
-
this.page.on('close', async () => {
|
|
73
|
-
clearInterval(interval);
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
interval = setInterval(async () => {
|
|
77
|
-
const newConnected = await page
|
|
78
|
-
.evaluate(() => WPP.conn.isRegistered())
|
|
79
|
-
.catch(() => null);
|
|
80
|
-
if (newConnected === null || newConnected === this.connected) {
|
|
81
|
-
return;
|
|
82
|
-
}
|
|
83
|
-
this.connected = newConnected;
|
|
84
|
-
if (!newConnected) {
|
|
85
|
-
this.log('info', 'Session Unpaired', { type: 'session' });
|
|
86
|
-
setTimeout(async () => {
|
|
87
|
-
if (this.statusFind) {
|
|
88
|
-
try {
|
|
89
|
-
this.statusFind('disconnectedMobile', session || '');
|
|
90
|
-
}
|
|
91
|
-
catch (error) { }
|
|
92
|
-
}
|
|
93
|
-
}, 1000);
|
|
94
|
-
}
|
|
95
|
-
}, 1000);
|
|
96
108
|
}
|
|
97
109
|
async afterPageScriptInjected() {
|
|
98
110
|
await super.afterPageScriptInjected();
|
|
111
|
+
await this.wireConnectionEvents();
|
|
99
112
|
this.page
|
|
100
113
|
.evaluate(() => WPP.conn.isRegistered())
|
|
101
114
|
.then((isAuthenticated) => {
|
|
102
|
-
|
|
115
|
+
// Do not overwrite a connection event that arrived while the initial
|
|
116
|
+
// state was being read.
|
|
117
|
+
if (this.connected === null) {
|
|
118
|
+
this.connected = isAuthenticated;
|
|
119
|
+
}
|
|
103
120
|
})
|
|
104
121
|
.catch(() => null);
|
|
105
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Forwards wa-js connection events to the Node side instead of polling
|
|
125
|
+
* `WPP.conn.isRegistered()` every second. Re-registered after every page
|
|
126
|
+
* load, since the in-page listeners do not survive navigation.
|
|
127
|
+
*/
|
|
128
|
+
async wireConnectionEvents() {
|
|
129
|
+
const page = this.page;
|
|
130
|
+
// `exposeFunction` can only bind a given name once and a page can be
|
|
131
|
+
// reused by a later client, so route the page binding through a per-page
|
|
132
|
+
// dispatcher. A second client re-points the existing binding at itself
|
|
133
|
+
// instead of leaving the previous client's callback installed.
|
|
134
|
+
await page
|
|
135
|
+
.exposeFunction('onConnectionChange', (isRegistered) => {
|
|
136
|
+
Whatsapp.connectionDispatchers.get(page)?.(isRegistered);
|
|
137
|
+
})
|
|
138
|
+
.catch(() => null);
|
|
139
|
+
Whatsapp.connectionDispatchers.set(page, (isRegistered) => this.onConnectionChange(isRegistered));
|
|
140
|
+
await (0, helpers_1.evaluateAndReturn)(page, () => {
|
|
141
|
+
const handler = window.onConnectionChange;
|
|
142
|
+
if (typeof handler !== 'function' || handler.__wppWired) {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
handler.__wppWired = true;
|
|
146
|
+
WPP.on('conn.authenticated', () => handler(true));
|
|
147
|
+
WPP.on('conn.main_ready', () => handler(true));
|
|
148
|
+
WPP.on('conn.logout', () => handler(false));
|
|
149
|
+
WPP.on('conn.require_auth', () => handler(false));
|
|
150
|
+
}).catch(() => null);
|
|
151
|
+
}
|
|
152
|
+
onConnectionChange(isRegistered) {
|
|
153
|
+
if (isRegistered === this.connected) {
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const wasConnected = this.connected;
|
|
157
|
+
this.connected = isRegistered;
|
|
158
|
+
// Only a registered -> unregistered transition is a disconnection. The
|
|
159
|
+
// first event on a fresh page can arrive before afterPageScriptInjected()
|
|
160
|
+
// records the initial state, and a page that was never paired is not a
|
|
161
|
+
// phone that disconnected.
|
|
162
|
+
if (!isRegistered && wasConnected === true) {
|
|
163
|
+
this.log('info', 'Session Unpaired', { type: 'session' });
|
|
164
|
+
setTimeout(() => {
|
|
165
|
+
if (this.statusFind) {
|
|
166
|
+
try {
|
|
167
|
+
this.statusFind('disconnectedMobile', this.session || '');
|
|
168
|
+
}
|
|
169
|
+
catch (error) { }
|
|
170
|
+
}
|
|
171
|
+
}, 1000);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
106
174
|
/**
|
|
107
175
|
* Decrypts message file
|
|
108
176
|
* @param data Message object
|
|
@@ -170,20 +238,10 @@ class Whatsapp extends business_layer_1.BusinessLayer {
|
|
|
170
238
|
*/
|
|
171
239
|
async close() {
|
|
172
240
|
this.cancelQrLoop();
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
/*
|
|
178
|
-
Code was removed as it is not necessary.
|
|
179
|
-
try {
|
|
180
|
-
const process = browser.process();
|
|
181
|
-
if (process) {
|
|
182
|
-
treekill(process.pid, 'SIGKILL');
|
|
183
|
-
}
|
|
184
|
-
} catch (error) {}
|
|
185
|
-
*/
|
|
186
|
-
}
|
|
241
|
+
// The page may already be closed (autoClose, crash or logout), but the
|
|
242
|
+
// browser and its OS process tree must still be released
|
|
243
|
+
await this.page.close().catch(() => null);
|
|
244
|
+
await (0, browser_1.closeBrowser)(this.page.browser());
|
|
187
245
|
return true;
|
|
188
246
|
}
|
|
189
247
|
/**
|
|
@@ -222,18 +280,9 @@ class Whatsapp extends business_layer_1.BusinessLayer {
|
|
|
222
280
|
const options = (0, decrypt_1.makeOptions)(WAuserAgente_1.useragentOverride);
|
|
223
281
|
if (!mediaUrl)
|
|
224
282
|
throw new Error('message is missing critical data (`mediaUrl`) needed to download the file.');
|
|
225
|
-
let haventGottenImageYet = true;
|
|
226
283
|
let res;
|
|
227
284
|
try {
|
|
228
|
-
|
|
229
|
-
res = await axios_1.default.get(mediaUrl.trim(), options);
|
|
230
|
-
if (res.status == 200) {
|
|
231
|
-
haventGottenImageYet = false;
|
|
232
|
-
}
|
|
233
|
-
else {
|
|
234
|
-
await (0, decrypt_1.timeout)(2000);
|
|
235
|
-
}
|
|
236
|
-
}
|
|
285
|
+
res = await getUntilOk(mediaUrl.trim(), options);
|
|
237
286
|
}
|
|
238
287
|
catch (error) {
|
|
239
288
|
throw new Error('Error trying to download the file.');
|
|
@@ -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
|
|
@@ -30,6 +32,16 @@ export interface CreateConfig {
|
|
|
30
32
|
* Parameters to be added into the chrome browser instance
|
|
31
33
|
*/
|
|
32
34
|
browserArgs?: string[];
|
|
35
|
+
/**
|
|
36
|
+
* Adds the protection-disabling launch flags (`--no-sandbox`,
|
|
37
|
+
* `--disable-setuid-sandbox`, `--ignore-certificate-errors` and
|
|
38
|
+
* `--disable-site-isolation-trials`) to the resolved launch arguments.
|
|
39
|
+
* Disabling these protections weakens the browser sandbox and certificate
|
|
40
|
+
* validation, so it is opt-in and should only be used where the environment
|
|
41
|
+
* requires it.
|
|
42
|
+
* @default false
|
|
43
|
+
*/
|
|
44
|
+
useInsecureChromiumArgs?: boolean;
|
|
33
45
|
/**
|
|
34
46
|
* Will be passed to puppeteer.launch
|
|
35
47
|
*/
|
|
@@ -115,7 +127,7 @@ export interface CreateConfig {
|
|
|
115
127
|
* Normalmente, versões mais antigas continuam funcionando por mais um tempo,
|
|
116
128
|
* assim, com essa opção, é possível ter uma janela de tempo maior para se preparar para atualizações.
|
|
117
129
|
* Caso seja definido vazio ou null, será usado a versão atual, ou seja, sem forçar versão específica.
|
|
118
|
-
* @default
|
|
130
|
+
* @default ''
|
|
119
131
|
*/
|
|
120
132
|
whatsappVersion?: string;
|
|
121
133
|
/**
|
|
@@ -10,7 +10,7 @@ exports.defaultOptions = {
|
|
|
10
10
|
debug: false,
|
|
11
11
|
logQR: true,
|
|
12
12
|
browserWS: '',
|
|
13
|
-
|
|
13
|
+
useInsecureChromiumArgs: false,
|
|
14
14
|
puppeteerOptions: {},
|
|
15
15
|
disableWelcome: false,
|
|
16
16
|
updatesLog: true,
|
|
@@ -21,7 +21,7 @@ exports.defaultOptions = {
|
|
|
21
21
|
waitForLogin: true,
|
|
22
22
|
logger: logger_1.defaultLogger,
|
|
23
23
|
tokenStore: 'file',
|
|
24
|
-
whatsappVersion: '
|
|
24
|
+
whatsappVersion: '',
|
|
25
25
|
deviceName: false,
|
|
26
26
|
linkPreviewApiServers: null,
|
|
27
27
|
disableGoogleAnalytics: true,
|
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
declare const puppeteerConfig: {
|
|
2
2
|
whatsappUrl: string;
|
|
3
|
+
/**
|
|
4
|
+
* Default launch and performance flags for headless/container environments.
|
|
5
|
+
* They do not disable browser protection; callers that need the flags in
|
|
6
|
+
* `protectionDisablingChromiumArgs` must opt in explicitly.
|
|
7
|
+
*/
|
|
3
8
|
chromiumArgs: string[];
|
|
9
|
+
/**
|
|
10
|
+
* Flags that disable browser protections. They are never applied by default:
|
|
11
|
+
* use `useInsecureChromiumArgs: true` or add them to `browserArgs` when an
|
|
12
|
+
* environment explicitly requires them (for example a container that cannot
|
|
13
|
+
* use the Chromium sandbox).
|
|
14
|
+
*/
|
|
15
|
+
protectionDisablingChromiumArgs: string[];
|
|
4
16
|
};
|
|
5
17
|
export { puppeteerConfig };
|
|
@@ -19,28 +19,26 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
19
19
|
exports.puppeteerConfig = void 0;
|
|
20
20
|
const puppeteerConfig = {
|
|
21
21
|
whatsappUrl: 'https://web.whatsapp.com',
|
|
22
|
+
/**
|
|
23
|
+
* Default launch and performance flags for headless/container environments.
|
|
24
|
+
* They do not disable browser protection; callers that need the flags in
|
|
25
|
+
* `protectionDisablingChromiumArgs` must opt in explicitly.
|
|
26
|
+
*/
|
|
22
27
|
chromiumArgs: [
|
|
23
28
|
// `--app=${WAUrl}`,
|
|
24
29
|
'--log-level=3', // fatal only
|
|
25
30
|
//'--start-maximized',
|
|
26
31
|
'--no-default-browser-check',
|
|
27
|
-
'--disable-site-isolation-trials',
|
|
28
32
|
'--no-experiments',
|
|
29
33
|
'--ignore-gpu-blacklist',
|
|
30
|
-
'--ignore-certificate-errors',
|
|
31
|
-
'--ignore-certificate-errors-spki-list',
|
|
32
34
|
'--disable-gpu',
|
|
33
35
|
'--disable-extensions',
|
|
34
36
|
'--disable-default-apps',
|
|
35
37
|
'--enable-features=NetworkService',
|
|
36
|
-
'--disable-setuid-sandbox',
|
|
37
|
-
'--no-sandbox',
|
|
38
38
|
// Extras
|
|
39
39
|
'--disable-webgl',
|
|
40
40
|
'--disable-infobars',
|
|
41
41
|
'--window-position=0,0',
|
|
42
|
-
'--ignore-certifcate-errors',
|
|
43
|
-
'--ignore-certifcate-errors-spki-list',
|
|
44
42
|
'--disable-threaded-animation',
|
|
45
43
|
'--disable-threaded-scrolling',
|
|
46
44
|
'--disable-in-process-stack-traces',
|
|
@@ -58,5 +56,17 @@ const puppeteerConfig = {
|
|
|
58
56
|
'--autoplay-policy=no-user-gesture-required',
|
|
59
57
|
'--disable-blink-features=AutomationControlled',
|
|
60
58
|
],
|
|
59
|
+
/**
|
|
60
|
+
* Flags that disable browser protections. They are never applied by default:
|
|
61
|
+
* use `useInsecureChromiumArgs: true` or add them to `browserArgs` when an
|
|
62
|
+
* environment explicitly requires them (for example a container that cannot
|
|
63
|
+
* use the Chromium sandbox).
|
|
64
|
+
*/
|
|
65
|
+
protectionDisablingChromiumArgs: [
|
|
66
|
+
'--no-sandbox',
|
|
67
|
+
'--disable-setuid-sandbox',
|
|
68
|
+
'--ignore-certificate-errors',
|
|
69
|
+
'--disable-site-isolation-trials',
|
|
70
|
+
],
|
|
61
71
|
};
|
|
62
72
|
exports.puppeteerConfig = puppeteerConfig;
|
package/dist/controllers/auth.js
CHANGED
|
@@ -94,7 +94,9 @@ const needsToScan = async (waPage) => {
|
|
|
94
94
|
};
|
|
95
95
|
exports.needsToScan = needsToScan;
|
|
96
96
|
const isInsideChat = async (waPage) => {
|
|
97
|
-
|
|
97
|
+
// Some WhatsApp versions report main_ready while still showing the QR screen.
|
|
98
|
+
// Read both conditions in the same document before treating it as a chat.
|
|
99
|
+
return await waPage.evaluate(() => WPP.conn.isRegistered() && WPP.conn.isMainReady());
|
|
98
100
|
};
|
|
99
101
|
exports.isInsideChat = isInsideChat;
|
|
100
102
|
const isConnectingToPhone = async (waPage) => {
|
|
@@ -38,9 +38,36 @@ export declare class InjectionTimeoutError extends Error {
|
|
|
38
38
|
*/
|
|
39
39
|
export declare function waitForWppReady(page: Page, options?: WaitForReadyOptions): Promise<void>;
|
|
40
40
|
export declare function injectApi(page: Page, onLoadingScreenCallBack?: LoadingScreenCallback, options?: InjectApiOptions): Promise<void>;
|
|
41
|
+
/**
|
|
42
|
+
* Resolves the Chromium launch arguments.
|
|
43
|
+
*
|
|
44
|
+
* When the caller passes no arguments (or an empty list) the default
|
|
45
|
+
* `puppeteerConfig.chromiumArgs` are used. A non-empty list replaces the
|
|
46
|
+
* defaults, matching the existing `browserArgs` contract. The default list only
|
|
47
|
+
* contains launch and performance flags; the flags that disable browser
|
|
48
|
+
* protections live in `puppeteerConfig.protectionDisablingChromiumArgs` and are
|
|
49
|
+
* only merged in when `useInsecureChromiumArgs` is explicitly enabled.
|
|
50
|
+
*/
|
|
51
|
+
export declare function resolveBrowserArgs(requested?: string[], useInsecure?: boolean): string[];
|
|
41
52
|
/**
|
|
42
53
|
* Initializes browser, will try to use chrome as default
|
|
43
54
|
* @param session
|
|
44
55
|
*/
|
|
45
56
|
export declare function initBrowser(session: string, options: CreateConfig, logger: Logger): Promise<Browser>;
|
|
57
|
+
/**
|
|
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.
|
|
61
|
+
* Remote browsers (`browserWS`) expose no process handle and are only
|
|
62
|
+
* disconnected. Safe to call when the page/browser was already closed.
|
|
63
|
+
*/
|
|
64
|
+
export declare function closeBrowser(browser: Browser): Promise<void>;
|
|
46
65
|
export declare function getOrCreatePage(browser: Browser | BrowserContext): Promise<Page>;
|
|
66
|
+
/**
|
|
67
|
+
* Returns whether at least one open, non-blank page remains.
|
|
68
|
+
*
|
|
69
|
+
* Puppeteer commonly leaves an `about:blank` tab behind after the session page
|
|
70
|
+
* is closed, so a non-empty `browser.pages()` does not prove a real page is
|
|
71
|
+
* still alive. This drives the auto-close guard in `create()`.
|
|
72
|
+
*/
|
|
73
|
+
export declare function hasAlivePage(pages: Page[]): boolean;
|
|
@@ -59,8 +59,11 @@ exports.initWhatsapp = initWhatsapp;
|
|
|
59
59
|
exports.onLoadingScreen = onLoadingScreen;
|
|
60
60
|
exports.waitForWppReady = waitForWppReady;
|
|
61
61
|
exports.injectApi = injectApi;
|
|
62
|
+
exports.resolveBrowserArgs = resolveBrowserArgs;
|
|
62
63
|
exports.initBrowser = initBrowser;
|
|
64
|
+
exports.closeBrowser = closeBrowser;
|
|
63
65
|
exports.getOrCreatePage = getOrCreatePage;
|
|
66
|
+
exports.hasAlivePage = hasAlivePage;
|
|
64
67
|
const ChromeLauncher = __importStar(require("chrome-launcher"));
|
|
65
68
|
const os = __importStar(require("os"));
|
|
66
69
|
const path = __importStar(require("path"));
|
|
@@ -72,6 +75,8 @@ const puppeteer_config_1 = require("../config/puppeteer.config");
|
|
|
72
75
|
const puppeteer_extra_plugin_stealth_1 = __importDefault(require("puppeteer-extra-plugin-stealth"));
|
|
73
76
|
const WAuserAgente_1 = require("../config/WAuserAgente");
|
|
74
77
|
const websocket_1 = require("./websocket");
|
|
78
|
+
const logger_1 = require("../utils/logger");
|
|
79
|
+
const treeKill = require('tree-kill');
|
|
75
80
|
async function unregisterServiceWorker(page) {
|
|
76
81
|
await page.evaluateOnNewDocument(() => {
|
|
77
82
|
// Remove existent service worker
|
|
@@ -86,10 +91,10 @@ async function unregisterServiceWorker(page) {
|
|
|
86
91
|
// Disable service worker registration
|
|
87
92
|
// @ts-ignore
|
|
88
93
|
navigator.serviceWorker.register = new Promise(() => { });
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
94
|
+
// Assign once per document; re-running this on an interval only wakes the
|
|
95
|
+
// renderer every 500ms for no benefit
|
|
96
|
+
window.onerror = console.error;
|
|
97
|
+
window.onunhandledrejection = console.error;
|
|
93
98
|
});
|
|
94
99
|
}
|
|
95
100
|
/**
|
|
@@ -243,6 +248,8 @@ async function waitForWppReady(page, options = {}) {
|
|
|
243
248
|
}, {
|
|
244
249
|
// 0 would mean no limit to puppeteer
|
|
245
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,
|
|
246
253
|
signal: options.signal,
|
|
247
254
|
});
|
|
248
255
|
}
|
|
@@ -327,6 +334,29 @@ async function runInjection(page, onLoadingScreenCallBack, options) {
|
|
|
327
334
|
// Make sure WAPI is initialized
|
|
328
335
|
await waitForWppReady(page, options);
|
|
329
336
|
}
|
|
337
|
+
/**
|
|
338
|
+
* Resolves the Chromium launch arguments.
|
|
339
|
+
*
|
|
340
|
+
* When the caller passes no arguments (or an empty list) the default
|
|
341
|
+
* `puppeteerConfig.chromiumArgs` are used. A non-empty list replaces the
|
|
342
|
+
* defaults, matching the existing `browserArgs` contract. The default list only
|
|
343
|
+
* contains launch and performance flags; the flags that disable browser
|
|
344
|
+
* protections live in `puppeteerConfig.protectionDisablingChromiumArgs` and are
|
|
345
|
+
* only merged in when `useInsecureChromiumArgs` is explicitly enabled.
|
|
346
|
+
*/
|
|
347
|
+
function resolveBrowserArgs(requested, useInsecure = false) {
|
|
348
|
+
const args = [
|
|
349
|
+
...(requested?.length ? requested : puppeteer_config_1.puppeteerConfig.chromiumArgs),
|
|
350
|
+
];
|
|
351
|
+
if (useInsecure) {
|
|
352
|
+
for (const arg of puppeteer_config_1.puppeteerConfig.protectionDisablingChromiumArgs) {
|
|
353
|
+
if (!args.includes(arg)) {
|
|
354
|
+
args.push(arg);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return args;
|
|
359
|
+
}
|
|
330
360
|
/**
|
|
331
361
|
* Initializes browser, will try to use chrome as default
|
|
332
362
|
* @param session
|
|
@@ -362,9 +392,7 @@ async function initBrowser(session, options, logger) {
|
|
|
362
392
|
* If proxy settings are provided, they are applied to the browser launch arguments.
|
|
363
393
|
* This allows the browser to use the specified proxy server for all network requests.
|
|
364
394
|
*/
|
|
365
|
-
const args = options.browserArgs
|
|
366
|
-
? options.browserArgs
|
|
367
|
-
: [...puppeteer_config_1.puppeteerConfig.chromiumArgs];
|
|
395
|
+
const args = resolveBrowserArgs(options.browserArgs, options.useInsecureChromiumArgs);
|
|
368
396
|
if (options.proxy && options.proxy.url) {
|
|
369
397
|
args.push(`--proxy-server=${options.proxy.url}`);
|
|
370
398
|
}
|
|
@@ -397,6 +425,89 @@ async function initBrowser(session, options, logger) {
|
|
|
397
425
|
}
|
|
398
426
|
return browser;
|
|
399
427
|
}
|
|
428
|
+
const closingBrowsers = new WeakMap();
|
|
429
|
+
/**
|
|
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.
|
|
433
|
+
* Remote browsers (`browserWS`) expose no process handle and are only
|
|
434
|
+
* disconnected. Safe to call when the page/browser was already closed.
|
|
435
|
+
*/
|
|
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) {
|
|
453
|
+
// Only browsers launched by this process expose a process handle
|
|
454
|
+
const child = browser.process?.();
|
|
455
|
+
const pid = child?.pid;
|
|
456
|
+
if (!pid) {
|
|
457
|
+
// Caller-supplied remote connection: detach this client only. Closing it
|
|
458
|
+
// would terminate the browser shared with every other connected client.
|
|
459
|
+
// Connections that expose neither a process handle nor a disconnect method
|
|
460
|
+
// (e.g. test doubles) fall back to close().
|
|
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;
|
|
470
|
+
}
|
|
471
|
+
catch (error) {
|
|
472
|
+
logger_1.defaultLogger.warn(`Browser ${action} failed`, { error });
|
|
473
|
+
return false;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
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
|
+
});
|
|
483
|
+
// Bound the graceful close so an unresponsive browser cannot hang teardown
|
|
484
|
+
let timer;
|
|
485
|
+
const timedOut = new Promise((resolve) => {
|
|
486
|
+
timer = setTimeout(resolve, 5000);
|
|
487
|
+
});
|
|
488
|
+
try {
|
|
489
|
+
await Promise.race([gracefulClose, timedOut]);
|
|
490
|
+
}
|
|
491
|
+
finally {
|
|
492
|
+
clearTimeout(timer);
|
|
493
|
+
}
|
|
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
|
+
});
|
|
509
|
+
});
|
|
510
|
+
}
|
|
400
511
|
async function getOrCreatePage(browser) {
|
|
401
512
|
const pages = await browser.pages();
|
|
402
513
|
if (pages.length) {
|
|
@@ -404,6 +515,16 @@ async function getOrCreatePage(browser) {
|
|
|
404
515
|
}
|
|
405
516
|
return await browser.newPage();
|
|
406
517
|
}
|
|
518
|
+
/**
|
|
519
|
+
* Returns whether at least one open, non-blank page remains.
|
|
520
|
+
*
|
|
521
|
+
* Puppeteer commonly leaves an `about:blank` tab behind after the session page
|
|
522
|
+
* is closed, so a non-empty `browser.pages()` does not prove a real page is
|
|
523
|
+
* still alive. This drives the auto-close guard in `create()`.
|
|
524
|
+
*/
|
|
525
|
+
function hasAlivePage(pages) {
|
|
526
|
+
return pages.some((page) => !page.isClosed() && page.url() !== 'about:blank');
|
|
527
|
+
}
|
|
407
528
|
/**
|
|
408
529
|
* Retrieves chrome instance path
|
|
409
530
|
*/
|