@midscene/web 0.7.2 → 0.7.3-beta-20241104100519.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1627 @@
1
+ (function(global, factory) {
2
+ if (typeof module === "object" && typeof module.exports === "object") factory(exports, require("assert"), require("fs"), require("path"), require("@midscene/shared/constants"), require("@midscene/shared/fs"), require("@midscene/shared/img"), require("@midscene/shared/utils"), require("@midscene/core"), require("@midscene/core/utils"), require("@midscene/shared/browser/img"));
3
+ else if (typeof define === "function" && define.amd) define([
4
+ "exports",
5
+ "assert",
6
+ "fs",
7
+ "path",
8
+ "@midscene/shared/constants",
9
+ "@midscene/shared/fs",
10
+ "@midscene/shared/img",
11
+ "@midscene/shared/utils",
12
+ "@midscene/core",
13
+ "@midscene/core/utils",
14
+ "@midscene/shared/browser/img"
15
+ ], factory);
16
+ else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.chromeExtension = {}, global.assert, global.fs, global.path, global.constants, global.fs, global.img, global.utils, global.core, global.utils, global.img);
17
+ })(this, function(exports, _assert, _fs, _path, _constants, _fs1, _img, _utils, _core, _utils1, _img1) {
18
+ "use strict";
19
+ Object.defineProperty(exports, "__esModule", {
20
+ value: true
21
+ });
22
+ function _export(target, all) {
23
+ for(var name in all)Object.defineProperty(target, name, {
24
+ enumerable: true,
25
+ get: all[name]
26
+ });
27
+ }
28
+ _export(exports, {
29
+ ChromeExtensionProxyPage: function() {
30
+ return ChromeExtensionProxyPage;
31
+ },
32
+ ChromeExtensionProxyPageAgent: function() {
33
+ return ChromeExtensionProxyPageAgent;
34
+ },
35
+ ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED: function() {
36
+ return ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED;
37
+ }
38
+ });
39
+ _assert = /*#__PURE__*/ _interop_require_default(_assert);
40
+ _path = /*#__PURE__*/ _interop_require_wildcard(_path);
41
+ function _interop_require_default(obj) {
42
+ return obj && obj.__esModule ? obj : {
43
+ default: obj
44
+ };
45
+ }
46
+ function _getRequireWildcardCache(nodeInterop) {
47
+ if (typeof WeakMap !== "function") return null;
48
+ var cacheBabelInterop = new WeakMap();
49
+ var cacheNodeInterop = new WeakMap();
50
+ return (_getRequireWildcardCache = function(nodeInterop) {
51
+ return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
52
+ })(nodeInterop);
53
+ }
54
+ function _interop_require_wildcard(obj, nodeInterop) {
55
+ if (!nodeInterop && obj && obj.__esModule) {
56
+ return obj;
57
+ }
58
+ if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
59
+ return {
60
+ default: obj
61
+ };
62
+ }
63
+ var cache = _getRequireWildcardCache(nodeInterop);
64
+ if (cache && cache.has(obj)) {
65
+ return cache.get(obj);
66
+ }
67
+ var newObj = {
68
+ __proto__: null
69
+ };
70
+ var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
71
+ for(var key in obj){
72
+ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
73
+ var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
74
+ if (desc && (desc.get || desc.set)) {
75
+ Object.defineProperty(newObj, key, desc);
76
+ } else {
77
+ newObj[key] = obj[key];
78
+ }
79
+ }
80
+ }
81
+ newObj.default = obj;
82
+ if (cache) {
83
+ cache.set(obj, newObj);
84
+ }
85
+ return newObj;
86
+ }
87
+ var __create = Object.create;
88
+ var __defProp = Object.defineProperty;
89
+ var __defProps = Object.defineProperties;
90
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
91
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
92
+ var __getOwnPropNames = Object.getOwnPropertyNames;
93
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
94
+ var __getProtoOf = Object.getPrototypeOf;
95
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
96
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
97
+ var __defNormalProp = (obj, key, value)=>key in obj ? __defProp(obj, key, {
98
+ enumerable: true,
99
+ configurable: true,
100
+ writable: true,
101
+ value
102
+ }) : obj[key] = value;
103
+ var __spreadValues = (a, b)=>{
104
+ for(var prop in b || (b = {}))if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]);
105
+ if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)){
106
+ if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]);
107
+ }
108
+ return a;
109
+ };
110
+ var __spreadProps = (a, b)=>__defProps(a, __getOwnPropDescs(b));
111
+ var __commonJS = (cb, mod)=>function __require() {
112
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = {
113
+ exports: {}
114
+ }).exports, mod), mod.exports;
115
+ };
116
+ var __copyProps = (to, from, except, desc)=>{
117
+ if (from && typeof from === "object" || typeof from === "function") {
118
+ for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
119
+ get: ()=>from[key],
120
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
121
+ });
122
+ }
123
+ return to;
124
+ };
125
+ var __toESM = (mod, isNodeMode, target)=>(target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM
126
+ // file that has been converted to a CommonJS file using a Babel-
127
+ // compatible transform (i.e. "__esModule" has not been set), then set
128
+ // "default" to the CommonJS "module.exports" for node compatibility.
129
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
130
+ value: mod,
131
+ enumerable: true
132
+ }) : target, mod));
133
+ var __async = (__this, __arguments, generator)=>{
134
+ return new Promise((resolve, reject)=>{
135
+ var fulfilled = (value)=>{
136
+ try {
137
+ step(generator.next(value));
138
+ } catch (e) {
139
+ reject(e);
140
+ }
141
+ };
142
+ var rejected = (value)=>{
143
+ try {
144
+ step(generator.throw(value));
145
+ } catch (e) {
146
+ reject(e);
147
+ }
148
+ };
149
+ var step = (x)=>x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
150
+ step((generator = generator.apply(__this, __arguments)).next());
151
+ });
152
+ };
153
+ // ../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.js
154
+ var require_dayjs_min = __commonJS({
155
+ "../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.js" (exports, module1) {
156
+ "use strict";
157
+ !function(t, e) {
158
+ "object" == typeof exports && "undefined" != typeof module1 ? module1.exports = e() : "function" == typeof define && define.amd ? define(e) : (t = "undefined" != typeof globalThis ? globalThis : t || self).dayjs = e();
159
+ }(exports, function() {
160
+ "use strict";
161
+ var t = 1e3, e = 6e4, n = 36e5, r = "millisecond", i = "second", s = "minute", u = "hour", a = "day", o = "week", c = "month", f = "quarter", h = "year", d = "date", l = "Invalid Date", $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M = {
162
+ name: "en",
163
+ weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
164
+ months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
165
+ ordinal: function(t2) {
166
+ var e2 = [
167
+ "th",
168
+ "st",
169
+ "nd",
170
+ "rd"
171
+ ], n2 = t2 % 100;
172
+ return "[" + t2 + (e2[(n2 - 20) % 10] || e2[n2] || e2[0]) + "]";
173
+ }
174
+ }, m = function(t2, e2, n2) {
175
+ var r2 = String(t2);
176
+ return !r2 || r2.length >= e2 ? t2 : "" + Array(e2 + 1 - r2.length).join(n2) + t2;
177
+ }, v = {
178
+ s: m,
179
+ z: function(t2) {
180
+ var e2 = -t2.utcOffset(), n2 = Math.abs(e2), r2 = Math.floor(n2 / 60), i2 = n2 % 60;
181
+ return (e2 <= 0 ? "+" : "-") + m(r2, 2, "0") + ":" + m(i2, 2, "0");
182
+ },
183
+ m: function t2(e2, n2) {
184
+ if (e2.date() < n2.date()) return -t2(n2, e2);
185
+ var r2 = 12 * (n2.year() - e2.year()) + (n2.month() - e2.month()), i2 = e2.clone().add(r2, c), s2 = n2 - i2 < 0, u2 = e2.clone().add(r2 + (s2 ? -1 : 1), c);
186
+ return +(-(r2 + (n2 - i2) / (s2 ? i2 - u2 : u2 - i2)) || 0);
187
+ },
188
+ a: function(t2) {
189
+ return t2 < 0 ? Math.ceil(t2) || 0 : Math.floor(t2);
190
+ },
191
+ p: function(t2) {
192
+ return ({
193
+ M: c,
194
+ y: h,
195
+ w: o,
196
+ d: a,
197
+ D: d,
198
+ h: u,
199
+ m: s,
200
+ s: i,
201
+ ms: r,
202
+ Q: f
203
+ })[t2] || String(t2 || "").toLowerCase().replace(/s$/, "");
204
+ },
205
+ u: function(t2) {
206
+ return void 0 === t2;
207
+ }
208
+ }, g = "en", D = {};
209
+ D[g] = M;
210
+ var p = "$isDayjsObject", S = function(t2) {
211
+ return t2 instanceof _ || !(!t2 || !t2[p]);
212
+ }, w = function t2(e2, n2, r2) {
213
+ var i2;
214
+ if (!e2) return g;
215
+ if ("string" == typeof e2) {
216
+ var s2 = e2.toLowerCase();
217
+ D[s2] && (i2 = s2), n2 && (D[s2] = n2, i2 = s2);
218
+ var u2 = e2.split("-");
219
+ if (!i2 && u2.length > 1) return t2(u2[0]);
220
+ } else {
221
+ var a2 = e2.name;
222
+ D[a2] = e2, i2 = a2;
223
+ }
224
+ return !r2 && i2 && (g = i2), i2 || !r2 && g;
225
+ }, O = function(t2, e2) {
226
+ if (S(t2)) return t2.clone();
227
+ var n2 = "object" == typeof e2 ? e2 : {};
228
+ return n2.date = t2, n2.args = arguments, new _(n2);
229
+ }, b = v;
230
+ b.l = w, b.i = S, b.w = function(t2, e2) {
231
+ return O(t2, {
232
+ locale: e2.$L,
233
+ utc: e2.$u,
234
+ x: e2.$x,
235
+ $offset: e2.$offset
236
+ });
237
+ };
238
+ var _ = function() {
239
+ function M2(t2) {
240
+ this.$L = w(t2.locale, null, true), this.parse(t2), this.$x = this.$x || t2.x || {}, this[p] = true;
241
+ }
242
+ var m2 = M2.prototype;
243
+ return m2.parse = function(t2) {
244
+ this.$d = function(t3) {
245
+ var e2 = t3.date, n2 = t3.utc;
246
+ if (null === e2) return /* @__PURE__ */ new Date(NaN);
247
+ if (b.u(e2)) return /* @__PURE__ */ new Date();
248
+ if (e2 instanceof Date) return new Date(e2);
249
+ if ("string" == typeof e2 && !/Z$/i.test(e2)) {
250
+ var r2 = e2.match($);
251
+ if (r2) {
252
+ var i2 = r2[2] - 1 || 0, s2 = (r2[7] || "0").substring(0, 3);
253
+ return n2 ? new Date(Date.UTC(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2)) : new Date(r2[1], i2, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2);
254
+ }
255
+ }
256
+ return new Date(e2);
257
+ }(t2), this.init();
258
+ }, m2.init = function() {
259
+ var t2 = this.$d;
260
+ this.$y = t2.getFullYear(), this.$M = t2.getMonth(), this.$D = t2.getDate(), this.$W = t2.getDay(), this.$H = t2.getHours(), this.$m = t2.getMinutes(), this.$s = t2.getSeconds(), this.$ms = t2.getMilliseconds();
261
+ }, m2.$utils = function() {
262
+ return b;
263
+ }, m2.isValid = function() {
264
+ return !(this.$d.toString() === l);
265
+ }, m2.isSame = function(t2, e2) {
266
+ var n2 = O(t2);
267
+ return this.startOf(e2) <= n2 && n2 <= this.endOf(e2);
268
+ }, m2.isAfter = function(t2, e2) {
269
+ return O(t2) < this.startOf(e2);
270
+ }, m2.isBefore = function(t2, e2) {
271
+ return this.endOf(e2) < O(t2);
272
+ }, m2.$g = function(t2, e2, n2) {
273
+ return b.u(t2) ? this[e2] : this.set(n2, t2);
274
+ }, m2.unix = function() {
275
+ return Math.floor(this.valueOf() / 1e3);
276
+ }, m2.valueOf = function() {
277
+ return this.$d.getTime();
278
+ }, m2.startOf = function(t2, e2) {
279
+ var n2 = this, r2 = !!b.u(e2) || e2, f2 = b.p(t2), l2 = function(t3, e3) {
280
+ var i2 = b.w(n2.$u ? Date.UTC(n2.$y, e3, t3) : new Date(n2.$y, e3, t3), n2);
281
+ return r2 ? i2 : i2.endOf(a);
282
+ }, $2 = function(t3, e3) {
283
+ return b.w(n2.toDate()[t3].apply(n2.toDate("s"), (r2 ? [
284
+ 0,
285
+ 0,
286
+ 0,
287
+ 0
288
+ ] : [
289
+ 23,
290
+ 59,
291
+ 59,
292
+ 999
293
+ ]).slice(e3)), n2);
294
+ }, y2 = this.$W, M3 = this.$M, m3 = this.$D, v2 = "set" + (this.$u ? "UTC" : "");
295
+ switch(f2){
296
+ case h:
297
+ return r2 ? l2(1, 0) : l2(31, 11);
298
+ case c:
299
+ return r2 ? l2(1, M3) : l2(0, M3 + 1);
300
+ case o:
301
+ var g2 = this.$locale().weekStart || 0, D2 = (y2 < g2 ? y2 + 7 : y2) - g2;
302
+ return l2(r2 ? m3 - D2 : m3 + (6 - D2), M3);
303
+ case a:
304
+ case d:
305
+ return $2(v2 + "Hours", 0);
306
+ case u:
307
+ return $2(v2 + "Minutes", 1);
308
+ case s:
309
+ return $2(v2 + "Seconds", 2);
310
+ case i:
311
+ return $2(v2 + "Milliseconds", 3);
312
+ default:
313
+ return this.clone();
314
+ }
315
+ }, m2.endOf = function(t2) {
316
+ return this.startOf(t2, false);
317
+ }, m2.$set = function(t2, e2) {
318
+ var n2, o2 = b.p(t2), f2 = "set" + (this.$u ? "UTC" : ""), l2 = (n2 = {}, n2[a] = f2 + "Date", n2[d] = f2 + "Date", n2[c] = f2 + "Month", n2[h] = f2 + "FullYear", n2[u] = f2 + "Hours", n2[s] = f2 + "Minutes", n2[i] = f2 + "Seconds", n2[r] = f2 + "Milliseconds", n2)[o2], $2 = o2 === a ? this.$D + (e2 - this.$W) : e2;
319
+ if (o2 === c || o2 === h) {
320
+ var y2 = this.clone().set(d, 1);
321
+ y2.$d[l2]($2), y2.init(), this.$d = y2.set(d, Math.min(this.$D, y2.daysInMonth())).$d;
322
+ } else l2 && this.$d[l2]($2);
323
+ return this.init(), this;
324
+ }, m2.set = function(t2, e2) {
325
+ return this.clone().$set(t2, e2);
326
+ }, m2.get = function(t2) {
327
+ return this[b.p(t2)]();
328
+ }, m2.add = function(r2, f2) {
329
+ var d2, l2 = this;
330
+ r2 = Number(r2);
331
+ var $2 = b.p(f2), y2 = function(t2) {
332
+ var e2 = O(l2);
333
+ return b.w(e2.date(e2.date() + Math.round(t2 * r2)), l2);
334
+ };
335
+ if ($2 === c) return this.set(c, this.$M + r2);
336
+ if ($2 === h) return this.set(h, this.$y + r2);
337
+ if ($2 === a) return y2(1);
338
+ if ($2 === o) return y2(7);
339
+ var M3 = (d2 = {}, d2[s] = e, d2[u] = n, d2[i] = t, d2)[$2] || 1, m3 = this.$d.getTime() + r2 * M3;
340
+ return b.w(m3, this);
341
+ }, m2.subtract = function(t2, e2) {
342
+ return this.add(-1 * t2, e2);
343
+ }, m2.format = function(t2) {
344
+ var e2 = this, n2 = this.$locale();
345
+ if (!this.isValid()) return n2.invalidDate || l;
346
+ var r2 = t2 || "YYYY-MM-DDTHH:mm:ssZ", i2 = b.z(this), s2 = this.$H, u2 = this.$m, a2 = this.$M, o2 = n2.weekdays, c2 = n2.months, f2 = n2.meridiem, h2 = function(t3, n3, i3, s3) {
347
+ return t3 && (t3[n3] || t3(e2, r2)) || i3[n3].slice(0, s3);
348
+ }, d2 = function(t3) {
349
+ return b.s(s2 % 12 || 12, t3, "0");
350
+ }, $2 = f2 || function(t3, e3, n3) {
351
+ var r3 = t3 < 12 ? "AM" : "PM";
352
+ return n3 ? r3.toLowerCase() : r3;
353
+ };
354
+ return r2.replace(y, function(t3, r3) {
355
+ return r3 || function(t4) {
356
+ switch(t4){
357
+ case "YY":
358
+ return String(e2.$y).slice(-2);
359
+ case "YYYY":
360
+ return b.s(e2.$y, 4, "0");
361
+ case "M":
362
+ return a2 + 1;
363
+ case "MM":
364
+ return b.s(a2 + 1, 2, "0");
365
+ case "MMM":
366
+ return h2(n2.monthsShort, a2, c2, 3);
367
+ case "MMMM":
368
+ return h2(c2, a2);
369
+ case "D":
370
+ return e2.$D;
371
+ case "DD":
372
+ return b.s(e2.$D, 2, "0");
373
+ case "d":
374
+ return String(e2.$W);
375
+ case "dd":
376
+ return h2(n2.weekdaysMin, e2.$W, o2, 2);
377
+ case "ddd":
378
+ return h2(n2.weekdaysShort, e2.$W, o2, 3);
379
+ case "dddd":
380
+ return o2[e2.$W];
381
+ case "H":
382
+ return String(s2);
383
+ case "HH":
384
+ return b.s(s2, 2, "0");
385
+ case "h":
386
+ return d2(1);
387
+ case "hh":
388
+ return d2(2);
389
+ case "a":
390
+ return $2(s2, u2, true);
391
+ case "A":
392
+ return $2(s2, u2, false);
393
+ case "m":
394
+ return String(u2);
395
+ case "mm":
396
+ return b.s(u2, 2, "0");
397
+ case "s":
398
+ return String(e2.$s);
399
+ case "ss":
400
+ return b.s(e2.$s, 2, "0");
401
+ case "SSS":
402
+ return b.s(e2.$ms, 3, "0");
403
+ case "Z":
404
+ return i2;
405
+ }
406
+ return null;
407
+ }(t3) || i2.replace(":", "");
408
+ });
409
+ }, m2.utcOffset = function() {
410
+ return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
411
+ }, m2.diff = function(r2, d2, l2) {
412
+ var $2, y2 = this, M3 = b.p(d2), m3 = O(r2), v2 = (m3.utcOffset() - this.utcOffset()) * e, g2 = this - m3, D2 = function() {
413
+ return b.m(y2, m3);
414
+ };
415
+ switch(M3){
416
+ case h:
417
+ $2 = D2() / 12;
418
+ break;
419
+ case c:
420
+ $2 = D2();
421
+ break;
422
+ case f:
423
+ $2 = D2() / 3;
424
+ break;
425
+ case o:
426
+ $2 = (g2 - v2) / 6048e5;
427
+ break;
428
+ case a:
429
+ $2 = (g2 - v2) / 864e5;
430
+ break;
431
+ case u:
432
+ $2 = g2 / n;
433
+ break;
434
+ case s:
435
+ $2 = g2 / e;
436
+ break;
437
+ case i:
438
+ $2 = g2 / t;
439
+ break;
440
+ default:
441
+ $2 = g2;
442
+ }
443
+ return l2 ? $2 : b.a($2);
444
+ }, m2.daysInMonth = function() {
445
+ return this.endOf(c).$D;
446
+ }, m2.$locale = function() {
447
+ return D[this.$L];
448
+ }, m2.locale = function(t2, e2) {
449
+ if (!t2) return this.$L;
450
+ var n2 = this.clone(), r2 = w(t2, e2, true);
451
+ return r2 && (n2.$L = r2), n2;
452
+ }, m2.clone = function() {
453
+ return b.w(this.$d, this);
454
+ }, m2.toDate = function() {
455
+ return new Date(this.valueOf());
456
+ }, m2.toJSON = function() {
457
+ return this.isValid() ? this.toISOString() : null;
458
+ }, m2.toISOString = function() {
459
+ return this.$d.toISOString();
460
+ }, m2.toString = function() {
461
+ return this.$d.toUTCString();
462
+ }, M2;
463
+ }(), k = _.prototype;
464
+ return O.prototype = k, [
465
+ [
466
+ "$ms",
467
+ r
468
+ ],
469
+ [
470
+ "$s",
471
+ i
472
+ ],
473
+ [
474
+ "$m",
475
+ s
476
+ ],
477
+ [
478
+ "$H",
479
+ u
480
+ ],
481
+ [
482
+ "$W",
483
+ a
484
+ ],
485
+ [
486
+ "$M",
487
+ c
488
+ ],
489
+ [
490
+ "$y",
491
+ h
492
+ ],
493
+ [
494
+ "$D",
495
+ d
496
+ ]
497
+ ].forEach(function(t2) {
498
+ k[t2[1]] = function(e2) {
499
+ return this.$g(e2, t2[0], t2[1]);
500
+ };
501
+ }), O.extend = function(t2, e2) {
502
+ return t2.$i || (t2(e2, _, O), t2.$i = true), O;
503
+ }, O.locale = w, O.isDayjs = S, O.unix = function(t2) {
504
+ return O(1e3 * t2);
505
+ }, O.en = D[g], O.Ls = D, O.p = {}, O;
506
+ });
507
+ }
508
+ });
509
+ // src/common/utils.ts
510
+ var import_dayjs = __toESM(require_dayjs_min());
511
+ // src/web-element.ts
512
+ var WebElementInfo = class {
513
+ constructor({ content, rect, page, locator, id, attributes, indexId }){
514
+ this.content = content;
515
+ this.rect = rect;
516
+ this.center = [
517
+ Math.floor(rect.left + rect.width / 2),
518
+ Math.floor(rect.top + rect.height / 2)
519
+ ];
520
+ this.page = page;
521
+ this.locator = locator;
522
+ this.id = id;
523
+ this.attributes = attributes;
524
+ this.indexId = indexId;
525
+ }
526
+ };
527
+ // src/common/utils.ts
528
+ function parseContextFromWebPage(page, _opt) {
529
+ return __async(this, null, function*() {
530
+ (0, _assert.default)(page, "page is required");
531
+ if (page._forceUsePageContext) {
532
+ return yield page._forceUsePageContext();
533
+ }
534
+ const url = yield page.url();
535
+ let screenshotBase64;
536
+ let elementsInfo;
537
+ yield Promise.all([
538
+ page.screenshotBase64().then((base64)=>{
539
+ screenshotBase64 = base64;
540
+ }),
541
+ page.getElementInfos().then((snapshot)=>__async(this, null, function*() {
542
+ elementsInfo = yield alignElements(snapshot, page);
543
+ }))
544
+ ]);
545
+ (0, _assert.default)(screenshotBase64, "screenshotBase64 is required");
546
+ const elementsPositionInfoWithoutText = elementsInfo.filter((elementInfo)=>{
547
+ if (elementInfo.attributes.nodeType === _constants.NodeType.TEXT) {
548
+ return false;
549
+ }
550
+ return true;
551
+ });
552
+ const size = yield page.size();
553
+ const width = size.width;
554
+ const height = size.height;
555
+ const screenshotBase64WithElementMarker = (_opt == null ? void 0 : _opt.ignoreMarker) ? void 0 : yield (0, _img.compositeElementInfoImg)({
556
+ inputImgBase64: screenshotBase64,
557
+ elementsPositionInfo: elementsPositionInfoWithoutText,
558
+ size: {
559
+ width,
560
+ height
561
+ }
562
+ });
563
+ return {
564
+ content: elementsInfo,
565
+ size: {
566
+ width,
567
+ height
568
+ },
569
+ screenshotBase64,
570
+ screenshotBase64WithElementMarker,
571
+ url
572
+ };
573
+ });
574
+ }
575
+ var sizeThreshold = 3;
576
+ function alignElements(elements, page) {
577
+ return __async(this, null, function*() {
578
+ const validElements = elements.filter((item)=>{
579
+ return item.rect.height >= sizeThreshold && item.rect.width >= sizeThreshold;
580
+ });
581
+ const textsAligned = [];
582
+ for (const item of validElements){
583
+ const { rect, id, content, attributes, locator, indexId } = item;
584
+ textsAligned.push(new WebElementInfo({
585
+ rect,
586
+ locator,
587
+ id,
588
+ content,
589
+ attributes,
590
+ page,
591
+ indexId
592
+ }));
593
+ }
594
+ return textsAligned;
595
+ });
596
+ }
597
+ function reportFileName(tag = "web") {
598
+ const dateTimeInFileName = (0, import_dayjs.default)().format("YYYY-MM-DD_HH-mm-ss-SSS");
599
+ return `${tag}-${dateTimeInFileName}`;
600
+ }
601
+ function printReportMsg(filepath) {
602
+ console.log("Midscene - report file updated:", filepath);
603
+ }
604
+ function getCurrentExecutionFile(trace) {
605
+ const error = new Error();
606
+ const stackTrace = trace || error.stack;
607
+ const pkgDir = process.cwd() || "";
608
+ if (stackTrace) {
609
+ const stackLines = stackTrace.split("\n");
610
+ for (const line of stackLines){
611
+ if (line.includes(".spec.") || line.includes(".test.") || line.includes(".ts") || line.includes(".js")) {
612
+ const match = line.match(/(?:at\s+)?(.*?\.(?:spec|test)\.[jt]s)/);
613
+ if (match == null ? void 0 : match[1]) {
614
+ const targetFileName = match[1].replace(pkgDir, "").trim().replace("at ", "");
615
+ return targetFileName;
616
+ }
617
+ }
618
+ }
619
+ }
620
+ return false;
621
+ }
622
+ var testFileIndex = /* @__PURE__ */ new Map();
623
+ function generateCacheId(fileName) {
624
+ let taskFile = fileName || getCurrentExecutionFile();
625
+ if (!taskFile) {
626
+ taskFile = (0, _utils.uuid)();
627
+ console.warn("Midscene - using random UUID for cache id. Cache may be invalid.");
628
+ }
629
+ if (testFileIndex.has(taskFile)) {
630
+ const currentIndex = testFileIndex.get(taskFile);
631
+ if (currentIndex !== void 0) {
632
+ testFileIndex.set(taskFile, currentIndex + 1);
633
+ }
634
+ } else {
635
+ testFileIndex.set(taskFile, 1);
636
+ }
637
+ return `${taskFile}-${testFileIndex.get(taskFile)}`;
638
+ }
639
+ var ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED = "NOT_IMPLEMENTED_AS_DESIGNED";
640
+ var TaskCache = class {
641
+ getCacheGroupByPrompt(aiActionPrompt) {
642
+ const { aiTasks = [] } = this.cache || {
643
+ aiTasks: []
644
+ };
645
+ const index = aiTasks.findIndex((item)=>item.prompt === aiActionPrompt);
646
+ const newCacheGroup = [];
647
+ this.newCache.aiTasks.push({
648
+ prompt: aiActionPrompt,
649
+ tasks: newCacheGroup
650
+ });
651
+ return {
652
+ readCache: (pageContext, type, actionPrompt)=>{
653
+ if (index === -1) {
654
+ return false;
655
+ }
656
+ if (type === "plan") {
657
+ return this.readCache(pageContext, type, actionPrompt, aiTasks[index].tasks);
658
+ }
659
+ return this.readCache(pageContext, type, actionPrompt, aiTasks[index].tasks);
660
+ },
661
+ saveCache: (cache)=>{
662
+ newCacheGroup.push(cache);
663
+ this.writeCacheToFile();
664
+ }
665
+ };
666
+ }
667
+ readCache(pageContext, type, userPrompt, cacheGroup) {
668
+ var _a;
669
+ if (cacheGroup.length > 0) {
670
+ const index = cacheGroup.findIndex((item)=>item.prompt === userPrompt);
671
+ if (index === -1) {
672
+ return false;
673
+ }
674
+ const taskRes = cacheGroup.splice(index, 1)[0];
675
+ if ((taskRes == null ? void 0 : taskRes.type) === "locate" && !((_a = taskRes.response) == null ? void 0 : _a.elements.every((element)=>{
676
+ const findIndex = pageContext.content.findIndex((contentElement)=>contentElement.id === element.id);
677
+ if (findIndex === -1) {
678
+ return false;
679
+ }
680
+ return true;
681
+ }))) {
682
+ return false;
683
+ }
684
+ if (taskRes && taskRes.type === type && taskRes.prompt === userPrompt && this.pageContextEqual(taskRes.pageContext, pageContext)) {
685
+ return taskRes.response;
686
+ }
687
+ }
688
+ return false;
689
+ }
690
+ pageContextEqual(taskPageContext, pageContext) {
691
+ return taskPageContext.size.width === pageContext.size.width && taskPageContext.size.height === pageContext.size.height;
692
+ }
693
+ /**
694
+ * Generate task cache data.
695
+ * This method is mainly used to create or obtain some cached data for tasks, and it returns a new cache object.
696
+ * In the cache object, it may contain task-related information, states, or other necessary data.
697
+ * It is assumed that the `newCache` property already exists in the current class or object and is a data structure used to store task cache.
698
+ * @returns {Object} Returns a new cache object, which may include task cache data.
699
+ */ generateTaskCache() {
700
+ return this.newCache;
701
+ }
702
+ readCacheFromFile() {
703
+ if (_utils.ifInBrowser) {
704
+ return void 0;
705
+ }
706
+ const cacheFile = (0, _path.join)((0, _utils1.getLogDirByType)("cache"), `${this.cacheId}.json`);
707
+ if (process.env.MIDSCENE_CACHE === "true" && (0, _fs.existsSync)(cacheFile)) {
708
+ try {
709
+ const data = (0, _fs.readFileSync)(cacheFile, "utf8");
710
+ const jsonData = JSON.parse(data);
711
+ if (!this.midscenePkgInfo) {
712
+ return void 0;
713
+ }
714
+ if (jsonData.pkgName !== this.midscenePkgInfo.name || jsonData.pkgVersion !== this.midscenePkgInfo.version) {
715
+ return void 0;
716
+ }
717
+ return jsonData;
718
+ } catch (err) {
719
+ return void 0;
720
+ }
721
+ }
722
+ return void 0;
723
+ }
724
+ writeCacheToFile() {
725
+ const midscenePkgInfo = (0, _fs1.getRunningPkgInfo)();
726
+ if (!midscenePkgInfo) {
727
+ return;
728
+ }
729
+ if (!_utils.ifInBrowser) {
730
+ (0, _utils1.writeLogFile)({
731
+ fileName: `${this.cacheId}`,
732
+ fileExt: "json",
733
+ fileContent: (0, _utils1.stringifyDumpData)(__spreadValues({
734
+ pkgName: midscenePkgInfo.name,
735
+ pkgVersion: midscenePkgInfo.version,
736
+ cacheId: this.cacheId
737
+ }, this.newCache), 2),
738
+ type: "cache"
739
+ });
740
+ }
741
+ }
742
+ constructor(opts){
743
+ this.midscenePkgInfo = (0, _fs1.getRunningPkgInfo)();
744
+ this.cacheId = generateCacheId(opts == null ? void 0 : opts.fileName);
745
+ this.cache = this.readCacheFromFile() || {
746
+ aiTasks: []
747
+ };
748
+ this.newCache = {
749
+ aiTasks: []
750
+ };
751
+ }
752
+ };
753
+ // src/common/tasks.ts
754
+ var PageTaskExecutor = class {
755
+ recordScreenshot(timing) {
756
+ return __async(this, null, function*() {
757
+ const base64 = yield this.page.screenshotBase64();
758
+ const item = {
759
+ type: "screenshot",
760
+ ts: Date.now(),
761
+ screenshot: base64,
762
+ timing
763
+ };
764
+ return item;
765
+ });
766
+ }
767
+ wrapExecutorWithScreenshot(taskApply) {
768
+ const taskWithScreenshot = __spreadProps(__spreadValues({}, taskApply), {
769
+ executor: (param, context, ...args)=>__async(this, null, function*() {
770
+ const recorder = [];
771
+ const { task } = context;
772
+ task.recorder = recorder;
773
+ const shot = yield this.recordScreenshot(`before ${task.type}`);
774
+ recorder.push(shot);
775
+ const result = yield taskApply.executor(param, context, ...args);
776
+ if (taskApply.type === "Action") {
777
+ yield (0, _utils1.sleep)(1e3);
778
+ const shot2 = yield this.recordScreenshot("after Action");
779
+ recorder.push(shot2);
780
+ }
781
+ return result;
782
+ })
783
+ });
784
+ return taskWithScreenshot;
785
+ }
786
+ convertPlanToExecutable(plans, cacheGroup) {
787
+ return __async(this, null, function*() {
788
+ const tasks = plans.map((plan2)=>{
789
+ if (plan2.type === "Locate") {
790
+ const taskFind = {
791
+ type: "Insight",
792
+ subType: "Locate",
793
+ param: plan2.param,
794
+ quickAnswer: plan2.quickAnswer,
795
+ executor: (param, taskContext)=>__async(this, null, function*() {
796
+ const { task } = taskContext;
797
+ let insightDump;
798
+ const dumpCollector = (dump)=>{
799
+ insightDump = dump;
800
+ };
801
+ this.insight.onceDumpUpdatedFn = dumpCollector;
802
+ const pageContext = yield this.insight.contextRetrieverFn();
803
+ const locateCache = cacheGroup == null ? void 0 : cacheGroup.readCache(pageContext, "locate", param.prompt);
804
+ let locateResult;
805
+ const callAI = this.insight.aiVendorFn;
806
+ const element = yield this.insight.locate(param.prompt, {
807
+ quickAnswer: task.quickAnswer,
808
+ callAI: (...message)=>__async(this, null, function*() {
809
+ if (locateCache) {
810
+ locateResult = locateCache;
811
+ return Promise.resolve(locateCache);
812
+ }
813
+ const aiResult = yield callAI(...message);
814
+ locateResult = (0, _core.transformElementPositionToId)(aiResult, pageContext.content);
815
+ (0, _assert.default)(locateResult);
816
+ return locateResult;
817
+ })
818
+ });
819
+ if (locateResult) {
820
+ cacheGroup == null ? void 0 : cacheGroup.saveCache({
821
+ type: "locate",
822
+ pageContext: {
823
+ url: pageContext.url,
824
+ size: pageContext.size
825
+ },
826
+ prompt: param.prompt,
827
+ response: locateResult
828
+ });
829
+ }
830
+ if (!element) {
831
+ task.log = {
832
+ dump: insightDump
833
+ };
834
+ throw new Error(`Element not found: ${param.prompt}`);
835
+ }
836
+ return {
837
+ output: {
838
+ element
839
+ },
840
+ log: {
841
+ dump: insightDump
842
+ },
843
+ cache: {
844
+ hit: Boolean(locateCache)
845
+ }
846
+ };
847
+ })
848
+ };
849
+ return taskFind;
850
+ }
851
+ if (plan2.type === "Assert" || plan2.type === "AssertWithoutThrow") {
852
+ const assertPlan = plan2;
853
+ const taskAssert = {
854
+ type: "Insight",
855
+ subType: "Assert",
856
+ param: assertPlan.param,
857
+ executor: (param, taskContext)=>__async(this, null, function*() {
858
+ const { task } = taskContext;
859
+ let insightDump;
860
+ const dumpCollector = (dump)=>{
861
+ insightDump = dump;
862
+ };
863
+ this.insight.onceDumpUpdatedFn = dumpCollector;
864
+ const assertion = yield this.insight.assert(assertPlan.param.assertion);
865
+ if (!assertion.pass) {
866
+ if (plan2.type === "Assert") {
867
+ task.output = assertion;
868
+ task.log = {
869
+ dump: insightDump
870
+ };
871
+ throw new Error(assertion.thought || "Assertion failed without reason");
872
+ }
873
+ task.error = assertion.thought;
874
+ }
875
+ return {
876
+ output: assertion,
877
+ log: {
878
+ dump: insightDump
879
+ }
880
+ };
881
+ })
882
+ };
883
+ return taskAssert;
884
+ }
885
+ if (plan2.type === "Input") {
886
+ const taskActionInput = {
887
+ type: "Action",
888
+ subType: "Input",
889
+ param: plan2.param,
890
+ executor: (_0, _1)=>__async(this, [
891
+ _0,
892
+ _1
893
+ ], function*(taskParam, { element }) {
894
+ if (element) {
895
+ yield this.page.clearInput(element);
896
+ if (taskParam.value === "") {
897
+ return;
898
+ }
899
+ yield this.page.keyboard.type(taskParam.value);
900
+ }
901
+ })
902
+ };
903
+ return taskActionInput;
904
+ }
905
+ if (plan2.type === "KeyboardPress") {
906
+ const taskActionKeyboardPress = {
907
+ type: "Action",
908
+ subType: "KeyboardPress",
909
+ param: plan2.param,
910
+ executor: (taskParam)=>__async(this, null, function*() {
911
+ (0, _assert.default)(taskParam.value, "No key to press");
912
+ yield this.page.keyboard.press(taskParam.value);
913
+ })
914
+ };
915
+ return taskActionKeyboardPress;
916
+ }
917
+ if (plan2.type === "Tap") {
918
+ const taskActionTap = {
919
+ type: "Action",
920
+ subType: "Tap",
921
+ executor: (_0, _1)=>__async(this, [
922
+ _0,
923
+ _1
924
+ ], function*(param, { element }) {
925
+ (0, _assert.default)(element, "Element not found, cannot tap");
926
+ yield this.page.mouse.click(element.center[0], element.center[1]);
927
+ })
928
+ };
929
+ return taskActionTap;
930
+ }
931
+ if (plan2.type === "Hover") {
932
+ const taskActionHover = {
933
+ type: "Action",
934
+ subType: "Hover",
935
+ executor: (_0, _1)=>__async(this, [
936
+ _0,
937
+ _1
938
+ ], function*(param, { element }) {
939
+ (0, _assert.default)(element, "Element not found, cannot hover");
940
+ yield this.page.mouse.move(element.center[0], element.center[1]);
941
+ })
942
+ };
943
+ return taskActionHover;
944
+ }
945
+ if (plan2.type === "Scroll") {
946
+ const taskActionScroll = {
947
+ type: "Action",
948
+ subType: "Scroll",
949
+ param: plan2.param,
950
+ executor: (taskParam)=>__async(this, null, function*() {
951
+ const scrollToEventName = taskParam.scrollType;
952
+ switch(scrollToEventName){
953
+ case "scrollUntilTop":
954
+ yield this.page.scrollUntilTop();
955
+ break;
956
+ case "scrollUntilBottom":
957
+ yield this.page.scrollUntilBottom();
958
+ break;
959
+ case "scrollUpOneScreen":
960
+ yield this.page.scrollUpOneScreen();
961
+ break;
962
+ case "scrollDownOneScreen":
963
+ yield this.page.scrollDownOneScreen();
964
+ break;
965
+ default:
966
+ console.error("Unknown scroll event type:", scrollToEventName);
967
+ }
968
+ })
969
+ };
970
+ return taskActionScroll;
971
+ }
972
+ if (plan2.type === "Sleep") {
973
+ const taskActionSleep = {
974
+ type: "Action",
975
+ subType: "Sleep",
976
+ param: plan2.param,
977
+ executor: (taskParam)=>__async(this, null, function*() {
978
+ yield (0, _utils1.sleep)(taskParam.timeMs || 3e3);
979
+ })
980
+ };
981
+ return taskActionSleep;
982
+ }
983
+ if (plan2.type === "Error") {
984
+ const taskActionError = {
985
+ type: "Action",
986
+ subType: "Error",
987
+ param: plan2.param,
988
+ executor: (taskParam)=>__async(this, null, function*() {
989
+ (0, _assert.default)(taskParam.thought, "An error occurred, but no thought provided");
990
+ throw new Error(taskParam.thought);
991
+ })
992
+ };
993
+ return taskActionError;
994
+ }
995
+ throw new Error(`Unknown or Unsupported task type: ${plan2.type}`);
996
+ }).map((task)=>{
997
+ return this.wrapExecutorWithScreenshot(task);
998
+ });
999
+ return tasks;
1000
+ });
1001
+ }
1002
+ action(userPrompt) {
1003
+ return __async(this, null, function*() {
1004
+ const taskExecutor = new _core.Executor(userPrompt);
1005
+ const cacheGroup = this.taskCache.getCacheGroupByPrompt(userPrompt);
1006
+ let plans = [];
1007
+ const planningTask = {
1008
+ type: "Planning",
1009
+ param: {
1010
+ userPrompt
1011
+ },
1012
+ executor: (param)=>__async(this, null, function*() {
1013
+ const pageContext = yield this.insight.contextRetrieverFn();
1014
+ let planResult;
1015
+ const planCache = cacheGroup.readCache(pageContext, "plan", userPrompt);
1016
+ if (planCache) {
1017
+ planResult = planCache;
1018
+ } else {
1019
+ planResult = yield (0, _core.plan)(param.userPrompt, {
1020
+ context: pageContext
1021
+ });
1022
+ }
1023
+ (0, _assert.default)(planResult.plans.length > 0, "No plans found");
1024
+ plans = planResult.plans;
1025
+ cacheGroup.saveCache({
1026
+ type: "plan",
1027
+ pageContext: {
1028
+ url: pageContext.url,
1029
+ size: pageContext.size
1030
+ },
1031
+ prompt: userPrompt,
1032
+ response: planResult
1033
+ });
1034
+ return {
1035
+ output: planResult,
1036
+ pageContext,
1037
+ cache: {
1038
+ hit: Boolean(planCache)
1039
+ }
1040
+ };
1041
+ })
1042
+ };
1043
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(planningTask));
1044
+ let output = yield taskExecutor.flush();
1045
+ if (taskExecutor.isInErrorState()) {
1046
+ return {
1047
+ output,
1048
+ executor: taskExecutor
1049
+ };
1050
+ }
1051
+ const executables = yield this.convertPlanToExecutable(plans, cacheGroup);
1052
+ yield taskExecutor.append(executables);
1053
+ output = yield taskExecutor.flush();
1054
+ return {
1055
+ output,
1056
+ executor: taskExecutor
1057
+ };
1058
+ });
1059
+ }
1060
+ query(demand) {
1061
+ return __async(this, null, function*() {
1062
+ const description = typeof demand === "string" ? demand : JSON.stringify(demand);
1063
+ const taskExecutor = new _core.Executor(description);
1064
+ const queryTask = {
1065
+ type: "Insight",
1066
+ subType: "Query",
1067
+ param: {
1068
+ dataDemand: demand
1069
+ },
1070
+ executor: (param)=>__async(this, null, function*() {
1071
+ let insightDump;
1072
+ const dumpCollector = (dump)=>{
1073
+ insightDump = dump;
1074
+ };
1075
+ this.insight.onceDumpUpdatedFn = dumpCollector;
1076
+ const data = yield this.insight.extract(param.dataDemand);
1077
+ return {
1078
+ output: data,
1079
+ log: {
1080
+ dump: insightDump
1081
+ }
1082
+ };
1083
+ })
1084
+ };
1085
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(queryTask));
1086
+ const output = yield taskExecutor.flush();
1087
+ return {
1088
+ output,
1089
+ executor: taskExecutor
1090
+ };
1091
+ });
1092
+ }
1093
+ assert(assertion) {
1094
+ return __async(this, null, function*() {
1095
+ const description = `assert: ${assertion}`;
1096
+ const taskExecutor = new _core.Executor(description);
1097
+ const assertionPlan = {
1098
+ type: "Assert",
1099
+ param: {
1100
+ assertion
1101
+ }
1102
+ };
1103
+ const assertTask = yield this.convertPlanToExecutable([
1104
+ assertionPlan
1105
+ ]);
1106
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(assertTask[0]));
1107
+ const output = yield taskExecutor.flush();
1108
+ return {
1109
+ output,
1110
+ executor: taskExecutor
1111
+ };
1112
+ });
1113
+ }
1114
+ waitFor(assertion, opt) {
1115
+ return __async(this, null, function*() {
1116
+ const description = `waitFor: ${assertion}`;
1117
+ const taskExecutor = new _core.Executor(description);
1118
+ const { timeoutMs, checkIntervalMs } = opt;
1119
+ (0, _assert.default)(assertion, "No assertion for waitFor");
1120
+ (0, _assert.default)(timeoutMs, "No timeoutMs for waitFor");
1121
+ (0, _assert.default)(checkIntervalMs, "No checkIntervalMs for waitFor");
1122
+ const overallStartTime = Date.now();
1123
+ let startTime = Date.now();
1124
+ let errorThought = "";
1125
+ while(Date.now() - overallStartTime < timeoutMs){
1126
+ startTime = Date.now();
1127
+ const assertPlan = {
1128
+ type: "AssertWithoutThrow",
1129
+ param: {
1130
+ assertion
1131
+ }
1132
+ };
1133
+ const assertTask = yield this.convertPlanToExecutable([
1134
+ assertPlan
1135
+ ]);
1136
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(assertTask[0]));
1137
+ const output = yield taskExecutor.flush();
1138
+ if (output == null ? void 0 : output.pass) {
1139
+ return {
1140
+ output: void 0,
1141
+ executor: taskExecutor
1142
+ };
1143
+ }
1144
+ errorThought = (output == null ? void 0 : output.thought) || "unknown error";
1145
+ const now = Date.now();
1146
+ if (now - startTime < checkIntervalMs) {
1147
+ const timeRemaining = checkIntervalMs - (now - startTime);
1148
+ const sleepPlan = {
1149
+ type: "Sleep",
1150
+ param: {
1151
+ timeMs: timeRemaining
1152
+ }
1153
+ };
1154
+ const sleepTask = yield this.convertPlanToExecutable([
1155
+ sleepPlan
1156
+ ]);
1157
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(sleepTask[0]));
1158
+ yield taskExecutor.flush();
1159
+ }
1160
+ }
1161
+ const errorPlan = {
1162
+ type: "Error",
1163
+ param: {
1164
+ thought: `waitFor timeout: ${errorThought}`
1165
+ }
1166
+ };
1167
+ const errorTask = yield this.convertPlanToExecutable([
1168
+ errorPlan
1169
+ ]);
1170
+ yield taskExecutor.append(errorTask[0]);
1171
+ yield taskExecutor.flush();
1172
+ return {
1173
+ output: void 0,
1174
+ executor: taskExecutor
1175
+ };
1176
+ });
1177
+ }
1178
+ constructor(page, insight, opts){
1179
+ this.page = page;
1180
+ this.insight = insight;
1181
+ this.taskCache = new TaskCache({
1182
+ fileName: opts == null ? void 0 : opts.cacheId
1183
+ });
1184
+ }
1185
+ };
1186
+ // src/common/agent.ts
1187
+ var PageAgent = class {
1188
+ getUIContext() {
1189
+ return __async(this, null, function*() {
1190
+ return yield parseContextFromWebPage(this.page);
1191
+ });
1192
+ }
1193
+ resetDump() {
1194
+ this.dump = {
1195
+ groupName: this.opts.groupName,
1196
+ groupDescription: this.opts.groupDescription,
1197
+ executions: []
1198
+ };
1199
+ return this.dump;
1200
+ }
1201
+ appendExecutionDump(execution) {
1202
+ const currentDump = this.dump;
1203
+ currentDump.executions.push(execution);
1204
+ }
1205
+ dumpDataString() {
1206
+ this.dump.groupName = this.opts.groupName;
1207
+ this.dump.groupDescription = this.opts.groupDescription;
1208
+ return (0, _utils1.stringifyDumpData)(this.dump);
1209
+ }
1210
+ reportHTMLString() {
1211
+ return (0, _utils1.reportHTMLContent)(this.dumpDataString());
1212
+ }
1213
+ writeOutActionDumps() {
1214
+ const { generateReport, autoPrintReportMsg } = this.opts;
1215
+ this.reportFile = (0, _utils1.writeLogFile)({
1216
+ fileName: this.reportFileName,
1217
+ fileExt: _utils1.groupedActionDumpFileExt,
1218
+ fileContent: this.dumpDataString(),
1219
+ type: "dump",
1220
+ generateReport
1221
+ });
1222
+ if (generateReport && autoPrintReportMsg && this.reportFile) {
1223
+ printReportMsg(this.reportFile);
1224
+ }
1225
+ }
1226
+ aiAction(taskPrompt) {
1227
+ return __async(this, null, function*() {
1228
+ const { executor } = yield this.taskExecutor.action(taskPrompt);
1229
+ this.appendExecutionDump(executor.dump());
1230
+ this.writeOutActionDumps();
1231
+ if (executor.isInErrorState()) {
1232
+ const errorTask = executor.latestErrorTask();
1233
+ throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1234
+ ${errorTask == null ? void 0 : errorTask.errorStack}`);
1235
+ }
1236
+ });
1237
+ }
1238
+ aiQuery(demand) {
1239
+ return __async(this, null, function*() {
1240
+ const { output, executor } = yield this.taskExecutor.query(demand);
1241
+ this.appendExecutionDump(executor.dump());
1242
+ this.writeOutActionDumps();
1243
+ if (executor.isInErrorState()) {
1244
+ const errorTask = executor.latestErrorTask();
1245
+ throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1246
+ ${errorTask == null ? void 0 : errorTask.errorStack}`);
1247
+ }
1248
+ return output;
1249
+ });
1250
+ }
1251
+ aiAssert(assertion, msg, opt) {
1252
+ return __async(this, null, function*() {
1253
+ var _a;
1254
+ const { output, executor } = yield this.taskExecutor.assert(assertion);
1255
+ this.appendExecutionDump(executor.dump());
1256
+ this.writeOutActionDumps();
1257
+ if (output && (opt == null ? void 0 : opt.keepRawResponse)) {
1258
+ return output;
1259
+ }
1260
+ if (!(output == null ? void 0 : output.pass)) {
1261
+ const errMsg = msg || `Assertion failed: ${assertion}`;
1262
+ const reasonMsg = `Reason: ${(output == null ? void 0 : output.thought) || ((_a = executor.latestErrorTask()) == null ? void 0 : _a.error) || "(no_reason)"}`;
1263
+ throw new Error(`${errMsg}
1264
+ ${reasonMsg}`);
1265
+ }
1266
+ });
1267
+ }
1268
+ aiWaitFor(assertion, opt) {
1269
+ return __async(this, null, function*() {
1270
+ const { executor } = yield this.taskExecutor.waitFor(assertion, {
1271
+ timeoutMs: (opt == null ? void 0 : opt.timeoutMs) || 15 * 1e3,
1272
+ checkIntervalMs: (opt == null ? void 0 : opt.checkIntervalMs) || 3 * 1e3,
1273
+ assertion
1274
+ });
1275
+ this.appendExecutionDump(executor.dump());
1276
+ this.writeOutActionDumps();
1277
+ if (executor.isInErrorState()) {
1278
+ const errorTask = executor.latestErrorTask();
1279
+ throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1280
+ ${errorTask == null ? void 0 : errorTask.errorStack}`);
1281
+ }
1282
+ });
1283
+ }
1284
+ ai(taskPrompt, type = "action") {
1285
+ return __async(this, null, function*() {
1286
+ if (type === "action") {
1287
+ return this.aiAction(taskPrompt);
1288
+ }
1289
+ if (type === "query") {
1290
+ return this.aiQuery(taskPrompt);
1291
+ }
1292
+ if (type === "assert") {
1293
+ return this.aiAssert(taskPrompt);
1294
+ }
1295
+ throw new Error(`Unknown type: ${type}, only support 'action', 'query', 'assert'`);
1296
+ });
1297
+ }
1298
+ destroy() {
1299
+ return __async(this, null, function*() {
1300
+ yield this.page.destroy();
1301
+ });
1302
+ }
1303
+ constructor(page, opts){
1304
+ /**
1305
+ * If true, the agent will not perform any actions
1306
+ */ this.dryMode = false;
1307
+ this.page = page;
1308
+ this.opts = Object.assign({
1309
+ generateReport: true,
1310
+ autoPrintReportMsg: true,
1311
+ groupName: "Midscene Report",
1312
+ groupDescription: ""
1313
+ }, opts || {});
1314
+ this.insight = new _core.Insight(()=>__async(this, null, function*() {
1315
+ return this.getUIContext();
1316
+ }), {
1317
+ generateElement: ({ content, rect })=>new WebElementInfo({
1318
+ content: content || "",
1319
+ rect,
1320
+ page,
1321
+ id: "",
1322
+ attributes: {
1323
+ nodeType: _constants.NodeType.CONTAINER
1324
+ },
1325
+ indexId: 0
1326
+ })
1327
+ });
1328
+ this.taskExecutor = new PageTaskExecutor(this.page, this.insight, {
1329
+ cacheId: opts == null ? void 0 : opts.cacheId
1330
+ });
1331
+ this.dump = this.resetDump();
1332
+ this.reportFileName = reportFileName((opts == null ? void 0 : opts.testId) || "web");
1333
+ }
1334
+ };
1335
+ // src/chrome-extension/agent.ts
1336
+ var ChromeExtensionProxyPageAgent = class extends PageAgent {
1337
+ constructor(page){
1338
+ super(page, {});
1339
+ }
1340
+ };
1341
+ var scriptFileToRetrieve = "./lib/htmlElement.js";
1342
+ function getActivePageContent(tabId) {
1343
+ return __async(this, null, function*() {
1344
+ const injectResult = yield chrome.scripting.executeScript({
1345
+ target: {
1346
+ tabId,
1347
+ allFrames: true
1348
+ },
1349
+ files: [
1350
+ scriptFileToRetrieve
1351
+ ]
1352
+ });
1353
+ console.log("injectResult", injectResult);
1354
+ const returnValue = yield chrome.scripting.executeScript({
1355
+ target: {
1356
+ tabId,
1357
+ allFrames: true
1358
+ },
1359
+ func: ()=>{
1360
+ return {
1361
+ context: window.midscene_element_inspector.webExtractTextWithPosition(),
1362
+ size: {
1363
+ width: document.documentElement.clientWidth,
1364
+ height: document.documentElement.clientHeight,
1365
+ dpr: window.devicePixelRatio
1366
+ }
1367
+ };
1368
+ }
1369
+ });
1370
+ if (!returnValue[0].result) {
1371
+ throw new Error(`Failed to get active page content of tabId: ${tabId}`);
1372
+ }
1373
+ return returnValue[0].result;
1374
+ });
1375
+ }
1376
+ var lastTwoCallTime = [
1377
+ 0,
1378
+ 0
1379
+ ];
1380
+ var callInterval = 1050;
1381
+ function getScreenshotBase64(windowId) {
1382
+ return __async(this, null, function*() {
1383
+ const activeWindow = yield chrome.windows.getAll({
1384
+ populate: true
1385
+ });
1386
+ if (activeWindow.find((w)=>w.id === windowId) === void 0) {
1387
+ throw new Error(`Window with id ${windowId} is not active`);
1388
+ }
1389
+ const now = Date.now();
1390
+ if (now - lastTwoCallTime[0] < callInterval) {
1391
+ const sleepTime = callInterval - (now - lastTwoCallTime[0]);
1392
+ console.warn(`Sleep for ${sleepTime}ms to avoid too frequent screenshot calls`);
1393
+ yield new Promise((resolve)=>setTimeout(resolve, sleepTime));
1394
+ }
1395
+ const base64 = yield chrome.tabs.captureVisibleTab(windowId, {
1396
+ format: "jpeg",
1397
+ quality: 70
1398
+ });
1399
+ lastTwoCallTime.shift();
1400
+ lastTwoCallTime.push(Date.now());
1401
+ return base64;
1402
+ });
1403
+ }
1404
+ function getScreenInfoOfTab(tabId) {
1405
+ return __async(this, null, function*() {
1406
+ const returnValue = yield chrome.scripting.executeScript({
1407
+ target: {
1408
+ tabId,
1409
+ allFrames: false
1410
+ },
1411
+ func: ()=>{
1412
+ return {
1413
+ dpr: window.devicePixelRatio,
1414
+ width: document.documentElement.clientWidth,
1415
+ height: document.documentElement.clientHeight
1416
+ };
1417
+ }
1418
+ });
1419
+ return returnValue[0].result;
1420
+ });
1421
+ }
1422
+ var ChromeExtensionProxyPage = class {
1423
+ attachDebugger() {
1424
+ return __async(this, null, function*() {
1425
+ if (this.debuggerAttached) return;
1426
+ yield chrome.debugger.attach({
1427
+ tabId: this.tabId
1428
+ }, "1.3");
1429
+ this.debuggerAttached = true;
1430
+ chrome.debugger.onEvent.addListener((source, method, params)=>{
1431
+ console.log("debugger event", source, method, params);
1432
+ if (method === "Debugger.detached") {
1433
+ this.debuggerAttached = false;
1434
+ }
1435
+ });
1436
+ });
1437
+ }
1438
+ detachDebugger() {
1439
+ return __async(this, null, function*() {
1440
+ if (!this.debuggerAttached) return;
1441
+ yield chrome.debugger.detach({
1442
+ tabId: this.tabId
1443
+ });
1444
+ this.debuggerAttached = false;
1445
+ });
1446
+ }
1447
+ sendCommandToDebugger(command, params) {
1448
+ return __async(this, null, function*() {
1449
+ yield this.attachDebugger();
1450
+ yield chrome.debugger.sendCommand({
1451
+ tabId: this.tabId
1452
+ }, command, params);
1453
+ });
1454
+ }
1455
+ getElementInfos() {
1456
+ return __async(this, null, function*() {
1457
+ const content = yield getActivePageContent(this.tabId);
1458
+ if (content == null ? void 0 : content.size) {
1459
+ this.viewportSize = content.size;
1460
+ }
1461
+ return (content == null ? void 0 : content.context) || [];
1462
+ });
1463
+ }
1464
+ size() {
1465
+ return __async(this, null, function*() {
1466
+ if (this.viewportSize) return this.viewportSize;
1467
+ const content = yield getActivePageContent(this.tabId);
1468
+ return content.size;
1469
+ });
1470
+ }
1471
+ screenshotBase64() {
1472
+ return __async(this, null, function*() {
1473
+ const base64 = yield getScreenshotBase64(this.windowId);
1474
+ const screenInfo = yield getScreenInfoOfTab(this.tabId);
1475
+ if (screenInfo.dpr > 1) {
1476
+ return yield (0, _img1.resizeImgBase64)(base64, {
1477
+ width: screenInfo.width,
1478
+ height: screenInfo.height
1479
+ });
1480
+ }
1481
+ return base64;
1482
+ });
1483
+ }
1484
+ url() {
1485
+ return __async(this, null, function*() {
1486
+ const url = yield chrome.tabs.get(this.tabId).then((tab)=>tab.url);
1487
+ return url || "";
1488
+ });
1489
+ }
1490
+ scrollUntilTop() {
1491
+ return __async(this, null, function*() {
1492
+ return this.mouse.wheel(0, -9999999);
1493
+ });
1494
+ }
1495
+ scrollUntilBottom() {
1496
+ return __async(this, null, function*() {
1497
+ return this.mouse.wheel(0, 9999999);
1498
+ });
1499
+ }
1500
+ scrollUpOneScreen() {
1501
+ return __async(this, null, function*() {
1502
+ yield chrome.scripting.executeScript({
1503
+ target: {
1504
+ tabId: this.tabId,
1505
+ allFrames: true
1506
+ },
1507
+ func: ()=>{
1508
+ window.scrollBy(0, -window.innerHeight * 0.7);
1509
+ }
1510
+ });
1511
+ });
1512
+ }
1513
+ scrollDownOneScreen() {
1514
+ return __async(this, null, function*() {
1515
+ yield chrome.scripting.executeScript({
1516
+ target: {
1517
+ tabId: this.tabId,
1518
+ allFrames: true
1519
+ },
1520
+ func: ()=>{
1521
+ window.scrollBy(0, window.innerHeight * 0.7);
1522
+ }
1523
+ });
1524
+ });
1525
+ }
1526
+ clearInput(element) {
1527
+ return __async(this, null, function*() {
1528
+ if (!element) {
1529
+ console.warn("No element to clear input");
1530
+ return;
1531
+ }
1532
+ yield this.mouse.click(element.center[0], element.center[1]);
1533
+ yield this.sendCommandToDebugger("Input.dispatchKeyEvent", {
1534
+ type: "keyDown",
1535
+ commands: [
1536
+ "selectAll"
1537
+ ]
1538
+ });
1539
+ yield this.sendCommandToDebugger("Input.dispatchKeyEvent", {
1540
+ type: "keyDown",
1541
+ key: "Backspace",
1542
+ code: "Backspace"
1543
+ });
1544
+ yield this.sendCommandToDebugger("Input.dispatchKeyEvent", {
1545
+ type: "keyUp",
1546
+ key: "Backspace",
1547
+ code: "Backspace"
1548
+ });
1549
+ });
1550
+ }
1551
+ destroy() {
1552
+ return __async(this, null, function*() {
1553
+ yield this.detachDebugger();
1554
+ });
1555
+ }
1556
+ constructor(tabId, windowId){
1557
+ this.pageType = "chrome-extension-proxy";
1558
+ this.debuggerAttached = false;
1559
+ this.mouse = {
1560
+ click: (x, y)=>__async(this, null, function*() {
1561
+ yield this.sendCommandToDebugger("Input.dispatchMouseEvent", {
1562
+ type: "mousePressed",
1563
+ x,
1564
+ y,
1565
+ button: "left",
1566
+ clickCount: 1
1567
+ });
1568
+ yield this.sendCommandToDebugger("Input.dispatchMouseEvent", {
1569
+ type: "mouseReleased",
1570
+ x,
1571
+ y,
1572
+ button: "left",
1573
+ clickCount: 1
1574
+ });
1575
+ }),
1576
+ wheel: (deltaX, deltaY)=>__async(this, null, function*() {
1577
+ yield this.sendCommandToDebugger("Input.dispatchMouseEvent", {
1578
+ type: "mouseWheel",
1579
+ x: 10,
1580
+ y: 10,
1581
+ deltaX,
1582
+ deltaY
1583
+ });
1584
+ }),
1585
+ move: (x, y)=>__async(this, null, function*() {
1586
+ yield this.sendCommandToDebugger("Input.dispatchMouseEvent", {
1587
+ type: "mouseMoved",
1588
+ x,
1589
+ y
1590
+ });
1591
+ })
1592
+ };
1593
+ this.keyboard = {
1594
+ type: (text)=>__async(this, null, function*() {
1595
+ for (const char of text){
1596
+ yield this.sendCommandToDebugger("Input.dispatchKeyEvent", {
1597
+ type: "char",
1598
+ text: char,
1599
+ key: char,
1600
+ unmodifiedText: char
1601
+ });
1602
+ yield new Promise((resolve)=>setTimeout(resolve, 50));
1603
+ }
1604
+ }),
1605
+ press: (key)=>__async(this, null, function*() {
1606
+ yield this.sendCommandToDebugger("Input.dispatchKeyEvent", {
1607
+ type: "rawKeyDown",
1608
+ code: key,
1609
+ key
1610
+ });
1611
+ yield this.sendCommandToDebugger("Input.dispatchKeyEvent", {
1612
+ type: "char",
1613
+ code: key,
1614
+ key
1615
+ });
1616
+ yield this.sendCommandToDebugger("Input.dispatchKeyEvent", {
1617
+ type: "keyUp",
1618
+ code: key,
1619
+ key
1620
+ });
1621
+ })
1622
+ };
1623
+ this.tabId = tabId;
1624
+ this.windowId = windowId;
1625
+ }
1626
+ };
1627
+ });