@thinkingos/vsl-mcp-server 1.3.9 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2508 +1,4 @@
1
1
  #!/usr/bin/env node
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 __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
- }) : x)(function(x) {
11
- if (typeof require !== "undefined") return require.apply(this, arguments);
12
- throw Error('Dynamic require of "' + x + '" is not supported');
13
- });
14
- var __esm = (fn, res) => function __init() {
15
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
16
- };
17
- var __commonJS = (cb, mod) => function __require2() {
18
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
- };
20
- var __export = (target, all) => {
21
- for (var name in all)
22
- __defProp(target, name, { get: all[name], enumerable: true });
23
- };
24
- var __copyProps = (to, from, except, desc) => {
25
- if (from && typeof from === "object" || typeof from === "function") {
26
- for (let key of __getOwnPropNames(from))
27
- if (!__hasOwnProp.call(to, key) && key !== except)
28
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
- }
30
- return to;
31
- };
32
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
33
- // If the importer is in node compatibility mode or this is not an ESM
34
- // file that has been converted to a CommonJS file using a Babel-
35
- // compatible transform (i.e. "__esModule" has not been set), then set
36
- // "default" to the CommonJS "module.exports" for node compatibility.
37
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
- mod
39
- ));
40
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
41
-
42
- // node_modules/ms/index.js
43
- var require_ms = __commonJS({
44
- "node_modules/ms/index.js"(exports, module) {
45
- "use strict";
46
- var s = 1e3;
47
- var m = s * 60;
48
- var h = m * 60;
49
- var d = h * 24;
50
- var w = d * 7;
51
- var y = d * 365.25;
52
- module.exports = function(val, options) {
53
- options = options || {};
54
- var type = typeof val;
55
- if (type === "string" && val.length > 0) {
56
- return parse(val);
57
- } else if (type === "number" && isFinite(val)) {
58
- return options.long ? fmtLong(val) : fmtShort(val);
59
- }
60
- throw new Error(
61
- "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
62
- );
63
- };
64
- function parse(str) {
65
- str = String(str);
66
- if (str.length > 100) {
67
- return;
68
- }
69
- var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
70
- str
71
- );
72
- if (!match) {
73
- return;
74
- }
75
- var n = parseFloat(match[1]);
76
- var type = (match[2] || "ms").toLowerCase();
77
- switch (type) {
78
- case "years":
79
- case "year":
80
- case "yrs":
81
- case "yr":
82
- case "y":
83
- return n * y;
84
- case "weeks":
85
- case "week":
86
- case "w":
87
- return n * w;
88
- case "days":
89
- case "day":
90
- case "d":
91
- return n * d;
92
- case "hours":
93
- case "hour":
94
- case "hrs":
95
- case "hr":
96
- case "h":
97
- return n * h;
98
- case "minutes":
99
- case "minute":
100
- case "mins":
101
- case "min":
102
- case "m":
103
- return n * m;
104
- case "seconds":
105
- case "second":
106
- case "secs":
107
- case "sec":
108
- case "s":
109
- return n * s;
110
- case "milliseconds":
111
- case "millisecond":
112
- case "msecs":
113
- case "msec":
114
- case "ms":
115
- return n;
116
- default:
117
- return void 0;
118
- }
119
- }
120
- function fmtShort(ms) {
121
- var msAbs = Math.abs(ms);
122
- if (msAbs >= d) {
123
- return Math.round(ms / d) + "d";
124
- }
125
- if (msAbs >= h) {
126
- return Math.round(ms / h) + "h";
127
- }
128
- if (msAbs >= m) {
129
- return Math.round(ms / m) + "m";
130
- }
131
- if (msAbs >= s) {
132
- return Math.round(ms / s) + "s";
133
- }
134
- return ms + "ms";
135
- }
136
- function fmtLong(ms) {
137
- var msAbs = Math.abs(ms);
138
- if (msAbs >= d) {
139
- return plural(ms, msAbs, d, "day");
140
- }
141
- if (msAbs >= h) {
142
- return plural(ms, msAbs, h, "hour");
143
- }
144
- if (msAbs >= m) {
145
- return plural(ms, msAbs, m, "minute");
146
- }
147
- if (msAbs >= s) {
148
- return plural(ms, msAbs, s, "second");
149
- }
150
- return ms + " ms";
151
- }
152
- function plural(ms, msAbs, n, name) {
153
- var isPlural = msAbs >= n * 1.5;
154
- return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
155
- }
156
- }
157
- });
158
-
159
- // node_modules/debug/src/common.js
160
- var require_common = __commonJS({
161
- "node_modules/debug/src/common.js"(exports, module) {
162
- "use strict";
163
- function setup(env) {
164
- createDebug.debug = createDebug;
165
- createDebug.default = createDebug;
166
- createDebug.coerce = coerce;
167
- createDebug.disable = disable;
168
- createDebug.enable = enable;
169
- createDebug.enabled = enabled;
170
- createDebug.humanize = require_ms();
171
- createDebug.destroy = destroy;
172
- Object.keys(env).forEach((key) => {
173
- createDebug[key] = env[key];
174
- });
175
- createDebug.names = [];
176
- createDebug.skips = [];
177
- createDebug.formatters = {};
178
- function selectColor(namespace) {
179
- let hash = 0;
180
- for (let i = 0; i < namespace.length; i++) {
181
- hash = (hash << 5) - hash + namespace.charCodeAt(i);
182
- hash |= 0;
183
- }
184
- return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
185
- }
186
- createDebug.selectColor = selectColor;
187
- function createDebug(namespace) {
188
- let prevTime;
189
- let enableOverride = null;
190
- let namespacesCache;
191
- let enabledCache;
192
- function debug3(...args) {
193
- if (!debug3.enabled) {
194
- return;
195
- }
196
- const self = debug3;
197
- const curr = Number(/* @__PURE__ */ new Date());
198
- const ms = curr - (prevTime || curr);
199
- self.diff = ms;
200
- self.prev = prevTime;
201
- self.curr = curr;
202
- prevTime = curr;
203
- args[0] = createDebug.coerce(args[0]);
204
- if (typeof args[0] !== "string") {
205
- args.unshift("%O");
206
- }
207
- let index = 0;
208
- args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
209
- if (match === "%%") {
210
- return "%";
211
- }
212
- index++;
213
- const formatter = createDebug.formatters[format];
214
- if (typeof formatter === "function") {
215
- const val = args[index];
216
- match = formatter.call(self, val);
217
- args.splice(index, 1);
218
- index--;
219
- }
220
- return match;
221
- });
222
- createDebug.formatArgs.call(self, args);
223
- const logFn = self.log || createDebug.log;
224
- logFn.apply(self, args);
225
- }
226
- debug3.namespace = namespace;
227
- debug3.useColors = createDebug.useColors();
228
- debug3.color = createDebug.selectColor(namespace);
229
- debug3.extend = extend;
230
- debug3.destroy = createDebug.destroy;
231
- Object.defineProperty(debug3, "enabled", {
232
- enumerable: true,
233
- configurable: false,
234
- get: () => {
235
- if (enableOverride !== null) {
236
- return enableOverride;
237
- }
238
- if (namespacesCache !== createDebug.namespaces) {
239
- namespacesCache = createDebug.namespaces;
240
- enabledCache = createDebug.enabled(namespace);
241
- }
242
- return enabledCache;
243
- },
244
- set: (v) => {
245
- enableOverride = v;
246
- }
247
- });
248
- if (typeof createDebug.init === "function") {
249
- createDebug.init(debug3);
250
- }
251
- return debug3;
252
- }
253
- function extend(namespace, delimiter) {
254
- const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
255
- newDebug.log = this.log;
256
- return newDebug;
257
- }
258
- function enable(namespaces) {
259
- createDebug.save(namespaces);
260
- createDebug.namespaces = namespaces;
261
- createDebug.names = [];
262
- createDebug.skips = [];
263
- const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
264
- for (const ns of split) {
265
- if (ns[0] === "-") {
266
- createDebug.skips.push(ns.slice(1));
267
- } else {
268
- createDebug.names.push(ns);
269
- }
270
- }
271
- }
272
- function matchesTemplate(search, template) {
273
- let searchIndex = 0;
274
- let templateIndex = 0;
275
- let starIndex = -1;
276
- let matchIndex = 0;
277
- while (searchIndex < search.length) {
278
- if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
279
- if (template[templateIndex] === "*") {
280
- starIndex = templateIndex;
281
- matchIndex = searchIndex;
282
- templateIndex++;
283
- } else {
284
- searchIndex++;
285
- templateIndex++;
286
- }
287
- } else if (starIndex !== -1) {
288
- templateIndex = starIndex + 1;
289
- matchIndex++;
290
- searchIndex = matchIndex;
291
- } else {
292
- return false;
293
- }
294
- }
295
- while (templateIndex < template.length && template[templateIndex] === "*") {
296
- templateIndex++;
297
- }
298
- return templateIndex === template.length;
299
- }
300
- function disable() {
301
- const namespaces = [
302
- ...createDebug.names,
303
- ...createDebug.skips.map((namespace) => "-" + namespace)
304
- ].join(",");
305
- createDebug.enable("");
306
- return namespaces;
307
- }
308
- function enabled(name) {
309
- for (const skip of createDebug.skips) {
310
- if (matchesTemplate(name, skip)) {
311
- return false;
312
- }
313
- }
314
- for (const ns of createDebug.names) {
315
- if (matchesTemplate(name, ns)) {
316
- return true;
317
- }
318
- }
319
- return false;
320
- }
321
- function coerce(val) {
322
- if (val instanceof Error) {
323
- return val.stack || val.message;
324
- }
325
- return val;
326
- }
327
- function destroy() {
328
- console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
329
- }
330
- createDebug.enable(createDebug.load());
331
- return createDebug;
332
- }
333
- module.exports = setup;
334
- }
335
- });
336
-
337
- // node_modules/debug/src/browser.js
338
- var require_browser = __commonJS({
339
- "node_modules/debug/src/browser.js"(exports, module) {
340
- "use strict";
341
- exports.formatArgs = formatArgs;
342
- exports.save = save;
343
- exports.load = load2;
344
- exports.useColors = useColors;
345
- exports.storage = localstorage();
346
- exports.destroy = /* @__PURE__ */ (() => {
347
- let warned = false;
348
- return () => {
349
- if (!warned) {
350
- warned = true;
351
- console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
352
- }
353
- };
354
- })();
355
- exports.colors = [
356
- "#0000CC",
357
- "#0000FF",
358
- "#0033CC",
359
- "#0033FF",
360
- "#0066CC",
361
- "#0066FF",
362
- "#0099CC",
363
- "#0099FF",
364
- "#00CC00",
365
- "#00CC33",
366
- "#00CC66",
367
- "#00CC99",
368
- "#00CCCC",
369
- "#00CCFF",
370
- "#3300CC",
371
- "#3300FF",
372
- "#3333CC",
373
- "#3333FF",
374
- "#3366CC",
375
- "#3366FF",
376
- "#3399CC",
377
- "#3399FF",
378
- "#33CC00",
379
- "#33CC33",
380
- "#33CC66",
381
- "#33CC99",
382
- "#33CCCC",
383
- "#33CCFF",
384
- "#6600CC",
385
- "#6600FF",
386
- "#6633CC",
387
- "#6633FF",
388
- "#66CC00",
389
- "#66CC33",
390
- "#9900CC",
391
- "#9900FF",
392
- "#9933CC",
393
- "#9933FF",
394
- "#99CC00",
395
- "#99CC33",
396
- "#CC0000",
397
- "#CC0033",
398
- "#CC0066",
399
- "#CC0099",
400
- "#CC00CC",
401
- "#CC00FF",
402
- "#CC3300",
403
- "#CC3333",
404
- "#CC3366",
405
- "#CC3399",
406
- "#CC33CC",
407
- "#CC33FF",
408
- "#CC6600",
409
- "#CC6633",
410
- "#CC9900",
411
- "#CC9933",
412
- "#CCCC00",
413
- "#CCCC33",
414
- "#FF0000",
415
- "#FF0033",
416
- "#FF0066",
417
- "#FF0099",
418
- "#FF00CC",
419
- "#FF00FF",
420
- "#FF3300",
421
- "#FF3333",
422
- "#FF3366",
423
- "#FF3399",
424
- "#FF33CC",
425
- "#FF33FF",
426
- "#FF6600",
427
- "#FF6633",
428
- "#FF9900",
429
- "#FF9933",
430
- "#FFCC00",
431
- "#FFCC33"
432
- ];
433
- function useColors() {
434
- if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
435
- return true;
436
- }
437
- if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
438
- return false;
439
- }
440
- let m;
441
- return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
442
- typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
443
- // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
444
- typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
445
- typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
446
- }
447
- function formatArgs(args) {
448
- args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
449
- if (!this.useColors) {
450
- return;
451
- }
452
- const c = "color: " + this.color;
453
- args.splice(1, 0, c, "color: inherit");
454
- let index = 0;
455
- let lastC = 0;
456
- args[0].replace(/%[a-zA-Z%]/g, (match) => {
457
- if (match === "%%") {
458
- return;
459
- }
460
- index++;
461
- if (match === "%c") {
462
- lastC = index;
463
- }
464
- });
465
- args.splice(lastC, 0, c);
466
- }
467
- exports.log = console.debug || console.log || (() => {
468
- });
469
- function save(namespaces) {
470
- try {
471
- if (namespaces) {
472
- exports.storage.setItem("debug", namespaces);
473
- } else {
474
- exports.storage.removeItem("debug");
475
- }
476
- } catch (error) {
477
- }
478
- }
479
- function load2() {
480
- let r;
481
- try {
482
- r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
483
- } catch (error) {
484
- }
485
- if (!r && typeof process !== "undefined" && "env" in process) {
486
- r = process.env.DEBUG;
487
- }
488
- return r;
489
- }
490
- function localstorage() {
491
- try {
492
- return localStorage;
493
- } catch (error) {
494
- }
495
- }
496
- module.exports = require_common()(exports);
497
- var { formatters } = module.exports;
498
- formatters.j = function(v) {
499
- try {
500
- return JSON.stringify(v);
501
- } catch (error) {
502
- return "[UnexpectedJSONParseError]: " + error.message;
503
- }
504
- };
505
- }
506
- });
507
-
508
- // node_modules/has-flag/index.js
509
- var require_has_flag = __commonJS({
510
- "node_modules/has-flag/index.js"(exports, module) {
511
- "use strict";
512
- module.exports = (flag, argv = process.argv) => {
513
- const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
514
- const position = argv.indexOf(prefix + flag);
515
- const terminatorPosition = argv.indexOf("--");
516
- return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
517
- };
518
- }
519
- });
520
-
521
- // node_modules/supports-color/index.js
522
- var require_supports_color = __commonJS({
523
- "node_modules/supports-color/index.js"(exports, module) {
524
- "use strict";
525
- var os2 = __require("os");
526
- var tty = __require("tty");
527
- var hasFlag = require_has_flag();
528
- var { env } = process;
529
- var forceColor;
530
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
531
- forceColor = 0;
532
- } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
533
- forceColor = 1;
534
- }
535
- if ("FORCE_COLOR" in env) {
536
- if (env.FORCE_COLOR === "true") {
537
- forceColor = 1;
538
- } else if (env.FORCE_COLOR === "false") {
539
- forceColor = 0;
540
- } else {
541
- forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
542
- }
543
- }
544
- function translateLevel(level) {
545
- if (level === 0) {
546
- return false;
547
- }
548
- return {
549
- level,
550
- hasBasic: true,
551
- has256: level >= 2,
552
- has16m: level >= 3
553
- };
554
- }
555
- function supportsColor(haveStream, streamIsTTY) {
556
- if (forceColor === 0) {
557
- return 0;
558
- }
559
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
560
- return 3;
561
- }
562
- if (hasFlag("color=256")) {
563
- return 2;
564
- }
565
- if (haveStream && !streamIsTTY && forceColor === void 0) {
566
- return 0;
567
- }
568
- const min = forceColor || 0;
569
- if (env.TERM === "dumb") {
570
- return min;
571
- }
572
- if (process.platform === "win32") {
573
- const osRelease = os2.release().split(".");
574
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
575
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
576
- }
577
- return 1;
578
- }
579
- if ("CI" in env) {
580
- if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
581
- return 1;
582
- }
583
- return min;
584
- }
585
- if ("TEAMCITY_VERSION" in env) {
586
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
587
- }
588
- if (env.COLORTERM === "truecolor") {
589
- return 3;
590
- }
591
- if ("TERM_PROGRAM" in env) {
592
- const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
593
- switch (env.TERM_PROGRAM) {
594
- case "iTerm.app":
595
- return version >= 3 ? 3 : 2;
596
- case "Apple_Terminal":
597
- return 2;
598
- }
599
- }
600
- if (/-256(color)?$/i.test(env.TERM)) {
601
- return 2;
602
- }
603
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
604
- return 1;
605
- }
606
- if ("COLORTERM" in env) {
607
- return 1;
608
- }
609
- return min;
610
- }
611
- function getSupportLevel(stream) {
612
- const level = supportsColor(stream, stream && stream.isTTY);
613
- return translateLevel(level);
614
- }
615
- module.exports = {
616
- supportsColor: getSupportLevel,
617
- stdout: translateLevel(supportsColor(true, tty.isatty(1))),
618
- stderr: translateLevel(supportsColor(true, tty.isatty(2)))
619
- };
620
- }
621
- });
622
-
623
- // node_modules/debug/src/node.js
624
- var require_node = __commonJS({
625
- "node_modules/debug/src/node.js"(exports, module) {
626
- "use strict";
627
- var tty = __require("tty");
628
- var util = __require("util");
629
- exports.init = init;
630
- exports.log = log;
631
- exports.formatArgs = formatArgs;
632
- exports.save = save;
633
- exports.load = load2;
634
- exports.useColors = useColors;
635
- exports.destroy = util.deprecate(
636
- () => {
637
- },
638
- "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
639
- );
640
- exports.colors = [6, 2, 3, 4, 5, 1];
641
- try {
642
- const supportsColor = require_supports_color();
643
- if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
644
- exports.colors = [
645
- 20,
646
- 21,
647
- 26,
648
- 27,
649
- 32,
650
- 33,
651
- 38,
652
- 39,
653
- 40,
654
- 41,
655
- 42,
656
- 43,
657
- 44,
658
- 45,
659
- 56,
660
- 57,
661
- 62,
662
- 63,
663
- 68,
664
- 69,
665
- 74,
666
- 75,
667
- 76,
668
- 77,
669
- 78,
670
- 79,
671
- 80,
672
- 81,
673
- 92,
674
- 93,
675
- 98,
676
- 99,
677
- 112,
678
- 113,
679
- 128,
680
- 129,
681
- 134,
682
- 135,
683
- 148,
684
- 149,
685
- 160,
686
- 161,
687
- 162,
688
- 163,
689
- 164,
690
- 165,
691
- 166,
692
- 167,
693
- 168,
694
- 169,
695
- 170,
696
- 171,
697
- 172,
698
- 173,
699
- 178,
700
- 179,
701
- 184,
702
- 185,
703
- 196,
704
- 197,
705
- 198,
706
- 199,
707
- 200,
708
- 201,
709
- 202,
710
- 203,
711
- 204,
712
- 205,
713
- 206,
714
- 207,
715
- 208,
716
- 209,
717
- 214,
718
- 215,
719
- 220,
720
- 221
721
- ];
722
- }
723
- } catch (error) {
724
- }
725
- exports.inspectOpts = Object.keys(process.env).filter((key) => {
726
- return /^debug_/i.test(key);
727
- }).reduce((obj, key) => {
728
- const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
729
- return k.toUpperCase();
730
- });
731
- let val = process.env[key];
732
- if (/^(yes|on|true|enabled)$/i.test(val)) {
733
- val = true;
734
- } else if (/^(no|off|false|disabled)$/i.test(val)) {
735
- val = false;
736
- } else if (val === "null") {
737
- val = null;
738
- } else {
739
- val = Number(val);
740
- }
741
- obj[prop] = val;
742
- return obj;
743
- }, {});
744
- function useColors() {
745
- return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
746
- }
747
- function formatArgs(args) {
748
- const { namespace: name, useColors: useColors2 } = this;
749
- if (useColors2) {
750
- const c = this.color;
751
- const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
752
- const prefix = ` ${colorCode};1m${name} \x1B[0m`;
753
- args[0] = prefix + args[0].split("\n").join("\n" + prefix);
754
- args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
755
- } else {
756
- args[0] = getDate() + name + " " + args[0];
757
- }
758
- }
759
- function getDate() {
760
- if (exports.inspectOpts.hideDate) {
761
- return "";
762
- }
763
- return (/* @__PURE__ */ new Date()).toISOString() + " ";
764
- }
765
- function log(...args) {
766
- return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + "\n");
767
- }
768
- function save(namespaces) {
769
- if (namespaces) {
770
- process.env.DEBUG = namespaces;
771
- } else {
772
- delete process.env.DEBUG;
773
- }
774
- }
775
- function load2() {
776
- return process.env.DEBUG;
777
- }
778
- function init(debug3) {
779
- debug3.inspectOpts = {};
780
- const keys = Object.keys(exports.inspectOpts);
781
- for (let i = 0; i < keys.length; i++) {
782
- debug3.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
783
- }
784
- }
785
- module.exports = require_common()(exports);
786
- var { formatters } = module.exports;
787
- formatters.o = function(v) {
788
- this.inspectOpts.colors = this.useColors;
789
- return util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
790
- };
791
- formatters.O = function(v) {
792
- this.inspectOpts.colors = this.useColors;
793
- return util.inspect(v, this.inspectOpts);
794
- };
795
- }
796
- });
797
-
798
- // node_modules/debug/src/index.js
799
- var require_src = __commonJS({
800
- "node_modules/debug/src/index.js"(exports, module) {
801
- "use strict";
802
- if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
803
- module.exports = require_browser();
804
- } else {
805
- module.exports = require_node();
806
- }
807
- }
808
- });
809
-
810
- // node_modules/playwright-extra/dist/index.esm.js
811
- var index_esm_exports = {};
812
- __export(index_esm_exports, {
813
- PlaywrightExtra: () => PlaywrightExtra,
814
- PlaywrightExtraClass: () => PlaywrightExtraClass,
815
- PluginList: () => PluginList,
816
- _android: () => _android,
817
- _electron: () => _electron,
818
- addExtra: () => addExtra,
819
- chromium: () => chromium,
820
- default: () => index_esm_default,
821
- devices: () => devices,
822
- errors: () => errors,
823
- firefox: () => firefox,
824
- request: () => request,
825
- selectors: () => selectors,
826
- webkit: () => webkit
827
- });
828
- function requirePackages(packageNames) {
829
- for (const name of packageNames) {
830
- try {
831
- return __require(name);
832
- } catch (_) {
833
- continue;
834
- }
835
- }
836
- return;
837
- }
838
- function addPuppeteerCompat(object) {
839
- if (!object || typeof object !== "object") {
840
- return object;
841
- }
842
- if (cache.objectToShim.has(object)) {
843
- return cache.objectToShim.get(object);
844
- }
845
- if (isPuppeteerCompat(object)) {
846
- return object;
847
- }
848
- debug("addPuppeteerCompat", cache.objectToShim.size);
849
- if (isPlaywrightPage(object) || isPlaywrightFrame(object)) {
850
- const shim = createPageShim(object);
851
- cache.objectToShim.set(object, shim);
852
- return shim;
853
- }
854
- if (isPlaywrightBrowser(object)) {
855
- const shim = createBrowserShim(object);
856
- cache.objectToShim.set(object, shim);
857
- return shim;
858
- }
859
- debug("Received unknown object:", Reflect.ownKeys(object));
860
- return object;
861
- }
862
- async function getPageCDPSession(page) {
863
- let session = cache.cdpSession.page.get(page);
864
- if (session) {
865
- debug("getPageCDPSession: use existing");
866
- return session;
867
- }
868
- debug("getPageCDPSession: use new");
869
- const context = isPlaywrightFrame(page) ? page.page().context() : page.context();
870
- try {
871
- session = await context.newCDPSession(page);
872
- cache.cdpSession.page.set(page, session);
873
- return session;
874
- } catch (err) {
875
- debug("getPageCDPSession: error while creating session:", err.message);
876
- debug("getPageCDPSession: Unable create CDP session (most likely a different browser than chromium) - returning a dummy");
877
- }
878
- return dummyCDPClient;
879
- }
880
- async function getBrowserCDPSession(browser) {
881
- let session = cache.cdpSession.browser.get(browser);
882
- if (session) {
883
- debug("getBrowserCDPSession: use existing");
884
- return session;
885
- }
886
- debug("getBrowserCDPSession: use new");
887
- try {
888
- session = await browser.newBrowserCDPSession();
889
- cache.cdpSession.browser.set(browser, session);
890
- return session;
891
- } catch (err) {
892
- debug("getBrowserCDPSession: error while creating session:", err.message);
893
- debug("getBrowserCDPSession: Unable create CDP session (most likely a different browser than chromium) - returning a dummy");
894
- }
895
- return dummyCDPClient;
896
- }
897
- function createPageShim(page) {
898
- const objId = Math.random().toString(36).substring(2, 7);
899
- const shim = new Proxy(page, {
900
- get(target, prop) {
901
- if (prop === "isCompatShim" || prop === "isPlaywright") {
902
- return true;
903
- }
904
- debug("page - get", objId, prop);
905
- if (prop === "_client") {
906
- return () => ({
907
- send: async (method, params) => {
908
- const session = await getPageCDPSession(page);
909
- return await session.send(method, params);
910
- },
911
- on: (event, listener) => {
912
- getPageCDPSession(page).then((session) => {
913
- session.on(event, listener);
914
- });
915
- }
916
- });
917
- }
918
- if (prop === "setBypassCSP") {
919
- return async (enabled) => {
920
- const session = await getPageCDPSession(page);
921
- return await session.send("Page.setBypassCSP", {
922
- enabled
923
- });
924
- };
925
- }
926
- if (prop === "setUserAgent") {
927
- return async (userAgent, userAgentMetadata) => {
928
- const session = await getPageCDPSession(page);
929
- return await session.send("Emulation.setUserAgentOverride", {
930
- userAgent,
931
- userAgentMetadata
932
- });
933
- };
934
- }
935
- if (prop === "browser") {
936
- if (isPlaywrightPage(page)) {
937
- return () => {
938
- let browser = page.context().browser();
939
- if (!browser) {
940
- debug("page.browser() - not available, most likely due to launchPersistentContext");
941
- browser = page;
942
- }
943
- return addPuppeteerCompat(browser);
944
- };
945
- }
946
- }
947
- if (prop === "evaluateOnNewDocument") {
948
- if (isPlaywrightPage(page)) {
949
- return async function(pageFunction, ...args) {
950
- return await page.addInitScript(pageFunction, args[0]);
951
- };
952
- }
953
- }
954
- if (prop === "userAgent") {
955
- return async (enabled) => {
956
- const session = await getPageCDPSession(page);
957
- const data = await session.send("Browser.getVersion");
958
- return data.userAgent;
959
- };
960
- }
961
- return Reflect.get(target, prop);
962
- }
963
- });
964
- return shim;
965
- }
966
- function createBrowserShim(browser) {
967
- const objId = Math.random().toString(36).substring(2, 7);
968
- const shim = new Proxy(browser, {
969
- get(target, prop) {
970
- if (prop === "isCompatShim" || prop === "isPlaywright") {
971
- return true;
972
- }
973
- debug("browser - get", objId, prop);
974
- if (prop === "pages") {
975
- return () => browser.contexts().flatMap((c) => c.pages().map((page) => addPuppeteerCompat(page)));
976
- }
977
- if (prop === "userAgent") {
978
- return async () => {
979
- const session = await getBrowserCDPSession(browser);
980
- const data = await session.send("Browser.getVersion");
981
- return data.userAgent;
982
- };
983
- }
984
- return Reflect.get(target, prop);
985
- }
986
- });
987
- return shim;
988
- }
989
- var import_debug, Loader, playwrightLoader, debug, isPlaywrightPage, isPlaywrightFrame, isPlaywrightBrowser, isPuppeteerCompat, cache, dummyCDPClient, debug$1, PluginList, debug$2, PlaywrightExtraClass, PlaywrightExtra, addExtra, chromium, firefox, webkit, _android, _electron, request, selectors, devices, errors, moduleExports, index_esm_default;
990
- var init_index_esm = __esm({
991
- "node_modules/playwright-extra/dist/index.esm.js"() {
992
- "use strict";
993
- import_debug = __toESM(require_src());
994
- Loader = class {
995
- constructor(moduleName, packageNames) {
996
- this.moduleName = moduleName;
997
- this.packageNames = packageNames;
998
- }
999
- /**
1000
- * Lazy load a top level export from another module by wrapping it in a JS proxy.
1001
- *
1002
- * This allows us to re-export e.g. `devices` from `playwright` while redirecting direct calls
1003
- * to it to the module version the user has installed, rather than shipping with a hardcoded version.
1004
- *
1005
- * If we don't do this and the user doesn't have the target module installed we'd throw immediately when our code is imported.
1006
- *
1007
- * We use a "super" Proxy defining all traps, so calls like `Object.keys(playwright.devices).length` will return the correct value.
1008
- */
1009
- lazyloadExportOrDie(exportName) {
1010
- const that = this;
1011
- const trapHandler = Object.fromEntries(Object.getOwnPropertyNames(Reflect).map((name) => [
1012
- name,
1013
- function(target, ...args) {
1014
- const moduleExport = that.loadModuleOrDie()[exportName];
1015
- const customTarget = moduleExport;
1016
- const result = Reflect[name](customTarget || target, ...args);
1017
- return result;
1018
- }
1019
- ]));
1020
- return new Proxy({}, trapHandler);
1021
- }
1022
- /** Load the module if possible */
1023
- loadModule() {
1024
- return requirePackages(this.packageNames);
1025
- }
1026
- /** Load the module if possible or throw */
1027
- loadModuleOrDie() {
1028
- const module = requirePackages(this.packageNames);
1029
- if (module) {
1030
- return module;
1031
- }
1032
- throw this.requireError;
1033
- }
1034
- get requireError() {
1035
- const moduleNamePretty = this.moduleName.charAt(0).toUpperCase() + this.moduleName.slice(1);
1036
- return new Error(`
1037
- ${moduleNamePretty} is missing. :-)
1038
-
1039
- I've tried loading ${this.packageNames.map((p) => `"${p}"`).join(", ")} - no luck.
1040
-
1041
- Make sure you install one of those packages or use the named 'addExtra' export,
1042
- to patch a specific (and maybe non-standard) implementation of ${moduleNamePretty}.
1043
-
1044
- To get the latest stable version of ${moduleNamePretty} run:
1045
- 'yarn add ${this.moduleName}' or 'npm i ${this.moduleName}'
1046
- `);
1047
- }
1048
- };
1049
- playwrightLoader = new Loader("playwright", [
1050
- "playwright-core",
1051
- "playwright"
1052
- ]);
1053
- debug = (0, import_debug.default)("playwright-extra:puppeteer-compat");
1054
- isPlaywrightPage = (obj) => {
1055
- return "unroute" in obj;
1056
- };
1057
- isPlaywrightFrame = (obj) => {
1058
- return ["parentFrame", "frameLocator"].every((x) => x in obj);
1059
- };
1060
- isPlaywrightBrowser = (obj) => {
1061
- return "newContext" in obj;
1062
- };
1063
- isPuppeteerCompat = (obj) => {
1064
- return !!obj && typeof obj === "object" && !!obj.isCompatShim;
1065
- };
1066
- cache = {
1067
- objectToShim: /* @__PURE__ */ new Map(),
1068
- cdpSession: {
1069
- page: /* @__PURE__ */ new Map(),
1070
- browser: /* @__PURE__ */ new Map()
1071
- }
1072
- };
1073
- dummyCDPClient = {
1074
- send: async (...args) => {
1075
- debug("dummy CDP client called", "send", args);
1076
- },
1077
- on: (...args) => {
1078
- debug("dummy CDP client called", "on", args);
1079
- }
1080
- };
1081
- debug$1 = (0, import_debug.default)("playwright-extra:plugins");
1082
- PluginList = class {
1083
- constructor() {
1084
- this._plugins = [];
1085
- this._dependencyDefaults = /* @__PURE__ */ new Map();
1086
- this._dependencyResolution = /* @__PURE__ */ new Map();
1087
- }
1088
- /**
1089
- * Get a list of all registered plugins.
1090
- */
1091
- get list() {
1092
- return this._plugins;
1093
- }
1094
- /**
1095
- * Get the names of all registered plugins.
1096
- */
1097
- get names() {
1098
- return this._plugins.map((p) => p.name);
1099
- }
1100
- /**
1101
- * Add a new plugin to the list (after checking if it's well-formed).
1102
- *
1103
- * @param plugin
1104
- * @internal
1105
- */
1106
- add(plugin) {
1107
- var _a;
1108
- if (!this.isValidPluginInstance(plugin)) {
1109
- return false;
1110
- }
1111
- if (!!plugin.onPluginRegistered) {
1112
- plugin.onPluginRegistered({ framework: "playwright" });
1113
- }
1114
- if (!!plugin._registerChildClassMembers) {
1115
- plugin._registerChildClassMembers(Object.getPrototypeOf(plugin));
1116
- }
1117
- if ((_a = plugin.requirements) === null || _a === void 0 ? void 0 : _a.has("dataFromPlugins")) {
1118
- plugin.getDataFromPlugins = this.getData.bind(this);
1119
- }
1120
- this._plugins.push(plugin);
1121
- return true;
1122
- }
1123
- /** Check if the shape of a plugin is correct or warn */
1124
- isValidPluginInstance(plugin) {
1125
- if (!plugin || typeof plugin !== "object" || !plugin._isPuppeteerExtraPlugin) {
1126
- console.error(`Warning: Plugin is not derived from PuppeteerExtraPlugin, ignoring.`, plugin);
1127
- return false;
1128
- }
1129
- if (!plugin.name) {
1130
- console.error(`Warning: Plugin with no name registering, ignoring.`, plugin);
1131
- return false;
1132
- }
1133
- return true;
1134
- }
1135
- /** Error callback in case calling a plugin method throws an error. Can be overwritten. */
1136
- onPluginError(plugin, method, err) {
1137
- console.warn(`An error occured while executing "${method}" in plugin "${plugin.name}":`, err);
1138
- }
1139
- /**
1140
- * Define default values for plugins implicitly required through the `dependencies` plugin stanza.
1141
- *
1142
- * @param dependencyPath - The string by which the dependency is listed (not the plugin name)
1143
- *
1144
- * @example
1145
- * chromium.use(stealth)
1146
- * chromium.plugins.setDependencyDefaults('stealth/evasions/webgl.vendor', { vendor: 'Bob', renderer: 'Alice' })
1147
- */
1148
- setDependencyDefaults(dependencyPath, opts) {
1149
- this._dependencyDefaults.set(dependencyPath, opts);
1150
- return this;
1151
- }
1152
- /**
1153
- * Define custom plugin modules for plugins implicitly required through the `dependencies` plugin stanza.
1154
- *
1155
- * Using this will prevent dynamic imports from being used, which JS bundlers often have issues with.
1156
- *
1157
- * @example
1158
- * chromium.use(stealth)
1159
- * chromium.plugins.setDependencyResolution('stealth/evasions/webgl.vendor', VendorPlugin)
1160
- */
1161
- setDependencyResolution(dependencyPath, pluginModule) {
1162
- this._dependencyResolution.set(dependencyPath, pluginModule);
1163
- return this;
1164
- }
1165
- /**
1166
- * Prepare plugins to be used (resolve dependencies, ordering)
1167
- * @internal
1168
- */
1169
- prepare() {
1170
- this.resolveDependencies();
1171
- this.order();
1172
- }
1173
- /** Return all plugins using the supplied method */
1174
- filterByMethod(methodName) {
1175
- return this._plugins.filter((plugin) => {
1176
- if (!!plugin._childClassMembers && Array.isArray(plugin._childClassMembers)) {
1177
- return plugin._childClassMembers.includes(methodName);
1178
- }
1179
- return methodName in plugin;
1180
- });
1181
- }
1182
- /** Conditionally add puppeteer compatibility to values provided to the plugins */
1183
- _addPuppeteerCompatIfNeeded(plugin, method, args) {
1184
- const canUseShim = plugin._isPuppeteerExtraPlugin && !plugin.noPuppeteerShim;
1185
- const methodWhitelist = [
1186
- "onBrowser",
1187
- "onPageCreated",
1188
- "onPageClose",
1189
- "afterConnect",
1190
- "afterLaunch"
1191
- ];
1192
- const shouldUseShim = methodWhitelist.includes(method);
1193
- if (!canUseShim || !shouldUseShim) {
1194
- return args;
1195
- }
1196
- debug$1("add puppeteer compatibility", plugin.name, method);
1197
- return [...args.map((arg) => addPuppeteerCompat(arg))];
1198
- }
1199
- /**
1200
- * Dispatch plugin lifecycle events in a typesafe way.
1201
- * Only Plugins that expose the supplied property will be called.
1202
- *
1203
- * Will not await results to dispatch events as fast as possible to all plugins.
1204
- *
1205
- * @param method - The lifecycle method name
1206
- * @param args - Optional: Any arguments to be supplied to the plugin methods
1207
- * @internal
1208
- */
1209
- dispatch(method, ...args) {
1210
- var _a, _b;
1211
- const plugins = this.filterByMethod(method);
1212
- debug$1("dispatch", method, {
1213
- all: this._plugins.length,
1214
- filteredByMethod: plugins.length
1215
- });
1216
- for (const plugin of plugins) {
1217
- try {
1218
- args = this._addPuppeteerCompatIfNeeded.bind(this)(plugin, method, args);
1219
- const fnType = (_b = (_a = plugin[method]) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name;
1220
- debug$1("dispatch to plugin", {
1221
- plugin: plugin.name,
1222
- method,
1223
- fnType
1224
- });
1225
- if (fnType === "AsyncFunction") {
1226
- ;
1227
- plugin[method](...args).catch((err) => this.onPluginError(plugin, method, err));
1228
- } else {
1229
- ;
1230
- plugin[method](...args);
1231
- }
1232
- } catch (err) {
1233
- this.onPluginError(plugin, method, err);
1234
- }
1235
- }
1236
- }
1237
- /**
1238
- * Dispatch plugin lifecycle events in a typesafe way.
1239
- * Only Plugins that expose the supplied property will be called.
1240
- *
1241
- * Can also be used to get a definite return value after passing it to plugins:
1242
- * Calls plugins sequentially and passes on a value (waterfall style).
1243
- *
1244
- * The plugins can either modify the value or return an updated one.
1245
- * Will return the latest, updated value which ran through all plugins.
1246
- *
1247
- * By convention only the first argument will be used as the updated value.
1248
- *
1249
- * @param method - The lifecycle method name
1250
- * @param args - Optional: Any arguments to be supplied to the plugin methods
1251
- * @internal
1252
- */
1253
- async dispatchBlocking(method, ...args) {
1254
- const plugins = this.filterByMethod(method);
1255
- debug$1("dispatchBlocking", method, {
1256
- all: this._plugins.length,
1257
- filteredByMethod: plugins.length
1258
- });
1259
- let retValue = null;
1260
- for (const plugin of plugins) {
1261
- try {
1262
- args = this._addPuppeteerCompatIfNeeded.bind(this)(plugin, method, args);
1263
- retValue = await plugin[method](...args);
1264
- if (retValue !== void 0) {
1265
- args[0] = retValue;
1266
- }
1267
- } catch (err) {
1268
- this.onPluginError(plugin, method, err);
1269
- return retValue;
1270
- }
1271
- }
1272
- return retValue;
1273
- }
1274
- /**
1275
- * Order plugins that have expressed a special placement requirement.
1276
- *
1277
- * This is useful/necessary for e.g. plugins that depend on the data from other plugins.
1278
- *
1279
- * @private
1280
- */
1281
- order() {
1282
- debug$1("order:before", this.names);
1283
- const runLast = this._plugins.filter((p) => {
1284
- var _a;
1285
- return (_a = p.requirements) === null || _a === void 0 ? void 0 : _a.has("runLast");
1286
- }).map((p) => p.name);
1287
- for (const name of runLast) {
1288
- const index = this._plugins.findIndex((p) => p.name === name);
1289
- this._plugins.push(this._plugins.splice(index, 1)[0]);
1290
- }
1291
- debug$1("order:after", this.names);
1292
- }
1293
- /**
1294
- * Collects the exposed `data` property of all registered plugins.
1295
- * Will be reduced/flattened to a single array.
1296
- *
1297
- * Can be accessed by plugins that listed the `dataFromPlugins` requirement.
1298
- *
1299
- * Implemented mainly for plugins that need data from other plugins (e.g. `user-preferences`).
1300
- *
1301
- * @see [PuppeteerExtraPlugin]/data
1302
- * @param name - Filter data by optional name
1303
- *
1304
- * @private
1305
- */
1306
- getData(name) {
1307
- const data = this._plugins.filter((p) => !!p.data).map((p) => Array.isArray(p.data) ? p.data : [p.data]).reduce((acc, arr) => [...acc, ...arr], []);
1308
- return name ? data.filter((d) => d.name === name) : data;
1309
- }
1310
- /**
1311
- * Handle `plugins` stanza (already instantiated plugins that don't require dynamic imports)
1312
- */
1313
- resolvePluginsStanza() {
1314
- debug$1("resolvePluginsStanza");
1315
- const pluginNames = new Set(this.names);
1316
- this._plugins.filter((p) => !!p.plugins && p.plugins.length).filter((p) => !pluginNames.has(p.name)).forEach((parent) => {
1317
- (parent.plugins || []).forEach((p) => {
1318
- debug$1(parent.name, "adding missing plugin", p.name);
1319
- this.add(p);
1320
- });
1321
- });
1322
- }
1323
- /**
1324
- * Handle `dependencies` stanza (which requires dynamic imports)
1325
- *
1326
- * Plugins can define `dependencies` as a Set or Array of dependency paths, or a Map with additional opts
1327
- *
1328
- * @note
1329
- * - The default opts for implicit dependencies can be defined using `setDependencyDefaults()`
1330
- * - Dynamic imports can be avoided by providing plugin modules with `setDependencyResolution()`
1331
- */
1332
- resolveDependenciesStanza() {
1333
- debug$1("resolveDependenciesStanza");
1334
- const requireDependencyOrDie = (parentName, dependencyPath) => {
1335
- if (this._dependencyResolution.has(dependencyPath)) {
1336
- return this._dependencyResolution.get(dependencyPath);
1337
- }
1338
- const possiblePrefixes = ["puppeteer-extra-plugin-"];
1339
- const isAlreadyPrefixed = possiblePrefixes.some((prefix) => dependencyPath.startsWith(prefix));
1340
- const packagePaths = [];
1341
- if (!isAlreadyPrefixed) {
1342
- packagePaths.push(...possiblePrefixes.map((prefix) => prefix + dependencyPath));
1343
- }
1344
- packagePaths.push(dependencyPath);
1345
- const pluginModule = requirePackages(packagePaths);
1346
- if (pluginModule) {
1347
- return pluginModule;
1348
- }
1349
- const explanation = `
1350
- The plugin '${parentName}' listed '${dependencyPath}' as dependency,
1351
- which could not be found. Please install it:
1352
-
1353
- ${packagePaths.map((packagePath) => `yarn add ${packagePath.split("/")[0]}`).join(`
1354
- or:
1355
- `)}
1356
-
1357
- Note: You don't need to require the plugin yourself,
1358
- unless you want to modify it's default settings.
1359
-
1360
- If your bundler has issues with dynamic imports take a look at '.plugins.setDependencyResolution()'.
1361
- `;
1362
- console.warn(explanation);
1363
- throw new Error("Plugin dependency not found");
1364
- };
1365
- const existingPluginNames = new Set(this.names);
1366
- const recursivelyLoadMissingDependencies = ({ name: parentName, dependencies }) => {
1367
- if (!dependencies) {
1368
- return;
1369
- }
1370
- const processDependency = (dependencyPath, opts) => {
1371
- const pluginModule = requireDependencyOrDie(parentName, dependencyPath);
1372
- opts = opts || this._dependencyDefaults.get(dependencyPath) || {};
1373
- const plugin = pluginModule(opts);
1374
- if (existingPluginNames.has(plugin.name)) {
1375
- debug$1(parentName, "=> dependency already exists:", plugin.name);
1376
- return;
1377
- }
1378
- existingPluginNames.add(plugin.name);
1379
- debug$1(parentName, "=> adding new dependency:", plugin.name, opts);
1380
- this.add(plugin);
1381
- return recursivelyLoadMissingDependencies(plugin);
1382
- };
1383
- if (dependencies instanceof Set || Array.isArray(dependencies)) {
1384
- return [...dependencies].forEach((dependencyPath) => processDependency(dependencyPath));
1385
- }
1386
- if (dependencies instanceof Map) {
1387
- return dependencies.forEach((v, k) => processDependency(k, v));
1388
- }
1389
- };
1390
- this.list.forEach(recursivelyLoadMissingDependencies);
1391
- }
1392
- /**
1393
- * Lightweight plugin dependency management to require plugins and code mods on demand.
1394
- * @private
1395
- */
1396
- resolveDependencies() {
1397
- debug$1("resolveDependencies");
1398
- this.resolvePluginsStanza();
1399
- this.resolveDependenciesStanza();
1400
- }
1401
- };
1402
- debug$2 = (0, import_debug.default)("playwright-extra");
1403
- PlaywrightExtraClass = class {
1404
- constructor(_launcher) {
1405
- this._launcher = _launcher;
1406
- this.plugins = new PluginList();
1407
- }
1408
- /**
1409
- * The **main interface** to register plugins.
1410
- *
1411
- * Can be called multiple times to enable multiple plugins.
1412
- *
1413
- * Plugins derived from `PuppeteerExtraPlugin` will be used with a compatiblity layer.
1414
- *
1415
- * @example
1416
- * chromium.use(plugin1).use(plugin2)
1417
- * firefox.use(plugin1).use(plugin2)
1418
- *
1419
- * @see [PuppeteerExtraPlugin]
1420
- *
1421
- * @return The same `PlaywrightExtra` instance (for optional chaining)
1422
- */
1423
- use(plugin) {
1424
- const isValid = plugin && "name" in plugin;
1425
- if (!isValid) {
1426
- throw new Error("A plugin must be provided to .use()");
1427
- }
1428
- if (this.plugins.add(plugin)) {
1429
- debug$2("Plugin registered", plugin.name);
1430
- }
1431
- return this;
1432
- }
1433
- /**
1434
- * In order to support a default export which will require vanilla playwright automatically,
1435
- * as well as `addExtra` to patch a provided launcher, we need to so some gymnastics here.
1436
- *
1437
- * Otherwise this would throw immediately, even when only using the `addExtra` export with an arbitrary compatible launcher.
1438
- *
1439
- * The solution is to make the vanilla launcher optional and only throw once we try to effectively use and can't find it.
1440
- *
1441
- * @internal
1442
- */
1443
- get launcher() {
1444
- if (!this._launcher) {
1445
- throw playwrightLoader.requireError;
1446
- }
1447
- return this._launcher;
1448
- }
1449
- async launch(...args) {
1450
- if (!this.launcher.launch) {
1451
- throw new Error('Launcher does not support "launch"');
1452
- }
1453
- let [options] = args;
1454
- options = Object.assign({ args: [] }, options || {});
1455
- debug$2("launch", options);
1456
- this.plugins.prepare();
1457
- options = await this.plugins.dispatchBlocking("beforeLaunch", options) || options;
1458
- debug$2("launch with options", options);
1459
- if ("userDataDir" in options) {
1460
- debug$2("A plugin defined userDataDir during .launch, which isn't supported by playwright - ignoring");
1461
- delete options.userDataDir;
1462
- }
1463
- const browser = await this.launcher["launch"](options);
1464
- await this.plugins.dispatchBlocking("onBrowser", browser);
1465
- await this._bindBrowserEvents(browser);
1466
- await this.plugins.dispatchBlocking("afterLaunch", browser);
1467
- return browser;
1468
- }
1469
- async launchPersistentContext(...args) {
1470
- if (!this.launcher.launchPersistentContext) {
1471
- throw new Error('Launcher does not support "launchPersistentContext"');
1472
- }
1473
- let [userDataDir, options] = args;
1474
- options = Object.assign({ args: [] }, options || {});
1475
- debug$2("launchPersistentContext", options);
1476
- this.plugins.prepare();
1477
- options = await this.plugins.dispatchBlocking("beforeLaunch", options) || options;
1478
- const context = await this.launcher["launchPersistentContext"](userDataDir, options);
1479
- await this.plugins.dispatchBlocking("afterLaunch", context);
1480
- this._bindBrowserContextEvents(context);
1481
- return context;
1482
- }
1483
- async connect(wsEndpointOrOptions, wsOptions = {}) {
1484
- if (!this.launcher.connect) {
1485
- throw new Error('Launcher does not support "connect"');
1486
- }
1487
- this.plugins.prepare();
1488
- let options = {};
1489
- let wsEndpointAsString = false;
1490
- if (typeof wsEndpointOrOptions === "object") {
1491
- options = Object.assign(Object.assign({}, wsEndpointOrOptions), wsOptions);
1492
- } else {
1493
- wsEndpointAsString = true;
1494
- options = Object.assign({ wsEndpoint: wsEndpointOrOptions }, wsOptions);
1495
- }
1496
- debug$2("connect", options);
1497
- options = await this.plugins.dispatchBlocking("beforeConnect", options) || options;
1498
- const args = [];
1499
- const wsEndpoint = options.wsEndpoint;
1500
- if (wsEndpointAsString) {
1501
- delete options.wsEndpoint;
1502
- args.push(wsEndpoint, options);
1503
- } else {
1504
- args.push(options);
1505
- }
1506
- const browser = await this.launcher["connect"](...args);
1507
- await this.plugins.dispatchBlocking("onBrowser", browser);
1508
- await this._bindBrowserEvents(browser);
1509
- await this.plugins.dispatchBlocking("afterConnect", browser);
1510
- return browser;
1511
- }
1512
- async connectOverCDP(wsEndpointOrOptions, wsOptions = {}) {
1513
- if (!this.launcher.connectOverCDP) {
1514
- throw new Error(`Launcher does not implement 'connectOverCDP'`);
1515
- }
1516
- this.plugins.prepare();
1517
- let options = {};
1518
- let wsEndpointAsString = false;
1519
- if (typeof wsEndpointOrOptions === "object") {
1520
- options = Object.assign(Object.assign({}, wsEndpointOrOptions), wsOptions);
1521
- } else {
1522
- wsEndpointAsString = true;
1523
- options = Object.assign({ endpointURL: wsEndpointOrOptions }, wsOptions);
1524
- }
1525
- debug$2("connectOverCDP"), options;
1526
- options = await this.plugins.dispatchBlocking("beforeConnect", options) || options;
1527
- const args = [];
1528
- const endpointURL = options.endpointURL;
1529
- if (wsEndpointAsString) {
1530
- delete options.endpointURL;
1531
- args.push(endpointURL, options);
1532
- } else {
1533
- args.push(options);
1534
- }
1535
- const browser = await this.launcher["connectOverCDP"](...args);
1536
- await this.plugins.dispatchBlocking("onBrowser", browser);
1537
- await this._bindBrowserEvents(browser);
1538
- await this.plugins.dispatchBlocking("afterConnect", browser);
1539
- return browser;
1540
- }
1541
- async _bindBrowserContextEvents(context, contextOptions) {
1542
- debug$2("_bindBrowserContextEvents");
1543
- this.plugins.dispatch("onContextCreated", context, contextOptions);
1544
- context.newPage = /* @__PURE__ */ ((originalMethod, ctx) => {
1545
- return async () => {
1546
- const page = await originalMethod.call(ctx);
1547
- await page.goto("about:blank");
1548
- return page;
1549
- };
1550
- })(context.newPage, context);
1551
- context.on("close", () => {
1552
- if (!context.browser()) {
1553
- this.plugins.dispatch("onDisconnected");
1554
- }
1555
- });
1556
- context.on("page", (page) => {
1557
- this.plugins.dispatch("onPageCreated", page);
1558
- page.on("close", () => {
1559
- this.plugins.dispatch("onPageClose", page);
1560
- });
1561
- });
1562
- }
1563
- async _bindBrowserEvents(browser) {
1564
- debug$2("_bindPlaywrightBrowserEvents");
1565
- browser.on("disconnected", () => {
1566
- this.plugins.dispatch("onDisconnected", browser);
1567
- });
1568
- browser.newContext = /* @__PURE__ */ ((originalMethod, ctx) => {
1569
- return async (options = {}) => {
1570
- const contextOptions = await this.plugins.dispatchBlocking("beforeContext", options, browser) || options;
1571
- const context = await originalMethod.call(ctx, contextOptions);
1572
- this._bindBrowserContextEvents(context, contextOptions);
1573
- return context;
1574
- };
1575
- })(browser.newContext, browser);
1576
- }
1577
- };
1578
- PlaywrightExtra = new Proxy(PlaywrightExtraClass, {
1579
- construct(classTarget, args) {
1580
- debug$2(`create instance of ${classTarget.name}`);
1581
- const result = Reflect.construct(classTarget, args);
1582
- return new Proxy(result, {
1583
- get(target, prop) {
1584
- if (prop in target) {
1585
- return Reflect.get(target, prop);
1586
- }
1587
- debug$2("proxying property to original launcher: ", prop);
1588
- return Reflect.get(target.launcher, prop);
1589
- }
1590
- });
1591
- }
1592
- });
1593
- addExtra = (launcher) => new PlaywrightExtra(launcher);
1594
- chromium = addExtra((playwrightLoader.loadModule() || {}).chromium);
1595
- firefox = addExtra((playwrightLoader.loadModule() || {}).firefox);
1596
- webkit = addExtra((playwrightLoader.loadModule() || {}).webkit);
1597
- _android = playwrightLoader.lazyloadExportOrDie("_android");
1598
- _electron = playwrightLoader.lazyloadExportOrDie("_electron");
1599
- request = playwrightLoader.lazyloadExportOrDie("request");
1600
- selectors = playwrightLoader.lazyloadExportOrDie("selectors");
1601
- devices = playwrightLoader.lazyloadExportOrDie("devices");
1602
- errors = playwrightLoader.lazyloadExportOrDie("errors");
1603
- moduleExports = {
1604
- // custom exports
1605
- PlaywrightExtra,
1606
- PlaywrightExtraClass,
1607
- PluginList,
1608
- addExtra,
1609
- chromium,
1610
- firefox,
1611
- webkit,
1612
- // vanilla exports
1613
- _android,
1614
- _electron,
1615
- request,
1616
- selectors,
1617
- devices,
1618
- errors
1619
- };
1620
- index_esm_default = moduleExports;
1621
- }
1622
- });
1623
-
1624
- // node_modules/arr-union/index.js
1625
- var require_arr_union = __commonJS({
1626
- "node_modules/arr-union/index.js"(exports, module) {
1627
- "use strict";
1628
- module.exports = function union(init) {
1629
- if (!Array.isArray(init)) {
1630
- throw new TypeError("arr-union expects the first argument to be an array.");
1631
- }
1632
- var len = arguments.length;
1633
- var i = 0;
1634
- while (++i < len) {
1635
- var arg = arguments[i];
1636
- if (!arg) continue;
1637
- if (!Array.isArray(arg)) {
1638
- arg = [arg];
1639
- }
1640
- for (var j = 0; j < arg.length; j++) {
1641
- var ele = arg[j];
1642
- if (init.indexOf(ele) >= 0) {
1643
- continue;
1644
- }
1645
- init.push(ele);
1646
- }
1647
- }
1648
- return init;
1649
- };
1650
- }
1651
- });
1652
-
1653
- // node_modules/lazy-cache/index.js
1654
- var require_lazy_cache = __commonJS({
1655
- "node_modules/lazy-cache/index.js"(exports, module) {
1656
- "use strict";
1657
- function lazyCache(fn) {
1658
- var cache2 = {};
1659
- var proxy = function(mod, name) {
1660
- name = name || camelcase(mod);
1661
- if (process.env.UNLAZY === "true" || process.env.UNLAZY === true || process.env.TRAVIS) {
1662
- cache2[name] = fn(mod);
1663
- }
1664
- Object.defineProperty(proxy, name, {
1665
- enumerable: true,
1666
- configurable: true,
1667
- get: getter
1668
- });
1669
- function getter() {
1670
- if (cache2.hasOwnProperty(name)) {
1671
- return cache2[name];
1672
- }
1673
- return cache2[name] = fn(mod);
1674
- }
1675
- return getter;
1676
- };
1677
- return proxy;
1678
- }
1679
- function camelcase(str) {
1680
- if (str.length === 1) {
1681
- return str.toLowerCase();
1682
- }
1683
- str = str.replace(/^[\W_]+|[\W_]+$/g, "").toLowerCase();
1684
- return str.replace(/[\W_]+(\w|$)/g, function(_, ch) {
1685
- return ch.toUpperCase();
1686
- });
1687
- }
1688
- module.exports = lazyCache;
1689
- }
1690
- });
1691
-
1692
- // node_modules/for-in/index.js
1693
- var require_for_in = __commonJS({
1694
- "node_modules/for-in/index.js"(exports, module) {
1695
- "use strict";
1696
- module.exports = function forIn(obj, fn, thisArg) {
1697
- for (var key in obj) {
1698
- if (fn.call(thisArg, obj[key], key, obj) === false) {
1699
- break;
1700
- }
1701
- }
1702
- };
1703
- }
1704
- });
1705
-
1706
- // node_modules/for-own/index.js
1707
- var require_for_own = __commonJS({
1708
- "node_modules/for-own/index.js"(exports, module) {
1709
- "use strict";
1710
- var forIn = require_for_in();
1711
- var hasOwn = Object.prototype.hasOwnProperty;
1712
- module.exports = function forOwn(obj, fn, thisArg) {
1713
- forIn(obj, function(val, key) {
1714
- if (hasOwn.call(obj, key)) {
1715
- return fn.call(thisArg, obj[key], key, obj);
1716
- }
1717
- });
1718
- };
1719
- }
1720
- });
1721
-
1722
- // node_modules/clone-deep/utils.js
1723
- var require_utils = __commonJS({
1724
- "node_modules/clone-deep/utils.js"(exports, module) {
1725
- "use strict";
1726
- var utils = require_lazy_cache()(__require);
1727
- var fn = __require;
1728
- __require = utils;
1729
- __require("is-plain-object", "isObject");
1730
- __require("shallow-clone", "clone");
1731
- __require("kind-of", "typeOf");
1732
- require_for_own();
1733
- __require = fn;
1734
- module.exports = utils;
1735
- }
1736
- });
1737
-
1738
- // node_modules/clone-deep/index.js
1739
- var require_clone_deep = __commonJS({
1740
- "node_modules/clone-deep/index.js"(exports, module) {
1741
- "use strict";
1742
- var utils = require_utils();
1743
- function cloneDeep(val, instanceClone) {
1744
- switch (utils.typeOf(val)) {
1745
- case "object":
1746
- return cloneObjectDeep(val, instanceClone);
1747
- case "array":
1748
- return cloneArrayDeep(val, instanceClone);
1749
- default:
1750
- return utils.clone(val);
1751
- }
1752
- }
1753
- function cloneObjectDeep(obj, instanceClone) {
1754
- if (utils.isObject(obj)) {
1755
- var res = {};
1756
- utils.forOwn(obj, function(obj2, key) {
1757
- this[key] = cloneDeep(obj2, instanceClone);
1758
- }, res);
1759
- return res;
1760
- } else if (instanceClone) {
1761
- return instanceClone(obj);
1762
- } else {
1763
- return obj;
1764
- }
1765
- }
1766
- function cloneArrayDeep(arr, instanceClone) {
1767
- var len = arr.length, res = [];
1768
- var i = -1;
1769
- while (++i < len) {
1770
- res[i] = cloneDeep(arr[i], instanceClone);
1771
- }
1772
- return res;
1773
- }
1774
- module.exports = cloneDeep;
1775
- }
1776
- });
1777
-
1778
- // node_modules/is-buffer/index.js
1779
- var require_is_buffer = __commonJS({
1780
- "node_modules/is-buffer/index.js"(exports, module) {
1781
- "use strict";
1782
- module.exports = function(obj) {
1783
- return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer);
1784
- };
1785
- function isBuffer(obj) {
1786
- return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
1787
- }
1788
- function isSlowBuffer(obj) {
1789
- return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isBuffer(obj.slice(0, 0));
1790
- }
1791
- }
1792
- });
1793
-
1794
- // node_modules/kind-of/index.js
1795
- var require_kind_of = __commonJS({
1796
- "node_modules/kind-of/index.js"(exports, module) {
1797
- "use strict";
1798
- var isBuffer = require_is_buffer();
1799
- var toString = Object.prototype.toString;
1800
- module.exports = function kindOf(val) {
1801
- if (typeof val === "undefined") {
1802
- return "undefined";
1803
- }
1804
- if (val === null) {
1805
- return "null";
1806
- }
1807
- if (val === true || val === false || val instanceof Boolean) {
1808
- return "boolean";
1809
- }
1810
- if (typeof val === "string" || val instanceof String) {
1811
- return "string";
1812
- }
1813
- if (typeof val === "number" || val instanceof Number) {
1814
- return "number";
1815
- }
1816
- if (typeof val === "function" || val instanceof Function) {
1817
- return "function";
1818
- }
1819
- if (typeof Array.isArray !== "undefined" && Array.isArray(val)) {
1820
- return "array";
1821
- }
1822
- if (val instanceof RegExp) {
1823
- return "regexp";
1824
- }
1825
- if (val instanceof Date) {
1826
- return "date";
1827
- }
1828
- var type = toString.call(val);
1829
- if (type === "[object RegExp]") {
1830
- return "regexp";
1831
- }
1832
- if (type === "[object Date]") {
1833
- return "date";
1834
- }
1835
- if (type === "[object Arguments]") {
1836
- return "arguments";
1837
- }
1838
- if (type === "[object Error]") {
1839
- return "error";
1840
- }
1841
- if (isBuffer(val)) {
1842
- return "buffer";
1843
- }
1844
- if (type === "[object Set]") {
1845
- return "set";
1846
- }
1847
- if (type === "[object WeakSet]") {
1848
- return "weakset";
1849
- }
1850
- if (type === "[object Map]") {
1851
- return "map";
1852
- }
1853
- if (type === "[object WeakMap]") {
1854
- return "weakmap";
1855
- }
1856
- if (type === "[object Symbol]") {
1857
- return "symbol";
1858
- }
1859
- if (type === "[object Int8Array]") {
1860
- return "int8array";
1861
- }
1862
- if (type === "[object Uint8Array]") {
1863
- return "uint8array";
1864
- }
1865
- if (type === "[object Uint8ClampedArray]") {
1866
- return "uint8clampedarray";
1867
- }
1868
- if (type === "[object Int16Array]") {
1869
- return "int16array";
1870
- }
1871
- if (type === "[object Uint16Array]") {
1872
- return "uint16array";
1873
- }
1874
- if (type === "[object Int32Array]") {
1875
- return "int32array";
1876
- }
1877
- if (type === "[object Uint32Array]") {
1878
- return "uint32array";
1879
- }
1880
- if (type === "[object Float32Array]") {
1881
- return "float32array";
1882
- }
1883
- if (type === "[object Float64Array]") {
1884
- return "float64array";
1885
- }
1886
- return "object";
1887
- };
1888
- }
1889
- });
1890
-
1891
- // node_modules/merge-deep/index.js
1892
- var require_merge_deep = __commonJS({
1893
- "node_modules/merge-deep/index.js"(exports, module) {
1894
- "use strict";
1895
- var union = require_arr_union();
1896
- var clone = require_clone_deep();
1897
- var typeOf = require_kind_of();
1898
- module.exports = function mergeDeep(orig, objects) {
1899
- if (!isObject(orig) && !Array.isArray(orig)) {
1900
- orig = {};
1901
- }
1902
- var target = clone(orig);
1903
- var len = arguments.length;
1904
- var idx = 0;
1905
- while (++idx < len) {
1906
- var val = arguments[idx];
1907
- if (isObject(val) || Array.isArray(val)) {
1908
- merge2(target, val);
1909
- }
1910
- }
1911
- return target;
1912
- };
1913
- function merge2(target, obj) {
1914
- for (var key in obj) {
1915
- if (!isValidKey(key) || !hasOwn(obj, key)) {
1916
- continue;
1917
- }
1918
- var oldVal = obj[key];
1919
- var newVal = target[key];
1920
- if (isObject(newVal) && isObject(oldVal)) {
1921
- target[key] = merge2(newVal, oldVal);
1922
- } else if (Array.isArray(newVal)) {
1923
- target[key] = union([], newVal, oldVal);
1924
- } else {
1925
- target[key] = clone(oldVal);
1926
- }
1927
- }
1928
- return target;
1929
- }
1930
- function hasOwn(obj, key) {
1931
- return Object.prototype.hasOwnProperty.call(obj, key);
1932
- }
1933
- function isObject(val) {
1934
- return typeOf(val) === "object" || typeOf(val) === "function";
1935
- }
1936
- function isValidKey(key) {
1937
- return key !== "__proto__" && key !== "constructor" && key !== "prototype";
1938
- }
1939
- }
1940
- });
1941
-
1942
- // node_modules/puppeteer-extra-plugin/dist/index.esm.js
1943
- var index_esm_exports2 = {};
1944
- __export(index_esm_exports2, {
1945
- PuppeteerExtraPlugin: () => PuppeteerExtraPlugin
1946
- });
1947
- var import_debug2, merge, PuppeteerExtraPlugin;
1948
- var init_index_esm2 = __esm({
1949
- "node_modules/puppeteer-extra-plugin/dist/index.esm.js"() {
1950
- "use strict";
1951
- import_debug2 = __toESM(require_src());
1952
- merge = require_merge_deep();
1953
- PuppeteerExtraPlugin = class {
1954
- constructor(opts) {
1955
- this._debugBase = (0, import_debug2.default)(`puppeteer-extra-plugin:base:${this.name}`);
1956
- this._childClassMembers = [];
1957
- this._opts = merge(this.defaults, opts || {});
1958
- this._debugBase("Initialized.");
1959
- }
1960
- /**
1961
- * Plugin name (required).
1962
- *
1963
- * Convention:
1964
- * - Package: `puppeteer-extra-plugin-anonymize-ua`
1965
- * - Name: `anonymize-ua`
1966
- *
1967
- * @example
1968
- * get name () { return 'anonymize-ua' }
1969
- */
1970
- get name() {
1971
- throw new Error('Plugin must override "name"');
1972
- }
1973
- /**
1974
- * Plugin defaults (optional).
1975
- *
1976
- * If defined will be ([deep-](https://github.com/jonschlinkert/merge-deep))merged with the (optional) user supplied options (supplied during plugin instantiation).
1977
- *
1978
- * The result of merging defaults with user supplied options can be accessed through `this.opts`.
1979
- *
1980
- * @see [[opts]]
1981
- *
1982
- * @example
1983
- * get defaults () {
1984
- * return {
1985
- * stripHeadless: true,
1986
- * makeWindows: true,
1987
- * customFn: null
1988
- * }
1989
- * }
1990
- *
1991
- * // Users can overwrite plugin defaults during instantiation:
1992
- * puppeteer.use(require('puppeteer-extra-plugin-foobar')({ makeWindows: false }))
1993
- */
1994
- get defaults() {
1995
- return {};
1996
- }
1997
- /**
1998
- * Plugin requirements (optional).
1999
- *
2000
- * Signal certain plugin requirements to the base class and the user.
2001
- *
2002
- * Currently supported:
2003
- * - `launch`
2004
- * - If the plugin only supports locally created browser instances (no `puppeteer.connect()`),
2005
- * will output a warning to the user.
2006
- * - `headful`
2007
- * - If the plugin doesn't work in `headless: true` mode,
2008
- * will output a warning to the user.
2009
- * - `dataFromPlugins`
2010
- * - In case the plugin requires data from other plugins.
2011
- * will enable usage of `this.getDataFromPlugins()`.
2012
- * - `runLast`
2013
- * - In case the plugin prefers to run after the others.
2014
- * Useful when the plugin needs data from others.
2015
- *
2016
- * @example
2017
- * get requirements () {
2018
- * return new Set(['runLast', 'dataFromPlugins'])
2019
- * }
2020
- */
2021
- get requirements() {
2022
- return /* @__PURE__ */ new Set([]);
2023
- }
2024
- /**
2025
- * Plugin dependencies (optional).
2026
- *
2027
- * Missing plugins will be required() by puppeteer-extra.
2028
- *
2029
- * @example
2030
- * get dependencies () {
2031
- * return new Set(['user-preferences'])
2032
- * }
2033
- * // Will ensure the 'puppeteer-extra-plugin-user-preferences' plugin is loaded.
2034
- */
2035
- get dependencies() {
2036
- return /* @__PURE__ */ new Set([]);
2037
- }
2038
- /**
2039
- * Plugin data (optional).
2040
- *
2041
- * Plugins can expose data (an array of objects), which in turn can be consumed by other plugins,
2042
- * that list the `dataFromPlugins` requirement (by using `this.getDataFromPlugins()`).
2043
- *
2044
- * Convention: `[ {name: 'Any name', value: 'Any value'} ]`
2045
- *
2046
- * @see [[getDataFromPlugins]]
2047
- *
2048
- * @example
2049
- * // plugin1.js
2050
- * get data () {
2051
- * return [
2052
- * {
2053
- * name: 'userPreferences',
2054
- * value: { foo: 'bar' }
2055
- * },
2056
- * {
2057
- * name: 'userPreferences',
2058
- * value: { hello: 'world' }
2059
- * }
2060
- * ]
2061
- *
2062
- * // plugin2.js
2063
- * get requirements () { return new Set(['dataFromPlugins']) }
2064
- *
2065
- * async beforeLaunch () {
2066
- * const prefs = this.getDataFromPlugins('userPreferences').map(d => d.value)
2067
- * this.debug(prefs) // => [ { foo: 'bar' }, { hello: 'world' } ]
2068
- * }
2069
- */
2070
- get data() {
2071
- return [];
2072
- }
2073
- /**
2074
- * Access the plugin options (usually the `defaults` merged with user defined options)
2075
- *
2076
- * To skip the auto-merging of defaults with user supplied opts don't define a `defaults`
2077
- * property and set the `this._opts` Object in your plugin constructor directly.
2078
- *
2079
- * @see [[defaults]]
2080
- *
2081
- * @example
2082
- * get defaults () { return { foo: "bar" } }
2083
- *
2084
- * async onPageCreated (page) {
2085
- * this.debug(this.opts.foo) // => bar
2086
- * }
2087
- */
2088
- get opts() {
2089
- return this._opts;
2090
- }
2091
- /**
2092
- * Convenience debug logger based on the [debug] module.
2093
- * Will automatically namespace the logging output to the plugin package name.
2094
- * [debug]: https://www.npmjs.com/package/debug
2095
- *
2096
- * ```bash
2097
- * # toggle output using environment variables
2098
- * DEBUG=puppeteer-extra-plugin:<plugin_name> node foo.js
2099
- * # to debug all the things:
2100
- * DEBUG=puppeteer-extra,puppeteer-extra-plugin:* node foo.js
2101
- * ```
2102
- *
2103
- * @example
2104
- * this.debug('hello world')
2105
- * // will output e.g. 'puppeteer-extra-plugin:anonymize-ua hello world'
2106
- */
2107
- get debug() {
2108
- return (0, import_debug2.default)(`puppeteer-extra-plugin:${this.name}`);
2109
- }
2110
- /**
2111
- * Before a new browser instance is created/launched.
2112
- *
2113
- * Can be used to modify the puppeteer launch options by modifying or returning them.
2114
- *
2115
- * Plugins using this method will be called in sequence to each
2116
- * be able to update the launch options.
2117
- *
2118
- * @example
2119
- * async beforeLaunch (options) {
2120
- * if (this.opts.flashPluginPath) {
2121
- * options.args.push(`--ppapi-flash-path=${this.opts.flashPluginPath}`)
2122
- * }
2123
- * }
2124
- *
2125
- * @param options - Puppeteer launch options
2126
- */
2127
- async beforeLaunch(options) {
2128
- }
2129
- /**
2130
- * After the browser has launched.
2131
- *
2132
- * Note: Don't assume that there will only be a single browser instance during the lifecycle of a plugin.
2133
- * It's possible that `pupeeteer.launch` will be called multiple times and more than one browser created.
2134
- * In order to make the plugins as stateless as possible don't store a reference to the browser instance
2135
- * in the plugin but rather consider alternatives.
2136
- *
2137
- * E.g. when using `onPageCreated` you can get a browser reference by using `page.browser()`.
2138
- *
2139
- * Alternatively you could expose a class method that takes a browser instance as a parameter to work with:
2140
- *
2141
- * ```es6
2142
- * const fancyPlugin = require('puppeteer-extra-plugin-fancy')()
2143
- * puppeteer.use(fancyPlugin)
2144
- * const browser = await puppeteer.launch()
2145
- * await fancyPlugin.killBrowser(browser)
2146
- * ```
2147
- *
2148
- * @param browser - The `puppeteer` browser instance.
2149
- * @param opts.options - Puppeteer launch options used.
2150
- *
2151
- * @example
2152
- * async afterLaunch (browser, opts) {
2153
- * this.debug('browser has been launched', opts.options)
2154
- * }
2155
- */
2156
- async afterLaunch(browser, opts = { options: {} }) {
2157
- }
2158
- /**
2159
- * Before connecting to an existing browser instance.
2160
- *
2161
- * Can be used to modify the puppeteer connect options by modifying or returning them.
2162
- *
2163
- * Plugins using this method will be called in sequence to each
2164
- * be able to update the launch options.
2165
- *
2166
- * @param {Object} options - Puppeteer connect options
2167
- * @return {Object=}
2168
- */
2169
- async beforeConnect(options) {
2170
- }
2171
- /**
2172
- * After connecting to an existing browser instance.
2173
- *
2174
- * > Note: Don't assume that there will only be a single browser instance during the lifecycle of a plugin.
2175
- *
2176
- * @param browser - The `puppeteer` browser instance.
2177
- * @param {Object} opts
2178
- * @param {Object} opts.options - Puppeteer connect options used.
2179
- *
2180
- */
2181
- async afterConnect(browser, opts = {}) {
2182
- }
2183
- /**
2184
- * Called when a browser instance is available.
2185
- *
2186
- * This applies to both `puppeteer.launch()` and `puppeteer.connect()`.
2187
- *
2188
- * Convenience method created for plugins that need access to a browser instance
2189
- * and don't mind if it has been created through `launch` or `connect`.
2190
- *
2191
- * > Note: Don't assume that there will only be a single browser instance during the lifecycle of a plugin.
2192
- *
2193
- * @param browser - The `puppeteer` browser instance.
2194
- */
2195
- async onBrowser(browser, opts) {
2196
- }
2197
- /**
2198
- * Called when a target is created, for example when a new page is opened by window.open or browser.newPage.
2199
- *
2200
- * > Note: This includes target creations in incognito browser contexts.
2201
- *
2202
- * > Note: This includes browser instances created through `.launch()` as well as `.connect()`.
2203
- *
2204
- * @param {Puppeteer.Target} target
2205
- */
2206
- async onTargetCreated(target) {
2207
- }
2208
- /**
2209
- * Same as `onTargetCreated` but prefiltered to only contain Pages, for convenience.
2210
- *
2211
- * > Note: This includes page creations in incognito browser contexts.
2212
- *
2213
- * > Note: This includes browser instances created through `.launch()` as well as `.connect()`.
2214
- *
2215
- * @param {Puppeteer.Target} target
2216
- *
2217
- * @example
2218
- * async onPageCreated (page) {
2219
- * let ua = await page.browser().userAgent()
2220
- * if (this.opts.stripHeadless) {
2221
- * ua = ua.replace('HeadlessChrome/', 'Chrome/')
2222
- * }
2223
- * this.debug('new ua', ua)
2224
- * await page.setUserAgent(ua)
2225
- * }
2226
- */
2227
- async onPageCreated(page) {
2228
- }
2229
- /**
2230
- * Called when the url of a target changes.
2231
- *
2232
- * > Note: This includes target changes in incognito browser contexts.
2233
- *
2234
- * > Note: This includes browser instances created through `.launch()` as well as `.connect()`.
2235
- *
2236
- * @param {Puppeteer.Target} target
2237
- */
2238
- async onTargetChanged(target) {
2239
- }
2240
- /**
2241
- * Called when a target is destroyed, for example when a page is closed.
2242
- *
2243
- * > Note: This includes target destructions in incognito browser contexts.
2244
- *
2245
- * > Note: This includes browser instances created through `.launch()` as well as `.connect()`.
2246
- *
2247
- * @param {Puppeteer.Target} target
2248
- */
2249
- async onTargetDestroyed(target) {
2250
- }
2251
- /**
2252
- * Called when Puppeteer gets disconnected from the Chromium instance.
2253
- *
2254
- * This might happen because of one of the following:
2255
- * - Chromium is closed or crashed
2256
- * - The `browser.disconnect` method was called
2257
- */
2258
- async onDisconnected() {
2259
- }
2260
- /**
2261
- * **Deprecated:** Since puppeteer v1.6.0 `onDisconnected` has been improved
2262
- * and should be used instead of `onClose`.
2263
- *
2264
- * In puppeteer < v1.6.0 `onDisconnected` was not catching all exit scenarios.
2265
- * In order for plugins to clean up properly (e.g. deleting temporary files)
2266
- * the `onClose` method had been introduced.
2267
- *
2268
- * > Note: Might be called multiple times on exit.
2269
- *
2270
- * > Note: This only includes browser instances created through `.launch()`.
2271
- */
2272
- async onClose() {
2273
- }
2274
- /**
2275
- * After the plugin has been registered in `puppeteer-extra`.
2276
- *
2277
- * Normally right after `puppeteer.use(plugin)` is called
2278
- */
2279
- async onPluginRegistered() {
2280
- }
2281
- /**
2282
- * Helper method to retrieve `data` objects from other plugins.
2283
- *
2284
- * A plugin needs to state the `dataFromPlugins` requirement
2285
- * in order to use this method. Will be mapped to `puppeteer.getPluginData`.
2286
- *
2287
- * @param name - Filter data by `name` property
2288
- *
2289
- * @see [data]
2290
- * @see [requirements]
2291
- */
2292
- getDataFromPlugins(name) {
2293
- return [];
2294
- }
2295
- /**
2296
- * Will match plugin dependencies against all currently registered plugins.
2297
- * Is being called by `puppeteer-extra` and used to require missing dependencies.
2298
- *
2299
- * @param {Array<Object>} plugins
2300
- * @return {Set} - list of missing plugin names
2301
- *
2302
- * @private
2303
- */
2304
- _getMissingDependencies(plugins) {
2305
- const pluginNames = new Set(plugins.map((p) => p.name));
2306
- const missing = new Set(Array.from(this.dependencies.values()).filter((x) => !pluginNames.has(x)));
2307
- return missing;
2308
- }
2309
- /**
2310
- * Conditionally bind browser/process events to class members.
2311
- * The idea is to reduce event binding boilerplate in plugins.
2312
- *
2313
- * For efficiency we make sure the plugin is using the respective event
2314
- * by checking the child class members before registering the listener.
2315
- *
2316
- * @param {<Puppeteer.Browser>} browser
2317
- * @param {Object} opts - Options
2318
- * @param {string} opts.context - Puppeteer context (launch/connect)
2319
- * @param {Object} [opts.options] - Puppeteer launch or connect options
2320
- * @param {Array<string>} [opts.defaultArgs] - The default flags that Chromium will be launched with
2321
- *
2322
- * @private
2323
- */
2324
- async _bindBrowserEvents(browser, opts = {}) {
2325
- if (this._hasChildClassMember("onTargetCreated") || this._hasChildClassMember("onPageCreated")) {
2326
- browser.on("targetcreated", this._onTargetCreated.bind(this));
2327
- }
2328
- if (this._hasChildClassMember("onTargetChanged") && this.onTargetChanged) {
2329
- browser.on("targetchanged", this.onTargetChanged.bind(this));
2330
- }
2331
- if (this._hasChildClassMember("onTargetDestroyed") && this.onTargetDestroyed) {
2332
- browser.on("targetdestroyed", this.onTargetDestroyed.bind(this));
2333
- }
2334
- if (this._hasChildClassMember("onDisconnected") && this.onDisconnected) {
2335
- browser.on("disconnected", this.onDisconnected.bind(this));
2336
- }
2337
- if (opts.context === "launch" && this._hasChildClassMember("onClose")) {
2338
- if (this.onClose) {
2339
- process.on("exit", this.onClose.bind(this));
2340
- browser.on("disconnected", this.onClose.bind(this));
2341
- if (opts.options.handleSIGINT !== false) {
2342
- process.on("SIGINT", this.onClose.bind(this));
2343
- }
2344
- if (opts.options.handleSIGTERM !== false) {
2345
- process.on("SIGTERM", this.onClose.bind(this));
2346
- }
2347
- if (opts.options.handleSIGHUP !== false) {
2348
- process.on("SIGHUP", this.onClose.bind(this));
2349
- }
2350
- }
2351
- }
2352
- if (opts.context === "launch" && this.afterLaunch) {
2353
- await this.afterLaunch(browser, opts);
2354
- }
2355
- if (opts.context === "connect" && this.afterConnect) {
2356
- await this.afterConnect(browser, opts);
2357
- }
2358
- if (this.onBrowser)
2359
- await this.onBrowser(browser, opts);
2360
- }
2361
- /**
2362
- * @private
2363
- */
2364
- async _onTargetCreated(target) {
2365
- if (this.onTargetCreated)
2366
- await this.onTargetCreated(target);
2367
- if (target.type() === "page") {
2368
- try {
2369
- const page = await target.page();
2370
- if (!page) {
2371
- return;
2372
- }
2373
- const validPage = "isClosed" in page && !page.isClosed();
2374
- if (this.onPageCreated && validPage) {
2375
- await this.onPageCreated(page);
2376
- }
2377
- } catch (err) {
2378
- console.error(err);
2379
- }
2380
- }
2381
- }
2382
- /**
2383
- * @private
2384
- */
2385
- _register(prototype) {
2386
- this._registerChildClassMembers(prototype);
2387
- if (this.onPluginRegistered)
2388
- this.onPluginRegistered();
2389
- }
2390
- /**
2391
- * @private
2392
- */
2393
- _registerChildClassMembers(prototype) {
2394
- this._childClassMembers = Object.getOwnPropertyNames(prototype);
2395
- }
2396
- /**
2397
- * @private
2398
- */
2399
- _hasChildClassMember(name) {
2400
- return !!this._childClassMembers.includes(name);
2401
- }
2402
- /**
2403
- * @private
2404
- */
2405
- get _isPuppeteerExtraPlugin() {
2406
- return true;
2407
- }
2408
- };
2409
- }
2410
- });
2411
-
2412
- // node_modules/puppeteer-extra-plugin-stealth/index.js
2413
- var require_puppeteer_extra_plugin_stealth = __commonJS({
2414
- "node_modules/puppeteer-extra-plugin-stealth/index.js"(exports, module) {
2415
- "use strict";
2416
- var { PuppeteerExtraPlugin: PuppeteerExtraPlugin2 } = (init_index_esm2(), __toCommonJS(index_esm_exports2));
2417
- var StealthPlugin = class extends PuppeteerExtraPlugin2 {
2418
- constructor(opts = {}) {
2419
- super(opts);
2420
- }
2421
- get name() {
2422
- return "stealth";
2423
- }
2424
- get defaults() {
2425
- const availableEvasions = /* @__PURE__ */ new Set([
2426
- "chrome.app",
2427
- "chrome.csi",
2428
- "chrome.loadTimes",
2429
- "chrome.runtime",
2430
- "defaultArgs",
2431
- "iframe.contentWindow",
2432
- "media.codecs",
2433
- "navigator.hardwareConcurrency",
2434
- "navigator.languages",
2435
- "navigator.permissions",
2436
- "navigator.plugins",
2437
- "navigator.webdriver",
2438
- "sourceurl",
2439
- "user-agent-override",
2440
- "webgl.vendor",
2441
- "window.outerdimensions"
2442
- ]);
2443
- return {
2444
- availableEvasions,
2445
- // Enable all available evasions by default
2446
- enabledEvasions: /* @__PURE__ */ new Set([...availableEvasions])
2447
- };
2448
- }
2449
- /**
2450
- * Requires evasion techniques dynamically based on configuration.
2451
- *
2452
- * @private
2453
- */
2454
- get dependencies() {
2455
- return new Set(
2456
- [...this.opts.enabledEvasions].map((e) => `${this.name}/evasions/${e}`)
2457
- );
2458
- }
2459
- /**
2460
- * Get all available evasions.
2461
- *
2462
- * Please look into the [evasions directory](./evasions/) for an up to date list.
2463
- *
2464
- * @type {Set<string>} - A Set of all available evasions.
2465
- *
2466
- * @example
2467
- * const pluginStealth = require('puppeteer-extra-plugin-stealth')()
2468
- * console.log(pluginStealth.availableEvasions) // => Set { 'user-agent', 'console.debug' }
2469
- * puppeteer.use(pluginStealth)
2470
- */
2471
- get availableEvasions() {
2472
- return this.defaults.availableEvasions;
2473
- }
2474
- /**
2475
- * Get all enabled evasions.
2476
- *
2477
- * Enabled evasions can be configured either through `opts` or by modifying this property.
2478
- *
2479
- * @type {Set<string>} - A Set of all enabled evasions.
2480
- *
2481
- * @example
2482
- * // Remove specific evasion from enabled ones dynamically
2483
- * const pluginStealth = require('puppeteer-extra-plugin-stealth')()
2484
- * pluginStealth.enabledEvasions.delete('console.debug')
2485
- * puppeteer.use(pluginStealth)
2486
- */
2487
- get enabledEvasions() {
2488
- return this.opts.enabledEvasions;
2489
- }
2490
- /**
2491
- * @private
2492
- */
2493
- set enabledEvasions(evasions) {
2494
- this.opts.enabledEvasions = evasions;
2495
- }
2496
- async onBrowser(browser) {
2497
- if (browser && browser.setMaxListeners) {
2498
- browser.setMaxListeners(30);
2499
- }
2500
- }
2501
- };
2502
- var defaultExport = (opts) => new StealthPlugin(opts);
2503
- module.exports = defaultExport;
2504
- }
2505
- });
2506
2
 
2507
3
  // src/index.ts
2508
4
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -2531,6 +27,14 @@ var DEFAULT_BROWSER_CONFIG = {
2531
27
  cdpPort: 9222
2532
28
  // Дефолтный CDP port для подключения множественных агентов
2533
29
  };
30
+ var DEFAULT_HUMANIZATION_CONFIG = {
31
+ enabled: true,
32
+ // Включено по умолчанию (решение пользователя от 2026-10-10)
33
+ internalHosts: [],
34
+ // Список внутренних хостов для автоотключения
35
+ sites: {}
36
+ // Пер-сайт переопределения
37
+ };
2534
38
  function loadConfig() {
2535
39
  const fileConfig = loadConfigFile();
2536
40
  const apiKeys = {
@@ -2549,8 +53,10 @@ function loadConfig() {
2549
53
  downloadTimeout: process.env.VSL_DOWNLOAD_TIMEOUT ? parseInt(process.env.VSL_DOWNLOAD_TIMEOUT, 10) : fileConfig.browser?.downloadTimeout ?? DEFAULT_BROWSER_CONFIG.downloadTimeout,
2550
54
  acceptDownloads: process.env.VSL_ACCEPT_DOWNLOADS ? process.env.VSL_ACCEPT_DOWNLOADS === "true" : fileConfig.browser?.acceptDownloads ?? DEFAULT_BROWSER_CONFIG.acceptDownloads,
2551
55
  userDataDir: process.env.VSL_USER_DATA_DIR || fileConfig.browser?.userDataDir || DEFAULT_BROWSER_CONFIG.userDataDir,
2552
- cdpPort: process.env.VSL_CDP_PORT ? parseInt(process.env.VSL_CDP_PORT, 10) : fileConfig.browser?.cdpPort ?? DEFAULT_BROWSER_CONFIG.cdpPort
56
+ cdpPort: process.env.VSL_CDP_PORT ? parseInt(process.env.VSL_CDP_PORT, 10) : fileConfig.browser?.cdpPort ?? DEFAULT_BROWSER_CONFIG.cdpPort,
57
+ proxy: parseProxyConfig(fileConfig)
2553
58
  };
59
+ const humanization = parseHumanizationConfig(fileConfig);
2554
60
  return {
2555
61
  vision: {
2556
62
  provider,
@@ -2559,9 +65,28 @@ function loadConfig() {
2559
65
  ...baseUrl ? { baseUrl } : {}
2560
66
  },
2561
67
  browser,
68
+ humanization,
2562
69
  apiKeys
2563
70
  };
2564
71
  }
72
+ function parseProxyConfig(fileConfig) {
73
+ const server = process.env.VSL_PROXY_SERVER || fileConfig.browser?.proxy?.server;
74
+ if (!server) return void 0;
75
+ const username = process.env.VSL_PROXY_USERNAME || fileConfig.browser?.proxy?.username;
76
+ const password = process.env.VSL_PROXY_PASSWORD || fileConfig.browser?.proxy?.password;
77
+ return {
78
+ server,
79
+ ...username ? { username } : {},
80
+ ...password ? { password } : {}
81
+ };
82
+ }
83
+ function parseHumanizationConfig(fileConfig) {
84
+ const fileHumanization = fileConfig.humanization;
85
+ const enabled = process.env.VSL_HUMANIZATION_ENABLED ? process.env.VSL_HUMANIZATION_ENABLED === "true" : fileHumanization?.enabled ?? DEFAULT_HUMANIZATION_CONFIG.enabled;
86
+ const internalHosts = process.env.VSL_HUMANIZATION_INTERNAL_HOSTS ? process.env.VSL_HUMANIZATION_INTERNAL_HOSTS.split(",").map((h) => h.trim()).filter((h) => h.length > 0) : fileHumanization?.internalHosts ?? DEFAULT_HUMANIZATION_CONFIG.internalHosts;
87
+ const sites = fileHumanization?.sites ?? DEFAULT_HUMANIZATION_CONFIG.sites;
88
+ return { enabled, internalHosts, sites };
89
+ }
2565
90
  function loadConfigFile() {
2566
91
  if (!existsSync(DEFAULT_CONFIG_PATH)) {
2567
92
  return {};
@@ -3637,6 +1162,453 @@ async function handleClearCache(session) {
3637
1162
  }
3638
1163
  }
3639
1164
 
1165
+ // src/config/humanizationConfig.ts
1166
+ var EFFECTIVE_DEFAULT = {
1167
+ enabled: true,
1168
+ internalHosts: [],
1169
+ sites: {}
1170
+ };
1171
+ function extractHostname(url) {
1172
+ try {
1173
+ return new URL(url).hostname;
1174
+ } catch {
1175
+ return "";
1176
+ }
1177
+ }
1178
+ function isLocalOrPrivateHostname(hostname) {
1179
+ const h = hostname.toLowerCase().replace(/^\[/, "").replace(/\]$/, "");
1180
+ if (h === "" || h === "localhost" || h.endsWith(".localhost")) return true;
1181
+ if (h === "::1" || h === "0.0.0.0") return true;
1182
+ if (h.startsWith("127.")) return true;
1183
+ if (h.endsWith(".local") || h.endsWith(".internal") || h.endsWith(".home")) return true;
1184
+ const m = h.match(/^(\d{1,3})\.(\d{1,3})\./);
1185
+ if (m) {
1186
+ const a = Number(m[1]);
1187
+ const b = Number(m[2]);
1188
+ if (a === 10) return true;
1189
+ if (a === 192 && b === 168) return true;
1190
+ if (a === 172 && b >= 16 && b <= 31) return true;
1191
+ if (a === 169 && b === 254) return true;
1192
+ }
1193
+ return false;
1194
+ }
1195
+ function findSiteOverride(hostname, sites) {
1196
+ const exact = sites[hostname];
1197
+ if (exact) return exact;
1198
+ const labels = hostname.split(".");
1199
+ for (let i = 1; i < labels.length - 1; i += 1) {
1200
+ const candidate = labels.slice(i).join(".");
1201
+ const override = sites[candidate];
1202
+ if (override) return override;
1203
+ }
1204
+ return void 0;
1205
+ }
1206
+ function resolveHumanizationForHost(urlOrHostname, config) {
1207
+ const effective = config ?? EFFECTIVE_DEFAULT;
1208
+ let hostname;
1209
+ try {
1210
+ hostname = new URL(urlOrHostname).hostname;
1211
+ } catch {
1212
+ hostname = urlOrHostname;
1213
+ }
1214
+ hostname = hostname.toLowerCase();
1215
+ if (!effective.enabled) {
1216
+ return { enabled: false, reason: "global-disabled" };
1217
+ }
1218
+ if (isLocalOrPrivateHostname(hostname)) {
1219
+ return { enabled: false, reason: "local-host" };
1220
+ }
1221
+ const isInternal = (effective.internalHosts ?? []).some((entry) => {
1222
+ const e = entry.toLowerCase().trim();
1223
+ return e.length > 0 && (hostname === e || hostname.endsWith(`.${e}`));
1224
+ });
1225
+ if (isInternal) {
1226
+ return { enabled: false, reason: "internal-host" };
1227
+ }
1228
+ const site = hostname ? findSiteOverride(hostname, effective.sites ?? {}) : void 0;
1229
+ if (site && typeof site.enabled === "boolean") {
1230
+ return {
1231
+ enabled: site.enabled,
1232
+ reason: site.enabled ? "site-override-enabled" : "site-override-disabled",
1233
+ site
1234
+ };
1235
+ }
1236
+ if (site) return { enabled: true, reason: "default-enabled", site };
1237
+ return { enabled: true, reason: "default-enabled" };
1238
+ }
1239
+
1240
+ // src/humanization/timingEngine.ts
1241
+ var DEFAULT_TIMING_PARAMS = {
1242
+ meanMs: 500,
1243
+ sigmaMs: 200,
1244
+ minMs: 200,
1245
+ maxMs: 2e3
1246
+ };
1247
+ function gaussianSample(mean, sigma, rng = Math.random) {
1248
+ const u1 = Math.max(1 - rng(), 1e-12);
1249
+ const u2 = rng();
1250
+ const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
1251
+ return mean + sigma * z;
1252
+ }
1253
+ function clamp(value, min, max) {
1254
+ return Math.min(Math.max(value, min), max);
1255
+ }
1256
+ var TimingEngine = class _TimingEngine {
1257
+ params;
1258
+ rng;
1259
+ constructor(params, rng = Math.random) {
1260
+ this.params = { ...DEFAULT_TIMING_PARAMS, ...params };
1261
+ this.rng = rng;
1262
+ }
1263
+ /**
1264
+ * Строит движок из пер-сайт конфигурации
1265
+ * (`humanization.sites.<host>.timing`); отсутствующие поля
1266
+ * заменяются дефолтами.
1267
+ */
1268
+ static fromSiteConfig(site, rng) {
1269
+ return new _TimingEngine(site?.timing, rng);
1270
+ }
1271
+ /** Возвращает копию действующих параметров. */
1272
+ getParams() {
1273
+ return { ...this.params };
1274
+ }
1275
+ /**
1276
+ * Случайная задержка в мс: гауссово распределение (μ, σ)
1277
+ * с клампом в [minMs, maxMs], округлённая до целых.
1278
+ */
1279
+ sampleDelayMs() {
1280
+ const raw = gaussianSample(this.params.meanMs, this.params.sigmaMs, this.rng);
1281
+ return Math.round(clamp(raw, this.params.minMs, this.params.maxMs));
1282
+ }
1283
+ };
1284
+
1285
+ // src/humanization/rateLimiter.ts
1286
+ var RATE_WINDOW_MS = 60 * 60 * 1e3;
1287
+ var DEFAULT_MAX_ACTIONS_PER_HOUR = 1e3;
1288
+ var RateLimiter = class _RateLimiter {
1289
+ maxActionsPerHour;
1290
+ now;
1291
+ timestamps = [];
1292
+ constructor(options = {}) {
1293
+ this.maxActionsPerHour = options.maxActionsPerHour ?? DEFAULT_MAX_ACTIONS_PER_HOUR;
1294
+ this.now = options.now ?? Date.now;
1295
+ }
1296
+ /** Строит лимитер из пер-сайт конфигурации (`rateLimits.maxActionsPerHour`). */
1297
+ static fromSiteConfig(site, now) {
1298
+ return new _RateLimiter({ maxActionsPerHour: site?.rateLimits?.maxActionsPerHour, now });
1299
+ }
1300
+ /** Возвращает действующий лимит. */
1301
+ getLimit() {
1302
+ return this.maxActionsPerHour;
1303
+ }
1304
+ /** Удаляет записи старше окна. */
1305
+ evict(currentTime) {
1306
+ const cutoff = currentTime - RATE_WINDOW_MS;
1307
+ while (this.timestamps.length > 0 && this.timestamps[0] <= cutoff) {
1308
+ this.timestamps.shift();
1309
+ }
1310
+ }
1311
+ /**
1312
+ * Пытается учесть действие: при превышении лимита действие НЕ учитывается
1313
+ * и возвращается время до освобождения слота.
1314
+ */
1315
+ tryAcquire() {
1316
+ const currentTime = this.now();
1317
+ this.evict(currentTime);
1318
+ if (this.timestamps.length >= this.maxActionsPerHour) {
1319
+ const oldest = this.timestamps[0];
1320
+ const retryAfterMs = Math.max(0, oldest + RATE_WINDOW_MS - currentTime);
1321
+ return { allowed: false, retryAfterMs, remaining: 0 };
1322
+ }
1323
+ this.timestamps.push(currentTime);
1324
+ return {
1325
+ allowed: true,
1326
+ retryAfterMs: 0,
1327
+ remaining: this.maxActionsPerHour - this.timestamps.length
1328
+ };
1329
+ }
1330
+ /** Оставшиеся действия без учёта нового (наблюдение). */
1331
+ peekRemaining() {
1332
+ this.evict(this.now());
1333
+ return Math.max(0, this.maxActionsPerHour - this.timestamps.length);
1334
+ }
1335
+ /** Полный сброс истории (например, при закрытии сессии). */
1336
+ reset() {
1337
+ this.timestamps = [];
1338
+ }
1339
+ };
1340
+
1341
+ // src/humanization/typingSimulator.ts
1342
+ var DEFAULT_TYPING_PARAMS = {
1343
+ minDelayMs: 50,
1344
+ maxDelayMs: 200,
1345
+ typoRate: 0.03
1346
+ };
1347
+ var QWERTY_NEIGHBORS = {
1348
+ a: "sqwz",
1349
+ b: "vghn",
1350
+ c: "xdfv",
1351
+ d: "serfcx",
1352
+ e: "wsdfr",
1353
+ f: "drtgvc",
1354
+ g: "tfyhvb",
1355
+ h: "gyujbn",
1356
+ i: "ujklo",
1357
+ j: "huiknm",
1358
+ k: "jiolm",
1359
+ l: "kop",
1360
+ m: "njk",
1361
+ n: "bhjm",
1362
+ o: "iklp",
1363
+ p: "ol",
1364
+ q: "wa",
1365
+ r: "edft",
1366
+ s: "awedxz",
1367
+ t: "rfgy",
1368
+ u: "yhjki",
1369
+ v: "cfgb",
1370
+ w: "qase",
1371
+ x: "zsdc",
1372
+ y: "tghu",
1373
+ z: "asx"
1374
+ };
1375
+ var TypingSimulator = class _TypingSimulator {
1376
+ params;
1377
+ rng;
1378
+ constructor(params, rng = Math.random) {
1379
+ this.params = { ...DEFAULT_TYPING_PARAMS, ...params };
1380
+ this.rng = rng;
1381
+ }
1382
+ /**
1383
+ * Строит симулятор из пер-сайт конфигурации
1384
+ * (`humanization.sites.<host>.typing`); отсутствующие поля — дефолты.
1385
+ */
1386
+ static fromSiteConfig(site, rng) {
1387
+ return new _TypingSimulator(site?.typing, rng);
1388
+ }
1389
+ /** Возвращает копию действующих параметров. */
1390
+ getParams() {
1391
+ return { ...this.params };
1392
+ }
1393
+ /** Случайная задержка между клавишами в [minDelayMs, maxDelayMs]. */
1394
+ sampleDelay() {
1395
+ const { minDelayMs, maxDelayMs } = this.params;
1396
+ return Math.round(minDelayMs + this.rng() * (maxDelayMs - minDelayMs));
1397
+ }
1398
+ /** Соседняя клавиша для опечатки (null, если символ вне QWERTY a–z). */
1399
+ typoFor(char) {
1400
+ const lower = char.toLowerCase();
1401
+ const neighbors = QWERTY_NEIGHBORS[lower];
1402
+ if (!neighbors) return null;
1403
+ const index = Math.floor(this.rng() * neighbors.length);
1404
+ const neighbor = neighbors[index] ?? neighbors[0];
1405
+ return char === lower ? neighbor : neighbor.toUpperCase();
1406
+ }
1407
+ /**
1408
+ * План ввода текста: посимвольно с задержками, редкими опечатками
1409
+ * (opечатка → Backspace → корректный символ) и удлинёнными паузами
1410
+ * после знаков препинания.
1411
+ */
1412
+ plan(text) {
1413
+ const keystrokes = [];
1414
+ const punctuation = /* @__PURE__ */ new Set([".", "!", "?", ",", ";", ":"]);
1415
+ for (let i = 0; i < text.length; i++) {
1416
+ const char = text[i];
1417
+ let delay = this.sampleDelay();
1418
+ const prev = i > 0 ? text[i - 1] : "";
1419
+ if (punctuation.has(prev)) {
1420
+ delay += Math.round(100 + this.rng() * 200);
1421
+ }
1422
+ if (this.rng() < this.params.typoRate) {
1423
+ const typoChar = this.typoFor(char);
1424
+ if (typoChar) {
1425
+ keystrokes.push({ kind: "typo", char: typoChar, delayMs: delay });
1426
+ keystrokes.push({ kind: "backspace", delayMs: this.sampleDelay() });
1427
+ keystrokes.push({ kind: "char", char, delayMs: this.sampleDelay() });
1428
+ continue;
1429
+ }
1430
+ }
1431
+ keystrokes.push({ kind: "char", char, delayMs: delay });
1432
+ }
1433
+ return keystrokes;
1434
+ }
1435
+ };
1436
+ async function executeTypingPlan(keyboard, waiter, keystrokes) {
1437
+ for (const k of keystrokes) {
1438
+ if (k.delayMs > 0) {
1439
+ await waiter.waitForTimeout(k.delayMs);
1440
+ }
1441
+ if (k.kind === "backspace") {
1442
+ await keyboard.press("Backspace");
1443
+ } else {
1444
+ await keyboard.type(k.char);
1445
+ }
1446
+ }
1447
+ }
1448
+
1449
+ // src/humanization/runtime.ts
1450
+ var cachedHumanization;
1451
+ var configLoaded = false;
1452
+ var rateLimiters = /* @__PURE__ */ new Map();
1453
+ function getHumanizationConfig() {
1454
+ if (!configLoaded) {
1455
+ try {
1456
+ cachedHumanization = loadConfig().humanization;
1457
+ } catch {
1458
+ cachedHumanization = void 0;
1459
+ }
1460
+ configLoaded = true;
1461
+ }
1462
+ return cachedHumanization;
1463
+ }
1464
+ function resolveHumanization(urlOrHostname) {
1465
+ return resolveHumanizationForHost(urlOrHostname, getHumanizationConfig());
1466
+ }
1467
+ function getRateLimiter(hostname, site) {
1468
+ const key = hostname || "<unknown>";
1469
+ let limiter = rateLimiters.get(key);
1470
+ if (!limiter) {
1471
+ limiter = RateLimiter.fromSiteConfig(site);
1472
+ rateLimiters.set(key, limiter);
1473
+ }
1474
+ return limiter;
1475
+ }
1476
+ function tryAcquireAction(hostname, site) {
1477
+ return getRateLimiter(hostname, site).tryAcquire();
1478
+ }
1479
+ function createTimingEngine(site) {
1480
+ return site ? TimingEngine.fromSiteConfig(site) : new TimingEngine();
1481
+ }
1482
+ function createTypingSimulator(site) {
1483
+ return site ? TypingSimulator.fromSiteConfig(site) : new TypingSimulator();
1484
+ }
1485
+
1486
+ // src/humanization/scrollRandomizer.ts
1487
+ var DEFAULT_SCROLL_PARAMS = {
1488
+ minStepPx: 50,
1489
+ maxStepPx: 300,
1490
+ minPauseMs: 150,
1491
+ maxPauseMs: 600,
1492
+ backProbability: 0.15,
1493
+ backMinPx: 40,
1494
+ backMaxPx: 100
1495
+ };
1496
+ function randomInRange(min, max, rng) {
1497
+ return Math.round(min + rng() * (max - min));
1498
+ }
1499
+ function normalizeZero(value) {
1500
+ return value === 0 ? 0 : value;
1501
+ }
1502
+ function planScroll(targetDx, targetDy, params = {}, rng = Math.random) {
1503
+ const p = { ...DEFAULT_SCROLL_PARAMS, ...params };
1504
+ const total = Math.hypot(targetDx, targetDy);
1505
+ if (total < 1) {
1506
+ return { steps: [], targetDx, targetDy, hasBackStep: false };
1507
+ }
1508
+ const unitX = targetDx / total;
1509
+ const unitY = targetDy / total;
1510
+ const steps = [];
1511
+ let covered = 0;
1512
+ let hasBackStep = false;
1513
+ while (covered < total) {
1514
+ const remaining = total - covered;
1515
+ const canBack = !hasBackStep && total >= 200 && covered > 0;
1516
+ if (canBack && rng() < p.backProbability) {
1517
+ hasBackStep = true;
1518
+ const backSize = randomInRange(p.backMinPx, p.backMaxPx, rng);
1519
+ steps.push({
1520
+ dx: normalizeZero(-unitX * backSize),
1521
+ dy: normalizeZero(-unitY * backSize),
1522
+ pauseMs: randomInRange(p.minPauseMs, p.maxPauseMs, rng),
1523
+ isBack: true
1524
+ });
1525
+ covered -= backSize;
1526
+ continue;
1527
+ }
1528
+ const stepSize = Math.min(remaining, randomInRange(p.minStepPx, p.maxStepPx, rng));
1529
+ steps.push({
1530
+ dx: normalizeZero(unitX * stepSize),
1531
+ dy: normalizeZero(unitY * stepSize),
1532
+ // Последний шаг — короткая пауза стабилизации
1533
+ pauseMs: remaining - stepSize <= 0 ? 100 : randomInRange(p.minPauseMs, p.maxPauseMs, rng)
1534
+ });
1535
+ covered += stepSize;
1536
+ }
1537
+ return { steps, targetDx, targetDy, hasBackStep };
1538
+ }
1539
+ async function executeScrollPlan(mouse, waiter, plan, pointerPosition) {
1540
+ if (plan.steps.length === 0) return;
1541
+ await mouse.move(pointerPosition.x, pointerPosition.y);
1542
+ for (const step of plan.steps) {
1543
+ await mouse.wheel(step.dx, step.dy);
1544
+ if (step.pauseMs > 0) {
1545
+ await waiter.waitForTimeout(step.pauseMs);
1546
+ }
1547
+ }
1548
+ }
1549
+
1550
+ // src/humanization/mouseSimulator.ts
1551
+ function cubicBezierPoint(t, p0, p1, p2, p3) {
1552
+ const mt = 1 - t;
1553
+ const a = mt * mt * mt;
1554
+ const b = 3 * mt * mt * t;
1555
+ const c = 3 * mt * t * t;
1556
+ const d = t * t * t;
1557
+ return {
1558
+ x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
1559
+ y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
1560
+ };
1561
+ }
1562
+ function generateMouseTrajectory(from, to, rng = Math.random) {
1563
+ const dx = to.x - from.x;
1564
+ const dy = to.y - from.y;
1565
+ const dist = Math.hypot(dx, dy);
1566
+ if (dist < 1) return [{ ...to }];
1567
+ const perpX = -dy / dist;
1568
+ const perpY = dx / dist;
1569
+ const jitter1 = (rng() - 0.5) * dist * 0.4;
1570
+ const jitter2 = (rng() - 0.5) * dist * 0.4;
1571
+ const c1 = { x: from.x + dx * 0.25 + perpX * jitter1, y: from.y + dy * 0.25 + perpY * jitter1 };
1572
+ const c2 = { x: from.x + dx * 0.75 + perpX * jitter2, y: from.y + dy * 0.75 + perpY * jitter2 };
1573
+ const steps = Math.max(10, Math.min(30, Math.round(dist / 25)));
1574
+ const points = [];
1575
+ for (let i = 1; i <= steps; i++) {
1576
+ points.push(cubicBezierPoint(i / steps, from, c1, c2, to));
1577
+ }
1578
+ const overshoot = dist * (0.05 + rng() * 0.1);
1579
+ const dirX = dx / dist;
1580
+ const dirY = dy / dist;
1581
+ points.push({ x: to.x + dirX * overshoot, y: to.y + dirY * overshoot });
1582
+ points.push({ ...to });
1583
+ return points;
1584
+ }
1585
+ function pickPointInRect(rect, rng = Math.random, insetRatio = 0.15) {
1586
+ const insetX = rect.width * insetRatio;
1587
+ const insetY = rect.height * insetRatio;
1588
+ const innerWidth = Math.max(rect.width - 2 * insetX, 0);
1589
+ const innerHeight = Math.max(rect.height - 2 * insetY, 0);
1590
+ return {
1591
+ x: rect.x + insetX + rng() * innerWidth,
1592
+ y: rect.y + insetY + rng() * innerHeight
1593
+ };
1594
+ }
1595
+ async function performHumanClick(mouse, from, target, options = {}) {
1596
+ const rng = options.rng ?? Math.random;
1597
+ const [pauseMin, pauseMax] = options.preClickPauseMs ?? [80, 330];
1598
+ const trajectory = generateMouseTrajectory(from, target, rng);
1599
+ for (let i = 0; i < trajectory.length; i++) {
1600
+ const point = trajectory[i];
1601
+ await mouse.move(point.x, point.y);
1602
+ if (i % 4 === 3 && options.waiter) {
1603
+ await options.waiter.waitForTimeout(10 + Math.round(rng() * 20));
1604
+ }
1605
+ }
1606
+ if (options.waiter) {
1607
+ await options.waiter.waitForTimeout(pauseMin + Math.round(rng() * (pauseMax - pauseMin)));
1608
+ }
1609
+ await mouse.click(target.x, target.y);
1610
+ }
1611
+
3640
1612
  // src/tools/executeAction.ts
3641
1613
  var VALID_ACTIONS = [
3642
1614
  "click",
@@ -3807,6 +1779,17 @@ async function handleExecuteAction(args, browser, session, sessionId) {
3807
1779
  error: "Playwright is not installed. Install it with: npm install playwright"
3808
1780
  };
3809
1781
  }
1782
+ const humanization = resolveHumanization(session.getSnapshot().canvas.url || "");
1783
+ const humanizationHost = extractHostname(session.getSnapshot().canvas.url || "");
1784
+ const rateGate = () => {
1785
+ if (!humanization.enabled) return null;
1786
+ const decision = tryAcquireAction(humanizationHost, humanization.site);
1787
+ if (decision.allowed) return null;
1788
+ return {
1789
+ status: "error",
1790
+ error: `Humanization rate limit exceeded for host ${humanizationHost}: retry after ${Math.ceil(decision.retryAfterMs / 1e3)}s`
1791
+ };
1792
+ };
3810
1793
  const snapshot = session.getSnapshot();
3811
1794
  const snapshotUrl = snapshot.canvas.url;
3812
1795
  const urlBeforeAction = await browser.evaluate(() => window.location.href, sessionId);
@@ -3934,6 +1917,37 @@ async function handleExecuteAction(args, browser, session, sessionId) {
3934
1917
  }
3935
1918
  switch (args.action) {
3936
1919
  case "click": {
1920
+ if (humanization.enabled && !targetFrame) {
1921
+ const blocked = rateGate();
1922
+ if (blocked) return blocked;
1923
+ const humanClickCount = await target.locator(selector).count();
1924
+ if (humanClickCount === 0) {
1925
+ return {
1926
+ status: "error",
1927
+ error: `Element not found for click: ${args.target_id} (selector: ${selector})`
1928
+ };
1929
+ }
1930
+ const clickBb = await target.evaluate((sel) => {
1931
+ const el = document.querySelector(sel);
1932
+ if (!el) return null;
1933
+ const r = el.getBoundingClientRect();
1934
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
1935
+ }, selector);
1936
+ if (!clickBb || clickBb.width <= 0 || clickBb.height <= 0) {
1937
+ return {
1938
+ status: "error",
1939
+ error: `Element has no bounding box for humanized click: ${args.target_id}`
1940
+ };
1941
+ }
1942
+ const clickViewport = session.getSnapshot().canvas?.viewport;
1943
+ const clickStart = {
1944
+ x: (clickViewport?.width ?? 1024) * (0.3 + Math.random() * 0.4),
1945
+ y: (clickViewport?.height ?? 768) * (0.3 + Math.random() * 0.4)
1946
+ };
1947
+ await performHumanClick(page.mouse, clickStart, pickPointInRect(clickBb), { waiter: page });
1948
+ await page.waitForTimeout(100);
1949
+ break;
1950
+ }
3937
1951
  try {
3938
1952
  const clickElementCount = await target.locator(selector).count();
3939
1953
  if (clickElementCount === 0) {
@@ -3995,6 +2009,28 @@ async function handleExecuteAction(args, browser, session, sessionId) {
3995
2009
  error: "value is required for type action"
3996
2010
  };
3997
2011
  }
2012
+ if (humanization.enabled && !targetFrame) {
2013
+ const blockedType = rateGate();
2014
+ if (blockedType) return blockedType;
2015
+ const typeElementCount = await target.locator(selector).count();
2016
+ if (typeElementCount === 0) {
2017
+ return {
2018
+ status: "error",
2019
+ error: `Element not found for fill: ${args.target_id} (selector: ${selector})`
2020
+ };
2021
+ }
2022
+ await target.evaluate((sel) => {
2023
+ const el = document.querySelector(sel);
2024
+ if (el) {
2025
+ el.focus();
2026
+ el.value = "";
2027
+ el.dispatchEvent(new Event("input", { bubbles: true }));
2028
+ }
2029
+ }, selector);
2030
+ const typingSimulator = createTypingSimulator(humanization.site);
2031
+ await executeTypingPlan(page.keyboard, page, typingSimulator.plan(args.value));
2032
+ break;
2033
+ }
3998
2034
  const fillElementCount = await target.locator(selector).count();
3999
2035
  if (fillElementCount === 0) {
4000
2036
  return {
@@ -4012,10 +2048,22 @@ async function handleExecuteAction(args, browser, session, sessionId) {
4012
2048
  const scrollAmount = scrollParts[1] !== void 0 ? Number(scrollParts[1]) : DEFAULT_SCROLL_AMOUNT;
4013
2049
  const dx = scrollDir === "left" ? -scrollAmount : scrollDir === "right" ? scrollAmount : 0;
4014
2050
  const dy = scrollDir === "up" ? -scrollAmount : scrollDir === "down" ? scrollAmount : 0;
4015
- await browser.evaluate(({ dx: dx2, dy: dy2 }) => {
4016
- window.scrollBy(dx2, dy2);
4017
- }, sessionId, { dx, dy });
4018
- await page.waitForTimeout(50);
2051
+ if (humanization.enabled) {
2052
+ const blockedScroll = rateGate();
2053
+ if (blockedScroll) return blockedScroll;
2054
+ const scrollViewport = session.getSnapshot().canvas?.viewport;
2055
+ const scrollPointer = {
2056
+ x: (scrollViewport?.width ?? 1024) / 2,
2057
+ y: (scrollViewport?.height ?? 768) / 2
2058
+ };
2059
+ const scrollPlan = planScroll(dx, dy);
2060
+ await executeScrollPlan(page.mouse, page, scrollPlan, scrollPointer);
2061
+ } else {
2062
+ await browser.evaluate(({ dx: dx2, dy: dy2 }) => {
2063
+ window.scrollBy(dx2, dy2);
2064
+ }, sessionId, { dx, dy });
2065
+ await page.waitForTimeout(50);
2066
+ }
4019
2067
  const prevScroll = session.getScrollContext();
4020
2068
  let newScroll = null;
4021
2069
  try {
@@ -4075,6 +2123,35 @@ async function handleExecuteAction(args, browser, session, sessionId) {
4075
2123
  }
4076
2124
  break;
4077
2125
  case "hover":
2126
+ if (humanization.enabled && !targetFrame) {
2127
+ const blockedHover = rateGate();
2128
+ if (blockedHover) return blockedHover;
2129
+ const hoverCount = await target.locator(selector).count();
2130
+ if (hoverCount === 0) {
2131
+ return {
2132
+ status: "error",
2133
+ error: `Element not found for hover: ${args.target_id} (selector: ${selector})`
2134
+ };
2135
+ }
2136
+ const hoverBb = await target.evaluate((sel) => {
2137
+ const el = document.querySelector(sel);
2138
+ if (!el) return null;
2139
+ const r = el.getBoundingClientRect();
2140
+ return { x: r.x, y: r.y, width: r.width, height: r.height };
2141
+ }, selector);
2142
+ if (hoverBb) {
2143
+ const hoverViewport = session.getSnapshot().canvas?.viewport;
2144
+ const hoverStart = {
2145
+ x: (hoverViewport?.width ?? 1024) * (0.3 + Math.random() * 0.4),
2146
+ y: (hoverViewport?.height ?? 768) * (0.3 + Math.random() * 0.4)
2147
+ };
2148
+ const hoverTrajectory = generateMouseTrajectory(hoverStart, pickPointInRect(hoverBb));
2149
+ for (const hoverPoint of hoverTrajectory) {
2150
+ await page.mouse.move(hoverPoint.x, hoverPoint.y);
2151
+ }
2152
+ }
2153
+ break;
2154
+ }
4078
2155
  if (targetFrame) {
4079
2156
  await browser.evaluateInFrame(targetFrame, (sel) => {
4080
2157
  const el = document.querySelector(sel);
@@ -4126,6 +2203,12 @@ async function handleExecuteAction(args, browser, session, sessionId) {
4126
2203
  error: 'value is required for press action (key name, e.g. "Enter", "Tab", "Escape")'
4127
2204
  };
4128
2205
  }
2206
+ if (humanization.enabled) {
2207
+ const blockedPress = rateGate();
2208
+ if (blockedPress) return blockedPress;
2209
+ const pressTiming = createTimingEngine(humanization.site);
2210
+ await page.waitForTimeout(pressTiming.sampleDelayMs());
2211
+ }
4129
2212
  await page.keyboard.press(args.value, { delay: 0 });
4130
2213
  await page.waitForTimeout(50);
4131
2214
  break;
@@ -4802,16 +2885,31 @@ var NOISY_SELECTORS = [
4802
2885
  ".advertisement",
4803
2886
  '[aria-hidden="true"]'
4804
2887
  ];
2888
+ var DEFAULT_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
2889
+ var DEFAULT_NAVIGATION_HEADERS = {
2890
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
2891
+ "Accept-Language": "en-US,en;q=0.9",
2892
+ "sec-fetch-dest": "document",
2893
+ "sec-fetch-mode": "navigate",
2894
+ "sec-fetch-site": "none",
2895
+ "sec-fetch-user": "?1",
2896
+ "Upgrade-Insecure-Requests": "1"
2897
+ };
2898
+ function buildRequestHeaders(userAgent = DEFAULT_USER_AGENT, overrides) {
2899
+ return {
2900
+ ...DEFAULT_NAVIGATION_HEADERS,
2901
+ "User-Agent": userAgent,
2902
+ ...overrides
2903
+ };
2904
+ }
4805
2905
  async function extractViaHttp(url, options = {}) {
4806
- const { readable = false, userAgent = "VSL-MCP-Server/1.0 (compatible; AI Agent)", timeout = 1e4 } = options;
2906
+ const { readable = false, userAgent = DEFAULT_USER_AGENT, timeout = 1e4 } = options;
4807
2907
  const controller = new AbortController();
4808
2908
  const timeoutId = setTimeout(() => controller.abort(), timeout);
4809
2909
  let response;
4810
2910
  try {
4811
2911
  response = await fetch(url, {
4812
- headers: {
4813
- "User-Agent": userAgent
4814
- },
2912
+ headers: buildRequestHeaders(userAgent, options.headers),
4815
2913
  signal: controller.signal
4816
2914
  });
4817
2915
  } catch (error) {
@@ -5460,11 +3558,32 @@ async function handleClickCoordinates(args, browser, session, sessionId) {
5460
3558
  width: snapshotObj.s[0],
5461
3559
  height: snapshotObj.s[1]
5462
3560
  };
3561
+ const humanizationUrl = snapshotDoc.canvas?.url ?? "";
3562
+ const humanization = resolveHumanization(humanizationUrl);
3563
+ const humanizationHost = extractHostname(humanizationUrl);
5463
3564
  let actionsCompleted = 0;
3565
+ let lastClickPoint = null;
5464
3566
  for (const click of args.clicks) {
5465
3567
  const absoluteX = elementRect.x + click.x;
5466
3568
  const absoluteY = elementRect.y + click.y;
5467
- await page.mouse.click(absoluteX, absoluteY);
3569
+ if (humanization.enabled) {
3570
+ const rateDecision = tryAcquireAction(humanizationHost, humanization.site);
3571
+ if (!rateDecision.allowed) {
3572
+ return {
3573
+ status: "error",
3574
+ error: `Humanization rate limit exceeded for host ${humanizationHost}: retry after ${Math.ceil(rateDecision.retryAfterMs / 1e3)}s`
3575
+ };
3576
+ }
3577
+ const clickViewport = snapshotDoc.canvas?.viewport;
3578
+ const startPoint = lastClickPoint ?? {
3579
+ x: (clickViewport?.width ?? 1024) * (0.3 + Math.random() * 0.4),
3580
+ y: (clickViewport?.height ?? 768) * (0.3 + Math.random() * 0.4)
3581
+ };
3582
+ await performHumanClick(page.mouse, startPoint, { x: absoluteX, y: absoluteY }, { waiter: page });
3583
+ lastClickPoint = { x: absoluteX, y: absoluteY };
3584
+ } else {
3585
+ await page.mouse.click(absoluteX, absoluteY);
3586
+ }
5468
3587
  actionsCompleted++;
5469
3588
  if (click.delay_after_ms && click.delay_after_ms > 0) {
5470
3589
  await page.waitForTimeout(click.delay_after_ms);
@@ -5686,8 +3805,8 @@ function registerTools(server, config, sessionManager) {
5686
3805
  tools: VSL_TOOLS
5687
3806
  };
5688
3807
  });
5689
- server.setRequestHandler(CallToolRequestSchema, async (request2) => {
5690
- const { name, arguments: args, _meta } = request2.params;
3808
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
3809
+ const { name, arguments: args, _meta } = request.params;
5691
3810
  const sessionId = _meta?.sessionId ?? sessionManager.getDefaultSessionId();
5692
3811
  const { session } = sessionManager.getSession(sessionId);
5693
3812
  const browser = sessionManager.getBrowserManager();
@@ -5783,9 +3902,9 @@ function registerResources(server, _config, sessionManager) {
5783
3902
  resources: VSL_RESOURCES
5784
3903
  };
5785
3904
  });
5786
- server.setRequestHandler(ReadResourceRequestSchema, async (request2) => {
5787
- const { uri } = request2.params;
5788
- const sessionId = request2.params._meta?.sessionId ?? sessionManager.getDefaultSessionId();
3905
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
3906
+ const { uri } = request.params;
3907
+ const sessionId = request.params._meta?.sessionId ?? sessionManager.getDefaultSessionId();
5789
3908
  const { session } = sessionManager.getSession(sessionId);
5790
3909
  ensureSubscribed(sessionId, session);
5791
3910
  switch (uri) {
@@ -5874,6 +3993,144 @@ function registerResources(server, _config, sessionManager) {
5874
3993
  // src/browser/manager.ts
5875
3994
  import path from "path";
5876
3995
  import os from "os";
3996
+
3997
+ // src/browser/challengeResolver.ts
3998
+ var ChallengeResolutionError = class extends Error {
3999
+ constructor(url, timeoutMs) {
4000
+ super(
4001
+ `Anti-bot challenge was not resolved within ${timeoutMs}ms for ${url}. The persistent browser profile stores cf_clearance cookies \u2014 retrying later may pass automatically. Alternatives: connect to a real browser via CDP (browser.cdpPort) or configure a proxy (browser.proxy).`
4002
+ );
4003
+ this.name = "ChallengeResolutionError";
4004
+ }
4005
+ };
4006
+ var TITLE_MARKERS = [
4007
+ /just a moment/i,
4008
+ /attention required/i,
4009
+ /checking your browser/i,
4010
+ /verify you are human/i
4011
+ ];
4012
+ var PRIMARY_HTML_MARKERS = ["cf-chl", "challenges.cloudflare.com"];
4013
+ var PRIMARY_URL_MARKERS = ["/cdn-cgi/challenge-platform", "challenges.cloudflare.com"];
4014
+ function detectChallengeMarkers(input) {
4015
+ const title = input.title ?? "";
4016
+ const html = (input.html ?? "").toLowerCase();
4017
+ const url = input.url ?? "";
4018
+ const titleHit = TITLE_MARKERS.some((m) => m.test(title));
4019
+ const htmlHit = PRIMARY_HTML_MARKERS.some((m) => html.includes(m));
4020
+ const urlHit = PRIMARY_URL_MARKERS.some((m) => url.includes(m));
4021
+ if (!titleHit && !htmlHit && !urlHit) {
4022
+ return { isChallenge: false, kind: null };
4023
+ }
4024
+ const kind = html.includes("challenges.cloudflare.com") || html.includes("turnstile") ? "turnstile" : "cloudflare";
4025
+ return { isChallenge: true, kind };
4026
+ }
4027
+ function pickCheckboxPoint(rect, rng = Math.random) {
4028
+ const offsetX = Math.min(rect.width * 0.2, 24 + rng() * 8);
4029
+ const offsetY = rect.height / 2 + (rng() - 0.5) * Math.min(6, rect.height * 0.2);
4030
+ return { x: rect.x + offsetX, y: rect.y + offsetY };
4031
+ }
4032
+ async function inspectPage(page) {
4033
+ const probe = await page.evaluate(() => {
4034
+ let turnstileRect = null;
4035
+ const iframes = Array.from(document.querySelectorAll("iframe"));
4036
+ for (const frame of iframes) {
4037
+ const src = frame.getAttribute("src") ?? "";
4038
+ if (src.includes("challenges.cloudflare.com") || src.includes("challenge-platform") || src.includes("turnstile")) {
4039
+ const rect = frame.getBoundingClientRect();
4040
+ if (rect.width > 0 && rect.height > 0) {
4041
+ turnstileRect = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
4042
+ break;
4043
+ }
4044
+ }
4045
+ }
4046
+ return {
4047
+ title: document.title,
4048
+ htmlSnippet: document.documentElement.innerHTML.slice(0, 3e4),
4049
+ url: window.location.href,
4050
+ turnstileRect,
4051
+ viewportWidth: window.innerWidth,
4052
+ viewportHeight: window.innerHeight
4053
+ };
4054
+ });
4055
+ const detection = detectChallengeMarkers({
4056
+ title: probe.title,
4057
+ html: probe.htmlSnippet,
4058
+ url: probe.url
4059
+ });
4060
+ return {
4061
+ isChallenge: detection.isChallenge,
4062
+ kind: detection.kind,
4063
+ turnstileRect: probe.turnstileRect,
4064
+ viewportWidth: probe.viewportWidth,
4065
+ viewportHeight: probe.viewportHeight
4066
+ };
4067
+ }
4068
+ async function humanLikeClick(page, inspection, rng) {
4069
+ if (!inspection.turnstileRect) return;
4070
+ const target = pickCheckboxPoint(inspection.turnstileRect, rng);
4071
+ const start = {
4072
+ x: inspection.viewportWidth * (0.3 + rng() * 0.4),
4073
+ y: inspection.viewportHeight * (0.3 + rng() * 0.4)
4074
+ };
4075
+ await performHumanClick(page.mouse, start, target, { rng, waiter: page });
4076
+ }
4077
+ function safeOrigin(url) {
4078
+ try {
4079
+ return new URL(url).origin;
4080
+ } catch {
4081
+ return null;
4082
+ }
4083
+ }
4084
+ async function resolveChallenge(page, targetUrl, options = {}) {
4085
+ const timeoutMs = options.timeoutMs ?? 2e4;
4086
+ const pollIntervalMs = options.pollIntervalMs ?? 2e3;
4087
+ const enableClick = options.enableClick !== false;
4088
+ const warmUp = options.warmUp !== false;
4089
+ const rng = options.rng ?? Math.random;
4090
+ let inspection = await inspectPage(page);
4091
+ if (!inspection.isChallenge) {
4092
+ return { status: "not_detected", attempts: 0 };
4093
+ }
4094
+ console.warn(
4095
+ `[VSL MCP Server] Anti-bot challenge detected (${inspection.kind ?? "generic"}) at ${targetUrl} \u2014 resolving (timeout ${timeoutMs}ms)`
4096
+ );
4097
+ const deadline = Date.now() + timeoutMs;
4098
+ let attempts = 0;
4099
+ let warmedUp = false;
4100
+ let clicked = false;
4101
+ while (Date.now() < deadline) {
4102
+ attempts++;
4103
+ if (warmUp && !warmedUp) {
4104
+ warmedUp = true;
4105
+ const origin = safeOrigin(targetUrl);
4106
+ if (origin && origin !== targetUrl) {
4107
+ try {
4108
+ await page.goto(origin, { timeout: timeoutMs, waitUntil: "domcontentloaded" });
4109
+ await page.waitForTimeout(Math.round(pollIntervalMs / 2));
4110
+ await page.goto(targetUrl, { timeout: timeoutMs, waitUntil: "domcontentloaded" });
4111
+ } catch {
4112
+ }
4113
+ }
4114
+ }
4115
+ inspection = await inspectPage(page);
4116
+ if (!inspection.isChallenge) {
4117
+ return { status: clicked ? "clicked" : "auto", attempts };
4118
+ }
4119
+ if (enableClick && !clicked && inspection.turnstileRect) {
4120
+ await humanLikeClick(page, inspection, rng);
4121
+ clicked = true;
4122
+ }
4123
+ await page.waitForTimeout(pollIntervalMs);
4124
+ }
4125
+ inspection = await inspectPage(page);
4126
+ attempts++;
4127
+ if (!inspection.isChallenge) {
4128
+ return { status: clicked ? "clicked" : "auto", attempts };
4129
+ }
4130
+ throw new ChallengeResolutionError(targetUrl, timeoutMs);
4131
+ }
4132
+
4133
+ // src/browser/manager.ts
5877
4134
  var BrowserManager = class {
5878
4135
  browser = null;
5879
4136
  context = null;
@@ -5887,6 +4144,15 @@ var BrowserManager = class {
5887
4144
  constructor(config) {
5888
4145
  this.config = config;
5889
4146
  }
4147
+ /**
4148
+ * Шов для динамического импорта модулей (Фаза 5).
4149
+ * Юнит-тесты переопределяют его через jest.spyOn, чтобы управлять
4150
+ * результатом импорта без реальных импортов и моков модулей.
4151
+ */
4152
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4153
+ async dynamicImport(specifier) {
4154
+ return import(specifier);
4155
+ }
5890
4156
  /**
5891
4157
  * Загружает Playwright (динамический импорт).
5892
4158
  * Если Playwright не установлен, возвращает null.
@@ -5894,16 +4160,17 @@ var BrowserManager = class {
5894
4160
  async loadPlaywright() {
5895
4161
  if (this.playwright) return this.playwright;
5896
4162
  try {
5897
- const pwExtra = await Promise.resolve().then(() => (init_index_esm(), index_esm_exports));
5898
- const stealthModule = await Promise.resolve().then(() => __toESM(require_puppeteer_extra_plugin_stealth(), 1));
4163
+ const pwExtra = await this.dynamicImport("playwright-extra");
4164
+ const stealthModule = await this.dynamicImport("puppeteer-extra-plugin-stealth");
5899
4165
  const stealth = stealthModule.default ?? stealthModule;
5900
- const chromium2 = pwExtra.chromium;
5901
- chromium2.use(stealth());
5902
- this.playwright = { chromium: chromium2 };
4166
+ const chromium = pwExtra.chromium;
4167
+ chromium.use(stealth());
4168
+ this.playwright = { chromium };
5903
4169
  return this.playwright;
5904
4170
  } catch {
4171
+ console.warn("[VSL MCP Server] playwright-extra/stealth plugin is unavailable \u2014 falling back to plain playwright. Anti-bot protection is DEGRADED.");
5905
4172
  try {
5906
- const pw = await import("playwright");
4173
+ const pw = await this.dynamicImport("playwright");
5907
4174
  this.playwright = pw;
5908
4175
  return this.playwright;
5909
4176
  } catch {
@@ -5957,9 +4224,18 @@ var BrowserManager = class {
5957
4224
  if (this.config.downloadsPath) {
5958
4225
  persistentOptions.downloadsPath = this.config.downloadsPath;
5959
4226
  }
4227
+ if (this.config.proxy) {
4228
+ persistentOptions.proxy = {
4229
+ server: this.config.proxy.server,
4230
+ ...this.config.proxy.username ? { username: this.config.proxy.username } : {},
4231
+ ...this.config.proxy.password ? { password: this.config.proxy.password } : {}
4232
+ };
4233
+ }
4234
+ const launchArgs = ["--disable-blink-features=AutomationControlled"];
5960
4235
  if (this.config.cdpPort) {
5961
- persistentOptions.args = [`--remote-debugging-port=${this.config.cdpPort}`];
4236
+ launchArgs.push(`--remote-debugging-port=${this.config.cdpPort}`);
5962
4237
  }
4238
+ persistentOptions.args = launchArgs;
5963
4239
  this.context = await pw.chromium.launchPersistentContext(
5964
4240
  userDataDir,
5965
4241
  persistentOptions
@@ -6000,6 +4276,12 @@ var BrowserManager = class {
6000
4276
  timeout: this.config.navigationTimeout,
6001
4277
  waitUntil: "domcontentloaded"
6002
4278
  });
4279
+ const resolution = await resolveChallenge(page, url);
4280
+ if (resolution.status !== "not_detected") {
4281
+ console.log(
4282
+ `[VSL MCP Server] Anti-bot challenge resolved (status: ${resolution.status}, attempts: ${resolution.attempts})`
4283
+ );
4284
+ }
6003
4285
  }
6004
4286
  /**
6005
4287
  * Получает HTML-контент текущей страницы.
@@ -6586,7 +4868,7 @@ var SessionManager = class {
6586
4868
  };
6587
4869
 
6588
4870
  // src/version.ts
6589
- var VSL_MCP_SERVER_VERSION = "1.3.9";
4871
+ var VSL_MCP_SERVER_VERSION = "1.4.1";
6590
4872
 
6591
4873
  // src/index.ts
6592
4874
  async function main() {
@@ -6635,52 +4917,4 @@ main().catch((error) => {
6635
4917
  console.error("[VSL MCP Server] Fatal error:", error);
6636
4918
  process.exit(1);
6637
4919
  });
6638
- /*! Bundled license information:
6639
-
6640
- playwright-extra/dist/index.esm.js:
6641
- (*!
6642
- * playwright-extra v4.3.5 by berstend
6643
- * https://github.com/berstend/puppeteer-extra/tree/master/packages/playwright-extra#readme
6644
- * @license MIT
6645
- *)
6646
-
6647
- for-in/index.js:
6648
- (*!
6649
- * for-in <https://github.com/jonschlinkert/for-in>
6650
- *
6651
- * Copyright (c) 2014-2017, Jon Schlinkert.
6652
- * Released under the MIT License.
6653
- *)
6654
-
6655
- for-own/index.js:
6656
- (*!
6657
- * for-own <https://github.com/jonschlinkert/for-own>
6658
- *
6659
- * Copyright (c) 2014-2017, Jon Schlinkert.
6660
- * Released under the MIT License.
6661
- *)
6662
-
6663
- is-buffer/index.js:
6664
- (*!
6665
- * Determine if an object is a Buffer
6666
- *
6667
- * @author Feross Aboukhadijeh <https://feross.org>
6668
- * @license MIT
6669
- *)
6670
-
6671
- merge-deep/index.js:
6672
- (*!
6673
- * merge-deep <https://github.com/jonschlinkert/merge-deep>
6674
- *
6675
- * Copyright (c) 2014-2015, Jon Schlinkert.
6676
- * Licensed under the MIT License.
6677
- *)
6678
-
6679
- puppeteer-extra-plugin/dist/index.esm.js:
6680
- (*!
6681
- * puppeteer-extra-plugin v3.2.2 by berstend
6682
- * https://github.com/berstend/puppeteer-extra/tree/master/packages/puppeteer-extra-plugin
6683
- * @license MIT
6684
- *)
6685
- */
6686
4920
  //# sourceMappingURL=index.js.map