tt-help-cli-ycl 1.3.24 → 1.3.26

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.
Files changed (60) hide show
  1. package/README.md +17 -17
  2. package/cli.js +9 -9
  3. package/package.json +47 -47
  4. package/scripts/run-explore copy.bat +68 -68
  5. package/scripts/run-explore.bat +68 -68
  6. package/scripts/run-explore.ps1 +81 -81
  7. package/scripts/run-explore.sh +73 -73
  8. package/scripts/test-captcha-lib.mjs +68 -0
  9. package/scripts/test-captcha.mjs +81 -0
  10. package/scripts/test-incognito-lib.mjs +36 -0
  11. package/scripts/test-login-state.mjs +128 -0
  12. package/scripts/test-safe-click.mjs +45 -0
  13. package/src/cli/attach.js +180 -180
  14. package/src/cli/auto.js +240 -186
  15. package/src/cli/config.js +152 -152
  16. package/src/cli/explore.js +439 -253
  17. package/src/cli/info.js +88 -88
  18. package/src/cli/open.js +102 -0
  19. package/src/cli/progress.js +111 -111
  20. package/src/cli/refresh.js +216 -216
  21. package/src/cli/scrape.js +47 -47
  22. package/src/cli/utils.js +18 -18
  23. package/src/cli/videos.js +41 -41
  24. package/src/cli/watch.js +31 -31
  25. package/src/lib/api-interceptor.js +191 -191
  26. package/src/lib/args.js +551 -517
  27. package/src/lib/browser/anti-detect.js +23 -23
  28. package/src/lib/browser/cdp.js +237 -194
  29. package/src/lib/browser/health-checker.js +93 -0
  30. package/src/lib/browser/launch.js +43 -43
  31. package/src/lib/browser/page.js +156 -156
  32. package/src/lib/constants.js +206 -199
  33. package/src/lib/delay.js +54 -54
  34. package/src/lib/explore-fetch.js +118 -118
  35. package/src/lib/fetcher.js +45 -45
  36. package/src/lib/filter.js +66 -66
  37. package/src/lib/io.js +54 -54
  38. package/src/lib/output.js +80 -80
  39. package/src/lib/page-error-detector.js +71 -71
  40. package/src/lib/parse-ssr.mjs +69 -69
  41. package/src/lib/parser.js +47 -47
  42. package/src/lib/retry.js +45 -45
  43. package/src/lib/scrape.js +89 -89
  44. package/src/lib/tiktok-scraper.mjs +194 -194
  45. package/src/lib/url.js +52 -52
  46. package/src/main.js +44 -42
  47. package/src/results/user-videos-bar.lar.lar.moeta.json +37 -0
  48. package/src/scraper/auto-core.js +203 -203
  49. package/src/scraper/core.js +211 -211
  50. package/src/scraper/explore-core.js +201 -189
  51. package/src/scraper/modules/captcha-handler.js +114 -114
  52. package/src/scraper/modules/comment-extractor.js +74 -74
  53. package/src/scraper/modules/follow-extractor.js +118 -118
  54. package/src/scraper/modules/guess-extractor.js +51 -51
  55. package/src/scraper/modules/page-helpers.js +48 -48
  56. package/src/scraper/refresh-core.js +179 -179
  57. package/src/videos/core.js +101 -101
  58. package/src/watch/data-store.js +828 -828
  59. package/src/watch/public/index.html +753 -753
  60. package/src/watch/server.js +705 -705
@@ -1,23 +1,23 @@
1
- export function getAntiDetectScript() {
2
- return () => {
3
- Object.defineProperty(navigator, 'webdriver', { get: () => false });
4
-
5
- if (!window.chrome) {
6
- window.chrome = { runtime: {} };
7
- }
8
-
9
- const originalQuery = window.navigator.permissions.query;
10
- window.navigator.permissions.query = (params) =>
11
- params.name === 'notifications'
12
- ? Promise.resolve({ state: Notification.permission })
13
- : originalQuery(params);
14
-
15
- Object.defineProperty(navigator, 'languages', {
16
- get: () => ['en-US', 'en'],
17
- });
18
-
19
- Object.defineProperty(navigator, 'plugins', {
20
- get: () => [1, 2, 3, 4, 5],
21
- });
22
- };
23
- }
1
+ export function getAntiDetectScript() {
2
+ return () => {
3
+ Object.defineProperty(navigator, 'webdriver', { get: () => false });
4
+
5
+ if (!window.chrome) {
6
+ window.chrome = { runtime: {} };
7
+ }
8
+
9
+ const originalQuery = window.navigator.permissions.query;
10
+ window.navigator.permissions.query = (params) =>
11
+ params.name === 'notifications'
12
+ ? Promise.resolve({ state: Notification.permission })
13
+ : originalQuery(params);
14
+
15
+ Object.defineProperty(navigator, 'languages', {
16
+ get: () => ['en-US', 'en'],
17
+ });
18
+
19
+ Object.defineProperty(navigator, 'plugins', {
20
+ get: () => [1, 2, 3, 4, 5],
21
+ });
22
+ };
23
+ }
@@ -1,194 +1,237 @@
1
- import { exec } from 'child_process';
2
- import { execSync } from 'child_process';
3
- import http from 'http';
4
- import os from 'os';
5
- import path from 'path';
6
- import { chromium } from 'playwright';
7
-
8
- const DEFAULT_CDP_PORT = 9222;
9
- const DEFAULT_USER_DATA_DIR = path.join(os.homedir(), 'Library', 'Application Support', 'Microsoft Edge For Testing');
10
-
11
- function getEdgePath() {
12
- const platform = os.platform();
13
- if (platform === 'darwin') return '"Microsoft Edge"';
14
- if (platform === 'win32') return 'msedge.exe';
15
- return 'msedge';
16
- }
17
-
18
- function isEdgeRunning() {
19
- return new Promise(resolve => {
20
- const platform = os.platform();
21
- let command;
22
- if (platform === 'darwin') {
23
- command = 'ps aux | grep -q "[M]icrosoft Edge.app/Contents/MacOS/Microsoft Edge" 2>/dev/null';
24
- } else if (platform === 'win32') {
25
- command = 'tasklist /FI "IMAGENAME eq msedge.exe" 2>nul | findstr /I msedge';
26
- } else {
27
- command = 'pgrep -f msedge > /dev/null 2>&1';
28
- }
29
- exec(command, (err) => resolve(!err));
30
- });
31
- }
32
-
33
- function checkCDPPort(port) {
34
- return new Promise(resolve => {
35
- const req = http.get(`http://127.0.0.1:${port}/json`, res => {
36
- res.on('data', () => {});
37
- res.on('end', () => resolve(res.statusCode === 200));
38
- });
39
- req.on('error', () => resolve(false));
40
- req.setTimeout(3000, () => { resolve(false); req.destroy(); });
41
- });
42
- }
43
-
44
- function checkEdgeArgs() {
45
- return new Promise(resolve => {
46
- const platform = os.platform();
47
- let command;
48
- if (platform === 'darwin') {
49
- command = 'ps aux | grep "[M]icrosoft Edge" | grep -v "Helper\\|crashpad" | grep "user-data-dir"';
50
- } else if (platform === 'win32') {
51
- command = 'wmic process where "name like \\"%msedge%\\"" get commandline | findstr "user-data-dir"';
52
- } else {
53
- command = 'ps aux | grep "[m]sedge" | grep -v "Helper\\|crashpad" | grep "user-data-dir"';
54
- }
55
- exec(command, (err, stdout) => resolve(!err && stdout.trim().length > 0));
56
- });
57
- }
58
-
59
- function killEdgeProcesses(targetDir) {
60
- return new Promise(resolve => {
61
- const platform = os.platform();
62
- let command;
63
- if (platform === 'darwin') {
64
- if (targetDir) {
65
- let pids = '';
66
- try {
67
- // ps aux 输出中 --user-data-dir= 后面没有引号
68
- // 用路径精确匹配,结尾加空格或行尾避免子串误杀
69
- const escapedDir = targetDir.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
70
- pids = execSync(
71
- `ps aux | grep "[M]icrosoft Edge" | grep -v "Helper\\|crashpad" | grep -E -- '--user-data-dir=${escapedDir}($|[^A-Za-z0-9_])' | awk '{print $2}'`
72
- ).toString().trim();
73
- } catch (e) {
74
- pids = '';
75
- }
76
- if (pids) {
77
- command = `kill -9 ${pids} 2>/dev/null; rm -f ~/Library/Caches/Microsoft\\ Edge/Singleton*; true`;
78
- } else {
79
- command = 'true';
80
- }
81
- } else {
82
- command = 'killall -9 "Microsoft Edge" 2>/dev/null; rm -f ~/Library/Caches/Microsoft\\ Edge/Singleton*; true';
83
- }
84
- } else if (platform === 'win32') {
85
- command = 'taskkill /F /IM msedge.exe 2>nul || exit 0';
86
- } else {
87
- if (targetDir) {
88
- const escapedDir = targetDir.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
89
- command = `ps aux | grep msedge | grep -v Helper | grep -E -- '--user-data-dir=${escapedDir}($|[^A-Za-z0-9_])' | awk '{print $2}' | xargs -r kill -9 2>/dev/null; true`;
90
- } else {
91
- command = 'pkill -9 -f msedge 2>/dev/null; true';
92
- }
93
- }
94
- exec(command, () => resolve());
95
- });
96
- }
97
-
98
- function launchEdgeWithCDP(port, userDataDir) {
99
- return new Promise((resolve, reject) => {
100
- const platform = os.platform();
101
- const edgePath = getEdgePath();
102
- let command;
103
-
104
- const extraArgs = [
105
- `--remote-debugging-port=${port}`,
106
- `--user-data-dir="${userDataDir}"`,
107
- '--disable-blink-features=AutomationControlled',
108
- '--no-first-run',
109
- '--no-default-browser-check',
110
- '--password-store=basic',
111
- '--disable-background-mode',
112
- '--disable-component-update',
113
- '--disable-crash-reporter',
114
- '--disable-breakpad',
115
- '--disable-background-networking',
116
- '--disable-sync',
117
- ].join(' ');
118
-
119
- if (platform === 'darwin') {
120
- command = `open -a ${edgePath} --new --args ${extraArgs}`;
121
- } else if (platform === 'win32') {
122
- command = `start msedge ${extraArgs}`;
123
- } else {
124
- command = `msedge ${extraArgs} &`;
125
- }
126
-
127
- exec(command, (err) => {
128
- if (err) reject(new Error(`启动 Edge 浏览器失败: ${err.message}`));
129
- else resolve();
130
- });
131
- });
132
- }
133
-
134
- async function waitForCDP(port, timeout = 30000, interval = 1000) {
135
- const start = Date.now();
136
- while (Date.now() - start < timeout) {
137
- const ready = await checkCDPPort(port);
138
- if (ready) return true;
139
- await new Promise(r => setTimeout(r, interval));
140
- }
141
- return false;
142
- }
143
-
144
- export { killEdgeProcesses };
145
-
146
- export async function ensureBrowserReady(options = {}) {
147
- const port = options.port || DEFAULT_CDP_PORT;
148
- const userDataDir = options.userDataDir || DEFAULT_USER_DATA_DIR;
149
- const isCustom = port !== DEFAULT_CDP_PORT || !!options.userDataDir;
150
-
151
- const isReady = await checkCDPPort(port);
152
- let needLaunch = !isReady;
153
-
154
- if (!needLaunch) {
155
- if (!isCustom) {
156
- const edgeArgsValid = await checkEdgeArgs();
157
- if (!edgeArgsValid) {
158
- console.error(`Edge 已运行但启动参数不完整,正在重启端口 ${port}...`);
159
- await killEdgeProcesses(userDataDir);
160
- await new Promise(r => setTimeout(r, 3000));
161
- needLaunch = true;
162
- }
163
- }
164
- }
165
-
166
- if (needLaunch) {
167
- if (isCustom) {
168
- console.error(`CDP 端口 ${port} 未就绪,正在启动 Edge 浏览器...`);
169
- } else {
170
- const edgeRunning = await isEdgeRunning();
171
- if (edgeRunning) {
172
- console.error(`Edge 已运行但 CDP 端口 ${port} 未启用,正在重启...`);
173
- await killEdgeProcesses(userDataDir);
174
- await new Promise(r => setTimeout(r, 3000));
175
- } else {
176
- console.error(`CDP 端口 ${port} 未就绪,正在启动 Edge 浏览器...`);
177
- }
178
- }
179
- await launchEdgeWithCDP(port, userDataDir);
180
-
181
- console.error('等待浏览器启动...');
182
- const launched = await waitForCDP(port);
183
- if (!launched) {
184
- throw new Error(
185
- `等待 CDP 端口 ${port} 超时。请确认 Edge 浏览器已安装,\n` +
186
- `或手动启动: Microsoft Edge --remote-debugging-port=${port} [参见 cdp.js extraArgs]`
187
- );
188
- }
189
- console.error('浏览器启动成功');
190
- }
191
-
192
- const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
193
- return browser;
194
- }
1
+ import { exec } from 'child_process';
2
+ import { execSync } from 'child_process';
3
+ import fs from 'fs';
4
+ import http from 'http';
5
+ import os from 'os';
6
+ import path from 'path';
7
+ import { chromium } from 'playwright';
8
+
9
+ const DEFAULT_CDP_PORT = 9222;
10
+ const DEFAULT_USER_DATA_DIR = path.join(os.homedir(), 'Library', 'Application Support', 'Microsoft Edge For Testing');
11
+
12
+ function getEdgePath() {
13
+ const platform = os.platform();
14
+ if (platform === 'darwin') return '"Microsoft Edge"';
15
+ if (platform === 'win32') return 'msedge.exe';
16
+ return 'msedge';
17
+ }
18
+
19
+ function isEdgeRunning() {
20
+ return new Promise(resolve => {
21
+ const platform = os.platform();
22
+ let command;
23
+ if (platform === 'darwin') {
24
+ command = 'ps aux | grep -q "[M]icrosoft Edge.app/Contents/MacOS/Microsoft Edge" 2>/dev/null';
25
+ } else if (platform === 'win32') {
26
+ command = 'tasklist /FI "IMAGENAME eq msedge.exe" 2>nul | findstr /I msedge';
27
+ } else {
28
+ command = 'pgrep -f msedge > /dev/null 2>&1';
29
+ }
30
+ exec(command, (err) => resolve(!err));
31
+ });
32
+ }
33
+
34
+ function checkCDPPort(port) {
35
+ return new Promise(resolve => {
36
+ const req = http.get(`http://127.0.0.1:${port}/json`, res => {
37
+ res.on('data', () => {});
38
+ res.on('end', () => resolve(res.statusCode === 200));
39
+ });
40
+ req.on('error', () => resolve(false));
41
+ req.setTimeout(3000, () => { resolve(false); req.destroy(); });
42
+ });
43
+ }
44
+
45
+ function checkEdgeArgs() {
46
+ return new Promise(resolve => {
47
+ const platform = os.platform();
48
+ let command;
49
+ if (platform === 'darwin') {
50
+ command = 'ps aux | grep "[M]icrosoft Edge" | grep -v "Helper\\|crashpad" | grep "user-data-dir"';
51
+ } else if (platform === 'win32') {
52
+ command = 'wmic process where "name like \\"%msedge%\\"" get commandline | findstr "user-data-dir"';
53
+ } else {
54
+ command = 'ps aux | grep "[m]sedge" | grep -v "Helper\\|crashpad" | grep "user-data-dir"';
55
+ }
56
+ exec(command, (err, stdout) => resolve(!err && stdout.trim().length > 0));
57
+ });
58
+ }
59
+
60
+ function killEdgeProcesses(targetDir) {
61
+ return new Promise(resolve => {
62
+ const platform = os.platform();
63
+ let command;
64
+ if (platform === 'darwin') {
65
+ if (targetDir) {
66
+ let pids = '';
67
+ try {
68
+ // ps aux 输出中 --user-data-dir= 后面没有引号
69
+ // 用路径精确匹配,结尾加空格或行尾避免子串误杀
70
+ const escapedDir = targetDir.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
71
+ pids = execSync(
72
+ `ps aux | grep "[M]icrosoft Edge" | grep -v "Helper\\|crashpad" | grep -E -- '--user-data-dir=${escapedDir}($|[^A-Za-z0-9_])' | awk '{print $2}'`
73
+ ).toString().trim();
74
+ } catch (e) {
75
+ pids = '';
76
+ }
77
+ if (pids) {
78
+ command = `kill -9 ${pids} 2>/dev/null; rm -f ~/Library/Caches/Microsoft\\ Edge/Singleton*; true`;
79
+ } else {
80
+ command = 'true';
81
+ }
82
+ } else {
83
+ command = 'killall -9 "Microsoft Edge" 2>/dev/null; rm -f ~/Library/Caches/Microsoft\\ Edge/Singleton*; true';
84
+ }
85
+ } else if (platform === 'win32') {
86
+ if (targetDir) {
87
+ try {
88
+ const ps1Path = path.join(os.tmpdir(), `kill-edge-${Date.now()}.ps1`);
89
+ const escapedDir = targetDir.replace(/'/g, "''");
90
+ const ps1Content = `$procs = Get-CimInstance Win32_Process -Filter "Name='msedge.exe'" 2>$null; ` +
91
+ `$count = 0; ` +
92
+ `foreach ($p in $procs) { ` +
93
+ ` if ($p.CommandLine -and $p.CommandLine -like "*${escapedDir}*") { ` +
94
+ ` Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue; ` +
95
+ ` $count++ ` +
96
+ ` } ` +
97
+ `}; ` +
98
+ `Get-ChildItem "$env:LOCALAPPDATA\\Microsoft\\Edge\\Singleton*" -ErrorAction SilentlyContinue | Remove-Item -Force; ` +
99
+ `Write-Output $count`;
100
+ fs.writeFileSync(ps1Path, ps1Content);
101
+ const result = execSync(
102
+ `powershell.exe -ExecutionPolicy Bypass -File "${ps1Path}"`
103
+ ).toString().trim();
104
+ fs.unlinkSync(ps1Path);
105
+ command = 'exit 0';
106
+ } catch {
107
+ command = 'taskkill /F /IM msedge.exe 2>nul || exit 0';
108
+ }
109
+ } else {
110
+ command = 'taskkill /F /IM msedge.exe 2>nul || exit 0';
111
+ }
112
+ } else {
113
+ if (targetDir) {
114
+ const escapedDir = targetDir.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
115
+ command = `ps aux | grep msedge | grep -v Helper | grep -E -- '--user-data-dir=${escapedDir}($|[^A-Za-z0-9_])' | awk '{print $2}' | xargs -r kill -9 2>/dev/null; true`;
116
+ } else {
117
+ command = 'pkill -9 -f msedge 2>/dev/null; true';
118
+ }
119
+ }
120
+ exec(command, () => resolve());
121
+ });
122
+ }
123
+
124
+ function launchEdgeWithCDP(port, userDataDir) {
125
+ return new Promise((resolve, reject) => {
126
+ const platform = os.platform();
127
+ const edgePath = getEdgePath();
128
+ let command;
129
+
130
+ const extraArgs = [
131
+ `--remote-debugging-port=${port}`,
132
+ `--user-data-dir="${userDataDir}"`,
133
+ '--disable-blink-features=AutomationControlled',
134
+ '--no-first-run',
135
+ '--no-default-browser-check',
136
+ '--password-store=basic',
137
+ '--disable-background-mode',
138
+ '--disable-component-update',
139
+ '--disable-crash-reporter',
140
+ '--disable-breakpad',
141
+ '--disable-background-networking',
142
+ '--disable-sync',
143
+ ].join(' ');
144
+
145
+ if (platform === 'darwin') {
146
+ command = `open -a ${edgePath} --new --args ${extraArgs}`;
147
+ } else if (platform === 'win32') {
148
+ command = `start msedge ${extraArgs}`;
149
+ } else {
150
+ command = `msedge ${extraArgs} &`;
151
+ }
152
+
153
+ exec(command, (err) => {
154
+ if (err) reject(new Error(`启动 Edge 浏览器失败: ${err.message}`));
155
+ else resolve();
156
+ });
157
+ });
158
+ }
159
+
160
+ async function waitForCDP(port, timeout = 30000, interval = 1000) {
161
+ const start = Date.now();
162
+ while (Date.now() - start < timeout) {
163
+ const ready = await checkCDPPort(port);
164
+ if (ready) return true;
165
+ await new Promise(r => setTimeout(r, interval));
166
+ }
167
+ return false;
168
+ }
169
+
170
+ export { killEdgeProcesses };
171
+
172
+ export async function ensureBrowserReady(options = {}) {
173
+ const port = options.port || DEFAULT_CDP_PORT;
174
+ const userDataDir = options.userDataDir || DEFAULT_USER_DATA_DIR;
175
+ const isCustom = port !== DEFAULT_CDP_PORT || !!options.userDataDir;
176
+
177
+ const isReady = await checkCDPPort(port);
178
+ let needLaunch = !isReady;
179
+
180
+ if (!needLaunch) {
181
+ if (!isCustom) {
182
+ const edgeArgsValid = await checkEdgeArgs();
183
+ if (!edgeArgsValid) {
184
+ console.error(`Edge 已运行但启动参数不完整,正在重启端口 ${port}...`);
185
+ await killEdgeProcesses(userDataDir);
186
+ await new Promise(r => setTimeout(r, 3000));
187
+ needLaunch = true;
188
+ }
189
+ }
190
+ }
191
+
192
+ if (needLaunch) {
193
+ if (isCustom) {
194
+ console.error(`CDP 端口 ${port} 未就绪,正在启动 Edge 浏览器...`);
195
+ } else {
196
+ const edgeRunning = await isEdgeRunning();
197
+ if (edgeRunning) {
198
+ console.error(`Edge 已运行但 CDP 端口 ${port} 未启用,正在重启...`);
199
+ await killEdgeProcesses(userDataDir);
200
+ await new Promise(r => setTimeout(r, 3000));
201
+ } else {
202
+ console.error(`CDP 端口 ${port} 未就绪,正在启动 Edge 浏览器...`);
203
+ }
204
+ }
205
+ await launchEdgeWithCDP(port, userDataDir);
206
+
207
+ console.error('等待浏览器启动...');
208
+ const launched = await waitForCDP(port);
209
+ if (!launched) {
210
+ throw new Error(
211
+ `等待 CDP 端口 ${port} 超时。请确认 Edge 浏览器已安装,\n` +
212
+ `或手动启动: Microsoft Edge --remote-debugging-port=${port} [参见 cdp.js extraArgs]`
213
+ );
214
+ }
215
+ console.error('浏览器启动成功');
216
+ }
217
+
218
+ const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
219
+ return browser;
220
+ }
221
+
222
+ export async function switchAccount(oldAccount, newAccount) {
223
+ console.error(`\n[账户切换] 从端口 ${oldAccount.port} -> ${newAccount.port}`);
224
+
225
+ await killEdgeProcesses(oldAccount.userDataDir);
226
+ await new Promise(r => setTimeout(r, 3000));
227
+
228
+ const newCdpOptions = {};
229
+ newCdpOptions.port = newAccount.port;
230
+ newCdpOptions.userDataDir = newAccount.userDataDir;
231
+
232
+ const browser = await ensureBrowserReady(newCdpOptions);
233
+
234
+ await new Promise(r => setTimeout(r, 10000));
235
+
236
+ return browser;
237
+ }
@@ -0,0 +1,93 @@
1
+ import os from "os";
2
+ import path from "path";
3
+ import { execSync } from "child_process";
4
+
5
+ const TOTAL_ACCOUNTS = 10;
6
+ const BASE_PORT = 9222;
7
+ const MEMORY_THRESHOLD = 0.9;
8
+ const ROTATE_INTERVAL_MS = 2 * 60 * 60 * 1000;
9
+
10
+ class HealthChecker {
11
+ constructor() {
12
+ this.accounts = [];
13
+ for (let i = 0; i < TOTAL_ACCOUNTS; i++) {
14
+ const port = BASE_PORT + i;
15
+ const profile = `p${port}`;
16
+ this.accounts.push({
17
+ port,
18
+ profile,
19
+ userDataDir: path.join(
20
+ os.homedir(),
21
+ "Library",
22
+ "Application Support",
23
+ `Microsoft Edge For Testing_${profile}`,
24
+ ),
25
+ });
26
+ }
27
+ this.currentIndex = 0;
28
+ this.startTime = Date.now();
29
+ }
30
+
31
+ getCurrentAccount() {
32
+ return this.accounts[this.currentIndex];
33
+ }
34
+
35
+ getNextAccount() {
36
+ this.currentIndex = (this.currentIndex + 1) % TOTAL_ACCOUNTS;
37
+ return this.accounts[this.currentIndex];
38
+ }
39
+
40
+ check() {
41
+ let memUsage;
42
+ const platform = os.platform();
43
+
44
+ if (platform === "darwin") {
45
+ // macOS 上 os.freemem() 不包含 inactive 内存,导致虚高
46
+ // 使用 vm_stat 获取准确数据
47
+ try {
48
+ const vmStat = execSync("vm_stat", { encoding: "utf-8" });
49
+ const parsePages = (line) => {
50
+ const match = line.match(/Pages (\w+(?:\s+\w+)*):\s+(\d+)/);
51
+ return match ? parseInt(match[2], 10) : 0;
52
+ };
53
+ const lines = vmStat.trim().split("\n");
54
+ const pageSize = 16384;
55
+ const active = parsePages(
56
+ lines.find((l) => l.includes("active")) || "",
57
+ );
58
+ const wired = parsePages(
59
+ lines.find((l) => l.includes("wired down")) || "",
60
+ );
61
+ const compressor = parsePages(
62
+ lines.find((l) => l.includes("occupied by compressor")) || "",
63
+ );
64
+ const total = os.totalmem();
65
+ const used = (active + wired + compressor) * pageSize;
66
+ memUsage = used / total;
67
+ } catch {
68
+ // 降级:使用估算
69
+ const total = os.totalmem();
70
+ const free = os.freemem();
71
+ const inactiveEstimate = total * 0.35;
72
+ memUsage = 1 - (free + inactiveEstimate) / total;
73
+ }
74
+ } else {
75
+ memUsage = 1 - os.freemem() / os.totalmem();
76
+ }
77
+ const memPercent = (memUsage * 100).toFixed(1);
78
+
79
+ if (memUsage >= MEMORY_THRESHOLD) {
80
+ return { shouldSwitch: true, reason: `系统内存 ${memPercent}%` };
81
+ }
82
+
83
+ const elapsed = Date.now() - this.startTime;
84
+ if (elapsed >= ROTATE_INTERVAL_MS) {
85
+ const mins = Math.round(elapsed / 60000);
86
+ return { shouldSwitch: true, reason: `运行 ${mins} 分钟` };
87
+ }
88
+
89
+ return { shouldSwitch: false };
90
+ }
91
+ }
92
+
93
+ export { HealthChecker };