@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.
@@ -1,1718 +1,1895 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __defProps = Object.defineProperties;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
- var __getProtoOf = Object.getPrototypeOf;
9
- var __hasOwnProp = Object.prototype.hasOwnProperty;
10
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
- var __spreadValues = (a, b) => {
13
- for (var prop in b || (b = {}))
14
- if (__hasOwnProp.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- if (__getOwnPropSymbols)
17
- for (var prop of __getOwnPropSymbols(b)) {
18
- if (__propIsEnum.call(b, prop))
19
- __defNormalProp(a, prop, b[prop]);
20
- }
21
- return a;
22
- };
23
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
25
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
26
- }) : x)(function(x) {
27
- if (typeof require !== "undefined")
28
- return require.apply(this, arguments);
29
- throw Error('Dynamic require of "' + x + '" is not supported');
30
- });
31
- var __commonJS = (cb, mod) => function __require2() {
32
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
33
- };
34
- var __copyProps = (to, from, except, desc) => {
35
- if (from && typeof from === "object" || typeof from === "function") {
36
- for (let key of __getOwnPropNames(from))
37
- if (!__hasOwnProp.call(to, key) && key !== except)
38
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
39
- }
40
- return to;
41
- };
42
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
43
- // If the importer is in node compatibility mode or this is not an ESM
44
- // file that has been converted to a CommonJS file using a Babel-
45
- // compatible transform (i.e. "__esModule" has not been set), then set
46
- // "default" to the CommonJS "module.exports" for node compatibility.
47
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
48
- mod
49
- ));
50
-
51
- // ../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.js
52
- var require_dayjs_min = __commonJS({
53
- "../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.js"(exports, module) {
1
+ (function(global, factory) {
2
+ if (typeof module === "object" && typeof module.exports === "object") factory(exports, require("assert"), require("crypto"), require("fs"), require("path"), require("@midscene/shared/constants"), require("@midscene/shared/fs"), require("@midscene/shared/img"), require("@midscene/shared/utils"), require("@midscene/core/utils"), require("cors"), require("express"), require("@midscene/core"));
3
+ else if (typeof define === "function" && define.amd) define([
4
+ "exports",
5
+ "assert",
6
+ "crypto",
7
+ "fs",
8
+ "path",
9
+ "@midscene/shared/constants",
10
+ "@midscene/shared/fs",
11
+ "@midscene/shared/img",
12
+ "@midscene/shared/utils",
13
+ "@midscene/core/utils",
14
+ "cors",
15
+ "express",
16
+ "@midscene/core"
17
+ ], factory);
18
+ else if (global = typeof globalThis !== "undefined" ? globalThis : global || self) factory(global.midscenePlayground = {}, global.assert, global.crypto, global.fs, global.path, global.constants, global.fs, global.img, global.utils, global.utils, global.cors, global.express, global.core);
19
+ })(this, function(exports, _assert, _crypto, _fs, _path, _constants, _fs1, _img, _utils, _utils1, _cors, _express, _core) {
54
20
  "use strict";
55
- !function(t, e) {
56
- "object" == typeof exports && "undefined" != typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define(e) : (t = "undefined" != typeof globalThis ? globalThis : t || self).dayjs = e();
57
- }(exports, function() {
58
- "use strict";
59
- 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 = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), ordinal: function(t2) {
60
- var e2 = ["th", "st", "nd", "rd"], n2 = t2 % 100;
61
- return "[" + t2 + (e2[(n2 - 20) % 10] || e2[n2] || e2[0]) + "]";
62
- } }, m = function(t2, e2, n2) {
63
- var r2 = String(t2);
64
- return !r2 || r2.length >= e2 ? t2 : "" + Array(e2 + 1 - r2.length).join(n2) + t2;
65
- }, v = { s: m, z: function(t2) {
66
- var e2 = -t2.utcOffset(), n2 = Math.abs(e2), r2 = Math.floor(n2 / 60), i2 = n2 % 60;
67
- return (e2 <= 0 ? "+" : "-") + m(r2, 2, "0") + ":" + m(i2, 2, "0");
68
- }, m: function t2(e2, n2) {
69
- if (e2.date() < n2.date())
70
- return -t2(n2, e2);
71
- 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);
72
- return +(-(r2 + (n2 - i2) / (s2 ? i2 - u2 : u2 - i2)) || 0);
73
- }, a: function(t2) {
74
- return t2 < 0 ? Math.ceil(t2) || 0 : Math.floor(t2);
75
- }, p: function(t2) {
76
- return { M: c, y: h, w: o, d: a, D: d, h: u, m: s, s: i, ms: r, Q: f }[t2] || String(t2 || "").toLowerCase().replace(/s$/, "");
77
- }, u: function(t2) {
78
- return void 0 === t2;
79
- } }, g = "en", D = {};
80
- D[g] = M;
81
- var p = "$isDayjsObject", S = function(t2) {
82
- return t2 instanceof _ || !(!t2 || !t2[p]);
83
- }, w = function t2(e2, n2, r2) {
84
- var i2;
85
- if (!e2)
86
- return g;
87
- if ("string" == typeof e2) {
88
- var s2 = e2.toLowerCase();
89
- D[s2] && (i2 = s2), n2 && (D[s2] = n2, i2 = s2);
90
- var u2 = e2.split("-");
91
- if (!i2 && u2.length > 1)
92
- return t2(u2[0]);
93
- } else {
94
- var a2 = e2.name;
95
- D[a2] = e2, i2 = a2;
21
+ Object.defineProperty(exports, "__esModule", {
22
+ value: true
23
+ });
24
+ _assert = /*#__PURE__*/ _interop_require_default(_assert);
25
+ _path = /*#__PURE__*/ _interop_require_wildcard(_path);
26
+ _cors = /*#__PURE__*/ _interop_require_default(_cors);
27
+ _express = /*#__PURE__*/ _interop_require_default(_express);
28
+ function _interop_require_default(obj) {
29
+ return obj && obj.__esModule ? obj : {
30
+ default: obj
31
+ };
32
+ }
33
+ function _getRequireWildcardCache(nodeInterop) {
34
+ if (typeof WeakMap !== "function") return null;
35
+ var cacheBabelInterop = new WeakMap();
36
+ var cacheNodeInterop = new WeakMap();
37
+ return (_getRequireWildcardCache = function(nodeInterop) {
38
+ return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
39
+ })(nodeInterop);
40
+ }
41
+ function _interop_require_wildcard(obj, nodeInterop) {
42
+ if (!nodeInterop && obj && obj.__esModule) {
43
+ return obj;
96
44
  }
97
- return !r2 && i2 && (g = i2), i2 || !r2 && g;
98
- }, O = function(t2, e2) {
99
- if (S(t2))
100
- return t2.clone();
101
- var n2 = "object" == typeof e2 ? e2 : {};
102
- return n2.date = t2, n2.args = arguments, new _(n2);
103
- }, b = v;
104
- b.l = w, b.i = S, b.w = function(t2, e2) {
105
- return O(t2, { locale: e2.$L, utc: e2.$u, x: e2.$x, $offset: e2.$offset });
106
- };
107
- var _ = function() {
108
- function M2(t2) {
109
- this.$L = w(t2.locale, null, true), this.parse(t2), this.$x = this.$x || t2.x || {}, this[p] = true;
45
+ if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
46
+ return {
47
+ default: obj
48
+ };
110
49
  }
111
- var m2 = M2.prototype;
112
- return m2.parse = function(t2) {
113
- this.$d = function(t3) {
114
- var e2 = t3.date, n2 = t3.utc;
115
- if (null === e2)
116
- return /* @__PURE__ */ new Date(NaN);
117
- if (b.u(e2))
118
- return /* @__PURE__ */ new Date();
119
- if (e2 instanceof Date)
120
- return new Date(e2);
121
- if ("string" == typeof e2 && !/Z$/i.test(e2)) {
122
- var r2 = e2.match($);
123
- if (r2) {
124
- var i2 = r2[2] - 1 || 0, s2 = (r2[7] || "0").substring(0, 3);
125
- 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);
126
- }
127
- }
128
- return new Date(e2);
129
- }(t2), this.init();
130
- }, m2.init = function() {
131
- var t2 = this.$d;
132
- 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();
133
- }, m2.$utils = function() {
134
- return b;
135
- }, m2.isValid = function() {
136
- return !(this.$d.toString() === l);
137
- }, m2.isSame = function(t2, e2) {
138
- var n2 = O(t2);
139
- return this.startOf(e2) <= n2 && n2 <= this.endOf(e2);
140
- }, m2.isAfter = function(t2, e2) {
141
- return O(t2) < this.startOf(e2);
142
- }, m2.isBefore = function(t2, e2) {
143
- return this.endOf(e2) < O(t2);
144
- }, m2.$g = function(t2, e2, n2) {
145
- return b.u(t2) ? this[e2] : this.set(n2, t2);
146
- }, m2.unix = function() {
147
- return Math.floor(this.valueOf() / 1e3);
148
- }, m2.valueOf = function() {
149
- return this.$d.getTime();
150
- }, m2.startOf = function(t2, e2) {
151
- var n2 = this, r2 = !!b.u(e2) || e2, f2 = b.p(t2), l2 = function(t3, e3) {
152
- var i2 = b.w(n2.$u ? Date.UTC(n2.$y, e3, t3) : new Date(n2.$y, e3, t3), n2);
153
- return r2 ? i2 : i2.endOf(a);
154
- }, $2 = function(t3, e3) {
155
- return b.w(n2.toDate()[t3].apply(n2.toDate("s"), (r2 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e3)), n2);
156
- }, y2 = this.$W, M3 = this.$M, m3 = this.$D, v2 = "set" + (this.$u ? "UTC" : "");
157
- switch (f2) {
158
- case h:
159
- return r2 ? l2(1, 0) : l2(31, 11);
160
- case c:
161
- return r2 ? l2(1, M3) : l2(0, M3 + 1);
162
- case o:
163
- var g2 = this.$locale().weekStart || 0, D2 = (y2 < g2 ? y2 + 7 : y2) - g2;
164
- return l2(r2 ? m3 - D2 : m3 + (6 - D2), M3);
165
- case a:
166
- case d:
167
- return $2(v2 + "Hours", 0);
168
- case u:
169
- return $2(v2 + "Minutes", 1);
170
- case s:
171
- return $2(v2 + "Seconds", 2);
172
- case i:
173
- return $2(v2 + "Milliseconds", 3);
174
- default:
175
- return this.clone();
176
- }
177
- }, m2.endOf = function(t2) {
178
- return this.startOf(t2, false);
179
- }, m2.$set = function(t2, e2) {
180
- 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;
181
- if (o2 === c || o2 === h) {
182
- var y2 = this.clone().set(d, 1);
183
- y2.$d[l2]($2), y2.init(), this.$d = y2.set(d, Math.min(this.$D, y2.daysInMonth())).$d;
184
- } else
185
- l2 && this.$d[l2]($2);
186
- return this.init(), this;
187
- }, m2.set = function(t2, e2) {
188
- return this.clone().$set(t2, e2);
189
- }, m2.get = function(t2) {
190
- return this[b.p(t2)]();
191
- }, m2.add = function(r2, f2) {
192
- var d2, l2 = this;
193
- r2 = Number(r2);
194
- var $2 = b.p(f2), y2 = function(t2) {
195
- var e2 = O(l2);
196
- return b.w(e2.date(e2.date() + Math.round(t2 * r2)), l2);
197
- };
198
- if ($2 === c)
199
- return this.set(c, this.$M + r2);
200
- if ($2 === h)
201
- return this.set(h, this.$y + r2);
202
- if ($2 === a)
203
- return y2(1);
204
- if ($2 === o)
205
- return y2(7);
206
- var M3 = (d2 = {}, d2[s] = e, d2[u] = n, d2[i] = t, d2)[$2] || 1, m3 = this.$d.getTime() + r2 * M3;
207
- return b.w(m3, this);
208
- }, m2.subtract = function(t2, e2) {
209
- return this.add(-1 * t2, e2);
210
- }, m2.format = function(t2) {
211
- var e2 = this, n2 = this.$locale();
212
- if (!this.isValid())
213
- return n2.invalidDate || l;
214
- 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) {
215
- return t3 && (t3[n3] || t3(e2, r2)) || i3[n3].slice(0, s3);
216
- }, d2 = function(t3) {
217
- return b.s(s2 % 12 || 12, t3, "0");
218
- }, $2 = f2 || function(t3, e3, n3) {
219
- var r3 = t3 < 12 ? "AM" : "PM";
220
- return n3 ? r3.toLowerCase() : r3;
221
- };
222
- return r2.replace(y, function(t3, r3) {
223
- return r3 || function(t4) {
224
- switch (t4) {
225
- case "YY":
226
- return String(e2.$y).slice(-2);
227
- case "YYYY":
228
- return b.s(e2.$y, 4, "0");
229
- case "M":
230
- return a2 + 1;
231
- case "MM":
232
- return b.s(a2 + 1, 2, "0");
233
- case "MMM":
234
- return h2(n2.monthsShort, a2, c2, 3);
235
- case "MMMM":
236
- return h2(c2, a2);
237
- case "D":
238
- return e2.$D;
239
- case "DD":
240
- return b.s(e2.$D, 2, "0");
241
- case "d":
242
- return String(e2.$W);
243
- case "dd":
244
- return h2(n2.weekdaysMin, e2.$W, o2, 2);
245
- case "ddd":
246
- return h2(n2.weekdaysShort, e2.$W, o2, 3);
247
- case "dddd":
248
- return o2[e2.$W];
249
- case "H":
250
- return String(s2);
251
- case "HH":
252
- return b.s(s2, 2, "0");
253
- case "h":
254
- return d2(1);
255
- case "hh":
256
- return d2(2);
257
- case "a":
258
- return $2(s2, u2, true);
259
- case "A":
260
- return $2(s2, u2, false);
261
- case "m":
262
- return String(u2);
263
- case "mm":
264
- return b.s(u2, 2, "0");
265
- case "s":
266
- return String(e2.$s);
267
- case "ss":
268
- return b.s(e2.$s, 2, "0");
269
- case "SSS":
270
- return b.s(e2.$ms, 3, "0");
271
- case "Z":
272
- return i2;
273
- }
274
- return null;
275
- }(t3) || i2.replace(":", "");
276
- });
277
- }, m2.utcOffset = function() {
278
- return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
279
- }, m2.diff = function(r2, d2, l2) {
280
- var $2, y2 = this, M3 = b.p(d2), m3 = O(r2), v2 = (m3.utcOffset() - this.utcOffset()) * e, g2 = this - m3, D2 = function() {
281
- return b.m(y2, m3);
282
- };
283
- switch (M3) {
284
- case h:
285
- $2 = D2() / 12;
286
- break;
287
- case c:
288
- $2 = D2();
289
- break;
290
- case f:
291
- $2 = D2() / 3;
292
- break;
293
- case o:
294
- $2 = (g2 - v2) / 6048e5;
295
- break;
296
- case a:
297
- $2 = (g2 - v2) / 864e5;
298
- break;
299
- case u:
300
- $2 = g2 / n;
301
- break;
302
- case s:
303
- $2 = g2 / e;
304
- break;
305
- case i:
306
- $2 = g2 / t;
307
- break;
308
- default:
309
- $2 = g2;
310
- }
311
- return l2 ? $2 : b.a($2);
312
- }, m2.daysInMonth = function() {
313
- return this.endOf(c).$D;
314
- }, m2.$locale = function() {
315
- return D[this.$L];
316
- }, m2.locale = function(t2, e2) {
317
- if (!t2)
318
- return this.$L;
319
- var n2 = this.clone(), r2 = w(t2, e2, true);
320
- return r2 && (n2.$L = r2), n2;
321
- }, m2.clone = function() {
322
- return b.w(this.$d, this);
323
- }, m2.toDate = function() {
324
- return new Date(this.valueOf());
325
- }, m2.toJSON = function() {
326
- return this.isValid() ? this.toISOString() : null;
327
- }, m2.toISOString = function() {
328
- return this.$d.toISOString();
329
- }, m2.toString = function() {
330
- return this.$d.toUTCString();
331
- }, M2;
332
- }(), k = _.prototype;
333
- return O.prototype = k, [["$ms", r], ["$s", i], ["$m", s], ["$H", u], ["$W", a], ["$M", c], ["$y", h], ["$D", d]].forEach(function(t2) {
334
- k[t2[1]] = function(e2) {
335
- return this.$g(e2, t2[0], t2[1]);
50
+ var cache = _getRequireWildcardCache(nodeInterop);
51
+ if (cache && cache.has(obj)) {
52
+ return cache.get(obj);
53
+ }
54
+ var newObj = {
55
+ __proto__: null
336
56
  };
337
- }), O.extend = function(t2, e2) {
338
- return t2.$i || (t2(e2, _, O), t2.$i = true), O;
339
- }, O.locale = w, O.isDayjs = S, O.unix = function(t2) {
340
- return O(1e3 * t2);
341
- }, O.en = D[g], O.Ls = D, O.p = {}, O;
57
+ var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
58
+ for(var key in obj){
59
+ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
60
+ var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
61
+ if (desc && (desc.get || desc.set)) {
62
+ Object.defineProperty(newObj, key, desc);
63
+ } else {
64
+ newObj[key] = obj[key];
65
+ }
66
+ }
67
+ }
68
+ newObj.default = obj;
69
+ if (cache) {
70
+ cache.set(obj, newObj);
71
+ }
72
+ return newObj;
73
+ }
74
+ var __create = Object.create;
75
+ var __defProp = Object.defineProperty;
76
+ var __defProps = Object.defineProperties;
77
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
78
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
79
+ var __getOwnPropNames = Object.getOwnPropertyNames;
80
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
81
+ var __getProtoOf = Object.getPrototypeOf;
82
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
83
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
84
+ var __defNormalProp = (obj, key, value)=>key in obj ? __defProp(obj, key, {
85
+ enumerable: true,
86
+ configurable: true,
87
+ writable: true,
88
+ value
89
+ }) : obj[key] = value;
90
+ var __spreadValues = (a, b)=>{
91
+ for(var prop in b || (b = {}))if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]);
92
+ if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)){
93
+ if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]);
94
+ }
95
+ return a;
96
+ };
97
+ var __spreadProps = (a, b)=>__defProps(a, __getOwnPropDescs(b));
98
+ var __require = /* @__PURE__ */ ((x)=>typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
99
+ get: (a, b)=>(typeof require !== "undefined" ? require : a)[b]
100
+ }) : x)(function(x) {
101
+ if (typeof require !== "undefined") return require.apply(this, arguments);
102
+ throw Error('Dynamic require of "' + x + '" is not supported');
342
103
  });
343
- }
344
- });
345
-
346
- // ../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json
347
- var require_package = __commonJS({
348
- "../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json"(exports, module) {
349
- module.exports = {
350
- name: "dotenv",
351
- version: "16.4.5",
352
- description: "Loads environment variables from .env file",
353
- main: "lib/main.js",
354
- types: "lib/main.d.ts",
355
- exports: {
356
- ".": {
357
- types: "./lib/main.d.ts",
358
- require: "./lib/main.js",
359
- default: "./lib/main.js"
360
- },
361
- "./config": "./config.js",
362
- "./config.js": "./config.js",
363
- "./lib/env-options": "./lib/env-options.js",
364
- "./lib/env-options.js": "./lib/env-options.js",
365
- "./lib/cli-options": "./lib/cli-options.js",
366
- "./lib/cli-options.js": "./lib/cli-options.js",
367
- "./package.json": "./package.json"
368
- },
369
- scripts: {
370
- "dts-check": "tsc --project tests/types/tsconfig.json",
371
- lint: "standard",
372
- "lint-readme": "standard-markdown",
373
- pretest: "npm run lint && npm run dts-check",
374
- test: "tap tests/*.js --100 -Rspec",
375
- "test:coverage": "tap --coverage-report=lcov",
376
- prerelease: "npm test",
377
- release: "standard-version"
378
- },
379
- repository: {
380
- type: "git",
381
- url: "git://github.com/motdotla/dotenv.git"
382
- },
383
- funding: "https://dotenvx.com",
384
- keywords: [
385
- "dotenv",
386
- "env",
387
- ".env",
388
- "environment",
389
- "variables",
390
- "config",
391
- "settings"
392
- ],
393
- readmeFilename: "README.md",
394
- license: "BSD-2-Clause",
395
- devDependencies: {
396
- "@definitelytyped/dtslint": "^0.0.133",
397
- "@types/node": "^18.11.3",
398
- decache: "^4.6.1",
399
- sinon: "^14.0.1",
400
- standard: "^17.0.0",
401
- "standard-markdown": "^7.1.0",
402
- "standard-version": "^9.5.0",
403
- tap: "^16.3.0",
404
- tar: "^6.1.11",
405
- typescript: "^4.8.4"
406
- },
407
- engines: {
408
- node: ">=12"
409
- },
410
- browser: {
411
- fs: false
412
- }
104
+ var __commonJS = (cb, mod)=>function __require2() {
105
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = {
106
+ exports: {}
107
+ }).exports, mod), mod.exports;
108
+ };
109
+ var __copyProps = (to, from, except, desc)=>{
110
+ if (from && typeof from === "object" || typeof from === "function") {
111
+ for (let key of __getOwnPropNames(from))if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
112
+ get: ()=>from[key],
113
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
114
+ });
115
+ }
116
+ return to;
413
117
  };
414
- }
415
- });
416
-
417
- // ../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js
418
- var require_main = __commonJS({
419
- "../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js"(exports, module) {
420
- "use strict";
421
- var fs = __require("fs");
422
- var path2 = __require("path");
423
- var os = __require("os");
424
- var crypto = __require("crypto");
425
- var packageJson = require_package();
426
- var version = packageJson.version;
427
- var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
428
- function parse(src) {
429
- const obj = {};
430
- let lines = src.toString();
431
- lines = lines.replace(/\r\n?/mg, "\n");
432
- let match;
433
- while ((match = LINE.exec(lines)) != null) {
434
- const key = match[1];
435
- let value = match[2] || "";
436
- value = value.trim();
437
- const maybeQuote = value[0];
438
- value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
439
- if (maybeQuote === '"') {
440
- value = value.replace(/\\n/g, "\n");
441
- value = value.replace(/\\r/g, "\r");
118
+ 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
119
+ // file that has been converted to a CommonJS file using a Babel-
120
+ // compatible transform (i.e. "__esModule" has not been set), then set
121
+ // "default" to the CommonJS "module.exports" for node compatibility.
122
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
123
+ value: mod,
124
+ enumerable: true
125
+ }) : target, mod));
126
+ var __async = (__this, __arguments, generator)=>{
127
+ return new Promise((resolve, reject)=>{
128
+ var fulfilled = (value)=>{
129
+ try {
130
+ step(generator.next(value));
131
+ } catch (e) {
132
+ reject(e);
133
+ }
134
+ };
135
+ var rejected = (value)=>{
136
+ try {
137
+ step(generator.throw(value));
138
+ } catch (e) {
139
+ reject(e);
140
+ }
141
+ };
142
+ var step = (x)=>x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
143
+ step((generator = generator.apply(__this, __arguments)).next());
144
+ });
145
+ };
146
+ // ../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.js
147
+ var require_dayjs_min = __commonJS({
148
+ "../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.js" (exports, module1) {
149
+ "use strict";
150
+ !function(t, e) {
151
+ "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();
152
+ }(exports, function() {
153
+ "use strict";
154
+ 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 = {
155
+ name: "en",
156
+ weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
157
+ months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
158
+ ordinal: function(t2) {
159
+ var e2 = [
160
+ "th",
161
+ "st",
162
+ "nd",
163
+ "rd"
164
+ ], n2 = t2 % 100;
165
+ return "[" + t2 + (e2[(n2 - 20) % 10] || e2[n2] || e2[0]) + "]";
166
+ }
167
+ }, m = function(t2, e2, n2) {
168
+ var r2 = String(t2);
169
+ return !r2 || r2.length >= e2 ? t2 : "" + Array(e2 + 1 - r2.length).join(n2) + t2;
170
+ }, v = {
171
+ s: m,
172
+ z: function(t2) {
173
+ var e2 = -t2.utcOffset(), n2 = Math.abs(e2), r2 = Math.floor(n2 / 60), i2 = n2 % 60;
174
+ return (e2 <= 0 ? "+" : "-") + m(r2, 2, "0") + ":" + m(i2, 2, "0");
175
+ },
176
+ m: function t2(e2, n2) {
177
+ if (e2.date() < n2.date()) return -t2(n2, e2);
178
+ 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);
179
+ return +(-(r2 + (n2 - i2) / (s2 ? i2 - u2 : u2 - i2)) || 0);
180
+ },
181
+ a: function(t2) {
182
+ return t2 < 0 ? Math.ceil(t2) || 0 : Math.floor(t2);
183
+ },
184
+ p: function(t2) {
185
+ return ({
186
+ M: c,
187
+ y: h,
188
+ w: o,
189
+ d: a,
190
+ D: d,
191
+ h: u,
192
+ m: s,
193
+ s: i,
194
+ ms: r,
195
+ Q: f
196
+ })[t2] || String(t2 || "").toLowerCase().replace(/s$/, "");
197
+ },
198
+ u: function(t2) {
199
+ return void 0 === t2;
200
+ }
201
+ }, g = "en", D = {};
202
+ D[g] = M;
203
+ var p = "$isDayjsObject", S = function(t2) {
204
+ return t2 instanceof _ || !(!t2 || !t2[p]);
205
+ }, w = function t2(e2, n2, r2) {
206
+ var i2;
207
+ if (!e2) return g;
208
+ if ("string" == typeof e2) {
209
+ var s2 = e2.toLowerCase();
210
+ D[s2] && (i2 = s2), n2 && (D[s2] = n2, i2 = s2);
211
+ var u2 = e2.split("-");
212
+ if (!i2 && u2.length > 1) return t2(u2[0]);
213
+ } else {
214
+ var a2 = e2.name;
215
+ D[a2] = e2, i2 = a2;
216
+ }
217
+ return !r2 && i2 && (g = i2), i2 || !r2 && g;
218
+ }, O = function(t2, e2) {
219
+ if (S(t2)) return t2.clone();
220
+ var n2 = "object" == typeof e2 ? e2 : {};
221
+ return n2.date = t2, n2.args = arguments, new _(n2);
222
+ }, b = v;
223
+ b.l = w, b.i = S, b.w = function(t2, e2) {
224
+ return O(t2, {
225
+ locale: e2.$L,
226
+ utc: e2.$u,
227
+ x: e2.$x,
228
+ $offset: e2.$offset
229
+ });
230
+ };
231
+ var _ = function() {
232
+ function M2(t2) {
233
+ this.$L = w(t2.locale, null, true), this.parse(t2), this.$x = this.$x || t2.x || {}, this[p] = true;
234
+ }
235
+ var m2 = M2.prototype;
236
+ return m2.parse = function(t2) {
237
+ this.$d = function(t3) {
238
+ var e2 = t3.date, n2 = t3.utc;
239
+ if (null === e2) return /* @__PURE__ */ new Date(NaN);
240
+ if (b.u(e2)) return /* @__PURE__ */ new Date();
241
+ if (e2 instanceof Date) return new Date(e2);
242
+ if ("string" == typeof e2 && !/Z$/i.test(e2)) {
243
+ var r2 = e2.match($);
244
+ if (r2) {
245
+ var i2 = r2[2] - 1 || 0, s2 = (r2[7] || "0").substring(0, 3);
246
+ 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);
247
+ }
248
+ }
249
+ return new Date(e2);
250
+ }(t2), this.init();
251
+ }, m2.init = function() {
252
+ var t2 = this.$d;
253
+ 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();
254
+ }, m2.$utils = function() {
255
+ return b;
256
+ }, m2.isValid = function() {
257
+ return !(this.$d.toString() === l);
258
+ }, m2.isSame = function(t2, e2) {
259
+ var n2 = O(t2);
260
+ return this.startOf(e2) <= n2 && n2 <= this.endOf(e2);
261
+ }, m2.isAfter = function(t2, e2) {
262
+ return O(t2) < this.startOf(e2);
263
+ }, m2.isBefore = function(t2, e2) {
264
+ return this.endOf(e2) < O(t2);
265
+ }, m2.$g = function(t2, e2, n2) {
266
+ return b.u(t2) ? this[e2] : this.set(n2, t2);
267
+ }, m2.unix = function() {
268
+ return Math.floor(this.valueOf() / 1e3);
269
+ }, m2.valueOf = function() {
270
+ return this.$d.getTime();
271
+ }, m2.startOf = function(t2, e2) {
272
+ var n2 = this, r2 = !!b.u(e2) || e2, f2 = b.p(t2), l2 = function(t3, e3) {
273
+ var i2 = b.w(n2.$u ? Date.UTC(n2.$y, e3, t3) : new Date(n2.$y, e3, t3), n2);
274
+ return r2 ? i2 : i2.endOf(a);
275
+ }, $2 = function(t3, e3) {
276
+ return b.w(n2.toDate()[t3].apply(n2.toDate("s"), (r2 ? [
277
+ 0,
278
+ 0,
279
+ 0,
280
+ 0
281
+ ] : [
282
+ 23,
283
+ 59,
284
+ 59,
285
+ 999
286
+ ]).slice(e3)), n2);
287
+ }, y2 = this.$W, M3 = this.$M, m3 = this.$D, v2 = "set" + (this.$u ? "UTC" : "");
288
+ switch(f2){
289
+ case h:
290
+ return r2 ? l2(1, 0) : l2(31, 11);
291
+ case c:
292
+ return r2 ? l2(1, M3) : l2(0, M3 + 1);
293
+ case o:
294
+ var g2 = this.$locale().weekStart || 0, D2 = (y2 < g2 ? y2 + 7 : y2) - g2;
295
+ return l2(r2 ? m3 - D2 : m3 + (6 - D2), M3);
296
+ case a:
297
+ case d:
298
+ return $2(v2 + "Hours", 0);
299
+ case u:
300
+ return $2(v2 + "Minutes", 1);
301
+ case s:
302
+ return $2(v2 + "Seconds", 2);
303
+ case i:
304
+ return $2(v2 + "Milliseconds", 3);
305
+ default:
306
+ return this.clone();
307
+ }
308
+ }, m2.endOf = function(t2) {
309
+ return this.startOf(t2, false);
310
+ }, m2.$set = function(t2, e2) {
311
+ 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;
312
+ if (o2 === c || o2 === h) {
313
+ var y2 = this.clone().set(d, 1);
314
+ y2.$d[l2]($2), y2.init(), this.$d = y2.set(d, Math.min(this.$D, y2.daysInMonth())).$d;
315
+ } else l2 && this.$d[l2]($2);
316
+ return this.init(), this;
317
+ }, m2.set = function(t2, e2) {
318
+ return this.clone().$set(t2, e2);
319
+ }, m2.get = function(t2) {
320
+ return this[b.p(t2)]();
321
+ }, m2.add = function(r2, f2) {
322
+ var d2, l2 = this;
323
+ r2 = Number(r2);
324
+ var $2 = b.p(f2), y2 = function(t2) {
325
+ var e2 = O(l2);
326
+ return b.w(e2.date(e2.date() + Math.round(t2 * r2)), l2);
327
+ };
328
+ if ($2 === c) return this.set(c, this.$M + r2);
329
+ if ($2 === h) return this.set(h, this.$y + r2);
330
+ if ($2 === a) return y2(1);
331
+ if ($2 === o) return y2(7);
332
+ var M3 = (d2 = {}, d2[s] = e, d2[u] = n, d2[i] = t, d2)[$2] || 1, m3 = this.$d.getTime() + r2 * M3;
333
+ return b.w(m3, this);
334
+ }, m2.subtract = function(t2, e2) {
335
+ return this.add(-1 * t2, e2);
336
+ }, m2.format = function(t2) {
337
+ var e2 = this, n2 = this.$locale();
338
+ if (!this.isValid()) return n2.invalidDate || l;
339
+ 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) {
340
+ return t3 && (t3[n3] || t3(e2, r2)) || i3[n3].slice(0, s3);
341
+ }, d2 = function(t3) {
342
+ return b.s(s2 % 12 || 12, t3, "0");
343
+ }, $2 = f2 || function(t3, e3, n3) {
344
+ var r3 = t3 < 12 ? "AM" : "PM";
345
+ return n3 ? r3.toLowerCase() : r3;
346
+ };
347
+ return r2.replace(y, function(t3, r3) {
348
+ return r3 || function(t4) {
349
+ switch(t4){
350
+ case "YY":
351
+ return String(e2.$y).slice(-2);
352
+ case "YYYY":
353
+ return b.s(e2.$y, 4, "0");
354
+ case "M":
355
+ return a2 + 1;
356
+ case "MM":
357
+ return b.s(a2 + 1, 2, "0");
358
+ case "MMM":
359
+ return h2(n2.monthsShort, a2, c2, 3);
360
+ case "MMMM":
361
+ return h2(c2, a2);
362
+ case "D":
363
+ return e2.$D;
364
+ case "DD":
365
+ return b.s(e2.$D, 2, "0");
366
+ case "d":
367
+ return String(e2.$W);
368
+ case "dd":
369
+ return h2(n2.weekdaysMin, e2.$W, o2, 2);
370
+ case "ddd":
371
+ return h2(n2.weekdaysShort, e2.$W, o2, 3);
372
+ case "dddd":
373
+ return o2[e2.$W];
374
+ case "H":
375
+ return String(s2);
376
+ case "HH":
377
+ return b.s(s2, 2, "0");
378
+ case "h":
379
+ return d2(1);
380
+ case "hh":
381
+ return d2(2);
382
+ case "a":
383
+ return $2(s2, u2, true);
384
+ case "A":
385
+ return $2(s2, u2, false);
386
+ case "m":
387
+ return String(u2);
388
+ case "mm":
389
+ return b.s(u2, 2, "0");
390
+ case "s":
391
+ return String(e2.$s);
392
+ case "ss":
393
+ return b.s(e2.$s, 2, "0");
394
+ case "SSS":
395
+ return b.s(e2.$ms, 3, "0");
396
+ case "Z":
397
+ return i2;
398
+ }
399
+ return null;
400
+ }(t3) || i2.replace(":", "");
401
+ });
402
+ }, m2.utcOffset = function() {
403
+ return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
404
+ }, m2.diff = function(r2, d2, l2) {
405
+ var $2, y2 = this, M3 = b.p(d2), m3 = O(r2), v2 = (m3.utcOffset() - this.utcOffset()) * e, g2 = this - m3, D2 = function() {
406
+ return b.m(y2, m3);
407
+ };
408
+ switch(M3){
409
+ case h:
410
+ $2 = D2() / 12;
411
+ break;
412
+ case c:
413
+ $2 = D2();
414
+ break;
415
+ case f:
416
+ $2 = D2() / 3;
417
+ break;
418
+ case o:
419
+ $2 = (g2 - v2) / 6048e5;
420
+ break;
421
+ case a:
422
+ $2 = (g2 - v2) / 864e5;
423
+ break;
424
+ case u:
425
+ $2 = g2 / n;
426
+ break;
427
+ case s:
428
+ $2 = g2 / e;
429
+ break;
430
+ case i:
431
+ $2 = g2 / t;
432
+ break;
433
+ default:
434
+ $2 = g2;
435
+ }
436
+ return l2 ? $2 : b.a($2);
437
+ }, m2.daysInMonth = function() {
438
+ return this.endOf(c).$D;
439
+ }, m2.$locale = function() {
440
+ return D[this.$L];
441
+ }, m2.locale = function(t2, e2) {
442
+ if (!t2) return this.$L;
443
+ var n2 = this.clone(), r2 = w(t2, e2, true);
444
+ return r2 && (n2.$L = r2), n2;
445
+ }, m2.clone = function() {
446
+ return b.w(this.$d, this);
447
+ }, m2.toDate = function() {
448
+ return new Date(this.valueOf());
449
+ }, m2.toJSON = function() {
450
+ return this.isValid() ? this.toISOString() : null;
451
+ }, m2.toISOString = function() {
452
+ return this.$d.toISOString();
453
+ }, m2.toString = function() {
454
+ return this.$d.toUTCString();
455
+ }, M2;
456
+ }(), k = _.prototype;
457
+ return O.prototype = k, [
458
+ [
459
+ "$ms",
460
+ r
461
+ ],
462
+ [
463
+ "$s",
464
+ i
465
+ ],
466
+ [
467
+ "$m",
468
+ s
469
+ ],
470
+ [
471
+ "$H",
472
+ u
473
+ ],
474
+ [
475
+ "$W",
476
+ a
477
+ ],
478
+ [
479
+ "$M",
480
+ c
481
+ ],
482
+ [
483
+ "$y",
484
+ h
485
+ ],
486
+ [
487
+ "$D",
488
+ d
489
+ ]
490
+ ].forEach(function(t2) {
491
+ k[t2[1]] = function(e2) {
492
+ return this.$g(e2, t2[0], t2[1]);
493
+ };
494
+ }), O.extend = function(t2, e2) {
495
+ return t2.$i || (t2(e2, _, O), t2.$i = true), O;
496
+ }, O.locale = w, O.isDayjs = S, O.unix = function(t2) {
497
+ return O(1e3 * t2);
498
+ }, O.en = D[g], O.Ls = D, O.p = {}, O;
499
+ });
442
500
  }
443
- obj[key] = value;
444
- }
445
- return obj;
446
- }
447
- function _parseVault(options) {
448
- const vaultPath = _vaultPath(options);
449
- const result = DotenvModule.configDotenv({ path: vaultPath });
450
- if (!result.parsed) {
451
- const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
452
- err.code = "MISSING_DATA";
453
- throw err;
454
- }
455
- const keys = _dotenvKey(options).split(",");
456
- const length = keys.length;
457
- let decrypted;
458
- for (let i = 0; i < length; i++) {
459
- try {
460
- const key = keys[i].trim();
461
- const attrs = _instructions(result, key);
462
- decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
463
- break;
464
- } catch (error) {
465
- if (i + 1 >= length) {
466
- throw error;
467
- }
501
+ });
502
+ // ../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json
503
+ var require_package = __commonJS({
504
+ "../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/package.json" (exports, module1) {
505
+ module1.exports = {
506
+ name: "dotenv",
507
+ version: "16.4.5",
508
+ description: "Loads environment variables from .env file",
509
+ main: "lib/main.js",
510
+ types: "lib/main.d.ts",
511
+ exports: {
512
+ ".": {
513
+ types: "./lib/main.d.ts",
514
+ require: "./lib/main.js",
515
+ default: "./lib/main.js"
516
+ },
517
+ "./config": "./config.js",
518
+ "./config.js": "./config.js",
519
+ "./lib/env-options": "./lib/env-options.js",
520
+ "./lib/env-options.js": "./lib/env-options.js",
521
+ "./lib/cli-options": "./lib/cli-options.js",
522
+ "./lib/cli-options.js": "./lib/cli-options.js",
523
+ "./package.json": "./package.json"
524
+ },
525
+ scripts: {
526
+ "dts-check": "tsc --project tests/types/tsconfig.json",
527
+ lint: "standard",
528
+ "lint-readme": "standard-markdown",
529
+ pretest: "npm run lint && npm run dts-check",
530
+ test: "tap tests/*.js --100 -Rspec",
531
+ "test:coverage": "tap --coverage-report=lcov",
532
+ prerelease: "npm test",
533
+ release: "standard-version"
534
+ },
535
+ repository: {
536
+ type: "git",
537
+ url: "git://github.com/motdotla/dotenv.git"
538
+ },
539
+ funding: "https://dotenvx.com",
540
+ keywords: [
541
+ "dotenv",
542
+ "env",
543
+ ".env",
544
+ "environment",
545
+ "variables",
546
+ "config",
547
+ "settings"
548
+ ],
549
+ readmeFilename: "README.md",
550
+ license: "BSD-2-Clause",
551
+ devDependencies: {
552
+ "@definitelytyped/dtslint": "^0.0.133",
553
+ "@types/node": "^18.11.3",
554
+ decache: "^4.6.1",
555
+ sinon: "^14.0.1",
556
+ standard: "^17.0.0",
557
+ "standard-markdown": "^7.1.0",
558
+ "standard-version": "^9.5.0",
559
+ tap: "^16.3.0",
560
+ tar: "^6.1.11",
561
+ typescript: "^4.8.4"
562
+ },
563
+ engines: {
564
+ node: ">=12"
565
+ },
566
+ browser: {
567
+ fs: false
568
+ }
569
+ };
468
570
  }
469
- }
470
- return DotenvModule.parse(decrypted);
471
- }
472
- function _log(message) {
473
- console.log(`[dotenv@${version}][INFO] ${message}`);
474
- }
475
- function _warn(message) {
476
- console.log(`[dotenv@${version}][WARN] ${message}`);
477
- }
478
- function _debug(message) {
479
- console.log(`[dotenv@${version}][DEBUG] ${message}`);
480
- }
481
- function _dotenvKey(options) {
482
- if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
483
- return options.DOTENV_KEY;
484
- }
485
- if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
486
- return process.env.DOTENV_KEY;
487
- }
488
- return "";
489
- }
490
- function _instructions(result, dotenvKey) {
491
- let uri;
492
- try {
493
- uri = new URL(dotenvKey);
494
- } catch (error) {
495
- if (error.code === "ERR_INVALID_URL") {
496
- const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
497
- err.code = "INVALID_DOTENV_KEY";
498
- throw err;
571
+ });
572
+ // ../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js
573
+ var require_main = __commonJS({
574
+ "../../node_modules/.pnpm/dotenv@16.4.5/node_modules/dotenv/lib/main.js" (exports, module1) {
575
+ "use strict";
576
+ var fs = __require("fs");
577
+ var path2 = __require("path");
578
+ var os = __require("os");
579
+ var crypto = __require("crypto");
580
+ var packageJson = require_package();
581
+ var version = packageJson.version;
582
+ var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
583
+ function parse(src) {
584
+ const obj = {};
585
+ let lines = src.toString();
586
+ lines = lines.replace(/\r\n?/mg, "\n");
587
+ let match;
588
+ while((match = LINE.exec(lines)) != null){
589
+ const key = match[1];
590
+ let value = match[2] || "";
591
+ value = value.trim();
592
+ const maybeQuote = value[0];
593
+ value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
594
+ if (maybeQuote === '"') {
595
+ value = value.replace(/\\n/g, "\n");
596
+ value = value.replace(/\\r/g, "\r");
597
+ }
598
+ obj[key] = value;
599
+ }
600
+ return obj;
601
+ }
602
+ function _parseVault(options) {
603
+ const vaultPath = _vaultPath(options);
604
+ const result = DotenvModule.configDotenv({
605
+ path: vaultPath
606
+ });
607
+ if (!result.parsed) {
608
+ const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
609
+ err.code = "MISSING_DATA";
610
+ throw err;
611
+ }
612
+ const keys = _dotenvKey(options).split(",");
613
+ const length = keys.length;
614
+ let decrypted;
615
+ for(let i = 0; i < length; i++){
616
+ try {
617
+ const key = keys[i].trim();
618
+ const attrs = _instructions(result, key);
619
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
620
+ break;
621
+ } catch (error) {
622
+ if (i + 1 >= length) {
623
+ throw error;
624
+ }
625
+ }
626
+ }
627
+ return DotenvModule.parse(decrypted);
628
+ }
629
+ function _log(message) {
630
+ console.log(`[dotenv@${version}][INFO] ${message}`);
631
+ }
632
+ function _warn(message) {
633
+ console.log(`[dotenv@${version}][WARN] ${message}`);
634
+ }
635
+ function _debug(message) {
636
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
637
+ }
638
+ function _dotenvKey(options) {
639
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
640
+ return options.DOTENV_KEY;
641
+ }
642
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
643
+ return process.env.DOTENV_KEY;
644
+ }
645
+ return "";
646
+ }
647
+ function _instructions(result, dotenvKey) {
648
+ let uri;
649
+ try {
650
+ uri = new URL(dotenvKey);
651
+ } catch (error) {
652
+ if (error.code === "ERR_INVALID_URL") {
653
+ const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
654
+ err.code = "INVALID_DOTENV_KEY";
655
+ throw err;
656
+ }
657
+ throw error;
658
+ }
659
+ const key = uri.password;
660
+ if (!key) {
661
+ const err = new Error("INVALID_DOTENV_KEY: Missing key part");
662
+ err.code = "INVALID_DOTENV_KEY";
663
+ throw err;
664
+ }
665
+ const environment = uri.searchParams.get("environment");
666
+ if (!environment) {
667
+ const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
668
+ err.code = "INVALID_DOTENV_KEY";
669
+ throw err;
670
+ }
671
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
672
+ const ciphertext = result.parsed[environmentKey];
673
+ if (!ciphertext) {
674
+ const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
675
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
676
+ throw err;
677
+ }
678
+ return {
679
+ ciphertext,
680
+ key
681
+ };
682
+ }
683
+ function _vaultPath(options) {
684
+ let possibleVaultPath = null;
685
+ if (options && options.path && options.path.length > 0) {
686
+ if (Array.isArray(options.path)) {
687
+ for (const filepath of options.path){
688
+ if (fs.existsSync(filepath)) {
689
+ possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
690
+ }
691
+ }
692
+ } else {
693
+ possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
694
+ }
695
+ } else {
696
+ possibleVaultPath = path2.resolve(process.cwd(), ".env.vault");
697
+ }
698
+ if (fs.existsSync(possibleVaultPath)) {
699
+ return possibleVaultPath;
700
+ }
701
+ return null;
702
+ }
703
+ function _resolveHome(envPath) {
704
+ return envPath[0] === "~" ? path2.join(os.homedir(), envPath.slice(1)) : envPath;
705
+ }
706
+ function _configVault(options) {
707
+ _log("Loading env from encrypted .env.vault");
708
+ const parsed = DotenvModule._parseVault(options);
709
+ let processEnv = process.env;
710
+ if (options && options.processEnv != null) {
711
+ processEnv = options.processEnv;
712
+ }
713
+ DotenvModule.populate(processEnv, parsed, options);
714
+ return {
715
+ parsed
716
+ };
717
+ }
718
+ function configDotenv(options) {
719
+ const dotenvPath = path2.resolve(process.cwd(), ".env");
720
+ let encoding = "utf8";
721
+ const debug = Boolean(options && options.debug);
722
+ if (options && options.encoding) {
723
+ encoding = options.encoding;
724
+ } else {
725
+ if (debug) {
726
+ _debug("No encoding is specified. UTF-8 is used by default");
727
+ }
728
+ }
729
+ let optionPaths = [
730
+ dotenvPath
731
+ ];
732
+ if (options && options.path) {
733
+ if (!Array.isArray(options.path)) {
734
+ optionPaths = [
735
+ _resolveHome(options.path)
736
+ ];
737
+ } else {
738
+ optionPaths = [];
739
+ for (const filepath of options.path){
740
+ optionPaths.push(_resolveHome(filepath));
741
+ }
742
+ }
743
+ }
744
+ let lastError;
745
+ const parsedAll = {};
746
+ for (const path3 of optionPaths){
747
+ try {
748
+ const parsed = DotenvModule.parse(fs.readFileSync(path3, {
749
+ encoding
750
+ }));
751
+ DotenvModule.populate(parsedAll, parsed, options);
752
+ } catch (e) {
753
+ if (debug) {
754
+ _debug(`Failed to load ${path3} ${e.message}`);
755
+ }
756
+ lastError = e;
757
+ }
758
+ }
759
+ let processEnv = process.env;
760
+ if (options && options.processEnv != null) {
761
+ processEnv = options.processEnv;
762
+ }
763
+ DotenvModule.populate(processEnv, parsedAll, options);
764
+ if (lastError) {
765
+ return {
766
+ parsed: parsedAll,
767
+ error: lastError
768
+ };
769
+ } else {
770
+ return {
771
+ parsed: parsedAll
772
+ };
773
+ }
774
+ }
775
+ function config(options) {
776
+ if (_dotenvKey(options).length === 0) {
777
+ return DotenvModule.configDotenv(options);
778
+ }
779
+ const vaultPath = _vaultPath(options);
780
+ if (!vaultPath) {
781
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
782
+ return DotenvModule.configDotenv(options);
783
+ }
784
+ return DotenvModule._configVault(options);
785
+ }
786
+ function decrypt(encrypted, keyStr) {
787
+ const key = Buffer.from(keyStr.slice(-64), "hex");
788
+ let ciphertext = Buffer.from(encrypted, "base64");
789
+ const nonce = ciphertext.subarray(0, 12);
790
+ const authTag = ciphertext.subarray(-16);
791
+ ciphertext = ciphertext.subarray(12, -16);
792
+ try {
793
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
794
+ aesgcm.setAuthTag(authTag);
795
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
796
+ } catch (error) {
797
+ const isRange = error instanceof RangeError;
798
+ const invalidKeyLength = error.message === "Invalid key length";
799
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
800
+ if (isRange || invalidKeyLength) {
801
+ const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
802
+ err.code = "INVALID_DOTENV_KEY";
803
+ throw err;
804
+ } else if (decryptionFailed) {
805
+ const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
806
+ err.code = "DECRYPTION_FAILED";
807
+ throw err;
808
+ } else {
809
+ throw error;
810
+ }
811
+ }
812
+ }
813
+ function populate(processEnv, parsed, options = {}) {
814
+ const debug = Boolean(options && options.debug);
815
+ const override = Boolean(options && options.override);
816
+ if (typeof parsed !== "object") {
817
+ const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
818
+ err.code = "OBJECT_REQUIRED";
819
+ throw err;
820
+ }
821
+ for (const key of Object.keys(parsed)){
822
+ if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
823
+ if (override === true) {
824
+ processEnv[key] = parsed[key];
825
+ }
826
+ if (debug) {
827
+ if (override === true) {
828
+ _debug(`"${key}" is already defined and WAS overwritten`);
829
+ } else {
830
+ _debug(`"${key}" is already defined and was NOT overwritten`);
831
+ }
832
+ }
833
+ } else {
834
+ processEnv[key] = parsed[key];
835
+ }
836
+ }
837
+ }
838
+ var DotenvModule = {
839
+ configDotenv,
840
+ _configVault,
841
+ _parseVault,
842
+ config,
843
+ decrypt,
844
+ parse,
845
+ populate
846
+ };
847
+ module1.exports.configDotenv = DotenvModule.configDotenv;
848
+ module1.exports._configVault = DotenvModule._configVault;
849
+ module1.exports._parseVault = DotenvModule._parseVault;
850
+ module1.exports.config = DotenvModule.config;
851
+ module1.exports.decrypt = DotenvModule.decrypt;
852
+ module1.exports.parse = DotenvModule.parse;
853
+ module1.exports.populate = DotenvModule.populate;
854
+ module1.exports = DotenvModule;
855
+ }
856
+ });
857
+ // src/common/utils.ts
858
+ var import_dayjs = __toESM(require_dayjs_min());
859
+ // src/web-element.ts
860
+ var WebElementInfo = class {
861
+ constructor({ content, rect, page, locator, id, attributes, indexId }){
862
+ this.content = content;
863
+ this.rect = rect;
864
+ this.center = [
865
+ Math.floor(rect.left + rect.width / 2),
866
+ Math.floor(rect.top + rect.height / 2)
867
+ ];
868
+ this.page = page;
869
+ this.locator = locator;
870
+ this.id = id;
871
+ this.attributes = attributes;
872
+ this.indexId = indexId;
499
873
  }
500
- throw error;
501
- }
502
- const key = uri.password;
503
- if (!key) {
504
- const err = new Error("INVALID_DOTENV_KEY: Missing key part");
505
- err.code = "INVALID_DOTENV_KEY";
506
- throw err;
507
- }
508
- const environment = uri.searchParams.get("environment");
509
- if (!environment) {
510
- const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
511
- err.code = "INVALID_DOTENV_KEY";
512
- throw err;
513
- }
514
- const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
515
- const ciphertext = result.parsed[environmentKey];
516
- if (!ciphertext) {
517
- const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
518
- err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
519
- throw err;
520
- }
521
- return { ciphertext, key };
874
+ };
875
+ // src/common/utils.ts
876
+ function parseContextFromWebPage(page, _opt) {
877
+ return __async(this, null, function*() {
878
+ (0, _assert.default)(page, "page is required");
879
+ if (page._forceUsePageContext) {
880
+ return yield page._forceUsePageContext();
881
+ }
882
+ const url = yield page.url();
883
+ let screenshotBase64;
884
+ let elementsInfo;
885
+ yield Promise.all([
886
+ page.screenshotBase64().then((base64)=>{
887
+ screenshotBase64 = base64;
888
+ }),
889
+ page.getElementInfos().then((snapshot)=>__async(this, null, function*() {
890
+ elementsInfo = yield alignElements(snapshot, page);
891
+ }))
892
+ ]);
893
+ (0, _assert.default)(screenshotBase64, "screenshotBase64 is required");
894
+ const elementsPositionInfoWithoutText = elementsInfo.filter((elementInfo)=>{
895
+ if (elementInfo.attributes.nodeType === _constants.NodeType.TEXT) {
896
+ return false;
897
+ }
898
+ return true;
899
+ });
900
+ const size = yield page.size();
901
+ const width = size.width;
902
+ const height = size.height;
903
+ const screenshotBase64WithElementMarker = (_opt == null ? void 0 : _opt.ignoreMarker) ? void 0 : yield (0, _img.compositeElementInfoImg)({
904
+ inputImgBase64: screenshotBase64,
905
+ elementsPositionInfo: elementsPositionInfoWithoutText,
906
+ size: {
907
+ width,
908
+ height
909
+ }
910
+ });
911
+ return {
912
+ content: elementsInfo,
913
+ size: {
914
+ width,
915
+ height
916
+ },
917
+ screenshotBase64,
918
+ screenshotBase64WithElementMarker,
919
+ url
920
+ };
921
+ });
522
922
  }
523
- function _vaultPath(options) {
524
- let possibleVaultPath = null;
525
- if (options && options.path && options.path.length > 0) {
526
- if (Array.isArray(options.path)) {
527
- for (const filepath of options.path) {
528
- if (fs.existsSync(filepath)) {
529
- possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
923
+ var sizeThreshold = 3;
924
+ function alignElements(elements, page) {
925
+ return __async(this, null, function*() {
926
+ const validElements = elements.filter((item)=>{
927
+ return item.rect.height >= sizeThreshold && item.rect.width >= sizeThreshold;
928
+ });
929
+ const textsAligned = [];
930
+ for (const item of validElements){
931
+ const { rect, id, content, attributes, locator, indexId } = item;
932
+ textsAligned.push(new WebElementInfo({
933
+ rect,
934
+ locator,
935
+ id,
936
+ content,
937
+ attributes,
938
+ page,
939
+ indexId
940
+ }));
530
941
  }
531
- }
532
- } else {
533
- possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
534
- }
535
- } else {
536
- possibleVaultPath = path2.resolve(process.cwd(), ".env.vault");
537
- }
538
- if (fs.existsSync(possibleVaultPath)) {
539
- return possibleVaultPath;
540
- }
541
- return null;
942
+ return textsAligned;
943
+ });
542
944
  }
543
- function _resolveHome(envPath) {
544
- return envPath[0] === "~" ? path2.join(os.homedir(), envPath.slice(1)) : envPath;
945
+ function reportFileName(tag = "web") {
946
+ const dateTimeInFileName = (0, import_dayjs.default)().format("YYYY-MM-DD_HH-mm-ss-SSS");
947
+ return `${tag}-${dateTimeInFileName}`;
545
948
  }
546
- function _configVault(options) {
547
- _log("Loading env from encrypted .env.vault");
548
- const parsed = DotenvModule._parseVault(options);
549
- let processEnv = process.env;
550
- if (options && options.processEnv != null) {
551
- processEnv = options.processEnv;
552
- }
553
- DotenvModule.populate(processEnv, parsed, options);
554
- return { parsed };
949
+ function printReportMsg(filepath) {
950
+ console.log("Midscene - report file updated:", filepath);
555
951
  }
556
- function configDotenv(options) {
557
- const dotenvPath = path2.resolve(process.cwd(), ".env");
558
- let encoding = "utf8";
559
- const debug = Boolean(options && options.debug);
560
- if (options && options.encoding) {
561
- encoding = options.encoding;
562
- } else {
563
- if (debug) {
564
- _debug("No encoding is specified. UTF-8 is used by default");
565
- }
566
- }
567
- let optionPaths = [dotenvPath];
568
- if (options && options.path) {
569
- if (!Array.isArray(options.path)) {
570
- optionPaths = [_resolveHome(options.path)];
571
- } else {
572
- optionPaths = [];
573
- for (const filepath of options.path) {
574
- optionPaths.push(_resolveHome(filepath));
575
- }
576
- }
577
- }
578
- let lastError;
579
- const parsedAll = {};
580
- for (const path3 of optionPaths) {
581
- try {
582
- const parsed = DotenvModule.parse(fs.readFileSync(path3, { encoding }));
583
- DotenvModule.populate(parsedAll, parsed, options);
584
- } catch (e) {
585
- if (debug) {
586
- _debug(`Failed to load ${path3} ${e.message}`);
587
- }
588
- lastError = e;
952
+ function getCurrentExecutionFile(trace) {
953
+ const error = new Error();
954
+ const stackTrace = trace || error.stack;
955
+ const pkgDir = process.cwd() || "";
956
+ if (stackTrace) {
957
+ const stackLines = stackTrace.split("\n");
958
+ for (const line of stackLines){
959
+ if (line.includes(".spec.") || line.includes(".test.") || line.includes(".ts") || line.includes(".js")) {
960
+ const match = line.match(/(?:at\s+)?(.*?\.(?:spec|test)\.[jt]s)/);
961
+ if (match == null ? void 0 : match[1]) {
962
+ const targetFileName = match[1].replace(pkgDir, "").trim().replace("at ", "");
963
+ return targetFileName;
964
+ }
965
+ }
966
+ }
589
967
  }
590
- }
591
- let processEnv = process.env;
592
- if (options && options.processEnv != null) {
593
- processEnv = options.processEnv;
594
- }
595
- DotenvModule.populate(processEnv, parsedAll, options);
596
- if (lastError) {
597
- return { parsed: parsedAll, error: lastError };
598
- } else {
599
- return { parsed: parsedAll };
600
- }
601
- }
602
- function config(options) {
603
- if (_dotenvKey(options).length === 0) {
604
- return DotenvModule.configDotenv(options);
605
- }
606
- const vaultPath = _vaultPath(options);
607
- if (!vaultPath) {
608
- _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
609
- return DotenvModule.configDotenv(options);
610
- }
611
- return DotenvModule._configVault(options);
968
+ return false;
612
969
  }
613
- function decrypt(encrypted, keyStr) {
614
- const key = Buffer.from(keyStr.slice(-64), "hex");
615
- let ciphertext = Buffer.from(encrypted, "base64");
616
- const nonce = ciphertext.subarray(0, 12);
617
- const authTag = ciphertext.subarray(-16);
618
- ciphertext = ciphertext.subarray(12, -16);
619
- try {
620
- const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
621
- aesgcm.setAuthTag(authTag);
622
- return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
623
- } catch (error) {
624
- const isRange = error instanceof RangeError;
625
- const invalidKeyLength = error.message === "Invalid key length";
626
- const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
627
- if (isRange || invalidKeyLength) {
628
- const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
629
- err.code = "INVALID_DOTENV_KEY";
630
- throw err;
631
- } else if (decryptionFailed) {
632
- const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
633
- err.code = "DECRYPTION_FAILED";
634
- throw err;
635
- } else {
636
- throw error;
970
+ var testFileIndex = /* @__PURE__ */ new Map();
971
+ function generateCacheId(fileName) {
972
+ let taskFile = fileName || getCurrentExecutionFile();
973
+ if (!taskFile) {
974
+ taskFile = (0, _utils.uuid)();
975
+ console.warn("Midscene - using random UUID for cache id. Cache may be invalid.");
637
976
  }
638
- }
639
- }
640
- function populate(processEnv, parsed, options = {}) {
641
- const debug = Boolean(options && options.debug);
642
- const override = Boolean(options && options.override);
643
- if (typeof parsed !== "object") {
644
- const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
645
- err.code = "OBJECT_REQUIRED";
646
- throw err;
647
- }
648
- for (const key of Object.keys(parsed)) {
649
- if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
650
- if (override === true) {
651
- processEnv[key] = parsed[key];
652
- }
653
- if (debug) {
654
- if (override === true) {
655
- _debug(`"${key}" is already defined and WAS overwritten`);
656
- } else {
657
- _debug(`"${key}" is already defined and was NOT overwritten`);
977
+ if (testFileIndex.has(taskFile)) {
978
+ const currentIndex = testFileIndex.get(taskFile);
979
+ if (currentIndex !== void 0) {
980
+ testFileIndex.set(taskFile, currentIndex + 1);
658
981
  }
659
- }
660
982
  } else {
661
- processEnv[key] = parsed[key];
662
- }
663
- }
664
- }
665
- var DotenvModule = {
666
- configDotenv,
667
- _configVault,
668
- _parseVault,
669
- config,
670
- decrypt,
671
- parse,
672
- populate
673
- };
674
- module.exports.configDotenv = DotenvModule.configDotenv;
675
- module.exports._configVault = DotenvModule._configVault;
676
- module.exports._parseVault = DotenvModule._parseVault;
677
- module.exports.config = DotenvModule.config;
678
- module.exports.decrypt = DotenvModule.decrypt;
679
- module.exports.parse = DotenvModule.parse;
680
- module.exports.populate = DotenvModule.populate;
681
- module.exports = DotenvModule;
682
- }
683
- });
684
-
685
- // src/playground/server.ts
686
- import assert3 from "assert";
687
- import { randomUUID as randomUUID2 } from "crypto";
688
- import { existsSync as existsSync2, readFileSync as readFileSync3, writeFileSync } from "fs";
689
- import { join as join2 } from "path";
690
-
691
- // src/common/utils.ts
692
- var import_dayjs = __toESM(require_dayjs_min());
693
- import assert from "assert";
694
- import { randomUUID } from "crypto";
695
- import { readFileSync } from "fs";
696
- import path from "path";
697
- import { NodeType } from "@midscene/shared/constants";
698
- import { findNearestPackageJson } from "@midscene/shared/fs";
699
- import {
700
- base64Encoded,
701
- imageInfoOfBase64
702
- } from "@midscene/shared/img";
703
- import { compositeElementInfoImg } from "@midscene/shared/img";
704
-
705
- // src/web-element.ts
706
- var WebElementInfo = class {
707
- constructor({
708
- content,
709
- rect,
710
- page,
711
- locator,
712
- id,
713
- attributes,
714
- indexId
715
- }) {
716
- this.content = content;
717
- this.rect = rect;
718
- this.center = [
719
- Math.floor(rect.left + rect.width / 2),
720
- Math.floor(rect.top + rect.height / 2)
721
- ];
722
- this.page = page;
723
- this.locator = locator;
724
- this.id = id;
725
- this.attributes = attributes;
726
- this.indexId = indexId;
727
- }
728
- };
729
-
730
- // src/common/utils.ts
731
- async function parseContextFromWebPage(page, _opt) {
732
- assert(page, "page is required");
733
- if (page._forceUsePageContext) {
734
- return await page._forceUsePageContext();
735
- }
736
- const url = page.url();
737
- const file = await page.screenshot();
738
- const screenshotBase64 = base64Encoded(file);
739
- const captureElementSnapshot = await page.getElementInfos();
740
- const elementsInfo = await alignElements(captureElementSnapshot, page);
741
- const elementsPositionInfoWithoutText = elementsInfo.filter((elementInfo) => {
742
- if (elementInfo.attributes.nodeType === NodeType.TEXT) {
743
- return false;
744
- }
745
- return true;
746
- });
747
- const size = await imageInfoOfBase64(screenshotBase64);
748
- const screenshotBase64WithElementMarker = await compositeElementInfoImg({
749
- inputImgBase64: screenshotBase64.split(";base64,").pop(),
750
- elementsPositionInfo: elementsPositionInfoWithoutText
751
- });
752
- return {
753
- content: elementsInfo,
754
- size,
755
- screenshotBase64,
756
- screenshotBase64WithElementMarker: `data:image/png;base64,${screenshotBase64WithElementMarker}`,
757
- url
758
- };
759
- }
760
- var sizeThreshold = 3;
761
- async function alignElements(elements, page) {
762
- const validElements = elements.filter((item) => {
763
- return item.rect.height >= sizeThreshold && item.rect.width >= sizeThreshold;
764
- });
765
- const textsAligned = [];
766
- for (const item of validElements) {
767
- const { rect, id, content, attributes, locator, indexId } = item;
768
- textsAligned.push(
769
- new WebElementInfo({
770
- rect,
771
- locator,
772
- id,
773
- content,
774
- attributes,
775
- page,
776
- indexId
777
- })
778
- );
779
- }
780
- return textsAligned;
781
- }
782
- function reportFileName(tag = "web") {
783
- const dateTimeInFileName = (0, import_dayjs.default)().format("YYYY-MM-DD_HH-mm-ss-SSS");
784
- return `${tag}-${dateTimeInFileName}`;
785
- }
786
- function printReportMsg(filepath) {
787
- console.log("Midscene - report file updated:", filepath);
788
- }
789
- function getCurrentExecutionFile(trace) {
790
- const error = new Error();
791
- const stackTrace = trace || error.stack;
792
- const pkgDir = process.cwd() || "";
793
- if (stackTrace) {
794
- const stackLines = stackTrace.split("\n");
795
- for (const line of stackLines) {
796
- if (line.includes(".spec.") || line.includes(".test.") || line.includes(".ts") || line.includes(".js")) {
797
- const match = line.match(/(?:at\s+)?(.*?\.(?:spec|test)\.[jt]s)/);
798
- if (match == null ? void 0 : match[1]) {
799
- const targetFileName = match[1].replace(pkgDir, "").trim().replace("at ", "");
800
- return targetFileName;
983
+ testFileIndex.set(taskFile, 1);
801
984
  }
802
- }
803
- }
804
- }
805
- return false;
806
- }
807
- var testFileIndex = /* @__PURE__ */ new Map();
808
- function generateCacheId(fileName) {
809
- let taskFile = fileName || getCurrentExecutionFile();
810
- if (!taskFile) {
811
- taskFile = randomUUID();
812
- console.warn(
813
- "Midscene - using random UUID for cache id. Cache may be invalid."
814
- );
815
- }
816
- if (testFileIndex.has(taskFile)) {
817
- const currentIndex = testFileIndex.get(taskFile);
818
- if (currentIndex !== void 0) {
819
- testFileIndex.set(taskFile, currentIndex + 1);
985
+ return `${taskFile}-${testFileIndex.get(taskFile)}`;
820
986
  }
821
- } else {
822
- testFileIndex.set(taskFile, 1);
823
- }
824
- return `${taskFile}-${testFileIndex.get(taskFile)}`;
825
- }
826
- var ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED = "NOT_IMPLEMENTED_AS_DESIGNED";
827
-
828
- // src/playground/server.ts
829
- var import_dotenv = __toESM(require_main());
830
- import { getTmpDir } from "@midscene/core/utils";
831
- import cors from "cors";
832
- import express from "express";
833
-
834
- // src/common/agent.ts
835
- import {
836
- groupedActionDumpFileExt,
837
- stringifyDumpData as stringifyDumpData2,
838
- writeLogFile as writeLogFile2
839
- } from "@midscene/core/utils";
840
-
841
- // src/common/tasks.ts
842
- import assert2 from "assert";
843
- import {
844
- Executor,
845
- Insight,
846
- plan
847
- } from "@midscene/core";
848
- import { sleep } from "@midscene/core/utils";
849
- import { base64Encoded as base64Encoded2 } from "@midscene/shared/img";
850
-
851
- // src/common/task-cache.ts
852
- import { existsSync, readFileSync as readFileSync2 } from "fs";
853
- import { join } from "path";
854
- import {
855
- getLogDirByType,
856
- stringifyDumpData,
857
- writeLogFile
858
- } from "@midscene/core/utils";
859
- import { getMidscenePkgInfo } from "@midscene/shared/fs";
860
- var TaskCache = class {
861
- constructor(opts) {
862
- this.midscenePkgInfo = getMidscenePkgInfo(__dirname);
863
- this.cacheId = generateCacheId(opts == null ? void 0 : opts.fileName);
864
- this.cache = this.readCacheFromFile() || {
865
- aiTasks: []
866
- };
867
- this.newCache = {
868
- aiTasks: []
869
- };
870
- }
871
- getCacheGroupByPrompt(aiActionPrompt) {
872
- const { aiTasks = [] } = this.cache || { aiTasks: [] };
873
- const index = aiTasks.findIndex((item) => item.prompt === aiActionPrompt);
874
- const newCacheGroup = [];
875
- this.newCache.aiTasks.push({
876
- prompt: aiActionPrompt,
877
- tasks: newCacheGroup
878
- });
879
- return {
880
- readCache: (pageContext, type, actionPrompt) => {
881
- if (index === -1) {
882
- return false;
987
+ var ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED = "NOT_IMPLEMENTED_AS_DESIGNED";
988
+ var TaskCache = class {
989
+ getCacheGroupByPrompt(aiActionPrompt) {
990
+ const { aiTasks = [] } = this.cache || {
991
+ aiTasks: []
992
+ };
993
+ const index = aiTasks.findIndex((item)=>item.prompt === aiActionPrompt);
994
+ const newCacheGroup = [];
995
+ this.newCache.aiTasks.push({
996
+ prompt: aiActionPrompt,
997
+ tasks: newCacheGroup
998
+ });
999
+ return {
1000
+ readCache: (pageContext, type, actionPrompt)=>{
1001
+ if (index === -1) {
1002
+ return false;
1003
+ }
1004
+ if (type === "plan") {
1005
+ return this.readCache(pageContext, type, actionPrompt, aiTasks[index].tasks);
1006
+ }
1007
+ return this.readCache(pageContext, type, actionPrompt, aiTasks[index].tasks);
1008
+ },
1009
+ saveCache: (cache)=>{
1010
+ newCacheGroup.push(cache);
1011
+ this.writeCacheToFile();
1012
+ }
1013
+ };
883
1014
  }
884
- if (type === "plan") {
885
- return this.readCache(
886
- pageContext,
887
- type,
888
- actionPrompt,
889
- aiTasks[index].tasks
890
- );
1015
+ readCache(pageContext, type, userPrompt, cacheGroup) {
1016
+ var _a;
1017
+ if (cacheGroup.length > 0) {
1018
+ const index = cacheGroup.findIndex((item)=>item.prompt === userPrompt);
1019
+ if (index === -1) {
1020
+ return false;
1021
+ }
1022
+ const taskRes = cacheGroup.splice(index, 1)[0];
1023
+ if ((taskRes == null ? void 0 : taskRes.type) === "locate" && !((_a = taskRes.response) == null ? void 0 : _a.elements.every((element)=>{
1024
+ const findIndex = pageContext.content.findIndex((contentElement)=>contentElement.id === element.id);
1025
+ if (findIndex === -1) {
1026
+ return false;
1027
+ }
1028
+ return true;
1029
+ }))) {
1030
+ return false;
1031
+ }
1032
+ if (taskRes && taskRes.type === type && taskRes.prompt === userPrompt && this.pageContextEqual(taskRes.pageContext, pageContext)) {
1033
+ return taskRes.response;
1034
+ }
1035
+ }
1036
+ return false;
891
1037
  }
892
- return this.readCache(
893
- pageContext,
894
- type,
895
- actionPrompt,
896
- aiTasks[index].tasks
897
- );
898
- },
899
- saveCache: (cache) => {
900
- newCacheGroup.push(cache);
901
- this.writeCacheToFile();
902
- }
903
- };
904
- }
905
- readCache(pageContext, type, userPrompt, cacheGroup) {
906
- var _a;
907
- if (cacheGroup.length > 0) {
908
- const index = cacheGroup.findIndex((item) => item.prompt === userPrompt);
909
- if (index === -1) {
910
- return false;
911
- }
912
- const taskRes = cacheGroup.splice(index, 1)[0];
913
- if ((taskRes == null ? void 0 : taskRes.type) === "locate" && !((_a = taskRes.response) == null ? void 0 : _a.elements.every((element) => {
914
- const findIndex = pageContext.content.findIndex(
915
- (contentElement) => contentElement.id === element.id
916
- );
917
- if (findIndex === -1) {
918
- return false;
1038
+ pageContextEqual(taskPageContext, pageContext) {
1039
+ return taskPageContext.size.width === pageContext.size.width && taskPageContext.size.height === pageContext.size.height;
919
1040
  }
920
- return true;
921
- }))) {
922
- return false;
923
- }
924
- if (taskRes && taskRes.type === type && taskRes.prompt === userPrompt && this.pageContextEqual(taskRes.pageContext, pageContext)) {
925
- return taskRes.response;
926
- }
927
- }
928
- return false;
929
- }
930
- pageContextEqual(taskPageContext, pageContext) {
931
- return taskPageContext.size.width === pageContext.size.width && taskPageContext.size.height === pageContext.size.height;
932
- }
933
- /**
1041
+ /**
934
1042
  * Generate task cache data.
935
1043
  * This method is mainly used to create or obtain some cached data for tasks, and it returns a new cache object.
936
1044
  * In the cache object, it may contain task-related information, states, or other necessary data.
937
1045
  * 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.
938
1046
  * @returns {Object} Returns a new cache object, which may include task cache data.
939
- */
940
- generateTaskCache() {
941
- return this.newCache;
942
- }
943
- readCacheFromFile() {
944
- const cacheFile = join(getLogDirByType("cache"), `${this.cacheId}.json`);
945
- if (process.env.MIDSCENE_CACHE === "true" && existsSync(cacheFile)) {
946
- try {
947
- const data = readFileSync2(cacheFile, "utf8");
948
- const jsonData = JSON.parse(data);
949
- if (jsonData.pkgName !== this.midscenePkgInfo.name || jsonData.pkgVersion !== this.midscenePkgInfo.version) {
950
- return void 0;
951
- }
952
- return jsonData;
953
- } catch (err) {
954
- return void 0;
955
- }
956
- }
957
- return void 0;
958
- }
959
- writeCacheToFile() {
960
- const midscenePkgInfo = getMidscenePkgInfo(__dirname);
961
- writeLogFile({
962
- fileName: `${this.cacheId}`,
963
- fileExt: "json",
964
- fileContent: stringifyDumpData(
965
- __spreadValues({
966
- pkgName: midscenePkgInfo.name,
967
- pkgVersion: midscenePkgInfo.version,
968
- cacheId: this.cacheId
969
- }, this.newCache),
970
- 2
971
- ),
972
- type: "cache"
973
- });
974
- }
975
- };
976
-
977
- // src/common/tasks.ts
978
- var PageTaskExecutor = class {
979
- constructor(page, opts) {
980
- this.page = page;
981
- this.insight = new Insight(async () => {
982
- return await parseContextFromWebPage(page);
983
- });
984
- this.taskCache = new TaskCache({
985
- fileName: opts == null ? void 0 : opts.cacheId
986
- });
987
- }
988
- async recordScreenshot(timing) {
989
- const file = await this.page.screenshot();
990
- const item = {
991
- type: "screenshot",
992
- ts: Date.now(),
993
- screenshot: base64Encoded2(file),
994
- timing
995
- };
996
- return item;
997
- }
998
- wrapExecutorWithScreenshot(taskApply) {
999
- const taskWithScreenshot = __spreadProps(__spreadValues({}, taskApply), {
1000
- executor: async (param, context, ...args) => {
1001
- const recorder = [];
1002
- const { task } = context;
1003
- task.recorder = recorder;
1004
- const shot = await this.recordScreenshot(`before ${task.type}`);
1005
- recorder.push(shot);
1006
- const result = await taskApply.executor(param, context, ...args);
1007
- if (taskApply.type === "Action") {
1008
- await sleep(1e3);
1009
- const shot2 = await this.recordScreenshot("after Action");
1010
- recorder.push(shot2);
1047
+ */ generateTaskCache() {
1048
+ return this.newCache;
1011
1049
  }
1012
- return result;
1013
- }
1014
- });
1015
- return taskWithScreenshot;
1016
- }
1017
- async convertPlanToExecutable(plans, cacheGroup) {
1018
- const tasks = plans.map((plan2) => {
1019
- if (plan2.type === "Locate") {
1020
- const taskFind = {
1021
- type: "Insight",
1022
- subType: "Locate",
1023
- param: plan2.param,
1024
- executor: async (param, taskContext) => {
1025
- const { task } = taskContext;
1026
- let insightDump;
1027
- const dumpCollector = (dump) => {
1028
- insightDump = dump;
1029
- };
1030
- this.insight.onceDumpUpdatedFn = dumpCollector;
1031
- const pageContext = await this.insight.contextRetrieverFn();
1032
- const locateCache = cacheGroup == null ? void 0 : cacheGroup.readCache(
1033
- pageContext,
1034
- "locate",
1035
- param.prompt
1036
- );
1037
- let locateResult;
1038
- const callAI = this.insight.aiVendorFn;
1039
- const element = await this.insight.locate(param.prompt, {
1040
- quickAnswer: plan2.quickAnswer,
1041
- callAI: async (...message) => {
1042
- if (locateCache) {
1043
- locateResult = locateCache;
1044
- return Promise.resolve(locateCache);
1045
- }
1046
- locateResult = await callAI(...message);
1047
- assert2(locateResult);
1048
- return locateResult;
1049
- }
1050
- });
1051
- if (locateResult) {
1052
- cacheGroup == null ? void 0 : cacheGroup.saveCache({
1053
- type: "locate",
1054
- pageContext: {
1055
- url: pageContext.url,
1056
- size: pageContext.size
1057
- },
1058
- prompt: param.prompt,
1059
- response: locateResult
1060
- });
1050
+ readCacheFromFile() {
1051
+ if (_utils.ifInBrowser) {
1052
+ return void 0;
1061
1053
  }
1062
- if (!element) {
1063
- task.log = {
1064
- dump: insightDump
1065
- };
1066
- throw new Error(`Element not found: ${param.prompt}`);
1067
- }
1068
- return {
1069
- output: {
1070
- element
1071
- },
1072
- log: {
1073
- dump: insightDump
1074
- },
1075
- cache: {
1076
- hit: Boolean(locateCache)
1077
- }
1078
- };
1079
- }
1080
- };
1081
- return taskFind;
1082
- }
1083
- if (plan2.type === "Assert" || plan2.type === "AssertWithoutThrow") {
1084
- const assertPlan = plan2;
1085
- const taskAssert = {
1086
- type: "Insight",
1087
- subType: "Assert",
1088
- param: assertPlan.param,
1089
- executor: async (param, taskContext) => {
1090
- const { task } = taskContext;
1091
- let insightDump;
1092
- const dumpCollector = (dump) => {
1093
- insightDump = dump;
1094
- };
1095
- this.insight.onceDumpUpdatedFn = dumpCollector;
1096
- const assertion = await this.insight.assert(
1097
- assertPlan.param.assertion
1098
- );
1099
- if (!assertion.pass) {
1100
- if (plan2.type === "Assert") {
1101
- task.output = assertion;
1102
- task.log = {
1103
- dump: insightDump
1104
- };
1105
- throw new Error(
1106
- assertion.thought || "Assertion failed without reason"
1107
- );
1108
- }
1109
- task.error = assertion.thought;
1054
+ const cacheFile = (0, _path.join)((0, _utils1.getLogDirByType)("cache"), `${this.cacheId}.json`);
1055
+ if (process.env.MIDSCENE_CACHE === "true" && (0, _fs.existsSync)(cacheFile)) {
1056
+ try {
1057
+ const data = (0, _fs.readFileSync)(cacheFile, "utf8");
1058
+ const jsonData = JSON.parse(data);
1059
+ if (!this.midscenePkgInfo) {
1060
+ return void 0;
1061
+ }
1062
+ if (jsonData.pkgName !== this.midscenePkgInfo.name || jsonData.pkgVersion !== this.midscenePkgInfo.version) {
1063
+ return void 0;
1064
+ }
1065
+ return jsonData;
1066
+ } catch (err) {
1067
+ return void 0;
1068
+ }
1110
1069
  }
1111
- return {
1112
- output: assertion,
1113
- log: {
1114
- dump: insightDump
1115
- }
1116
- };
1117
- }
1118
- };
1119
- return taskAssert;
1120
- }
1121
- if (plan2.type === "Input") {
1122
- const taskActionInput = {
1123
- type: "Action",
1124
- subType: "Input",
1125
- param: plan2.param,
1126
- executor: async (taskParam, { element }) => {
1127
- if (element) {
1128
- await this.page.clearInput(element);
1129
- if (taskParam.value === "") {
1070
+ return void 0;
1071
+ }
1072
+ writeCacheToFile() {
1073
+ const midscenePkgInfo = (0, _fs1.getRunningPkgInfo)();
1074
+ if (!midscenePkgInfo) {
1130
1075
  return;
1131
- }
1132
- await this.page.keyboard.type(taskParam.value);
1133
1076
  }
1134
- }
1135
- };
1136
- return taskActionInput;
1137
- }
1138
- if (plan2.type === "KeyboardPress") {
1139
- const taskActionKeyboardPress = {
1140
- type: "Action",
1141
- subType: "KeyboardPress",
1142
- param: plan2.param,
1143
- executor: async (taskParam) => {
1144
- assert2(taskParam.value, "No key to press");
1145
- await this.page.keyboard.press(taskParam.value);
1146
- }
1147
- };
1148
- return taskActionKeyboardPress;
1149
- }
1150
- if (plan2.type === "Tap") {
1151
- const taskActionTap = {
1152
- type: "Action",
1153
- subType: "Tap",
1154
- executor: async (param, { element }) => {
1155
- assert2(element, "Element not found, cannot tap");
1156
- await this.page.mouse.click(
1157
- element.center[0],
1158
- element.center[1]
1159
- );
1160
- }
1161
- };
1162
- return taskActionTap;
1163
- }
1164
- if (plan2.type === "Hover") {
1165
- const taskActionHover = {
1166
- type: "Action",
1167
- subType: "Hover",
1168
- executor: async (param, { element }) => {
1169
- assert2(element, "Element not found, cannot hover");
1170
- await this.page.mouse.move(
1171
- element.center[0],
1172
- element.center[1]
1173
- );
1174
- }
1175
- };
1176
- return taskActionHover;
1177
- }
1178
- if (plan2.type === "Scroll") {
1179
- const taskActionScroll = {
1180
- type: "Action",
1181
- subType: "Scroll",
1182
- param: plan2.param,
1183
- executor: async (taskParam) => {
1184
- const scrollToEventName = taskParam.scrollType;
1185
- switch (scrollToEventName) {
1186
- case "scrollUntilTop":
1187
- await this.page.scrollUntilTop();
1188
- break;
1189
- case "scrollUntilBottom":
1190
- await this.page.scrollUntilBottom();
1191
- break;
1192
- case "scrollUpOneScreen":
1193
- await this.page.scrollUpOneScreen();
1194
- break;
1195
- case "scrollDownOneScreen":
1196
- await this.page.scrollDownOneScreen();
1197
- break;
1198
- default:
1199
- console.error(
1200
- "Unknown scroll event type:",
1201
- scrollToEventName
1202
- );
1077
+ if (!_utils.ifInBrowser) {
1078
+ (0, _utils1.writeLogFile)({
1079
+ fileName: `${this.cacheId}`,
1080
+ fileExt: "json",
1081
+ fileContent: (0, _utils1.stringifyDumpData)(__spreadValues({
1082
+ pkgName: midscenePkgInfo.name,
1083
+ pkgVersion: midscenePkgInfo.version,
1084
+ cacheId: this.cacheId
1085
+ }, this.newCache), 2),
1086
+ type: "cache"
1087
+ });
1203
1088
  }
1204
- }
1205
- };
1206
- return taskActionScroll;
1207
- }
1208
- if (plan2.type === "Sleep") {
1209
- const taskActionSleep = {
1210
- type: "Action",
1211
- subType: "Sleep",
1212
- param: plan2.param,
1213
- executor: async (taskParam) => {
1214
- await sleep(taskParam.timeMs || 3e3);
1215
- }
1216
- };
1217
- return taskActionSleep;
1218
- }
1219
- if (plan2.type === "Error") {
1220
- const taskActionError = {
1221
- type: "Action",
1222
- subType: "Error",
1223
- param: plan2.param,
1224
- executor: async (taskParam) => {
1225
- assert2(
1226
- taskParam.thought,
1227
- "An error occurred, but no thought provided"
1228
- );
1229
- throw new Error(taskParam.thought);
1230
- }
1231
- };
1232
- return taskActionError;
1233
- }
1234
- throw new Error(`Unknown or Unsupported task type: ${plan2.type}`);
1235
- }).map((task) => {
1236
- return this.wrapExecutorWithScreenshot(task);
1237
- });
1238
- return tasks;
1239
- }
1240
- async action(userPrompt) {
1241
- const taskExecutor = new Executor(userPrompt);
1242
- const cacheGroup = this.taskCache.getCacheGroupByPrompt(userPrompt);
1243
- let plans = [];
1244
- const planningTask = {
1245
- type: "Planning",
1246
- param: {
1247
- userPrompt
1248
- },
1249
- executor: async (param) => {
1250
- const pageContext = await this.insight.contextRetrieverFn();
1251
- let planResult;
1252
- const planCache = cacheGroup.readCache(pageContext, "plan", userPrompt);
1253
- if (planCache) {
1254
- planResult = planCache;
1255
- } else {
1256
- planResult = await plan(param.userPrompt, {
1257
- context: pageContext
1258
- });
1259
1089
  }
1260
- assert2(planResult.plans.length > 0, "No plans found");
1261
- plans = planResult.plans;
1262
- cacheGroup.saveCache({
1263
- type: "plan",
1264
- pageContext: {
1265
- url: pageContext.url,
1266
- size: pageContext.size
1267
- },
1268
- prompt: userPrompt,
1269
- response: planResult
1270
- });
1271
- return {
1272
- output: planResult,
1273
- cache: {
1274
- hit: Boolean(planCache)
1275
- }
1276
- };
1277
- }
1278
- };
1279
- await taskExecutor.append(this.wrapExecutorWithScreenshot(planningTask));
1280
- let output = await taskExecutor.flush();
1281
- if (taskExecutor.isInErrorState()) {
1282
- return {
1283
- output,
1284
- executor: taskExecutor
1285
- };
1286
- }
1287
- const executables = await this.convertPlanToExecutable(plans, cacheGroup);
1288
- await taskExecutor.append(executables);
1289
- output = await taskExecutor.flush();
1290
- return {
1291
- output,
1292
- executor: taskExecutor
1293
- };
1294
- }
1295
- async query(demand) {
1296
- const description = typeof demand === "string" ? demand : JSON.stringify(demand);
1297
- const taskExecutor = new Executor(description);
1298
- const queryTask = {
1299
- type: "Insight",
1300
- subType: "Query",
1301
- param: {
1302
- dataDemand: demand
1303
- },
1304
- executor: async (param) => {
1305
- let insightDump;
1306
- const dumpCollector = (dump) => {
1307
- insightDump = dump;
1308
- };
1309
- this.insight.onceDumpUpdatedFn = dumpCollector;
1310
- const data = await this.insight.extract(param.dataDemand);
1311
- return {
1312
- output: data,
1313
- log: { dump: insightDump }
1314
- };
1315
- }
1316
- };
1317
- await taskExecutor.append(this.wrapExecutorWithScreenshot(queryTask));
1318
- const output = await taskExecutor.flush();
1319
- return {
1320
- output,
1321
- executor: taskExecutor
1322
- };
1323
- }
1324
- async assert(assertion) {
1325
- const description = `assert: ${assertion}`;
1326
- const taskExecutor = new Executor(description);
1327
- const assertionPlan = {
1328
- type: "Assert",
1329
- param: {
1330
- assertion
1331
- }
1332
- };
1333
- const assertTask = await this.convertPlanToExecutable([assertionPlan]);
1334
- await taskExecutor.append(this.wrapExecutorWithScreenshot(assertTask[0]));
1335
- const output = await taskExecutor.flush();
1336
- return {
1337
- output,
1338
- executor: taskExecutor
1339
- };
1340
- }
1341
- async waitFor(assertion, opt) {
1342
- const description = `waitFor: ${assertion}`;
1343
- const taskExecutor = new Executor(description);
1344
- const { timeoutMs, checkIntervalMs } = opt;
1345
- assert2(assertion, "No assertion for waitFor");
1346
- assert2(timeoutMs, "No timeoutMs for waitFor");
1347
- assert2(checkIntervalMs, "No checkIntervalMs for waitFor");
1348
- const overallStartTime = Date.now();
1349
- let startTime = Date.now();
1350
- let errorThought = "";
1351
- while (Date.now() - overallStartTime < timeoutMs) {
1352
- startTime = Date.now();
1353
- const assertPlan = {
1354
- type: "AssertWithoutThrow",
1355
- param: {
1356
- assertion
1090
+ constructor(opts){
1091
+ this.midscenePkgInfo = (0, _fs1.getRunningPkgInfo)();
1092
+ this.cacheId = generateCacheId(opts == null ? void 0 : opts.fileName);
1093
+ this.cache = this.readCacheFromFile() || {
1094
+ aiTasks: []
1095
+ };
1096
+ this.newCache = {
1097
+ aiTasks: []
1098
+ };
1357
1099
  }
1358
- };
1359
- const assertTask = await this.convertPlanToExecutable([assertPlan]);
1360
- await taskExecutor.append(this.wrapExecutorWithScreenshot(assertTask[0]));
1361
- const output = await taskExecutor.flush();
1362
- if (output == null ? void 0 : output.pass) {
1363
- return {
1364
- output: void 0,
1365
- executor: taskExecutor
1366
- };
1367
- }
1368
- errorThought = (output == null ? void 0 : output.thought) || "unknown error";
1369
- const now = Date.now();
1370
- if (now - startTime < checkIntervalMs) {
1371
- const timeRemaining = checkIntervalMs - (now - startTime);
1372
- const sleepPlan = {
1373
- type: "Sleep",
1374
- param: {
1375
- timeMs: timeRemaining
1376
- }
1377
- };
1378
- const sleepTask = await this.convertPlanToExecutable([sleepPlan]);
1379
- await taskExecutor.append(
1380
- this.wrapExecutorWithScreenshot(sleepTask[0])
1381
- );
1382
- await taskExecutor.flush();
1383
- }
1384
- }
1385
- const errorPlan = {
1386
- type: "Error",
1387
- param: {
1388
- thought: `waitFor timeout: ${errorThought}`
1389
- }
1390
- };
1391
- const errorTask = await this.convertPlanToExecutable([errorPlan]);
1392
- await taskExecutor.append(errorTask[0]);
1393
- await taskExecutor.flush();
1394
- return {
1395
- output: void 0,
1396
- executor: taskExecutor
1397
1100
  };
1398
- }
1399
- };
1400
-
1401
- // src/common/agent.ts
1402
- var PageAgent = class {
1403
- constructor(page, opts) {
1404
- this.page = page;
1405
- this.opts = Object.assign(
1406
- {
1407
- generateReport: true,
1408
- autoPrintReportMsg: true,
1409
- groupName: "Midscene Report",
1410
- groupDescription: ""
1411
- },
1412
- opts || {}
1413
- );
1414
- this.dump = {
1415
- groupName: this.opts.groupName,
1416
- groupDescription: this.opts.groupDescription,
1417
- executions: []
1101
+ // src/common/tasks.ts
1102
+ var PageTaskExecutor = class {
1103
+ recordScreenshot(timing) {
1104
+ return __async(this, null, function*() {
1105
+ const base64 = yield this.page.screenshotBase64();
1106
+ const item = {
1107
+ type: "screenshot",
1108
+ ts: Date.now(),
1109
+ screenshot: base64,
1110
+ timing
1111
+ };
1112
+ return item;
1113
+ });
1114
+ }
1115
+ wrapExecutorWithScreenshot(taskApply) {
1116
+ const taskWithScreenshot = __spreadProps(__spreadValues({}, taskApply), {
1117
+ executor: (param, context, ...args)=>__async(this, null, function*() {
1118
+ const recorder = [];
1119
+ const { task } = context;
1120
+ task.recorder = recorder;
1121
+ const shot = yield this.recordScreenshot(`before ${task.type}`);
1122
+ recorder.push(shot);
1123
+ const result = yield taskApply.executor(param, context, ...args);
1124
+ if (taskApply.type === "Action") {
1125
+ yield (0, _utils1.sleep)(1e3);
1126
+ const shot2 = yield this.recordScreenshot("after Action");
1127
+ recorder.push(shot2);
1128
+ }
1129
+ return result;
1130
+ })
1131
+ });
1132
+ return taskWithScreenshot;
1133
+ }
1134
+ convertPlanToExecutable(plans, cacheGroup) {
1135
+ return __async(this, null, function*() {
1136
+ const tasks = plans.map((plan2)=>{
1137
+ if (plan2.type === "Locate") {
1138
+ const taskFind = {
1139
+ type: "Insight",
1140
+ subType: "Locate",
1141
+ param: plan2.param,
1142
+ quickAnswer: plan2.quickAnswer,
1143
+ executor: (param, taskContext)=>__async(this, null, function*() {
1144
+ const { task } = taskContext;
1145
+ let insightDump;
1146
+ const dumpCollector = (dump)=>{
1147
+ insightDump = dump;
1148
+ };
1149
+ this.insight.onceDumpUpdatedFn = dumpCollector;
1150
+ const pageContext = yield this.insight.contextRetrieverFn();
1151
+ const locateCache = cacheGroup == null ? void 0 : cacheGroup.readCache(pageContext, "locate", param.prompt);
1152
+ let locateResult;
1153
+ const callAI = this.insight.aiVendorFn;
1154
+ const element = yield this.insight.locate(param.prompt, {
1155
+ quickAnswer: task.quickAnswer,
1156
+ callAI: (...message)=>__async(this, null, function*() {
1157
+ if (locateCache) {
1158
+ locateResult = locateCache;
1159
+ return Promise.resolve(locateCache);
1160
+ }
1161
+ const aiResult = yield callAI(...message);
1162
+ locateResult = (0, _core.transformElementPositionToId)(aiResult, pageContext.content);
1163
+ (0, _assert.default)(locateResult);
1164
+ return locateResult;
1165
+ })
1166
+ });
1167
+ if (locateResult) {
1168
+ cacheGroup == null ? void 0 : cacheGroup.saveCache({
1169
+ type: "locate",
1170
+ pageContext: {
1171
+ url: pageContext.url,
1172
+ size: pageContext.size
1173
+ },
1174
+ prompt: param.prompt,
1175
+ response: locateResult
1176
+ });
1177
+ }
1178
+ if (!element) {
1179
+ task.log = {
1180
+ dump: insightDump
1181
+ };
1182
+ throw new Error(`Element not found: ${param.prompt}`);
1183
+ }
1184
+ return {
1185
+ output: {
1186
+ element
1187
+ },
1188
+ log: {
1189
+ dump: insightDump
1190
+ },
1191
+ cache: {
1192
+ hit: Boolean(locateCache)
1193
+ }
1194
+ };
1195
+ })
1196
+ };
1197
+ return taskFind;
1198
+ }
1199
+ if (plan2.type === "Assert" || plan2.type === "AssertWithoutThrow") {
1200
+ const assertPlan = plan2;
1201
+ const taskAssert = {
1202
+ type: "Insight",
1203
+ subType: "Assert",
1204
+ param: assertPlan.param,
1205
+ executor: (param, taskContext)=>__async(this, null, function*() {
1206
+ const { task } = taskContext;
1207
+ let insightDump;
1208
+ const dumpCollector = (dump)=>{
1209
+ insightDump = dump;
1210
+ };
1211
+ this.insight.onceDumpUpdatedFn = dumpCollector;
1212
+ const assertion = yield this.insight.assert(assertPlan.param.assertion);
1213
+ if (!assertion.pass) {
1214
+ if (plan2.type === "Assert") {
1215
+ task.output = assertion;
1216
+ task.log = {
1217
+ dump: insightDump
1218
+ };
1219
+ throw new Error(assertion.thought || "Assertion failed without reason");
1220
+ }
1221
+ task.error = assertion.thought;
1222
+ }
1223
+ return {
1224
+ output: assertion,
1225
+ log: {
1226
+ dump: insightDump
1227
+ }
1228
+ };
1229
+ })
1230
+ };
1231
+ return taskAssert;
1232
+ }
1233
+ if (plan2.type === "Input") {
1234
+ const taskActionInput = {
1235
+ type: "Action",
1236
+ subType: "Input",
1237
+ param: plan2.param,
1238
+ executor: (_0, _1)=>__async(this, [
1239
+ _0,
1240
+ _1
1241
+ ], function*(taskParam, { element }) {
1242
+ if (element) {
1243
+ yield this.page.clearInput(element);
1244
+ if (taskParam.value === "") {
1245
+ return;
1246
+ }
1247
+ yield this.page.keyboard.type(taskParam.value);
1248
+ }
1249
+ })
1250
+ };
1251
+ return taskActionInput;
1252
+ }
1253
+ if (plan2.type === "KeyboardPress") {
1254
+ const taskActionKeyboardPress = {
1255
+ type: "Action",
1256
+ subType: "KeyboardPress",
1257
+ param: plan2.param,
1258
+ executor: (taskParam)=>__async(this, null, function*() {
1259
+ (0, _assert.default)(taskParam.value, "No key to press");
1260
+ yield this.page.keyboard.press(taskParam.value);
1261
+ })
1262
+ };
1263
+ return taskActionKeyboardPress;
1264
+ }
1265
+ if (plan2.type === "Tap") {
1266
+ const taskActionTap = {
1267
+ type: "Action",
1268
+ subType: "Tap",
1269
+ executor: (_0, _1)=>__async(this, [
1270
+ _0,
1271
+ _1
1272
+ ], function*(param, { element }) {
1273
+ (0, _assert.default)(element, "Element not found, cannot tap");
1274
+ yield this.page.mouse.click(element.center[0], element.center[1]);
1275
+ })
1276
+ };
1277
+ return taskActionTap;
1278
+ }
1279
+ if (plan2.type === "Hover") {
1280
+ const taskActionHover = {
1281
+ type: "Action",
1282
+ subType: "Hover",
1283
+ executor: (_0, _1)=>__async(this, [
1284
+ _0,
1285
+ _1
1286
+ ], function*(param, { element }) {
1287
+ (0, _assert.default)(element, "Element not found, cannot hover");
1288
+ yield this.page.mouse.move(element.center[0], element.center[1]);
1289
+ })
1290
+ };
1291
+ return taskActionHover;
1292
+ }
1293
+ if (plan2.type === "Scroll") {
1294
+ const taskActionScroll = {
1295
+ type: "Action",
1296
+ subType: "Scroll",
1297
+ param: plan2.param,
1298
+ executor: (taskParam)=>__async(this, null, function*() {
1299
+ const scrollToEventName = taskParam.scrollType;
1300
+ switch(scrollToEventName){
1301
+ case "scrollUntilTop":
1302
+ yield this.page.scrollUntilTop();
1303
+ break;
1304
+ case "scrollUntilBottom":
1305
+ yield this.page.scrollUntilBottom();
1306
+ break;
1307
+ case "scrollUpOneScreen":
1308
+ yield this.page.scrollUpOneScreen();
1309
+ break;
1310
+ case "scrollDownOneScreen":
1311
+ yield this.page.scrollDownOneScreen();
1312
+ break;
1313
+ default:
1314
+ console.error("Unknown scroll event type:", scrollToEventName);
1315
+ }
1316
+ })
1317
+ };
1318
+ return taskActionScroll;
1319
+ }
1320
+ if (plan2.type === "Sleep") {
1321
+ const taskActionSleep = {
1322
+ type: "Action",
1323
+ subType: "Sleep",
1324
+ param: plan2.param,
1325
+ executor: (taskParam)=>__async(this, null, function*() {
1326
+ yield (0, _utils1.sleep)(taskParam.timeMs || 3e3);
1327
+ })
1328
+ };
1329
+ return taskActionSleep;
1330
+ }
1331
+ if (plan2.type === "Error") {
1332
+ const taskActionError = {
1333
+ type: "Action",
1334
+ subType: "Error",
1335
+ param: plan2.param,
1336
+ executor: (taskParam)=>__async(this, null, function*() {
1337
+ (0, _assert.default)(taskParam.thought, "An error occurred, but no thought provided");
1338
+ throw new Error(taskParam.thought);
1339
+ })
1340
+ };
1341
+ return taskActionError;
1342
+ }
1343
+ throw new Error(`Unknown or Unsupported task type: ${plan2.type}`);
1344
+ }).map((task)=>{
1345
+ return this.wrapExecutorWithScreenshot(task);
1346
+ });
1347
+ return tasks;
1348
+ });
1349
+ }
1350
+ action(userPrompt) {
1351
+ return __async(this, null, function*() {
1352
+ const taskExecutor = new _core.Executor(userPrompt);
1353
+ const cacheGroup = this.taskCache.getCacheGroupByPrompt(userPrompt);
1354
+ let plans = [];
1355
+ const planningTask = {
1356
+ type: "Planning",
1357
+ param: {
1358
+ userPrompt
1359
+ },
1360
+ executor: (param)=>__async(this, null, function*() {
1361
+ const pageContext = yield this.insight.contextRetrieverFn();
1362
+ let planResult;
1363
+ const planCache = cacheGroup.readCache(pageContext, "plan", userPrompt);
1364
+ if (planCache) {
1365
+ planResult = planCache;
1366
+ } else {
1367
+ planResult = yield (0, _core.plan)(param.userPrompt, {
1368
+ context: pageContext
1369
+ });
1370
+ }
1371
+ (0, _assert.default)(planResult.plans.length > 0, "No plans found");
1372
+ plans = planResult.plans;
1373
+ cacheGroup.saveCache({
1374
+ type: "plan",
1375
+ pageContext: {
1376
+ url: pageContext.url,
1377
+ size: pageContext.size
1378
+ },
1379
+ prompt: userPrompt,
1380
+ response: planResult
1381
+ });
1382
+ return {
1383
+ output: planResult,
1384
+ pageContext,
1385
+ cache: {
1386
+ hit: Boolean(planCache)
1387
+ }
1388
+ };
1389
+ })
1390
+ };
1391
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(planningTask));
1392
+ let output = yield taskExecutor.flush();
1393
+ if (taskExecutor.isInErrorState()) {
1394
+ return {
1395
+ output,
1396
+ executor: taskExecutor
1397
+ };
1398
+ }
1399
+ const executables = yield this.convertPlanToExecutable(plans, cacheGroup);
1400
+ yield taskExecutor.append(executables);
1401
+ output = yield taskExecutor.flush();
1402
+ return {
1403
+ output,
1404
+ executor: taskExecutor
1405
+ };
1406
+ });
1407
+ }
1408
+ query(demand) {
1409
+ return __async(this, null, function*() {
1410
+ const description = typeof demand === "string" ? demand : JSON.stringify(demand);
1411
+ const taskExecutor = new _core.Executor(description);
1412
+ const queryTask = {
1413
+ type: "Insight",
1414
+ subType: "Query",
1415
+ param: {
1416
+ dataDemand: demand
1417
+ },
1418
+ executor: (param)=>__async(this, null, function*() {
1419
+ let insightDump;
1420
+ const dumpCollector = (dump)=>{
1421
+ insightDump = dump;
1422
+ };
1423
+ this.insight.onceDumpUpdatedFn = dumpCollector;
1424
+ const data = yield this.insight.extract(param.dataDemand);
1425
+ return {
1426
+ output: data,
1427
+ log: {
1428
+ dump: insightDump
1429
+ }
1430
+ };
1431
+ })
1432
+ };
1433
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(queryTask));
1434
+ const output = yield taskExecutor.flush();
1435
+ return {
1436
+ output,
1437
+ executor: taskExecutor
1438
+ };
1439
+ });
1440
+ }
1441
+ assert(assertion) {
1442
+ return __async(this, null, function*() {
1443
+ const description = `assert: ${assertion}`;
1444
+ const taskExecutor = new _core.Executor(description);
1445
+ const assertionPlan = {
1446
+ type: "Assert",
1447
+ param: {
1448
+ assertion
1449
+ }
1450
+ };
1451
+ const assertTask = yield this.convertPlanToExecutable([
1452
+ assertionPlan
1453
+ ]);
1454
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(assertTask[0]));
1455
+ const output = yield taskExecutor.flush();
1456
+ return {
1457
+ output,
1458
+ executor: taskExecutor
1459
+ };
1460
+ });
1461
+ }
1462
+ waitFor(assertion, opt) {
1463
+ return __async(this, null, function*() {
1464
+ const description = `waitFor: ${assertion}`;
1465
+ const taskExecutor = new _core.Executor(description);
1466
+ const { timeoutMs, checkIntervalMs } = opt;
1467
+ (0, _assert.default)(assertion, "No assertion for waitFor");
1468
+ (0, _assert.default)(timeoutMs, "No timeoutMs for waitFor");
1469
+ (0, _assert.default)(checkIntervalMs, "No checkIntervalMs for waitFor");
1470
+ const overallStartTime = Date.now();
1471
+ let startTime = Date.now();
1472
+ let errorThought = "";
1473
+ while(Date.now() - overallStartTime < timeoutMs){
1474
+ startTime = Date.now();
1475
+ const assertPlan = {
1476
+ type: "AssertWithoutThrow",
1477
+ param: {
1478
+ assertion
1479
+ }
1480
+ };
1481
+ const assertTask = yield this.convertPlanToExecutable([
1482
+ assertPlan
1483
+ ]);
1484
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(assertTask[0]));
1485
+ const output = yield taskExecutor.flush();
1486
+ if (output == null ? void 0 : output.pass) {
1487
+ return {
1488
+ output: void 0,
1489
+ executor: taskExecutor
1490
+ };
1491
+ }
1492
+ errorThought = (output == null ? void 0 : output.thought) || "unknown error";
1493
+ const now = Date.now();
1494
+ if (now - startTime < checkIntervalMs) {
1495
+ const timeRemaining = checkIntervalMs - (now - startTime);
1496
+ const sleepPlan = {
1497
+ type: "Sleep",
1498
+ param: {
1499
+ timeMs: timeRemaining
1500
+ }
1501
+ };
1502
+ const sleepTask = yield this.convertPlanToExecutable([
1503
+ sleepPlan
1504
+ ]);
1505
+ yield taskExecutor.append(this.wrapExecutorWithScreenshot(sleepTask[0]));
1506
+ yield taskExecutor.flush();
1507
+ }
1508
+ }
1509
+ const errorPlan = {
1510
+ type: "Error",
1511
+ param: {
1512
+ thought: `waitFor timeout: ${errorThought}`
1513
+ }
1514
+ };
1515
+ const errorTask = yield this.convertPlanToExecutable([
1516
+ errorPlan
1517
+ ]);
1518
+ yield taskExecutor.append(errorTask[0]);
1519
+ yield taskExecutor.flush();
1520
+ return {
1521
+ output: void 0,
1522
+ executor: taskExecutor
1523
+ };
1524
+ });
1525
+ }
1526
+ constructor(page, insight, opts){
1527
+ this.page = page;
1528
+ this.insight = insight;
1529
+ this.taskCache = new TaskCache({
1530
+ fileName: opts == null ? void 0 : opts.cacheId
1531
+ });
1532
+ }
1418
1533
  };
1419
- this.taskExecutor = new PageTaskExecutor(this.page, {
1420
- cacheId: opts == null ? void 0 : opts.cacheId
1421
- });
1422
- this.reportFileName = reportFileName((opts == null ? void 0 : opts.testId) || "web");
1423
- }
1424
- appendExecutionDump(execution) {
1425
- const currentDump = this.dump;
1426
- currentDump.executions.push(execution);
1427
- }
1428
- dumpDataString() {
1429
- this.dump.groupName = this.opts.groupName;
1430
- this.dump.groupDescription = this.opts.groupDescription;
1431
- return stringifyDumpData2(this.dump);
1432
- }
1433
- writeOutActionDumps() {
1434
- const { generateReport, autoPrintReportMsg } = this.opts;
1435
- this.reportFile = writeLogFile2({
1436
- fileName: this.reportFileName,
1437
- fileExt: groupedActionDumpFileExt,
1438
- fileContent: this.dumpDataString(),
1439
- type: "dump",
1440
- generateReport
1441
- });
1442
- if (generateReport && autoPrintReportMsg) {
1443
- printReportMsg(this.reportFile);
1444
- }
1445
- }
1446
- async aiAction(taskPrompt) {
1447
- const { executor } = await this.taskExecutor.action(taskPrompt);
1448
- this.appendExecutionDump(executor.dump());
1449
- this.writeOutActionDumps();
1450
- if (executor.isInErrorState()) {
1451
- const errorTask = executor.latestErrorTask();
1452
- throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1534
+ // src/common/agent.ts
1535
+ var PageAgent = class {
1536
+ getUIContext() {
1537
+ return __async(this, null, function*() {
1538
+ return yield parseContextFromWebPage(this.page);
1539
+ });
1540
+ }
1541
+ resetDump() {
1542
+ this.dump = {
1543
+ groupName: this.opts.groupName,
1544
+ groupDescription: this.opts.groupDescription,
1545
+ executions: []
1546
+ };
1547
+ return this.dump;
1548
+ }
1549
+ appendExecutionDump(execution) {
1550
+ const currentDump = this.dump;
1551
+ currentDump.executions.push(execution);
1552
+ }
1553
+ dumpDataString() {
1554
+ this.dump.groupName = this.opts.groupName;
1555
+ this.dump.groupDescription = this.opts.groupDescription;
1556
+ return (0, _utils1.stringifyDumpData)(this.dump);
1557
+ }
1558
+ reportHTMLString() {
1559
+ return (0, _utils1.reportHTMLContent)(this.dumpDataString());
1560
+ }
1561
+ writeOutActionDumps() {
1562
+ const { generateReport, autoPrintReportMsg } = this.opts;
1563
+ this.reportFile = (0, _utils1.writeLogFile)({
1564
+ fileName: this.reportFileName,
1565
+ fileExt: _utils1.groupedActionDumpFileExt,
1566
+ fileContent: this.dumpDataString(),
1567
+ type: "dump",
1568
+ generateReport
1569
+ });
1570
+ if (generateReport && autoPrintReportMsg && this.reportFile) {
1571
+ printReportMsg(this.reportFile);
1572
+ }
1573
+ }
1574
+ aiAction(taskPrompt) {
1575
+ return __async(this, null, function*() {
1576
+ const { executor } = yield this.taskExecutor.action(taskPrompt);
1577
+ this.appendExecutionDump(executor.dump());
1578
+ this.writeOutActionDumps();
1579
+ if (executor.isInErrorState()) {
1580
+ const errorTask = executor.latestErrorTask();
1581
+ throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1453
1582
  ${errorTask == null ? void 0 : errorTask.errorStack}`);
1454
- }
1455
- }
1456
- async aiQuery(demand) {
1457
- const { output, executor } = await this.taskExecutor.query(demand);
1458
- this.appendExecutionDump(executor.dump());
1459
- this.writeOutActionDumps();
1460
- if (executor.isInErrorState()) {
1461
- const errorTask = executor.latestErrorTask();
1462
- throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1583
+ }
1584
+ });
1585
+ }
1586
+ aiQuery(demand) {
1587
+ return __async(this, null, function*() {
1588
+ const { output, executor } = yield this.taskExecutor.query(demand);
1589
+ this.appendExecutionDump(executor.dump());
1590
+ this.writeOutActionDumps();
1591
+ if (executor.isInErrorState()) {
1592
+ const errorTask = executor.latestErrorTask();
1593
+ throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1463
1594
  ${errorTask == null ? void 0 : errorTask.errorStack}`);
1464
- }
1465
- return output;
1466
- }
1467
- async aiAssert(assertion, msg, opt) {
1468
- const { output, executor } = await this.taskExecutor.assert(assertion);
1469
- this.appendExecutionDump(executor.dump());
1470
- this.writeOutActionDumps();
1471
- if (opt == null ? void 0 : opt.keepRawResponse) {
1472
- return output;
1473
- }
1474
- if (!(output == null ? void 0 : output.pass)) {
1475
- const errMsg = msg || `Assertion failed: ${assertion}`;
1476
- const reasonMsg = `Reason: ${(output == null ? void 0 : output.thought) || "(no_reason)"}`;
1477
- throw new Error(`${errMsg}
1595
+ }
1596
+ return output;
1597
+ });
1598
+ }
1599
+ aiAssert(assertion, msg, opt) {
1600
+ return __async(this, null, function*() {
1601
+ var _a;
1602
+ const { output, executor } = yield this.taskExecutor.assert(assertion);
1603
+ this.appendExecutionDump(executor.dump());
1604
+ this.writeOutActionDumps();
1605
+ if (output && (opt == null ? void 0 : opt.keepRawResponse)) {
1606
+ return output;
1607
+ }
1608
+ if (!(output == null ? void 0 : output.pass)) {
1609
+ const errMsg = msg || `Assertion failed: ${assertion}`;
1610
+ const reasonMsg = `Reason: ${(output == null ? void 0 : output.thought) || ((_a = executor.latestErrorTask()) == null ? void 0 : _a.error) || "(no_reason)"}`;
1611
+ throw new Error(`${errMsg}
1478
1612
  ${reasonMsg}`);
1479
- }
1480
- }
1481
- async aiWaitFor(assertion, opt) {
1482
- const { executor } = await this.taskExecutor.waitFor(assertion, {
1483
- timeoutMs: (opt == null ? void 0 : opt.timeoutMs) || 15 * 1e3,
1484
- checkIntervalMs: (opt == null ? void 0 : opt.checkIntervalMs) || 3 * 1e3,
1485
- assertion
1486
- });
1487
- this.appendExecutionDump(executor.dump());
1488
- this.writeOutActionDumps();
1489
- if (executor.isInErrorState()) {
1490
- const errorTask = executor.latestErrorTask();
1491
- throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1613
+ }
1614
+ });
1615
+ }
1616
+ aiWaitFor(assertion, opt) {
1617
+ return __async(this, null, function*() {
1618
+ const { executor } = yield this.taskExecutor.waitFor(assertion, {
1619
+ timeoutMs: (opt == null ? void 0 : opt.timeoutMs) || 15 * 1e3,
1620
+ checkIntervalMs: (opt == null ? void 0 : opt.checkIntervalMs) || 3 * 1e3,
1621
+ assertion
1622
+ });
1623
+ this.appendExecutionDump(executor.dump());
1624
+ this.writeOutActionDumps();
1625
+ if (executor.isInErrorState()) {
1626
+ const errorTask = executor.latestErrorTask();
1627
+ throw new Error(`${errorTask == null ? void 0 : errorTask.error}
1492
1628
  ${errorTask == null ? void 0 : errorTask.errorStack}`);
1493
- }
1494
- }
1495
- async ai(taskPrompt, type = "action") {
1496
- if (type === "action") {
1497
- return this.aiAction(taskPrompt);
1498
- }
1499
- if (type === "query") {
1500
- return this.aiQuery(taskPrompt);
1501
- }
1502
- if (type === "assert") {
1503
- return this.aiAssert(taskPrompt);
1504
- }
1505
- throw new Error(
1506
- `Unknown type: ${type}, only support 'action', 'query', 'assert'`
1507
- );
1508
- }
1509
- };
1510
-
1511
- // src/playground/agent.ts
1512
- var StaticPageAgent = class extends PageAgent {
1513
- constructor(page) {
1514
- super(page, {});
1515
- }
1516
- };
1517
-
1518
- // src/playground/static-page.ts
1519
- import { getTmpFile } from "@midscene/core/utils";
1520
- import { saveBase64Image } from "@midscene/shared/img";
1521
- var ThrowNotImplemented = (methodName) => {
1522
- throw new Error(
1523
- `The method "${methodName}" is not implemented as designed since this is a static UI context. (${ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED})`
1524
- );
1525
- };
1526
- var StaticPage = class {
1527
- constructor(uiContext) {
1528
- this.pageType = "static";
1529
- this.mouse = {
1530
- click: ThrowNotImplemented.bind(null, "mouse.click"),
1531
- wheel: ThrowNotImplemented.bind(null, "mouse.wheel"),
1532
- move: ThrowNotImplemented.bind(null, "mouse.move")
1629
+ }
1630
+ });
1631
+ }
1632
+ ai(taskPrompt, type = "action") {
1633
+ return __async(this, null, function*() {
1634
+ if (type === "action") {
1635
+ return this.aiAction(taskPrompt);
1636
+ }
1637
+ if (type === "query") {
1638
+ return this.aiQuery(taskPrompt);
1639
+ }
1640
+ if (type === "assert") {
1641
+ return this.aiAssert(taskPrompt);
1642
+ }
1643
+ throw new Error(`Unknown type: ${type}, only support 'action', 'query', 'assert'`);
1644
+ });
1645
+ }
1646
+ destroy() {
1647
+ return __async(this, null, function*() {
1648
+ yield this.page.destroy();
1649
+ });
1650
+ }
1651
+ constructor(page, opts){
1652
+ /**
1653
+ * If true, the agent will not perform any actions
1654
+ */ this.dryMode = false;
1655
+ this.page = page;
1656
+ this.opts = Object.assign({
1657
+ generateReport: true,
1658
+ autoPrintReportMsg: true,
1659
+ groupName: "Midscene Report",
1660
+ groupDescription: ""
1661
+ }, opts || {});
1662
+ this.insight = new _core.Insight(()=>__async(this, null, function*() {
1663
+ return this.getUIContext();
1664
+ }), {
1665
+ generateElement: ({ content, rect })=>new WebElementInfo({
1666
+ content: content || "",
1667
+ rect,
1668
+ page,
1669
+ id: "",
1670
+ attributes: {
1671
+ nodeType: _constants.NodeType.CONTAINER
1672
+ },
1673
+ indexId: 0
1674
+ })
1675
+ });
1676
+ this.taskExecutor = new PageTaskExecutor(this.page, this.insight, {
1677
+ cacheId: opts == null ? void 0 : opts.cacheId
1678
+ });
1679
+ this.dump = this.resetDump();
1680
+ this.reportFileName = reportFileName((opts == null ? void 0 : opts.testId) || "web");
1681
+ }
1533
1682
  };
1534
- this.keyboard = {
1535
- type: ThrowNotImplemented.bind(null, "keyboard.type"),
1536
- press: ThrowNotImplemented.bind(null, "keyboard.press")
1683
+ // src/playground/agent.ts
1684
+ var StaticPageAgent = class extends PageAgent {
1685
+ constructor(page){
1686
+ super(page, {});
1687
+ this.dryMode = true;
1688
+ }
1537
1689
  };
1538
- this.uiContext = uiContext;
1539
- }
1540
- async getElementInfos() {
1541
- return ThrowNotImplemented("getElementInfos");
1542
- }
1543
- async screenshot() {
1544
- const base64 = this.uiContext.screenshotBase64;
1545
- if (!base64) {
1546
- throw new Error("screenshot base64 is empty");
1547
- }
1548
- const tmpFilePath = getTmpFile("png");
1549
- await saveBase64Image({ base64Data: base64, outputPath: tmpFilePath });
1550
- return tmpFilePath;
1551
- }
1552
- url() {
1553
- return this.uiContext.url;
1554
- }
1555
- async scrollUntilTop() {
1556
- return ThrowNotImplemented("scrollUntilTop");
1557
- }
1558
- async scrollUntilBottom() {
1559
- return ThrowNotImplemented("scrollUntilBottom");
1560
- }
1561
- async scrollUpOneScreen() {
1562
- return ThrowNotImplemented("scrollUpOneScreen");
1563
- }
1564
- async scrollDownOneScreen() {
1565
- return ThrowNotImplemented("scrollDownOneScreen");
1566
- }
1567
- async clearInput() {
1568
- return ThrowNotImplemented("clearInput");
1569
- }
1570
- async _forceUsePageContext() {
1571
- return this.uiContext;
1572
- }
1573
- };
1574
-
1575
- // src/playground/server.ts
1576
- var defaultPort = 5800;
1577
- var staticPath = join2(__dirname, "../../static");
1578
- var agentRequestCount = 1;
1579
- var errorHandler = (err, req, res, next) => {
1580
- console.error(err);
1581
- res.status(500).json({
1582
- error: err.message
1583
- });
1584
- };
1585
- var setup = () => {
1586
- import_dotenv.default.config();
1587
- };
1588
- var PlaygroundServer = class {
1589
- constructor() {
1590
- this.app = express();
1591
- this.tmpDir = getTmpDir();
1592
- setup();
1593
- }
1594
- filePathForUuid(uuid) {
1595
- return join2(this.tmpDir, `${uuid}.json`);
1596
- }
1597
- saveContextFile(uuid, context) {
1598
- const tmpFile = this.filePathForUuid(uuid);
1599
- console.log(`save context file: ${tmpFile}`);
1600
- writeFileSync(tmpFile, context);
1601
- return tmpFile;
1602
- }
1603
- async launch() {
1604
- this.app.use(errorHandler);
1605
- this.app.use(
1606
- cors({
1607
- origin: "*",
1608
- credentials: true
1609
- })
1610
- );
1611
- this.app.get("/status", cors(), async (req, res) => {
1612
- res.send({
1613
- status: "ok"
1614
- });
1615
- });
1616
- this.app.get("/", (req, res) => {
1617
- res.sendFile(join2(staticPath, "index.html"));
1618
- });
1619
- this.app.get("/playground/:uuid", async (req, res) => {
1620
- res.sendFile(join2(staticPath, "index.html"));
1621
- });
1622
- this.app.get("/context/:uuid", async (req, res) => {
1623
- const { uuid } = req.params;
1624
- const contextFile = this.filePathForUuid(uuid);
1625
- assert3(existsSync2(contextFile), "Context not found");
1626
- const context = readFileSync3(contextFile, "utf8");
1627
- res.json({
1628
- context
1629
- });
1630
- });
1631
- this.app.post(
1632
- "/playground-with-context",
1633
- express.json({ limit: "50mb" }),
1634
- async (req, res) => {
1635
- const context = req.body.context;
1636
- assert3(context, "context is required");
1637
- const uuid = randomUUID2();
1638
- this.saveContextFile(uuid, context);
1639
- return res.json({
1640
- location: `/playground/${uuid}`,
1641
- uuid
1690
+ // src/playground/static-page.ts
1691
+ var ThrowNotImplemented = (methodName)=>{
1692
+ throw new Error(`The method "${methodName}" is not implemented as designed since this is a static UI context. (${ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED})`);
1693
+ };
1694
+ var StaticPage = class {
1695
+ getElementInfos() {
1696
+ return __async(this, null, function*() {
1697
+ return ThrowNotImplemented("getElementInfos");
1698
+ });
1699
+ }
1700
+ size() {
1701
+ return __async(this, null, function*() {
1702
+ return this.uiContext.size;
1703
+ });
1704
+ }
1705
+ screenshotBase64() {
1706
+ return __async(this, null, function*() {
1707
+ const base64 = this.uiContext.screenshotBase64;
1708
+ if (!base64) {
1709
+ throw new Error("screenshot base64 is empty");
1710
+ }
1711
+ return base64;
1712
+ });
1713
+ }
1714
+ url() {
1715
+ return __async(this, null, function*() {
1716
+ return this.uiContext.url;
1717
+ });
1718
+ }
1719
+ scrollUntilTop() {
1720
+ return __async(this, null, function*() {
1721
+ return ThrowNotImplemented("scrollUntilTop");
1722
+ });
1723
+ }
1724
+ scrollUntilBottom() {
1725
+ return __async(this, null, function*() {
1726
+ return ThrowNotImplemented("scrollUntilBottom");
1727
+ });
1728
+ }
1729
+ scrollUpOneScreen() {
1730
+ return __async(this, null, function*() {
1731
+ return ThrowNotImplemented("scrollUpOneScreen");
1732
+ });
1733
+ }
1734
+ scrollDownOneScreen() {
1735
+ return __async(this, null, function*() {
1736
+ return ThrowNotImplemented("scrollDownOneScreen");
1737
+ });
1738
+ }
1739
+ clearInput() {
1740
+ return __async(this, null, function*() {
1741
+ return ThrowNotImplemented("clearInput");
1742
+ });
1743
+ }
1744
+ _forceUsePageContext() {
1745
+ return __async(this, null, function*() {
1746
+ return this.uiContext;
1747
+ });
1748
+ }
1749
+ destroy() {
1750
+ return __async(this, null, function*() {});
1751
+ }
1752
+ constructor(uiContext){
1753
+ this.pageType = "static";
1754
+ this.mouse = {
1755
+ click: ThrowNotImplemented.bind(null, "mouse.click"),
1756
+ wheel: ThrowNotImplemented.bind(null, "mouse.wheel"),
1757
+ move: ThrowNotImplemented.bind(null, "mouse.move")
1758
+ };
1759
+ this.keyboard = {
1760
+ type: ThrowNotImplemented.bind(null, "keyboard.type"),
1761
+ press: ThrowNotImplemented.bind(null, "keyboard.press")
1762
+ };
1763
+ this.uiContext = uiContext;
1764
+ }
1765
+ };
1766
+ // src/playground/server.ts
1767
+ var defaultPort = 5800;
1768
+ var agentRequestCount = 1;
1769
+ var errorHandler = (err, req, res, next)=>{
1770
+ console.error(err);
1771
+ res.status(500).json({
1772
+ error: err.message
1642
1773
  });
1643
- }
1644
- );
1645
- this.app.post(
1646
- "/execute",
1647
- express.json({ limit: "30mb" }),
1648
- async (req, res) => {
1649
- const { context, type, prompt } = req.body;
1650
- assert3(context, "context is required");
1651
- assert3(type, "type is required");
1652
- assert3(prompt, "prompt is required");
1653
- const requestId = agentRequestCount++;
1654
- console.log(`handle request: #${requestId}, ${type}, ${prompt}`);
1655
- const page = new StaticPage(context);
1656
- const agent = new StaticPageAgent(page);
1657
- const response = {
1658
- result: null,
1659
- dump: null,
1660
- error: null
1661
- };
1662
- try {
1663
- if (type === "aiQuery") {
1664
- response.result = await agent.aiQuery(prompt);
1665
- } else if (type === "aiAction") {
1666
- response.result = await agent.aiAction(prompt);
1667
- } else if (type === "aiAssert") {
1668
- response.result = await agent.aiAssert(prompt, void 0, {
1669
- keepRawResponse: true
1774
+ };
1775
+ var setup = ()=>__async(void 0, null, function*() {
1776
+ if (!_utils.ifInBrowser) {
1777
+ const dotenv = yield Promise.resolve().then(()=>__toESM(require_main()));
1778
+ dotenv.config();
1779
+ }
1780
+ });
1781
+ var PlaygroundServer = class {
1782
+ filePathForUuid(uuid2) {
1783
+ return (0, _path.join)(this.tmpDir, `${uuid2}.json`);
1784
+ }
1785
+ saveContextFile(uuid2, context) {
1786
+ const tmpFile = this.filePathForUuid(uuid2);
1787
+ console.log(`save context file: ${tmpFile}`);
1788
+ (0, _fs.writeFileSync)(tmpFile, context);
1789
+ return tmpFile;
1790
+ }
1791
+ launch() {
1792
+ return __async(this, null, function*() {
1793
+ this.app.use(errorHandler);
1794
+ this.app.use((0, _cors.default)({
1795
+ origin: "*",
1796
+ credentials: true
1797
+ }));
1798
+ this.app.get("/status", (0, _cors.default)(), (req, res)=>__async(this, null, function*() {
1799
+ res.send({
1800
+ status: "ok"
1801
+ });
1802
+ }));
1803
+ this.app.get("/context/:uuid", (req, res)=>__async(this, null, function*() {
1804
+ const { uuid: uuid2 } = req.params;
1805
+ const contextFile = this.filePathForUuid(uuid2);
1806
+ (0, _assert.default)((0, _fs.existsSync)(contextFile), "Context not found");
1807
+ const context = (0, _fs.readFileSync)(contextFile, "utf8");
1808
+ res.json({
1809
+ context
1810
+ });
1811
+ }));
1812
+ this.app.post("/playground-with-context", _express.default.json({
1813
+ limit: "50mb"
1814
+ }), (req, res)=>__async(this, null, function*() {
1815
+ const context = req.body.context;
1816
+ (0, _assert.default)(context, "context is required");
1817
+ const uuid2 = (0, _crypto.randomUUID)();
1818
+ this.saveContextFile(uuid2, context);
1819
+ return res.json({
1820
+ location: `/playground/${uuid2}`,
1821
+ uuid: uuid2
1822
+ });
1823
+ }));
1824
+ this.app.post("/execute", _express.default.json({
1825
+ limit: "30mb"
1826
+ }), (req, res)=>__async(this, null, function*() {
1827
+ const { context, type, prompt } = req.body;
1828
+ (0, _assert.default)(context, "context is required");
1829
+ (0, _assert.default)(type, "type is required");
1830
+ (0, _assert.default)(prompt, "prompt is required");
1831
+ const requestId = agentRequestCount++;
1832
+ console.log(`handle request: #${requestId}, ${type}, ${prompt}`);
1833
+ const page = new StaticPage(context);
1834
+ const agent = new StaticPageAgent(page);
1835
+ const response = {
1836
+ result: null,
1837
+ dump: null,
1838
+ error: null
1839
+ };
1840
+ try {
1841
+ if (type === "aiQuery") {
1842
+ response.result = yield agent.aiQuery(prompt);
1843
+ } else if (type === "aiAction") {
1844
+ response.result = yield agent.aiAction(prompt);
1845
+ } else if (type === "aiAssert") {
1846
+ response.result = yield agent.aiAssert(prompt, void 0, {
1847
+ keepRawResponse: true
1848
+ });
1849
+ } else {
1850
+ response.error = `Unknown type: ${type}`;
1851
+ }
1852
+ } catch (error) {
1853
+ if (!error.message.includes(ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED)) {
1854
+ response.error = error.message;
1855
+ }
1856
+ }
1857
+ try {
1858
+ response.dump = JSON.parse(agent.dumpDataString());
1859
+ agent.writeOutActionDumps();
1860
+ } catch (error) {
1861
+ console.error(`write out dump failed: #${requestId}, ${error.message}`);
1862
+ }
1863
+ res.send(response);
1864
+ if (response.error) {
1865
+ console.error(`handle request failed: #${requestId}, ${response.error}`);
1866
+ } else {
1867
+ console.log(`handle request done: #${requestId}`);
1868
+ }
1869
+ }));
1870
+ return new Promise((resolve, reject)=>{
1871
+ const port = this.port || defaultPort;
1872
+ this.server = this.app.listen(port, ()=>{
1873
+ this.port = port;
1874
+ resolve(this);
1875
+ });
1876
+ });
1670
1877
  });
1671
- } else {
1672
- response.error = `Unknown type: ${type}`;
1673
- }
1674
- } catch (error) {
1675
- if (!error.message.includes(ERROR_CODE_NOT_IMPLEMENTED_AS_DESIGNED)) {
1676
- response.error = error.message;
1677
- }
1678
1878
  }
1679
- try {
1680
- response.dump = JSON.parse(agent.dumpDataString());
1681
- agent.writeOutActionDumps();
1682
- } catch (error) {
1683
- console.error(
1684
- `write out dump failed: #${requestId}, ${error.message}`
1685
- );
1879
+ close() {
1880
+ if (this.server) {
1881
+ return this.server.close();
1882
+ }
1686
1883
  }
1687
- res.send(response);
1688
- if (response.error) {
1689
- console.error(
1690
- `handle request failed: #${requestId}, ${response.error}`
1691
- );
1692
- } else {
1693
- console.log(`handle request done: #${requestId}`);
1884
+ constructor(){
1885
+ this.app = (0, _express.default)();
1886
+ this.tmpDir = (0, _utils1.getTmpDir)();
1887
+ setup();
1694
1888
  }
1695
- }
1696
- );
1697
- return new Promise((resolve, reject) => {
1698
- const port = this.port || defaultPort;
1699
- this.server = this.app.listen(port, () => {
1700
- this.port = port;
1701
- resolve(this);
1702
- });
1889
+ };
1890
+ // src/playground/bin.ts
1891
+ var server = new PlaygroundServer();
1892
+ Promise.resolve().then(()=>server.launch()).then(()=>{
1893
+ console.log(`Midscene playground server is running on http://localhost:${server.port}`);
1703
1894
  });
1704
- }
1705
- close() {
1706
- if (this.server) {
1707
- return this.server.close();
1708
- }
1709
- }
1710
- };
1711
-
1712
- // src/playground/bin.ts
1713
- var server = new PlaygroundServer();
1714
- Promise.resolve().then(() => server.launch()).then(() => {
1715
- console.log(
1716
- `Midscene playground server is running on http://localhost:${server.port}`
1717
- );
1718
1895
  });