@burdenoff/ui-engine 2026.1127.2 → 2026.1127.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +74 -4
  2. package/dist/capture.js +3 -2
  3. package/dist/dom-runtime/actions.d.ts +65 -0
  4. package/dist/dom-runtime/iife.d.ts +1 -0
  5. package/dist/dom-runtime/index.d.ts +7 -0
  6. package/dist/dom-runtime/runtime.d.ts +79 -0
  7. package/dist/dom-runtime.d.ts +2 -0
  8. package/dist/dom-runtime.iife.js +1 -0
  9. package/dist/dom-runtime.js +30 -0
  10. package/dist/drivers/dom-driver.d.ts +44 -0
  11. package/dist/drivers/index.d.ts +7 -0
  12. package/dist/drivers/snapshot-driver.d.ts +59 -0
  13. package/dist/drivers.d.ts +2 -0
  14. package/dist/drivers.js +170 -0
  15. package/dist/{index-n5amgh31.js → index-2kgsgn1c.js} +1 -1
  16. package/dist/index-3f1j8386.js +334 -0
  17. package/dist/index-3jymbm5t.js +315 -0
  18. package/dist/index-5k26keah.js +815 -0
  19. package/dist/index-77pcz6n3.js +303 -0
  20. package/dist/index-895kscx3.js +741 -0
  21. package/dist/{index-phd8yhyg.js → index-bnvmt4wf.js} +7 -5
  22. package/dist/{index-c6pmt2rg.js → index-cs6acyjn.js} +6 -59
  23. package/dist/index-ct2xctrq.js +229 -0
  24. package/dist/index-h88y5qgv.js +400 -0
  25. package/dist/index-mgztm37r.js +57 -0
  26. package/dist/{index-tqffkt91.js → index-pm13mvvc.js} +26 -1009
  27. package/dist/index-vg8r40y7.js +220 -0
  28. package/dist/index-ycs2bz1a.js +589 -0
  29. package/dist/index-zzhysbkj.js +1731 -0
  30. package/dist/index.d.ts +1 -0
  31. package/dist/index.js +130 -42
  32. package/dist/interpret/compile.d.ts +58 -0
  33. package/dist/interpret/driver.d.ts +171 -0
  34. package/dist/interpret/errors.d.ts +194 -0
  35. package/dist/interpret/events.d.ts +73 -0
  36. package/dist/interpret/expr.d.ts +35 -0
  37. package/dist/interpret/index.d.ts +13 -0
  38. package/dist/interpret/run.d.ts +77 -0
  39. package/dist/interpret.d.ts +2 -0
  40. package/dist/interpret.js +84 -0
  41. package/dist/recording.js +1 -1
  42. package/dist/replay.js +2 -2
  43. package/dist/script/adapters/browser-action-contract.d.ts +5 -2
  44. package/dist/script/limits.d.ts +2 -0
  45. package/dist/script.js +44 -38
  46. package/dist/target/aria.d.ts +31 -0
  47. package/dist/target/dom.d.ts +35 -0
  48. package/dist/target/index.d.ts +13 -0
  49. package/dist/target/markers.d.ts +18 -0
  50. package/dist/target/methods.d.ts +52 -0
  51. package/dist/target/resolve.d.ts +63 -0
  52. package/dist/target/snapshot.d.ts +57 -0
  53. package/dist/target/text.d.ts +23 -0
  54. package/dist/target/types.d.ts +88 -0
  55. package/dist/target.d.ts +2 -0
  56. package/dist/target.js +96 -0
  57. package/dist/testing/fake-web-driver.d.ts +28 -0
  58. package/dist/testing/fixtures/ambiguous.d.ts +7 -0
  59. package/dist/testing/fixtures/iframe.d.ts +6 -0
  60. package/dist/testing/fixtures/index.d.ts +26 -0
  61. package/dist/testing/fixtures/invoices-v2.d.ts +8 -0
  62. package/dist/testing/fixtures/invoices-v3.d.ts +7 -0
  63. package/dist/testing/fixtures/invoices.d.ts +6 -0
  64. package/dist/testing/fixtures/login.d.ts +6 -0
  65. package/dist/testing/fixtures/shadow.d.ts +7 -0
  66. package/dist/testing/index.d.ts +7 -0
  67. package/dist/testing/mount.d.ts +18 -0
  68. package/dist/testing.d.ts +2 -0
  69. package/dist/testing.js +379 -0
  70. package/package.json +29 -5
@@ -0,0 +1,1731 @@
1
+ import {
2
+ UiScriptError2,
3
+ parseUiScript2
4
+ } from "./index-895kscx3.js";
5
+ import {
6
+ isUiErrorCode2,
7
+ isRetryableInScript2,
8
+ UiRunError2,
9
+ UiDriverError2,
10
+ realClock2
11
+ } from "./index-vg8r40y7.js";
12
+ import {
13
+ walkSteps2,
14
+ stepTargets2,
15
+ missingCapabilities2
16
+ } from "./index-3jymbm5t.js";
17
+ import {
18
+ MAX_TYPED_TEXT2
19
+ } from "./index-77pcz6n3.js";
20
+ import {
21
+ containsText2
22
+ } from "./index-ycs2bz1a.js";
23
+ import {
24
+ redactCredentials2
25
+ } from "./index-mgztm37r.js";
26
+
27
+ // src/interpret/expr.ts
28
+ var MAX_VALUE_TEXT2 = 1e6;
29
+ var MAX_VALUE_ITEMS2 = 1e4;
30
+ function fail(op, problem) {
31
+ throw new UiRunError2("EXPRESSION_ERROR", op === "value" ? problem : `The operator "${op}" ${problem}`, {
32
+ ...op === "value" ? {} : { op }
33
+ });
34
+ }
35
+ function isRecord(value) {
36
+ return value !== null && typeof value === "object" && !Array.isArray(value);
37
+ }
38
+ function toUiValue2(value, depth = 0) {
39
+ if (value === null || value === undefined)
40
+ return null;
41
+ if (typeof value === "string" || typeof value === "boolean")
42
+ return value;
43
+ if (typeof value === "number")
44
+ return Number.isFinite(value) ? value : null;
45
+ if (depth > 32)
46
+ return null;
47
+ if (Array.isArray(value))
48
+ return value.slice(0, MAX_VALUE_ITEMS2).map((item) => toUiValue2(item, depth + 1));
49
+ if (typeof value === "object") {
50
+ const entries = Object.entries(value).slice(0, MAX_VALUE_ITEMS2);
51
+ return Object.fromEntries(entries.map(([key, item]) => [key, toUiValue2(item, depth + 1)]));
52
+ }
53
+ return null;
54
+ }
55
+ function readPath2(value, path) {
56
+ let current = value;
57
+ for (const key of path ?? []) {
58
+ if (Array.isArray(current) && typeof key === "number")
59
+ current = current[key] ?? null;
60
+ else if (isRecord(current) && typeof key === "string" && Object.hasOwn(current, key))
61
+ current = current[key] ?? null;
62
+ else
63
+ return null;
64
+ }
65
+ return current;
66
+ }
67
+ function truthy2(value) {
68
+ if (value === null)
69
+ return false;
70
+ if (typeof value === "boolean")
71
+ return value;
72
+ if (typeof value === "number")
73
+ return value !== 0 && !Number.isNaN(value);
74
+ if (typeof value === "string") {
75
+ const text = value.trim().toLowerCase();
76
+ return text !== "" && text !== "false" && text !== "0" && text !== "no";
77
+ }
78
+ if (Array.isArray(value))
79
+ return value.length > 0;
80
+ return Object.keys(value).length > 0;
81
+ }
82
+ function valuesEqual2(a, b) {
83
+ if (a === b)
84
+ return true;
85
+ if (Array.isArray(a) || Array.isArray(b)) {
86
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => valuesEqual2(item, b[i] ?? null));
87
+ }
88
+ if (isRecord(a) && isRecord(b)) {
89
+ const keys = Object.keys(a);
90
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && valuesEqual2(a[key] ?? null, b[key] ?? null));
91
+ }
92
+ return false;
93
+ }
94
+ function boundedText(op, text) {
95
+ if (text.length > MAX_VALUE_TEXT2)
96
+ fail(op, `produced text longer than ${MAX_VALUE_TEXT2} characters`);
97
+ return text;
98
+ }
99
+ function joinBounded(op, parts, separator) {
100
+ let length = Math.max(0, parts.length - 1) * separator.length;
101
+ for (const part of parts)
102
+ length += part.length;
103
+ if (length > MAX_VALUE_TEXT2)
104
+ fail(op, `produced text longer than ${MAX_VALUE_TEXT2} characters`);
105
+ return parts.join(separator);
106
+ }
107
+ function finite(op, value) {
108
+ if (!Number.isFinite(value))
109
+ fail(op, "produced a number that is not finite");
110
+ return value;
111
+ }
112
+ function toText2(value, op = "toText") {
113
+ if (value === null)
114
+ return "";
115
+ if (typeof value === "string")
116
+ return value;
117
+ if (typeof value === "number" || typeof value === "boolean")
118
+ return String(value);
119
+ return boundedText(op, JSON.stringify(value));
120
+ }
121
+ function toNumber2(value, op = "toNumber") {
122
+ if (value === null)
123
+ return 0;
124
+ if (typeof value === "number")
125
+ return finite(op, value);
126
+ if (typeof value === "boolean")
127
+ return value ? 1 : 0;
128
+ if (typeof value === "string") {
129
+ const text = value.trim();
130
+ const parsed = text === "" ? Number.NaN : Number(text);
131
+ if (Number.isFinite(parsed))
132
+ return parsed;
133
+ return fail(op, "needs a number, and a text that is not a number was given");
134
+ }
135
+ return fail(op, "needs a number, and a list or an object was given");
136
+ }
137
+ function needText(op, value) {
138
+ if (Array.isArray(value) || isRecord(value))
139
+ fail(op, "needs text, and a list or an object was given");
140
+ return toText2(value, op);
141
+ }
142
+ function needList(op, value) {
143
+ if (!Array.isArray(value))
144
+ fail(op, "needs a list");
145
+ return value;
146
+ }
147
+ function compare(op, a, b) {
148
+ if (typeof a === "string" && typeof b === "string")
149
+ return a < b ? -1 : a > b ? 1 : 0;
150
+ return toNumber2(a, op) - toNumber2(b, op);
151
+ }
152
+ var DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
153
+ function toDate(op, value) {
154
+ const date = typeof value === "number" ? new Date(value) : typeof value === "string" && value.trim() !== "" ? new Date(DATE_ONLY.test(value.trim()) ? `${value.trim()}T00:00:00Z` : value.trim()) : null;
155
+ if (!date || Number.isNaN(date.getTime()))
156
+ fail(op, "needs a date (ISO 8601 text or milliseconds)");
157
+ return date;
158
+ }
159
+ var pad = (value, size = 2) => String(value).padStart(size, "0");
160
+ function formatDate(date, pattern) {
161
+ const tokens = {
162
+ YYYY: pad(date.getUTCFullYear(), 4),
163
+ MM: pad(date.getUTCMonth() + 1),
164
+ DD: pad(date.getUTCDate()),
165
+ HH: pad(date.getUTCHours()),
166
+ mm: pad(date.getUTCMinutes()),
167
+ ss: pad(date.getUTCSeconds())
168
+ };
169
+ return pattern.replace(/YYYY|MM|DD|HH|mm|ss/g, (token) => tokens[token] ?? token);
170
+ }
171
+ function replaceAll(text, search, replacement) {
172
+ if (search === "")
173
+ return text;
174
+ return text.split(search).join(replacement);
175
+ }
176
+ function evaluateExpression2(expression, scope) {
177
+ try {
178
+ return evaluate(expression, scope);
179
+ } catch (error) {
180
+ if (error instanceof RangeError)
181
+ fail("value", "An expression produced a value too large to hold");
182
+ throw error;
183
+ }
184
+ }
185
+ function evaluate(expression, scope) {
186
+ if (expression === null || typeof expression !== "object")
187
+ return expression;
188
+ if ("input" in expression) {
189
+ const value = Object.hasOwn(scope.inputs, expression.input) ? scope.inputs[expression.input] ?? null : null;
190
+ return readPath2(value, expression.path);
191
+ }
192
+ if ("var" in expression)
193
+ return readPath2(scope.variables.get(expression.var) ?? null, expression.path);
194
+ if ("list" in expression) {
195
+ if (expression.list.length > MAX_VALUE_ITEMS2)
196
+ fail("value", `A list holds at most ${MAX_VALUE_ITEMS2} items`);
197
+ return expression.list.map((item) => evaluate(item, scope));
198
+ }
199
+ if ("object" in expression) {
200
+ return Object.fromEntries(Object.entries(expression.object).map(([key, item]) => [key, evaluate(item, scope)]));
201
+ }
202
+ return applyOperator(expression.op, expression.args, scope);
203
+ }
204
+ function applyOperator(op, args, scope) {
205
+ const at = (index) => {
206
+ const arg = args[index];
207
+ return arg === undefined ? null : evaluate(arg, scope);
208
+ };
209
+ const all = () => args.map((arg) => evaluate(arg, scope));
210
+ const operands = () => {
211
+ const values = all();
212
+ return values.length === 1 && Array.isArray(values[0]) ? values[0] : values;
213
+ };
214
+ switch (op) {
215
+ case "eq":
216
+ return valuesEqual2(at(0), at(1));
217
+ case "ne":
218
+ return !valuesEqual2(at(0), at(1));
219
+ case "lt":
220
+ return compare(op, at(0), at(1)) < 0;
221
+ case "le":
222
+ return compare(op, at(0), at(1)) <= 0;
223
+ case "gt":
224
+ return compare(op, at(0), at(1)) > 0;
225
+ case "ge":
226
+ return compare(op, at(0), at(1)) >= 0;
227
+ case "and":
228
+ return args.every((arg) => truthy2(evaluate(arg, scope)));
229
+ case "or":
230
+ return args.some((arg) => truthy2(evaluate(arg, scope)));
231
+ case "not":
232
+ return !truthy2(at(0));
233
+ case "add":
234
+ return finite(op, all().reduce((sum, value) => sum + toNumber2(value, op), 0));
235
+ case "sub":
236
+ return finite(op, toNumber2(at(0), op) - toNumber2(at(1), op));
237
+ case "mul":
238
+ return finite(op, all().reduce((product, value) => product * toNumber2(value, op), 1));
239
+ case "div": {
240
+ const divisor = toNumber2(at(1), op);
241
+ if (divisor === 0)
242
+ fail(op, "divided by zero");
243
+ return finite(op, toNumber2(at(0), op) / divisor);
244
+ }
245
+ case "mod": {
246
+ const divisor = toNumber2(at(1), op);
247
+ if (divisor === 0)
248
+ fail(op, "divided by zero");
249
+ return finite(op, toNumber2(at(0), op) % divisor);
250
+ }
251
+ case "neg":
252
+ return finite(op, -toNumber2(at(0), op));
253
+ case "abs":
254
+ return Math.abs(toNumber2(at(0), op));
255
+ case "round": {
256
+ const digits = args.length > 1 ? toNumber2(at(1), op) : 0;
257
+ if (!Number.isInteger(digits) || digits < 0 || digits > 10)
258
+ fail(op, "takes 0 to 10 decimal places");
259
+ const factor = 10 ** digits;
260
+ return finite(op, Math.round(toNumber2(at(0), op) * factor) / factor);
261
+ }
262
+ case "min":
263
+ case "max": {
264
+ const values = operands();
265
+ if (values.length === 0)
266
+ fail(op, "needs at least one value");
267
+ const numbers = values.map((value) => toNumber2(value, op));
268
+ return op === "min" ? Math.min(...numbers) : Math.max(...numbers);
269
+ }
270
+ case "concat":
271
+ return joinBounded(op, all().map((value) => toText2(value, op)), "");
272
+ case "contains": {
273
+ const haystack = at(0);
274
+ const needle = at(1);
275
+ if (Array.isArray(haystack))
276
+ return haystack.some((item) => valuesEqual2(item, needle));
277
+ return needText(op, haystack).includes(needText(op, needle));
278
+ }
279
+ case "startsWith":
280
+ return needText(op, at(0)).startsWith(needText(op, at(1)));
281
+ case "endsWith":
282
+ return needText(op, at(0)).endsWith(needText(op, at(1)));
283
+ case "lower":
284
+ return needText(op, at(0)).toLowerCase();
285
+ case "upper":
286
+ return needText(op, at(0)).toUpperCase();
287
+ case "trim":
288
+ return needText(op, at(0)).trim();
289
+ case "replace": {
290
+ const text = needText(op, at(0));
291
+ const search = needText(op, at(1));
292
+ const replacement = needText(op, at(2));
293
+ const occurrences = search === "" ? 0 : text.split(search).length - 1;
294
+ if (text.length + occurrences * (replacement.length - search.length) > MAX_VALUE_TEXT2) {
295
+ fail(op, `produced text longer than ${MAX_VALUE_TEXT2} characters`);
296
+ }
297
+ return replaceAll(text, search, replacement);
298
+ }
299
+ case "split": {
300
+ const text = needText(op, at(0));
301
+ const separator = needText(op, at(1));
302
+ const parts = separator === "" ? Array.from(text) : text.split(separator);
303
+ if (parts.length > MAX_VALUE_ITEMS2)
304
+ fail(op, `produced more than ${MAX_VALUE_ITEMS2} items`);
305
+ return parts;
306
+ }
307
+ case "join": {
308
+ const list = needList(op, at(0));
309
+ const separator = args.length > 1 ? needText(op, at(1)) : ",";
310
+ return joinBounded(op, list.map((item) => toText2(item, op)), separator);
311
+ }
312
+ case "length": {
313
+ const value = at(0);
314
+ if (value === null)
315
+ return 0;
316
+ if (typeof value === "string" || Array.isArray(value))
317
+ return value.length;
318
+ if (isRecord(value))
319
+ return Object.keys(value).length;
320
+ return toText2(value, op).length;
321
+ }
322
+ case "toNumber":
323
+ return toNumber2(at(0), op);
324
+ case "toText":
325
+ return toText2(at(0), op);
326
+ case "toBoolean":
327
+ return truthy2(at(0));
328
+ case "isEmpty": {
329
+ const value = at(0);
330
+ if (value === null || value === "")
331
+ return true;
332
+ if (Array.isArray(value))
333
+ return value.length === 0;
334
+ return isRecord(value) && Object.keys(value).length === 0;
335
+ }
336
+ case "coalesce":
337
+ for (const arg of args) {
338
+ const value = evaluate(arg, scope);
339
+ if (value !== null)
340
+ return value;
341
+ }
342
+ return null;
343
+ case "if":
344
+ return truthy2(at(0)) ? at(1) : at(2);
345
+ case "get": {
346
+ const value = at(0);
347
+ const key = at(1);
348
+ if (Array.isArray(value) && typeof key === "number")
349
+ return value[key] ?? null;
350
+ if (isRecord(value) && typeof key === "string")
351
+ return Object.hasOwn(value, key) ? value[key] ?? null : null;
352
+ return null;
353
+ }
354
+ case "now":
355
+ return new Date(scope.now()).toISOString();
356
+ case "formatDate": {
357
+ const pattern = args.length > 1 ? needText(op, at(1)) : "YYYY-MM-DD";
358
+ if (pattern.length > 100)
359
+ fail(op, "takes a format of at most 100 characters");
360
+ return formatDate(toDate(op, at(0)), pattern);
361
+ }
362
+ case "addDays": {
363
+ const input = at(0);
364
+ const days = toNumber2(at(1), op);
365
+ if (!Number.isInteger(days) || Math.abs(days) > 1e6)
366
+ fail(op, "adds a whole number of days");
367
+ const date = toDate(op, input);
368
+ const moved = new Date(date.getTime() + days * 86400000);
369
+ if (Number.isNaN(moved.getTime()))
370
+ fail(op, "produced a date out of range");
371
+ return typeof input === "string" && DATE_ONLY.test(input.trim()) ? formatDate(moved, "YYYY-MM-DD") : moved.toISOString();
372
+ }
373
+ default:
374
+ return fail("value", "Unknown operator");
375
+ }
376
+ }
377
+
378
+ // src/interpret/events.ts
379
+ var UI_RUN_EVENT_KINDS2 = [
380
+ "STEP_STARTED",
381
+ "STEP_PASSED",
382
+ "STEP_FAILED",
383
+ "STEP_SKIPPED",
384
+ "PAUSED",
385
+ "RESUMED",
386
+ "LOG",
387
+ "FINISHED"
388
+ ];
389
+ var DEFAULT_MAX_EVENTS2 = 1e4;
390
+ var MAX_STEP_LOG_ENTRIES2 = 500;
391
+ var MAX_EVENT_MESSAGE2 = 2000;
392
+
393
+ class EventEmitter {
394
+ maxEvents;
395
+ now;
396
+ deliver;
397
+ seq = 0;
398
+ dropped = 0;
399
+ truncated = false;
400
+ constructor(maxEvents, now, deliver) {
401
+ this.maxEvents = maxEvents;
402
+ this.now = now;
403
+ this.deliver = deliver;
404
+ }
405
+ get emitted() {
406
+ return this.seq;
407
+ }
408
+ get droppedCount() {
409
+ return this.dropped;
410
+ }
411
+ get isTruncated() {
412
+ return this.truncated;
413
+ }
414
+ async emit(draft) {
415
+ if (draft.kind !== "FINISHED") {
416
+ if (this.truncated) {
417
+ this.dropped += 1;
418
+ return;
419
+ }
420
+ if (this.seq >= this.maxEvents - 1) {
421
+ this.truncated = true;
422
+ this.dropped += 1;
423
+ await this.send({
424
+ kind: "LOG",
425
+ message: `The run reached ${this.maxEvents} events; later step events are not reported`,
426
+ detail: { level: "warn", truncated: true }
427
+ });
428
+ return;
429
+ }
430
+ }
431
+ await this.send(draft);
432
+ }
433
+ async send(draft) {
434
+ this.seq += 1;
435
+ const event = { seq: this.seq, at: new Date(this.now()).toISOString(), ...draft };
436
+ if (!this.deliver)
437
+ return;
438
+ try {
439
+ await this.deliver(event);
440
+ } catch {}
441
+ }
442
+ }
443
+
444
+ // src/interpret/run.ts
445
+ var DEFAULT_FIRST_WAIT_MS2 = 30000;
446
+ var DEFAULT_WAIT_MS2 = 1e4;
447
+ var DEFAULT_RETRY_DELAY_MS2 = 1000;
448
+ var DEFAULT_POLL_INTERVAL_MS2 = 250;
449
+ var MAX_EVENTS_LIMIT2 = 1e5;
450
+ var MAX_PAGE_TEXT2 = 1e6;
451
+ var DEFAULT_LIST_ITEMS2 = 100;
452
+
453
+ class StopSignal extends Error {
454
+ kind;
455
+ constructor(kind) {
456
+ super(kind);
457
+ this.kind = kind;
458
+ }
459
+ }
460
+
461
+ class StepFailure extends Error {
462
+ code;
463
+ stepPath;
464
+ stepId;
465
+ detail;
466
+ constructor(code, message, stepPath, stepId, detail) {
467
+ super(message);
468
+ this.code = code;
469
+ this.stepPath = stepPath;
470
+ this.stepId = stepId;
471
+ this.detail = detail;
472
+ }
473
+ }
474
+ var FLOW_ACTIONS = new Set(["if", "forEach", "while", "retryScope", "set", "log", "call"]);
475
+ function clipMessage(text) {
476
+ return redactCredentials2(text).slice(0, MAX_EVENT_MESSAGE2);
477
+ }
478
+ function failureDetail(failure, waitedMs) {
479
+ const resolution = failure.resolution;
480
+ return {
481
+ waitedMs,
482
+ ...failure.reason ? { reason: failure.reason } : {},
483
+ ...isUiErrorCode2(failure.code) ? {} : { problem: failure.code },
484
+ ...resolution ? {
485
+ attempts: resolution.attempts,
486
+ ...resolution.status === "failed" ? {
487
+ candidates: resolution.candidates,
488
+ candidateCount: resolution.candidateCount,
489
+ ...resolution.frame ? { frame: resolution.frame } : {}
490
+ } : { method: resolution.method, fallback: resolution.fallback }
491
+ } : {}
492
+ };
493
+ }
494
+ function codeOfFailure(failure) {
495
+ if (failure.code === "ELEMENT_NOT_FOUND" || failure.code === "ELEMENT_AMBIGUOUS")
496
+ return failure.code;
497
+ if (failure.code === "ELEMENT_NOT_INTERACTABLE")
498
+ return failure.code;
499
+ if (failure.code === "SENSITIVE_ELEMENT")
500
+ return "SENSITIVE_ELEMENT";
501
+ return "ACTION_FAILED";
502
+ }
503
+ var FAILURE_MESSAGES = {
504
+ ELEMENT_NOT_FOUND: "No target method found the element",
505
+ ELEMENT_AMBIGUOUS: "More than one element matched the target; nothing was acted on",
506
+ ELEMENT_NOT_INTERACTABLE: "The element was found but could not be used (disabled, hidden or covered)",
507
+ SENSITIVE_ELEMENT: "Reading a sensitive field is not allowed",
508
+ ACTION_FAILED: "The action does not apply to the element the target found"
509
+ };
510
+ function isGone(resolution, hiddenCounts) {
511
+ if (resolution.status === "found")
512
+ return false;
513
+ return resolution.code === "ELEMENT_NOT_FOUND" || hiddenCounts && resolution.code === "ELEMENT_NOT_INTERACTABLE";
514
+ }
515
+ function isFinalFailure(failure) {
516
+ const code = codeOfFailure(failure);
517
+ return code === "ACTION_FAILED" || code === "SENSITIVE_ELEMENT";
518
+ }
519
+ function readKindOf(field) {
520
+ switch (field.attribute) {
521
+ case undefined:
522
+ return { kind: "auto" };
523
+ case "text":
524
+ case "value":
525
+ case "html":
526
+ return { kind: field.attribute };
527
+ default:
528
+ return { kind: "attribute", name: field.attribute };
529
+ }
530
+ }
531
+ function typeMatches(type, value) {
532
+ switch (type) {
533
+ case undefined:
534
+ case "any":
535
+ return true;
536
+ case "text":
537
+ return typeof value === "string";
538
+ case "number":
539
+ return typeof value === "number";
540
+ case "boolean":
541
+ return typeof value === "boolean";
542
+ case "list":
543
+ return Array.isArray(value);
544
+ case "object":
545
+ return value !== null && typeof value === "object" && !Array.isArray(value);
546
+ }
547
+ }
548
+ async function runUiScript2(script, driver, options = {}) {
549
+ return new Interpreter(driver, options).run(script);
550
+ }
551
+
552
+ class Interpreter {
553
+ driver;
554
+ options;
555
+ clock;
556
+ emitter;
557
+ startedAt;
558
+ pollMs;
559
+ test;
560
+ script;
561
+ inputs = {};
562
+ variables = new Map;
563
+ results = {};
564
+ stepLog = [];
565
+ stepLogTruncated = false;
566
+ lastCompleted;
567
+ completed = 0;
568
+ freshScreen = true;
569
+ started = true;
570
+ rangeAncestors = new Set;
571
+ stepping = false;
572
+ ending = false;
573
+ inCleanup = false;
574
+ iterations = [];
575
+ constructor(driver, options) {
576
+ this.driver = driver;
577
+ this.options = options;
578
+ this.clock = driver.clock ?? realClock2;
579
+ this.startedAt = this.clock.now();
580
+ const maxEvents = Math.min(MAX_EVENTS_LIMIT2, Math.max(1, Math.floor(options.maxEvents ?? DEFAULT_MAX_EVENTS2)));
581
+ this.emitter = new EventEmitter(maxEvents, () => this.clock.now(), options.onEvent);
582
+ this.pollMs = Math.max(10, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS2);
583
+ this.test = options.mode === "test" && typeof options.waitForCommand === "function";
584
+ this.stepping = this.test && options.stepThrough === true;
585
+ }
586
+ get scope() {
587
+ return { inputs: this.inputs, variables: this.variables, now: () => this.clock.now() };
588
+ }
589
+ async run(input) {
590
+ try {
591
+ this.preflight(input);
592
+ } catch (error) {
593
+ const failure = error instanceof UiRunError2 ? error : new UiRunError2("INVALID_SCRIPT", "The UI script could not be read");
594
+ return this.finish("failed", { code: failure.code, family: failure.family, message: failure.message }, failure.detail);
595
+ }
596
+ let status = "succeeded";
597
+ let failure;
598
+ let failureDetailValue;
599
+ let stopKind;
600
+ try {
601
+ await this.runList(this.script.steps, "");
602
+ } catch (error) {
603
+ if (error instanceof StopSignal)
604
+ stopKind = error.kind;
605
+ else if (error instanceof StepFailure) {
606
+ status = "failed";
607
+ failure = this.failureOf(error);
608
+ failureDetailValue = error.detail;
609
+ } else
610
+ throw error;
611
+ }
612
+ if (stopKind === "cancelled" || stopKind === "stopped")
613
+ this.ending = true;
614
+ if (stopKind === "cancelled") {
615
+ status = "cancelled";
616
+ failure = { code: "CANCELLED", family: "CANCELLED", message: "The run was cancelled" };
617
+ } else if (stopKind === "stopped") {
618
+ status = "stopped";
619
+ failure = { code: "STOPPED_BY_USER", family: "CANCELLED", message: "The run was stopped by a person" };
620
+ }
621
+ const cleanupInRange = stopKind !== "rangeEnd" && (this.started || this.rangeStartsInCleanup());
622
+ const skipCleanup = stopKind === "cancelled" && this.options.skipCleanupOnCancel === true;
623
+ if (this.script.cleanup && cleanupInRange && !skipCleanup) {
624
+ const cleanup = await this.runCleanup(this.script.cleanup);
625
+ if (cleanup.stopped && status === "succeeded") {
626
+ status = "stopped";
627
+ failure = { code: "STOPPED_BY_USER", family: "CANCELLED", message: "The run was stopped by a person" };
628
+ } else if (cleanup.failure && status === "succeeded") {
629
+ status = "failed";
630
+ failure = this.failureOf(cleanup.failure);
631
+ failureDetailValue = cleanup.failure.detail;
632
+ }
633
+ }
634
+ if (status === "succeeded" && !this.started) {
635
+ status = "failed";
636
+ failure = {
637
+ code: "INVALID_STEP_RANGE",
638
+ family: "VALIDATION",
639
+ message: "The run never reached the step range start (a block around it was disabled, skipped or ran no pass)"
640
+ };
641
+ }
642
+ let outputs = {};
643
+ if (status === "succeeded") {
644
+ try {
645
+ outputs = this.evaluateOutputs();
646
+ } catch (error) {
647
+ if (!(error instanceof UiRunError2))
648
+ throw error;
649
+ status = "failed";
650
+ failure = { code: error.code, family: error.family, message: error.message };
651
+ }
652
+ }
653
+ return this.finish(status, failure, failureDetailValue, outputs);
654
+ }
655
+ failureOf(error) {
656
+ const known = new UiRunError2(error.code, error.message);
657
+ return {
658
+ code: error.code,
659
+ family: known.family,
660
+ message: error.message,
661
+ stepPath: error.stepPath,
662
+ stepId: error.stepId
663
+ };
664
+ }
665
+ async finish(status, failure, detail, outputs = {}) {
666
+ const durationMs = Math.max(0, this.clock.now() - this.startedAt);
667
+ await this.emitter.emit({
668
+ kind: "FINISHED",
669
+ durationMs,
670
+ ...failure ? { errorCode: failure.code, message: clipMessage(failure.message) } : {},
671
+ ...failure?.stepPath === undefined ? {} : { stepPath: failure.stepPath, stepId: failure.stepId },
672
+ detail: {
673
+ status,
674
+ droppedEvents: this.emitter.droppedCount,
675
+ ...this.lastCompleted === undefined ? {} : { lastCompletedStepPath: this.lastCompleted },
676
+ ...failure && failure.stepPath === undefined && detail ? detail : {}
677
+ }
678
+ });
679
+ return {
680
+ status,
681
+ outputs,
682
+ results: this.results,
683
+ stepLog: this.stepLog,
684
+ stepLogTruncated: this.stepLogTruncated,
685
+ ...failure ? { error: failure } : {},
686
+ ...this.lastCompleted === undefined ? {} : { lastCompletedStepPath: this.lastCompleted },
687
+ completedSteps: this.completed,
688
+ events: {
689
+ emitted: this.emitter.emitted,
690
+ dropped: this.emitter.droppedCount,
691
+ truncated: this.emitter.isTruncated
692
+ },
693
+ durationMs
694
+ };
695
+ }
696
+ preflight(input) {
697
+ try {
698
+ this.script = parseUiScript2(input, { resolved: true });
699
+ } catch (error) {
700
+ if (error instanceof UiScriptError2) {
701
+ throw new UiRunError2("INVALID_SCRIPT", error.message, {
702
+ engineCode: error.code,
703
+ ...error.path === undefined ? {} : { path: error.path }
704
+ });
705
+ }
706
+ throw error;
707
+ }
708
+ const missing = missingCapabilities2(this.script, this.driver.capabilities);
709
+ const needed = this.test ? missing : missing.filter((id) => id !== "step:breakpoint");
710
+ if (needed.length > 0) {
711
+ throw new UiRunError2("UNSUPPORTED_ON_DESK", `The desk cannot run this script: it lacks ${needed.join(", ")}`, {
712
+ missing: needed
713
+ });
714
+ }
715
+ for (const { step, path } of walkSteps2(this.script)) {
716
+ if (step.action === "type" && step.masked === true && step.text === undefined && step.disabled !== true) {
717
+ throw new UiRunError2("INVALID_SCRIPT", `Step ${step.id} types a masked value and needs a value before it can run`, {
718
+ path
719
+ });
720
+ }
721
+ }
722
+ this.checkRange();
723
+ this.bindInputs();
724
+ for (const variable of this.script.variables ?? []) {
725
+ this.variables.set(variable.name, variable.initial === undefined ? null : this.evaluateOrInvalid(variable.initial, `variables.${variable.name}`));
726
+ }
727
+ }
728
+ evaluateOrInvalid(expression, where) {
729
+ try {
730
+ return evaluateExpression2(expression, this.scope);
731
+ } catch (error) {
732
+ if (error instanceof UiRunError2)
733
+ throw new UiRunError2("INVALID_INPUT", `${where}: ${error.message}`);
734
+ throw error;
735
+ }
736
+ }
737
+ bindInputs() {
738
+ const given = this.options.inputs ?? {};
739
+ const bound = {};
740
+ for (const declared of this.script.inputs ?? []) {
741
+ if (Object.hasOwn(given, declared.name) && given[declared.name] !== undefined) {
742
+ const value = toUiValue2(given[declared.name]);
743
+ if (!typeMatches(declared.type, value)) {
744
+ throw new UiRunError2("INVALID_INPUT", `The input "${declared.name}" must be ${declared.type ?? "any"}`, {
745
+ input: declared.name
746
+ });
747
+ }
748
+ bound[declared.name] = value;
749
+ } else if (declared.default !== undefined) {
750
+ this.inputs = bound;
751
+ bound[declared.name] = this.evaluateOrInvalid(declared.default, `inputs.${declared.name}`);
752
+ } else if (declared.required === true) {
753
+ throw new UiRunError2("INVALID_INPUT", `The input "${declared.name}" is required`, { input: declared.name });
754
+ } else {
755
+ bound[declared.name] = null;
756
+ }
757
+ }
758
+ this.inputs = bound;
759
+ }
760
+ checkRange() {
761
+ const { startAt, stopAfter } = this.options;
762
+ if (startAt === undefined && stopAfter === undefined)
763
+ return;
764
+ const order = new Map;
765
+ for (const [index, { path }] of Array.from(walkSteps2(this.script)).entries())
766
+ order.set(path, index);
767
+ for (const [name, path] of [
768
+ ["startAt", startAt],
769
+ ["stopAfter", stopAfter]
770
+ ]) {
771
+ if (path !== undefined && !order.has(path)) {
772
+ throw new UiRunError2("INVALID_STEP_RANGE", `The step range ${name} names a step the script does not have`, {
773
+ [name]: path.slice(0, 200)
774
+ });
775
+ }
776
+ }
777
+ if (startAt !== undefined && stopAfter !== undefined) {
778
+ const first = order.get(startAt) ?? 0;
779
+ const last = order.get(stopAfter) ?? 0;
780
+ if (last < first && !startAt.startsWith(`${stopAfter}.`)) {
781
+ throw new UiRunError2("INVALID_STEP_RANGE", "The step range ends before it starts", { startAt, stopAfter });
782
+ }
783
+ }
784
+ if (startAt !== undefined) {
785
+ this.started = false;
786
+ const parts = startAt.split(".");
787
+ for (let end = 1;end < parts.length; end += 1) {
788
+ const prefix = parts.slice(0, end).join(".");
789
+ if (order.has(prefix))
790
+ this.rangeAncestors.add(prefix);
791
+ }
792
+ }
793
+ }
794
+ rangeStartsInCleanup() {
795
+ return this.options.startAt?.startsWith("cleanup.") === true;
796
+ }
797
+ evaluateOutputs() {
798
+ const outputs = {};
799
+ for (const output of this.script.outputs ?? [])
800
+ outputs[output.name] = evaluateExpression2(output.value, this.scope);
801
+ return outputs;
802
+ }
803
+ async runCleanup(steps) {
804
+ this.inCleanup = true;
805
+ let first;
806
+ let stopped = false;
807
+ for (const [index, step] of steps.entries()) {
808
+ try {
809
+ await this.runStep(step, `cleanup.${index}`);
810
+ } catch (error) {
811
+ if (error instanceof StepFailure)
812
+ first ??= error;
813
+ else if (error instanceof StopSignal) {
814
+ if (error.kind === "stopped")
815
+ stopped = true;
816
+ if (error.kind === "rangeEnd" || error.kind === "stopped")
817
+ break;
818
+ } else
819
+ throw error;
820
+ }
821
+ }
822
+ this.inCleanup = false;
823
+ return { ...first ? { failure: first } : {}, stopped };
824
+ }
825
+ async runList(steps, prefix) {
826
+ for (const [index, step] of steps.entries()) {
827
+ await this.runStep(step, prefix ? `${prefix}.${index}` : String(index));
828
+ }
829
+ }
830
+ checkCancelled() {
831
+ if (this.options.signal?.aborted && !this.inCleanup)
832
+ throw new StopSignal("cancelled");
833
+ }
834
+ context(step, path, attempt) {
835
+ return {
836
+ path,
837
+ stepId: step.id,
838
+ action: step.action,
839
+ attempt,
840
+ ...this.options.signal && !this.inCleanup ? { signal: this.options.signal } : {}
841
+ };
842
+ }
843
+ async emit(draft) {
844
+ await this.emitter.emit(draft);
845
+ }
846
+ iterationDetail() {
847
+ const iteration = this.iterations[this.iterations.length - 1];
848
+ return iteration === undefined ? {} : { iteration };
849
+ }
850
+ log(entry) {
851
+ if (this.stepLog.length >= MAX_STEP_LOG_ENTRIES2) {
852
+ this.stepLogTruncated = true;
853
+ return;
854
+ }
855
+ this.stepLog.push(entry);
856
+ }
857
+ elementIdOf(step) {
858
+ const ref = stepTargets2(step).find(([field]) => field === "target")?.[1];
859
+ if (!ref || !("element" in ref))
860
+ return;
861
+ return this.script.elements?.[ref.element]?.elementId;
862
+ }
863
+ async skip(step, path, reason) {
864
+ await this.emit({
865
+ kind: "STEP_SKIPPED",
866
+ stepPath: path,
867
+ stepId: step.id,
868
+ action: step.action,
869
+ detail: { reason, ...this.iterationDetail() }
870
+ });
871
+ this.log({ path, stepId: step.id, action: step.action, status: "skipped", durationMs: 0 });
872
+ }
873
+ async maybePause(step, path) {
874
+ if (!this.test || !this.options.waitForCommand || this.ending)
875
+ return true;
876
+ if (!this.stepping && step.breakpoint !== true)
877
+ return true;
878
+ await this.emit({ kind: "PAUSED", stepPath: path, stepId: step.id, action: step.action });
879
+ let command;
880
+ try {
881
+ command = await this.awaitCommand({ stepPath: path, stepId: step.id });
882
+ } catch (error) {
883
+ if (error instanceof StopSignal)
884
+ throw error;
885
+ const message = error instanceof Error ? error.message : "unknown problem";
886
+ throw new StepFailure("DRIVER_ERROR", clipMessage(`The step-through control failed: ${message}`), path, step.id, undefined);
887
+ }
888
+ if (command === "STOP") {
889
+ this.ending = true;
890
+ throw new StopSignal("stopped");
891
+ }
892
+ await this.emit({ kind: "RESUMED", stepPath: path, stepId: step.id, action: step.action, detail: { command } });
893
+ this.stepping = command !== "CONTINUE";
894
+ if (command === "SKIP") {
895
+ await this.skip(step, path, "user");
896
+ return false;
897
+ }
898
+ return true;
899
+ }
900
+ async awaitCommand(paused) {
901
+ const waitForCommand = this.options.waitForCommand;
902
+ if (!waitForCommand)
903
+ return "CONTINUE";
904
+ const signal = this.options.signal;
905
+ if (!signal || this.inCleanup)
906
+ return waitForCommand(paused);
907
+ if (signal.aborted)
908
+ throw new StopSignal("cancelled");
909
+ return new Promise((resolve, reject) => {
910
+ const onAbort = () => reject(new StopSignal("cancelled"));
911
+ signal.addEventListener("abort", onAbort, { once: true });
912
+ waitForCommand(paused).then((command) => {
913
+ signal.removeEventListener("abort", onAbort);
914
+ resolve(command);
915
+ }, (error) => {
916
+ signal.removeEventListener("abort", onAbort);
917
+ reject(error instanceof Error ? error : new Error("waitForCommand failed"));
918
+ });
919
+ });
920
+ }
921
+ async runStep(step, path) {
922
+ this.checkCancelled();
923
+ if (!this.started) {
924
+ if (path === this.options.startAt)
925
+ this.started = true;
926
+ else if (!this.rangeAncestors.has(path)) {
927
+ await this.skip(step, path, "outsideRange");
928
+ return;
929
+ }
930
+ }
931
+ if (step.disabled === true) {
932
+ await this.skip(step, path, "disabled");
933
+ this.endIfStopAfter(path);
934
+ return;
935
+ }
936
+ const enteringForRange = !this.started && this.rangeAncestors.has(path);
937
+ let proceed = true;
938
+ try {
939
+ proceed = enteringForRange || await this.maybePause(step, path);
940
+ } catch (error) {
941
+ if (!(error instanceof StepFailure))
942
+ throw error;
943
+ await this.emit({
944
+ kind: "STEP_FAILED",
945
+ stepPath: path,
946
+ stepId: step.id,
947
+ action: step.action,
948
+ durationMs: 0,
949
+ errorCode: error.code,
950
+ message: error.message
951
+ });
952
+ this.log({ path, stepId: step.id, action: step.action, status: "failed", durationMs: 0, error: error.code });
953
+ throw error;
954
+ }
955
+ if (!proceed) {
956
+ this.endIfStopAfter(path);
957
+ return;
958
+ }
959
+ const began = this.clock.now();
960
+ await this.emit({
961
+ kind: "STEP_STARTED",
962
+ stepPath: path,
963
+ stepId: step.id,
964
+ action: step.action,
965
+ detail: this.iterationDetail()
966
+ });
967
+ const attempts = 1 + (step.retry?.attempts ?? 0);
968
+ let outcome;
969
+ let failure;
970
+ let tried = 0;
971
+ for (let attempt = 1;attempt <= attempts; attempt += 1) {
972
+ tried = attempt;
973
+ try {
974
+ outcome = await this.attemptStep(step, path, attempt, enteringForRange);
975
+ failure = undefined;
976
+ break;
977
+ } catch (error) {
978
+ if (!(error instanceof StepFailure))
979
+ throw error;
980
+ failure = error;
981
+ const willRetry = attempt < attempts && isRetryableInScript2(error.code);
982
+ if (!willRetry)
983
+ break;
984
+ await this.emit({
985
+ kind: "LOG",
986
+ stepPath: path,
987
+ stepId: step.id,
988
+ action: step.action,
989
+ errorCode: error.code,
990
+ message: clipMessage(`Attempt ${attempt} failed; retrying`),
991
+ detail: { level: "warn", attempt, willRetry: true }
992
+ });
993
+ await this.sleep(step.retry?.delayMs ?? DEFAULT_RETRY_DELAY_MS2);
994
+ }
995
+ }
996
+ const durationMs = Math.max(0, this.clock.now() - began);
997
+ const elementId = this.elementIdOf(step);
998
+ if (failure) {
999
+ const own = failure.stepPath === path;
1000
+ const screenshotFileId = own ? await this.screenshotFor(step, path, "failure") : undefined;
1001
+ await this.emit({
1002
+ kind: "STEP_FAILED",
1003
+ stepPath: path,
1004
+ stepId: step.id,
1005
+ action: step.action,
1006
+ durationMs,
1007
+ errorCode: failure.code,
1008
+ message: clipMessage(failure.message),
1009
+ ...screenshotFileId ? { screenshotFileId } : {},
1010
+ detail: {
1011
+ ...own ? failure.detail ?? {} : { failedStepPath: failure.stepPath },
1012
+ stepAttempts: tried,
1013
+ ...this.iterationDetail()
1014
+ }
1015
+ });
1016
+ this.log({
1017
+ path,
1018
+ stepId: step.id,
1019
+ action: step.action,
1020
+ status: "failed",
1021
+ durationMs,
1022
+ ...elementId ? { elementId } : {},
1023
+ ...screenshotFileId ? { screenshotFileId } : {},
1024
+ error: failure.code
1025
+ });
1026
+ if (step.onError === "continue") {
1027
+ if (step.saveAs !== undefined)
1028
+ this.store(step.saveAs, null);
1029
+ this.endIfStopAfter(path);
1030
+ return;
1031
+ }
1032
+ throw failure;
1033
+ }
1034
+ const screenshotFileId = outcome?.screenshotFileId ?? await this.screenshotFor(step, path, "success");
1035
+ if (step.saveAs !== undefined && outcome && "value" in outcome)
1036
+ this.store(step.saveAs, outcome.value ?? null);
1037
+ await this.emit({
1038
+ kind: "STEP_PASSED",
1039
+ stepPath: path,
1040
+ stepId: step.id,
1041
+ action: step.action,
1042
+ durationMs,
1043
+ ...outcome?.resolvedBy ? { resolvedBy: outcome.resolvedBy } : {},
1044
+ ...screenshotFileId ? { screenshotFileId } : {},
1045
+ detail: this.iterationDetail()
1046
+ });
1047
+ this.log({
1048
+ path,
1049
+ stepId: step.id,
1050
+ action: step.action,
1051
+ status: "passed",
1052
+ durationMs,
1053
+ ...outcome?.resolvedBy ? { method: outcome.resolvedBy } : {},
1054
+ ...elementId ? { elementId } : {},
1055
+ ...screenshotFileId ? { screenshotFileId } : {}
1056
+ });
1057
+ if (!FLOW_ACTIONS.has(step.action)) {
1058
+ this.lastCompleted = path;
1059
+ this.completed += 1;
1060
+ }
1061
+ this.endIfStopAfter(path);
1062
+ }
1063
+ endIfStopAfter(path) {
1064
+ if (this.started && this.options.stopAfter === path)
1065
+ throw new StopSignal("rangeEnd");
1066
+ }
1067
+ store(name, value) {
1068
+ this.variables.set(name, value);
1069
+ if (!name.startsWith("__"))
1070
+ this.results[name] = value;
1071
+ }
1072
+ async sleep(ms) {
1073
+ if (ms <= 0)
1074
+ return;
1075
+ const signal = this.inCleanup ? undefined : this.options.signal;
1076
+ try {
1077
+ await this.clock.sleep(ms, signal);
1078
+ } catch (error) {
1079
+ if (signal?.aborted)
1080
+ throw new StopSignal("cancelled");
1081
+ throw error;
1082
+ }
1083
+ }
1084
+ async screenshotFor(step, path, when) {
1085
+ if (!this.driver.screenshot || FLOW_ACTIONS.has(step.action) || step.action === "screenshot")
1086
+ return;
1087
+ const settings = this.script.settings?.screenshots ?? "onFailure";
1088
+ const policy = step.screenshot ?? (settings === "everyStep" ? "always" : settings);
1089
+ if (policy === "never" || policy === "onFailure" && when === "success")
1090
+ return;
1091
+ try {
1092
+ return await this.driver.screenshot({}, this.context(step, path, 1)) ?? undefined;
1093
+ } catch {
1094
+ return;
1095
+ }
1096
+ }
1097
+ async attemptStep(step, path, attempt, enteringForRange) {
1098
+ const outcome = await this.perform(step, path, attempt, enteringForRange);
1099
+ if (step.verify && !this.driver.replay)
1100
+ await this.verify(step, step.verify, path, attempt);
1101
+ return outcome;
1102
+ }
1103
+ fail(step, path, failure) {
1104
+ throw new StepFailure(failure.code, failure.message, path, step.id, failure.detail);
1105
+ }
1106
+ evaluate(step, path, expression) {
1107
+ try {
1108
+ return evaluateExpression2(expression, this.scope);
1109
+ } catch (error) {
1110
+ if (error instanceof UiRunError2)
1111
+ this.fail(step, path, {
1112
+ code: error.code,
1113
+ message: error.message,
1114
+ ...error.detail ? { detail: error.detail } : {}
1115
+ });
1116
+ throw error;
1117
+ }
1118
+ }
1119
+ targetOf(ref) {
1120
+ return "element" in ref ? this.script.elements?.[ref.element]?.target ?? { methods: [] } : ref;
1121
+ }
1122
+ waitFor(step) {
1123
+ const settings = this.script.settings;
1124
+ if (step.timeoutMs !== undefined) {
1125
+ this.freshScreen = false;
1126
+ return step.timeoutMs;
1127
+ }
1128
+ const wait = this.freshScreen ? settings?.firstWaitMs ?? DEFAULT_FIRST_WAIT_MS2 : settings?.waitMs ?? DEFAULT_WAIT_MS2;
1129
+ this.freshScreen = false;
1130
+ return wait;
1131
+ }
1132
+ async call(step, path, run) {
1133
+ try {
1134
+ return await run();
1135
+ } catch (error) {
1136
+ if (error instanceof StopSignal || error instanceof StepFailure)
1137
+ throw error;
1138
+ if (this.options.signal?.aborted && !this.inCleanup)
1139
+ throw new StopSignal("cancelled");
1140
+ if (error instanceof UiDriverError2) {
1141
+ this.fail(step, path, {
1142
+ code: error.code,
1143
+ message: error.message,
1144
+ ...error.detail ? { detail: error.detail } : {}
1145
+ });
1146
+ }
1147
+ const message = error instanceof Error ? error.message : "The desk failed";
1148
+ return this.fail(step, path, { code: "DRIVER_ERROR", message: clipMessage(`The desk failed: ${message}`) });
1149
+ }
1150
+ }
1151
+ async poll(step, path, waitMs, attemptOnce) {
1152
+ const start = this.clock.now();
1153
+ for (;; ) {
1154
+ this.checkCancelled();
1155
+ const result = await this.call(step, path, attemptOnce);
1156
+ const waitedMs = Math.max(0, this.clock.now() - start);
1157
+ if (result.ok || isFinalFailure(result) || this.driver.staticPage || waitedMs >= waitMs)
1158
+ return { result, waitedMs };
1159
+ await this.sleep(Math.min(this.pollMs, Math.max(0, waitMs - waitedMs)));
1160
+ }
1161
+ }
1162
+ async onTarget(step, path, attempt, ref, run, waitMs = this.waitFor(step)) {
1163
+ const target = this.targetOf(ref);
1164
+ const context = this.context(step, path, attempt);
1165
+ const { result, waitedMs } = await this.poll(step, path, waitMs, () => run(target, context));
1166
+ if (!result.ok) {
1167
+ const code = codeOfFailure(result);
1168
+ this.fail(step, path, {
1169
+ code,
1170
+ message: FAILURE_MESSAGES[code] ?? "The step failed",
1171
+ detail: failureDetail(result, waitedMs)
1172
+ });
1173
+ }
1174
+ return {
1175
+ ..."value" in result ? { value: result.value ?? null } : {},
1176
+ ...result.resolution?.status === "found" ? { resolvedBy: result.resolution.method } : {}
1177
+ };
1178
+ }
1179
+ async act(step, path, attempt, ref, action, state) {
1180
+ if (!ref) {
1181
+ const context = this.context(step, path, attempt);
1182
+ const result = await this.call(step, path, () => this.driver.act(null, action, {}, context));
1183
+ if (!result.ok) {
1184
+ const code = codeOfFailure(result);
1185
+ this.fail(step, path, {
1186
+ code,
1187
+ message: FAILURE_MESSAGES[code] ?? "The step failed",
1188
+ detail: failureDetail(result, 0)
1189
+ });
1190
+ }
1191
+ return "value" in result ? { value: result.value ?? null } : {};
1192
+ }
1193
+ return this.onTarget(step, path, attempt, ref, (target, context) => this.driver.act(target, action, state ? { state } : {}, context));
1194
+ }
1195
+ async read(step, path, attempt, ref, kind) {
1196
+ return this.onTarget(step, path, attempt, ref, (target, context) => this.driver.read(target, kind, context));
1197
+ }
1198
+ async exists(step, path, attempt, ref, waitMs) {
1199
+ const target = this.targetOf(ref);
1200
+ const context = this.context(step, path, attempt);
1201
+ const start = this.clock.now();
1202
+ for (;; ) {
1203
+ this.checkCancelled();
1204
+ const resolution = await this.call(step, path, () => this.driver.resolve(target, { state: "visible" }, context));
1205
+ if (resolution.status === "found")
1206
+ return true;
1207
+ if (resolution.code === "ELEMENT_AMBIGUOUS") {
1208
+ this.fail(step, path, {
1209
+ code: "ELEMENT_AMBIGUOUS",
1210
+ message: FAILURE_MESSAGES.ELEMENT_AMBIGUOUS ?? "",
1211
+ detail: failureDetail({ ok: false, code: resolution.code, resolution }, Math.max(0, this.clock.now() - start))
1212
+ });
1213
+ }
1214
+ const waited = this.clock.now() - start;
1215
+ if (this.driver.staticPage || waited >= waitMs)
1216
+ return false;
1217
+ await this.sleep(Math.min(this.pollMs, waitMs - waited));
1218
+ }
1219
+ }
1220
+ text(step, path, expression) {
1221
+ return expression === undefined ? "" : toText2(this.evaluate(step, path, expression));
1222
+ }
1223
+ async perform(step, path, attempt, enteringForRange) {
1224
+ const context = () => this.context(step, path, attempt);
1225
+ switch (step.action) {
1226
+ case "navigate": {
1227
+ const url = this.text(step, path, step.url);
1228
+ let parsed;
1229
+ try {
1230
+ parsed = new URL(url);
1231
+ } catch {
1232
+ parsed = undefined;
1233
+ }
1234
+ if (!parsed || parsed.protocol !== "https:" && parsed.protocol !== "http:") {
1235
+ this.fail(step, path, { code: "URL_NOT_ALLOWED", message: "A navigation URL must be http or https" });
1236
+ }
1237
+ const timeoutMs = step.timeoutMs ?? this.script.settings?.firstWaitMs ?? DEFAULT_FIRST_WAIT_MS2;
1238
+ if (!this.driver.replay) {
1239
+ await this.call(step, path, () => this.driver.navigate(parsed.href, { waitUntil: step.waitUntil ?? "load", timeoutMs }, context()));
1240
+ }
1241
+ this.freshScreen = true;
1242
+ return {};
1243
+ }
1244
+ case "goBack":
1245
+ case "reload": {
1246
+ const timeoutMs = step.timeoutMs ?? this.script.settings?.firstWaitMs ?? DEFAULT_FIRST_WAIT_MS2;
1247
+ if (!this.driver.replay) {
1248
+ await this.call(step, path, () => step.action === "goBack" ? this.driver.goBack({ timeoutMs }, context()) : this.driver.reload({ timeoutMs }, context()));
1249
+ }
1250
+ this.freshScreen = true;
1251
+ return {};
1252
+ }
1253
+ case "closeTab":
1254
+ if (!this.driver.replay)
1255
+ await this.call(step, path, () => this.driver.closeTab(context()));
1256
+ this.freshScreen = true;
1257
+ return {};
1258
+ case "click":
1259
+ return this.act(step, path, attempt, step.target, { kind: "click", button: step.button ?? "left" });
1260
+ case "doubleClick":
1261
+ if (step.button === "right") {
1262
+ this.fail(step, path, {
1263
+ code: "ACTION_FAILED",
1264
+ message: "A double click uses the left button",
1265
+ detail: { problem: "INVALID_ACTION" }
1266
+ });
1267
+ }
1268
+ return this.act(step, path, attempt, step.target, { kind: "doubleClick" });
1269
+ case "hover":
1270
+ return this.act(step, path, attempt, step.target, { kind: "hover" });
1271
+ case "type":
1272
+ return this.typeText(step, path, attempt);
1273
+ case "typeSecret": {
1274
+ const typeSecret = this.driver.typeSecret?.bind(this.driver);
1275
+ if (!typeSecret)
1276
+ this.fail(step, path, { code: "UNSUPPORTED_ON_DESK", message: "This desk cannot type secrets" });
1277
+ const secret = {
1278
+ secretRef: step.secretRef,
1279
+ ...step.expectedOrigin ? { expectedOrigin: step.expectedOrigin } : {}
1280
+ };
1281
+ return this.onTarget(step, path, attempt, step.target, (target, ctx) => typeSecret(target, secret, ctx));
1282
+ }
1283
+ case "clear":
1284
+ return this.act(step, path, attempt, step.target, { kind: "clear" });
1285
+ case "select":
1286
+ return this.selectValues(step, path, attempt);
1287
+ case "check":
1288
+ return this.act(step, path, attempt, step.target, { kind: "check", checked: step.checked !== false });
1289
+ case "pressKey": {
1290
+ const keys = step.keys;
1291
+ if (!step.target) {
1292
+ const result = await this.call(step, path, () => this.driver.pressKeys(null, keys, context()));
1293
+ if (!result.ok) {
1294
+ const code = codeOfFailure(result);
1295
+ this.fail(step, path, {
1296
+ code,
1297
+ message: FAILURE_MESSAGES[code] ?? "The step failed",
1298
+ detail: failureDetail(result, 0)
1299
+ });
1300
+ }
1301
+ return {};
1302
+ }
1303
+ return this.onTarget(step, path, attempt, step.target, (target, ctx) => this.driver.pressKeys(target, keys, ctx));
1304
+ }
1305
+ case "scroll": {
1306
+ if (!step.target) {
1307
+ if (!this.driver.replay) {
1308
+ await this.call(step, path, () => this.driver.scrollPage({
1309
+ ...step.dx === undefined ? {} : { dx: step.dx },
1310
+ ...step.dy === undefined ? {} : { dy: step.dy },
1311
+ ...step.to === undefined ? {} : { to: step.to }
1312
+ }, context()));
1313
+ }
1314
+ return {};
1315
+ }
1316
+ const action = step.dx !== undefined || step.dy !== undefined ? { kind: "scroll", dx: step.dx ?? 0, dy: step.dy ?? 0 } : { kind: "scrollIntoView" };
1317
+ return this.act(step, path, attempt, step.target, action, "visible");
1318
+ }
1319
+ case "waitFor":
1320
+ return this.waitForStep(step, path, attempt);
1321
+ case "extract": {
1322
+ const values = {};
1323
+ let resolvedBy;
1324
+ for (const field of step.fields) {
1325
+ const read = await this.readField(step, path, attempt, field);
1326
+ values[field.name] = read.value ?? null;
1327
+ resolvedBy ??= read.resolvedBy;
1328
+ }
1329
+ return { value: values, ...resolvedBy ? { resolvedBy } : {} };
1330
+ }
1331
+ case "extractList":
1332
+ return this.extractList(step, path, attempt);
1333
+ case "getText":
1334
+ return this.read(step, path, attempt, step.target, { kind: "text" });
1335
+ case "getValue":
1336
+ return this.read(step, path, attempt, step.target, { kind: "value" });
1337
+ case "getAttribute":
1338
+ return this.read(step, path, attempt, step.target, { kind: "attribute", name: step.attribute });
1339
+ case "elementExists": {
1340
+ const found = await this.exists(step, path, attempt, step.target, step.timeoutMs ?? 0);
1341
+ return { value: found };
1342
+ }
1343
+ case "getPageText": {
1344
+ const text = await this.call(step, path, () => this.driver.pageText(context()));
1345
+ return { value: String(text).slice(0, MAX_PAGE_TEXT2) };
1346
+ }
1347
+ case "getPageHtml": {
1348
+ const html = await this.call(step, path, () => this.driver.pageHtml(context()));
1349
+ return { value: String(html).slice(0, MAX_PAGE_TEXT2) };
1350
+ }
1351
+ case "screenshot": {
1352
+ const take = this.driver.screenshot?.bind(this.driver);
1353
+ if (!take)
1354
+ this.fail(step, path, { code: "UNSUPPORTED_ON_DESK", message: "This desk cannot take screenshots" });
1355
+ const options = {
1356
+ ...step.target ? { target: this.targetOf(step.target) } : {},
1357
+ ...step.fullPage ? { fullPage: true } : {}
1358
+ };
1359
+ const fileId = await this.call(step, path, () => take(options, context()));
1360
+ return { value: fileId ?? null, ...fileId ? { screenshotFileId: fileId } : {} };
1361
+ }
1362
+ case "login": {
1363
+ const login = this.driver.login?.bind(this.driver);
1364
+ if (!login)
1365
+ this.fail(step, path, {
1366
+ code: "UNSUPPORTED_ON_DESK",
1367
+ message: "This desk cannot sign in through a connection"
1368
+ });
1369
+ const targets = {
1370
+ ...step.username ? { username: this.targetOf(step.username) } : {},
1371
+ ...step.password ? { password: this.targetOf(step.password) } : {},
1372
+ ...step.submit ? { submit: this.targetOf(step.submit) } : {},
1373
+ ...step.success ? { success: this.targetOf(step.success) } : {}
1374
+ };
1375
+ const timeoutMs = this.waitFor(step);
1376
+ await this.call(step, path, () => login(targets, { timeoutMs }, context()));
1377
+ this.freshScreen = true;
1378
+ return {};
1379
+ }
1380
+ case "focusWindow":
1381
+ return this.fail(step, path, {
1382
+ code: "UNSUPPORTED_ON_DESK",
1383
+ message: "A web desk cannot focus a desktop window"
1384
+ });
1385
+ case "if": {
1386
+ if (enteringForRange) {
1387
+ const inElse = this.options.startAt?.startsWith(`${path}.else.`) === true;
1388
+ if (inElse && step.else)
1389
+ await this.runList(step.else, `${path}.else`);
1390
+ else
1391
+ await this.runList(step.then, `${path}.then`);
1392
+ return {};
1393
+ }
1394
+ const take = step.elementExists ? await this.exists(step, path, attempt, step.elementExists, 0) : truthy2(this.evaluate(step, path, step.condition ?? false));
1395
+ if (take)
1396
+ await this.runList(step.then, `${path}.then`);
1397
+ else if (step.else)
1398
+ await this.runList(step.else, `${path}.else`);
1399
+ return {};
1400
+ }
1401
+ case "forEach":
1402
+ return this.forEach(step, path, attempt);
1403
+ case "while": {
1404
+ for (let iteration = 0;; iteration += 1) {
1405
+ if (iteration >= step.maxIterations) {
1406
+ await this.emit({
1407
+ kind: "LOG",
1408
+ stepPath: path,
1409
+ stepId: step.id,
1410
+ action: step.action,
1411
+ message: `The loop stopped at its limit of ${step.maxIterations} iterations`,
1412
+ detail: { level: "warn", limitReached: true }
1413
+ });
1414
+ break;
1415
+ }
1416
+ const go = enteringForRange && iteration === 0 ? true : step.elementExists ? await this.exists(step, path, attempt, step.elementExists, 0) : truthy2(this.evaluate(step, path, step.condition ?? false));
1417
+ if (!go)
1418
+ break;
1419
+ this.iterations.push(iteration);
1420
+ try {
1421
+ await this.runList(step.steps, `${path}.steps`);
1422
+ } finally {
1423
+ this.iterations.pop();
1424
+ }
1425
+ }
1426
+ return {};
1427
+ }
1428
+ case "retryScope": {
1429
+ for (let scopeAttempt = 1;; scopeAttempt += 1) {
1430
+ try {
1431
+ await this.runList(step.steps, `${path}.steps`);
1432
+ return {};
1433
+ } catch (error) {
1434
+ if (!(error instanceof StepFailure) || scopeAttempt >= step.attempts || !isRetryableInScript2(error.code))
1435
+ throw error;
1436
+ await this.emit({
1437
+ kind: "LOG",
1438
+ stepPath: path,
1439
+ stepId: step.id,
1440
+ action: step.action,
1441
+ errorCode: error.code,
1442
+ message: `Attempt ${scopeAttempt} of the block failed; retrying`,
1443
+ detail: { level: "warn", attempt: scopeAttempt, willRetry: true }
1444
+ });
1445
+ await this.sleep(step.delayMs ?? DEFAULT_RETRY_DELAY_MS2);
1446
+ }
1447
+ }
1448
+ }
1449
+ case "set":
1450
+ this.store(step.name, this.evaluate(step, path, step.value));
1451
+ return {};
1452
+ case "log": {
1453
+ const message = this.text(step, path, step.message);
1454
+ await this.emit({
1455
+ kind: "LOG",
1456
+ stepPath: path,
1457
+ stepId: step.id,
1458
+ action: step.action,
1459
+ message: clipMessage(message),
1460
+ detail: { level: step.level ?? "info" }
1461
+ });
1462
+ return {};
1463
+ }
1464
+ case "call":
1465
+ return this.fail(step, path, {
1466
+ code: "INVALID_SCRIPT",
1467
+ message: "A call to a shared sequence must be compiled first"
1468
+ });
1469
+ }
1470
+ }
1471
+ async typeText(step, path, attempt) {
1472
+ if (step.text === undefined)
1473
+ return {};
1474
+ const text = this.text(step, path, step.text);
1475
+ if (text.length > MAX_TYPED_TEXT2) {
1476
+ this.fail(step, path, {
1477
+ code: "ACTION_FAILED",
1478
+ message: `A type step types at most ${MAX_TYPED_TEXT2} characters`,
1479
+ detail: { problem: "INVALID_ACTION" }
1480
+ });
1481
+ }
1482
+ let outcome;
1483
+ if (step.delayMs !== undefined && step.delayMs > 0 && !this.driver.replay) {
1484
+ if (step.clear !== false)
1485
+ outcome = await this.act(step, path, attempt, step.target, { kind: "clear" });
1486
+ else
1487
+ outcome = {};
1488
+ for (const character of Array.from(text)) {
1489
+ const typed = await this.act(step, path, attempt, step.target, { kind: "type", text: character, append: true });
1490
+ outcome = { ...outcome, ...typed.resolvedBy ? { resolvedBy: typed.resolvedBy } : {} };
1491
+ await this.sleep(step.delayMs);
1492
+ }
1493
+ } else {
1494
+ outcome = await this.act(step, path, attempt, step.target, { kind: "type", text, append: step.clear === false });
1495
+ }
1496
+ if (step.pressEnter === true) {
1497
+ const target = step.target ? this.targetOf(step.target) : null;
1498
+ const context = this.context(step, path, attempt);
1499
+ const result = await this.call(step, path, () => this.driver.pressKeys(target, ["Enter"], context));
1500
+ if (!result.ok) {
1501
+ const code = codeOfFailure(result);
1502
+ this.fail(step, path, {
1503
+ code,
1504
+ message: FAILURE_MESSAGES[code] ?? "The step failed",
1505
+ detail: failureDetail(result, 0)
1506
+ });
1507
+ }
1508
+ }
1509
+ return outcome.resolvedBy ? { resolvedBy: outcome.resolvedBy } : {};
1510
+ }
1511
+ async selectValues(step, path, attempt) {
1512
+ let resolvedBy;
1513
+ for (const expression of step.values) {
1514
+ const wanted = toText2(this.evaluate(step, path, expression));
1515
+ const outcome = await this.onTarget(step, path, attempt, step.target, async (target, context) => {
1516
+ const byValue = await this.driver.act(target, { kind: "select", value: wanted }, {}, context);
1517
+ if (byValue.ok || byValue.code !== "OPTION_NOT_FOUND")
1518
+ return byValue;
1519
+ return this.driver.act(target, { kind: "select", label: wanted }, {}, context);
1520
+ });
1521
+ resolvedBy ??= outcome.resolvedBy;
1522
+ }
1523
+ return resolvedBy ? { resolvedBy } : {};
1524
+ }
1525
+ async readField(step, path, attempt, field) {
1526
+ const kind = readKindOf(field);
1527
+ if (field.all !== true)
1528
+ return this.read(step, path, attempt, field.target, kind);
1529
+ const target = this.targetOf(field.target);
1530
+ const context = this.context(step, path, attempt);
1531
+ const result = await this.call(step, path, () => this.driver.readAll(target, kind, context));
1532
+ if (!result.ok) {
1533
+ if (result.code === "ELEMENT_NOT_FOUND")
1534
+ return { value: [] };
1535
+ const code = codeOfFailure(result);
1536
+ this.fail(step, path, {
1537
+ code,
1538
+ message: FAILURE_MESSAGES[code] ?? "The step failed",
1539
+ detail: failureDetail(result, 0)
1540
+ });
1541
+ }
1542
+ return {
1543
+ value: result.items.map((item) => toUiValue2(item)),
1544
+ ...result.resolution?.status === "found" ? { resolvedBy: result.resolution.method } : {}
1545
+ };
1546
+ }
1547
+ async extractList(step, path, attempt) {
1548
+ const item = this.targetOf(step.item);
1549
+ const fields = step.fields.map((field) => ({
1550
+ name: field.name,
1551
+ target: this.targetOf(field.target),
1552
+ read: readKindOf(field),
1553
+ all: field.all === true
1554
+ }));
1555
+ const maxItems = step.maxItems ?? DEFAULT_LIST_ITEMS2;
1556
+ const maxPages = this.driver.replay ? 1 : step.maxPages ?? 1;
1557
+ const context = this.context(step, path, attempt);
1558
+ const rows = [];
1559
+ let resolvedBy;
1560
+ const readPage = async (remaining) => {
1561
+ const result = await this.call(step, path, () => this.driver.listItems(item, fields, remaining, context));
1562
+ if (!result.ok) {
1563
+ if (result.code === "ELEMENT_NOT_FOUND")
1564
+ return [];
1565
+ const code = codeOfFailure(result);
1566
+ return this.fail(step, path, {
1567
+ code,
1568
+ message: FAILURE_MESSAGES[code] ?? "The step failed",
1569
+ detail: failureDetail(result, 0)
1570
+ });
1571
+ }
1572
+ if (result.resolution?.status === "found")
1573
+ resolvedBy ??= result.resolution.method;
1574
+ return result.items.map((row) => toUiValue2(row));
1575
+ };
1576
+ const firstWait = step.timeoutMs ?? 0;
1577
+ const start = this.clock.now();
1578
+ let page = await readPage(maxItems);
1579
+ while (page.length === 0 && !this.driver.staticPage && this.clock.now() - start < firstWait) {
1580
+ await this.sleep(this.pollMs);
1581
+ page = await readPage(maxItems);
1582
+ }
1583
+ rows.push(...page);
1584
+ for (let pageNumber = 1;pageNumber < maxPages && rows.length < maxItems && step.next; pageNumber += 1) {
1585
+ const next = this.targetOf(step.next);
1586
+ const clicked = await this.call(step, path, () => this.driver.act(next, { kind: "click", button: "left" }, {}, context));
1587
+ if (!clicked.ok)
1588
+ break;
1589
+ const previous = JSON.stringify(page);
1590
+ const waitMs = this.script.settings?.waitMs ?? DEFAULT_WAIT_MS2;
1591
+ const pageStart = this.clock.now();
1592
+ page = await readPage(maxItems);
1593
+ while (JSON.stringify(page) === previous && this.clock.now() - pageStart < waitMs) {
1594
+ await this.sleep(this.pollMs);
1595
+ page = await readPage(maxItems);
1596
+ }
1597
+ if (JSON.stringify(page) === previous)
1598
+ break;
1599
+ rows.push(...page.slice(0, maxItems - rows.length));
1600
+ }
1601
+ return { value: rows.slice(0, maxItems), ...resolvedBy ? { resolvedBy } : {} };
1602
+ }
1603
+ async forEach(step, path, attempt) {
1604
+ let items;
1605
+ if (step.elements) {
1606
+ const target = this.targetOf(step.elements);
1607
+ const context = this.context(step, path, attempt);
1608
+ const result = await this.call(step, path, () => this.driver.readAll(target, { kind: "text" }, context));
1609
+ if (!result.ok && result.code !== "ELEMENT_NOT_FOUND") {
1610
+ const code = codeOfFailure(result);
1611
+ this.fail(step, path, {
1612
+ code,
1613
+ message: FAILURE_MESSAGES[code] ?? "The step failed",
1614
+ detail: failureDetail(result, 0)
1615
+ });
1616
+ }
1617
+ items = result.ok ? result.items.map((value) => toUiValue2(value)) : [];
1618
+ } else {
1619
+ const value = this.evaluate(step, path, step.in ?? { list: [] });
1620
+ if (!Array.isArray(value)) {
1621
+ this.fail(step, path, { code: "EXPRESSION_ERROR", message: "A for each block needs a list" });
1622
+ }
1623
+ items = value;
1624
+ }
1625
+ const limit = Math.min(items.length, step.max ?? items.length);
1626
+ for (let index = 0;index < limit; index += 1) {
1627
+ this.variables.set(step.as, items[index] ?? null);
1628
+ if (step.index !== undefined)
1629
+ this.variables.set(step.index, index);
1630
+ this.iterations.push(index);
1631
+ try {
1632
+ await this.runList(step.steps, `${path}.steps`);
1633
+ } finally {
1634
+ this.iterations.pop();
1635
+ }
1636
+ }
1637
+ return {};
1638
+ }
1639
+ async waitForStep(step, path, attempt) {
1640
+ if (step.milliseconds !== undefined) {
1641
+ if (!this.driver.replay)
1642
+ await this.sleep(step.milliseconds);
1643
+ return {};
1644
+ }
1645
+ if (step.target) {
1646
+ const state = step.state ?? "visible";
1647
+ if (state === "visible" || state === "attached") {
1648
+ const target = step.target;
1649
+ const outcome = await this.onTarget(step, path, attempt, target, async (resolved, context) => {
1650
+ const resolution = await this.driver.resolve(resolved, { state }, context);
1651
+ return resolution.status === "found" ? { ok: true, resolution } : { ok: false, code: resolution.code, resolution };
1652
+ });
1653
+ return outcome.resolvedBy ? { resolvedBy: outcome.resolvedBy } : {};
1654
+ }
1655
+ if (this.driver.replay)
1656
+ return {};
1657
+ const target = this.targetOf(step.target);
1658
+ const resolveState = state === "hidden" ? "visible" : "attached";
1659
+ const gone = await this.waitUntil(step, path, this.waitFor(step), async (context) => {
1660
+ const resolution = await this.driver.resolve(target, { state: resolveState }, context);
1661
+ return isGone(resolution, state === "hidden");
1662
+ }, attempt);
1663
+ if (!gone)
1664
+ this.fail(step, path, { code: "WAIT_TIMEOUT", message: "The element did not disappear within the wait" });
1665
+ return {};
1666
+ }
1667
+ if (this.driver.replay)
1668
+ return {};
1669
+ if (step.urlContains !== undefined) {
1670
+ const wanted = this.text(step, path, step.urlContains);
1671
+ const reached = await this.waitUntil(step, path, this.waitFor(step), async (context) => (await this.driver.currentUrl(context)).includes(wanted), attempt);
1672
+ if (!reached)
1673
+ this.fail(step, path, { code: "WAIT_TIMEOUT", message: "The page address did not match within the wait" });
1674
+ return {};
1675
+ }
1676
+ const wanted = this.text(step, path, step.text);
1677
+ const present = await this.waitUntil(step, path, this.waitFor(step), async (context) => containsText2(await this.driver.pageText(context), wanted), attempt);
1678
+ if (!present)
1679
+ this.fail(step, path, { code: "WAIT_TIMEOUT", message: "The text did not appear within the wait" });
1680
+ return {};
1681
+ }
1682
+ async waitUntil(step, path, waitMs, condition, attempt) {
1683
+ const context = this.context(step, path, attempt);
1684
+ const start = this.clock.now();
1685
+ for (;; ) {
1686
+ this.checkCancelled();
1687
+ if (await this.call(step, path, () => condition(context)))
1688
+ return true;
1689
+ const waited = this.clock.now() - start;
1690
+ if (this.driver.staticPage || waited >= waitMs)
1691
+ return false;
1692
+ await this.sleep(Math.min(this.pollMs, waitMs - waited));
1693
+ }
1694
+ }
1695
+ async verify(step, verify, path, attempt) {
1696
+ const waitMs = verify.timeoutMs ?? this.script.settings?.waitMs ?? DEFAULT_WAIT_MS2;
1697
+ const check = async (context) => {
1698
+ switch (verify.kind) {
1699
+ case "elementVisible": {
1700
+ const resolution = await this.driver.resolve(this.targetOf(verify.target), { state: "visible" }, context);
1701
+ return resolution.status === "found";
1702
+ }
1703
+ case "elementGone": {
1704
+ const resolution = await this.driver.resolve(this.targetOf(verify.target), { state: "visible" }, context);
1705
+ return isGone(resolution, true);
1706
+ }
1707
+ case "urlContains":
1708
+ return (await this.driver.currentUrl(context)).includes(this.text(step, path, verify.value));
1709
+ case "textPresent":
1710
+ return containsText2(await this.driver.pageText(context), this.text(step, path, verify.text));
1711
+ case "valueEquals": {
1712
+ const read = await this.driver.read(this.targetOf(verify.target), { kind: "value" }, context);
1713
+ if (!read.ok)
1714
+ return false;
1715
+ const expected = this.evaluate(step, path, verify.value);
1716
+ return valuesEqual2(read.value ?? null, expected) || toText2(read.value ?? null) === toText2(expected);
1717
+ }
1718
+ }
1719
+ };
1720
+ const held = await this.waitUntil(step, path, waitMs, check, attempt);
1721
+ if (!held) {
1722
+ this.fail(step, path, {
1723
+ code: "VERIFY_FAILED",
1724
+ message: "The expected outcome did not occur",
1725
+ detail: { verify: verify.kind, waitedMs: waitMs }
1726
+ });
1727
+ }
1728
+ }
1729
+ }
1730
+
1731
+ export { MAX_VALUE_TEXT2, MAX_VALUE_ITEMS2, toUiValue2, readPath2, truthy2, valuesEqual2, toText2, toNumber2, evaluateExpression2, UI_RUN_EVENT_KINDS2, DEFAULT_MAX_EVENTS2, MAX_STEP_LOG_ENTRIES2, MAX_EVENT_MESSAGE2, DEFAULT_FIRST_WAIT_MS2, DEFAULT_WAIT_MS2, DEFAULT_RETRY_DELAY_MS2, DEFAULT_POLL_INTERVAL_MS2, MAX_EVENTS_LIMIT2, MAX_PAGE_TEXT2, DEFAULT_LIST_ITEMS2, runUiScript2 };