automation_model 1.0.659-dev → 1.0.659-stage

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +3 -1
  2. package/lib/analyze_helper.js.map +1 -1
  3. package/lib/api.d.ts +0 -1
  4. package/lib/api.js +35 -21
  5. package/lib/api.js.map +1 -1
  6. package/lib/auto_page.d.ts +1 -1
  7. package/lib/auto_page.js +145 -58
  8. package/lib/auto_page.js.map +1 -1
  9. package/lib/browser_manager.js +28 -8
  10. package/lib/browser_manager.js.map +1 -1
  11. package/lib/bruno.d.ts +2 -0
  12. package/lib/bruno.js +381 -0
  13. package/lib/bruno.js.map +1 -0
  14. package/lib/command_common.d.ts +1 -1
  15. package/lib/command_common.js +24 -4
  16. package/lib/command_common.js.map +1 -1
  17. package/lib/date_time.js.map +1 -1
  18. package/lib/drawRect.js.map +1 -1
  19. package/lib/environment.d.ts +1 -0
  20. package/lib/environment.js +1 -0
  21. package/lib/environment.js.map +1 -1
  22. package/lib/error-messages.js.map +1 -1
  23. package/lib/file_checker.d.ts +1 -0
  24. package/lib/file_checker.js +61 -0
  25. package/lib/file_checker.js.map +1 -0
  26. package/lib/find_function.js.map +1 -1
  27. package/lib/index.d.ts +2 -0
  28. package/lib/index.js +2 -0
  29. package/lib/index.js.map +1 -1
  30. package/lib/init_browser.js +4 -4
  31. package/lib/init_browser.js.map +1 -1
  32. package/lib/locate_element.js.map +1 -1
  33. package/lib/locator.d.ts +1 -0
  34. package/lib/locator.js +10 -3
  35. package/lib/locator.js.map +1 -1
  36. package/lib/locator_log.js.map +1 -1
  37. package/lib/network.js.map +1 -1
  38. package/lib/route.d.ts +33 -0
  39. package/lib/route.js +268 -0
  40. package/lib/route.js.map +1 -0
  41. package/lib/scripts/axe.mini.js +3 -3
  42. package/lib/snapshot_validation.d.ts +37 -0
  43. package/lib/snapshot_validation.js +357 -0
  44. package/lib/snapshot_validation.js.map +1 -0
  45. package/lib/stable_browser.d.ts +62 -25
  46. package/lib/stable_browser.js +941 -224
  47. package/lib/stable_browser.js.map +1 -1
  48. package/lib/table.d.ts +9 -7
  49. package/lib/table.js +82 -12
  50. package/lib/table.js.map +1 -1
  51. package/lib/table_analyze.js.map +1 -1
  52. package/lib/table_helper.js +15 -0
  53. package/lib/table_helper.js.map +1 -1
  54. package/lib/test_context.d.ts +1 -0
  55. package/lib/test_context.js +1 -0
  56. package/lib/test_context.js.map +1 -1
  57. package/lib/utils.d.ts +16 -2
  58. package/lib/utils.js +109 -60
  59. package/lib/utils.js.map +1 -1
  60. package/package.json +13 -6
@@ -10,11 +10,12 @@ import { getDateTimeValue } from "./date_time.js";
10
10
  import drawRectangle from "./drawRect.js";
11
11
  //import { closeUnexpectedPopups } from "./popups.js";
12
12
  import { getTableCells, getTableData } from "./table_analyze.js";
13
- import { _convertToRegexQuery, _copyContext, _fixLocatorUsingParams, _fixUsingParams, _getServerUrl, extractStepExampleParameters, KEYBOARD_EVENTS, maskValue, replaceWithLocalTestData, scrollPageToLoadLazyElements, unEscapeString, _getDataFile, testForRegex, performAction, } from "./utils.js";
13
+ import { _convertToRegexQuery, _copyContext, _fixLocatorUsingParams, _fixUsingParams, _getServerUrl, extractStepExampleParameters, KEYBOARD_EVENTS, maskValue, replaceWithLocalTestData, scrollPageToLoadLazyElements, unEscapeString, _getDataFile, testForRegex, performAction, _getTestData, } from "./utils.js";
14
14
  import csv from "csv-parser";
15
15
  import { Readable } from "node:stream";
16
16
  import readline from "readline";
17
17
  import { getContext, refreshBrowser } from "./init_browser.js";
18
+ import { getTestData } from "./auto_page.js";
18
19
  import { locate_element } from "./locate_element.js";
19
20
  import { randomUUID } from "crypto";
20
21
  import { _commandError, _commandFinally, _preCommand, _validateSelectors, _screenshot, _reportToWorld, } from "./command_common.js";
@@ -22,23 +23,29 @@ import { registerDownloadEvent, registerNetworkEvents } from "./network.js";
22
23
  import { LocatorLog } from "./locator_log.js";
23
24
  import axios from "axios";
24
25
  import { _findCellArea, findElementsInArea } from "./table_helper.js";
26
+ import { highlightSnapshot, snapshotValidation } from "./snapshot_validation.js";
27
+ import { loadBrunoParams } from "./bruno.js";
28
+ import { registerAfterStepRoutes, registerBeforeStepRoutes } from "./route.js";
25
29
  export const Types = {
26
30
  CLICK: "click_element",
27
31
  WAIT_ELEMENT: "wait_element",
28
32
  NAVIGATE: "navigate",
33
+ GO_BACK: "go_back",
34
+ GO_FORWARD: " go_forward",
29
35
  FILL: "fill_element",
30
- EXECUTE: "execute_page_method",
31
- OPEN: "open_environment",
36
+ EXECUTE: "execute_page_method", //
37
+ OPEN: "open_environment", //
32
38
  COMPLETE: "step_complete",
33
39
  ASK: "information_needed",
34
- GET_PAGE_STATUS: "get_page_status",
35
- CLICK_ROW_ACTION: "click_row_action",
40
+ GET_PAGE_STATUS: "get_page_status", ///
41
+ CLICK_ROW_ACTION: "click_row_action", //
36
42
  VERIFY_ELEMENT_CONTAINS_TEXT: "verify_element_contains_text",
37
43
  VERIFY_PAGE_CONTAINS_TEXT: "verify_page_contains_text",
38
44
  VERIFY_PAGE_CONTAINS_NO_TEXT: "verify_page_contains_no_text",
39
45
  ANALYZE_TABLE: "analyze_table",
40
- SELECT: "select_combobox",
46
+ SELECT: "select_combobox", //
41
47
  VERIFY_PAGE_PATH: "verify_page_path",
48
+ VERIFY_PAGE_TITLE: "verify_page_title",
42
49
  TYPE_PRESS: "type_press",
43
50
  PRESS: "press_key",
44
51
  HOVER: "hover_element",
@@ -55,6 +62,13 @@ export const Types = {
55
62
  WAIT_FOR_TEXT_TO_DISAPPEAR: "wait_for_text_to_disappear",
56
63
  VERIFY_ATTRIBUTE: "verify_element_attribute",
57
64
  VERIFY_TEXT_WITH_RELATION: "verify_text_with_relation",
65
+ BRUNO: "bruno",
66
+ VERIFY_FILE_EXISTS: "verify_file_exists",
67
+ SET_INPUT_FILES: "set_input_files",
68
+ SNAPSHOT_VALIDATION: "snapshot_validation",
69
+ REPORT_COMMAND: "report_command",
70
+ STEP_COMPLETE: "step_complete",
71
+ SLEEP: "sleep",
58
72
  };
59
73
  export const apps = {};
60
74
  const formatElementName = (elementName) => {
@@ -66,6 +80,7 @@ class StableBrowser {
66
80
  logger;
67
81
  context;
68
82
  world;
83
+ fastMode;
69
84
  project_path = null;
70
85
  webLogFile = null;
71
86
  networkLogger = null;
@@ -74,12 +89,13 @@ class StableBrowser {
74
89
  tags = null;
75
90
  isRecording = false;
76
91
  initSnapshotTaken = false;
77
- constructor(browser, page, logger = null, context = null, world = null) {
92
+ constructor(browser, page, logger = null, context = null, world = null, fastMode = false) {
78
93
  this.browser = browser;
79
94
  this.page = page;
80
95
  this.logger = logger;
81
96
  this.context = context;
82
97
  this.world = world;
98
+ this.fastMode = fastMode;
83
99
  if (!this.logger) {
84
100
  this.logger = console;
85
101
  }
@@ -108,6 +124,18 @@ class StableBrowser {
108
124
  context.pages = [this.page];
109
125
  const logFolder = path.join(this.project_path, "logs", "web");
110
126
  this.world = world;
127
+ if (this.configuration && this.configuration.fastMode === true) {
128
+ this.fastMode = true;
129
+ }
130
+ if (process.env.FAST_MODE === "true") {
131
+ this.fastMode = true;
132
+ }
133
+ if (process.env.FAST_MODE === "false") {
134
+ this.fastMode = false;
135
+ }
136
+ if (this.context) {
137
+ this.context.fastMode = this.fastMode;
138
+ }
111
139
  this.registerEventListeners(this.context);
112
140
  registerNetworkEvents(this.world, this, this.context, this.page);
113
141
  registerDownloadEvent(this.page, this.world, this.context);
@@ -118,6 +146,9 @@ class StableBrowser {
118
146
  if (!context.pageLoading) {
119
147
  context.pageLoading = { status: false };
120
148
  }
149
+ if (this.configuration && this.configuration.acceptDialog && this.page) {
150
+ this.page.on("dialog", (dialog) => dialog.accept());
151
+ }
121
152
  context.playContext.on("page", async function (page) {
122
153
  if (this.configuration && this.configuration.closePopups === true) {
123
154
  console.log("close unexpected popups");
@@ -126,6 +157,14 @@ class StableBrowser {
126
157
  }
127
158
  context.pageLoading.status = true;
128
159
  this.page = page;
160
+ try {
161
+ if (this.configuration && this.configuration.acceptDialog) {
162
+ await page.on("dialog", (dialog) => dialog.accept());
163
+ }
164
+ }
165
+ catch (error) {
166
+ console.error("Error on dialog accept registration", error);
167
+ }
129
168
  context.page = page;
130
169
  context.pages.push(page);
131
170
  registerNetworkEvents(this.world, this, context, this.page);
@@ -177,8 +216,34 @@ class StableBrowser {
177
216
  if (newContextCreated) {
178
217
  this.registerEventListeners(this.context);
179
218
  await this.goto(this.context.environment.baseUrl);
180
- await this.waitForPageLoad();
219
+ if (!this.fastMode) {
220
+ await this.waitForPageLoad();
221
+ }
222
+ }
223
+ }
224
+ async switchTab(tabTitleOrIndex) {
225
+ // first check if the tabNameOrIndex is a number
226
+ let index = parseInt(tabTitleOrIndex);
227
+ if (!isNaN(index)) {
228
+ if (index >= 0 && index < this.context.pages.length) {
229
+ this.page = this.context.pages[index];
230
+ this.context.page = this.page;
231
+ await this.page.bringToFront();
232
+ return;
233
+ }
234
+ }
235
+ // if the tabNameOrIndex is a string, find the tab by name
236
+ for (let i = 0; i < this.context.pages.length; i++) {
237
+ let page = this.context.pages[i];
238
+ let title = await page.title();
239
+ if (title.includes(tabTitleOrIndex)) {
240
+ this.page = page;
241
+ this.context.page = this.page;
242
+ await this.page.bringToFront();
243
+ return;
244
+ }
181
245
  }
246
+ throw new Error("Tab not found: " + tabTitleOrIndex);
182
247
  }
183
248
  registerConsoleLogListener(page, context) {
184
249
  if (!this.context.webLogger) {
@@ -247,6 +312,7 @@ class StableBrowser {
247
312
  if (!url) {
248
313
  throw new Error("url is null, verify that the environment file is correct");
249
314
  }
315
+ url = await this._replaceWithLocalData(url, this.world);
250
316
  if (!url.startsWith("http")) {
251
317
  url = "https://" + url;
252
318
  }
@@ -275,7 +341,65 @@ class StableBrowser {
275
341
  _commandError(state, error, this);
276
342
  }
277
343
  finally {
278
- _commandFinally(state, this);
344
+ await _commandFinally(state, this);
345
+ }
346
+ }
347
+ async goBack(options, world = null) {
348
+ const state = {
349
+ value: "",
350
+ world: world,
351
+ type: Types.GO_BACK,
352
+ text: `Browser navigate back`,
353
+ operation: "goBack",
354
+ log: "***** navigate back *****\n",
355
+ info: {},
356
+ locate: false,
357
+ scroll: false,
358
+ screenshot: false,
359
+ highlight: false,
360
+ };
361
+ try {
362
+ await _preCommand(state, this);
363
+ await this.page.goBack({
364
+ waitUntil: "load",
365
+ });
366
+ await _screenshot(state, this);
367
+ }
368
+ catch (error) {
369
+ console.error("Error on goBack", error);
370
+ _commandError(state, error, this);
371
+ }
372
+ finally {
373
+ await _commandFinally(state, this);
374
+ }
375
+ }
376
+ async goForward(options, world = null) {
377
+ const state = {
378
+ value: "",
379
+ world: world,
380
+ type: Types.GO_FORWARD,
381
+ text: `Browser navigate forward`,
382
+ operation: "goForward",
383
+ log: "***** navigate forward *****\n",
384
+ info: {},
385
+ locate: false,
386
+ scroll: false,
387
+ screenshot: false,
388
+ highlight: false,
389
+ };
390
+ try {
391
+ await _preCommand(state, this);
392
+ await this.page.goForward({
393
+ waitUntil: "load",
394
+ });
395
+ await _screenshot(state, this);
396
+ }
397
+ catch (error) {
398
+ console.error("Error on goForward", error);
399
+ _commandError(state, error, this);
400
+ }
401
+ finally {
402
+ await _commandFinally(state, this);
279
403
  }
280
404
  }
281
405
  async _getLocator(locator, scope, _params) {
@@ -391,7 +515,7 @@ class StableBrowser {
391
515
  }
392
516
  return { elementCount: tagCount, randomToken };
393
517
  }
394
- async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null) {
518
+ async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null, logErrors = false) {
395
519
  if (!info) {
396
520
  info = {};
397
521
  }
@@ -458,7 +582,7 @@ class StableBrowser {
458
582
  }
459
583
  return;
460
584
  }
461
- if (info.locatorLog && count === 0) {
585
+ if (info.locatorLog && count === 0 && logErrors) {
462
586
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "NOT_FOUND");
463
587
  }
464
588
  for (let j = 0; j < count; j++) {
@@ -473,7 +597,7 @@ class StableBrowser {
473
597
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "FOUND");
474
598
  }
475
599
  }
476
- else {
600
+ else if (logErrors) {
477
601
  info.failCause.visible = visible;
478
602
  info.failCause.enabled = enabled;
479
603
  if (!info.printMessages) {
@@ -565,7 +689,7 @@ class StableBrowser {
565
689
  let element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
566
690
  if (!element.rerun) {
567
691
  const randomToken = Math.random().toString(36).substring(7);
568
- element.evaluate((el, randomToken) => {
692
+ await element.evaluate((el, randomToken) => {
569
693
  el.setAttribute("data-blinq-id-" + randomToken, "");
570
694
  }, randomToken);
571
695
  // if (element._frame) {
@@ -579,7 +703,7 @@ class StableBrowser {
579
703
  if (frameSelectorIndex !== -1) {
580
704
  // remove everything after the >> internal:control=enter-frame
581
705
  const frameSelector = element._selector.substring(0, frameSelectorIndex);
582
- prefixSelector = frameSelector + " >> internal:control=enter-frame";
706
+ prefixSelector = frameSelector + " >> internal:control=enter-frame >>";
583
707
  }
584
708
  // if (element?._frame?._selector) {
585
709
  // prefixSelector = element._frame._selector + " >> " + prefixSelector;
@@ -814,7 +938,7 @@ class StableBrowser {
814
938
  }
815
939
  throw new Error("failed to locate first element no elements found, " + info.log);
816
940
  }
817
- async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name) {
941
+ async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name, logErrors = false) {
818
942
  let foundElements = [];
819
943
  const result = {
820
944
  foundElements: foundElements,
@@ -833,7 +957,9 @@ class StableBrowser {
833
957
  await this._collectLocatorInformation(locatorsGroup, i, this.page, foundLocators, _params, info, visibleOnly, allowDisabled, element_name);
834
958
  }
835
959
  catch (e) {
836
- this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
960
+ if (logErrors) {
961
+ this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
962
+ }
837
963
  }
838
964
  }
839
965
  if (foundLocators.length === 1) {
@@ -874,7 +1000,7 @@ class StableBrowser {
874
1000
  });
875
1001
  result.locatorIndex = i;
876
1002
  }
877
- else {
1003
+ else if (logErrors) {
878
1004
  info.failCause.foundMultiple = true;
879
1005
  if (info.locatorLog) {
880
1006
  info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
@@ -926,7 +1052,7 @@ class StableBrowser {
926
1052
  await _commandError(state, "timeout looking for " + elementDescription, this);
927
1053
  }
928
1054
  finally {
929
- _commandFinally(state, this);
1055
+ await _commandFinally(state, this);
930
1056
  }
931
1057
  }
932
1058
  }
@@ -975,7 +1101,7 @@ class StableBrowser {
975
1101
  await _commandError(state, "timeout looking for " + elementDescription, this);
976
1102
  }
977
1103
  finally {
978
- _commandFinally(state, this);
1104
+ await _commandFinally(state, this);
979
1105
  }
980
1106
  }
981
1107
  }
@@ -997,14 +1123,16 @@ class StableBrowser {
997
1123
  try {
998
1124
  await _preCommand(state, this);
999
1125
  await performAction("click", state.element, options, this, state, _params);
1000
- await this.waitForPageLoad();
1126
+ if (!this.fastMode) {
1127
+ await this.waitForPageLoad();
1128
+ }
1001
1129
  return state.info;
1002
1130
  }
1003
1131
  catch (e) {
1004
1132
  await _commandError(state, e, this);
1005
1133
  }
1006
1134
  finally {
1007
- _commandFinally(state, this);
1135
+ await _commandFinally(state, this);
1008
1136
  }
1009
1137
  }
1010
1138
  async waitForElement(selectors, _params, options = {}, world = null) {
@@ -1035,7 +1163,7 @@ class StableBrowser {
1035
1163
  // await _commandError(state, e, this);
1036
1164
  }
1037
1165
  finally {
1038
- _commandFinally(state, this);
1166
+ await _commandFinally(state, this);
1039
1167
  }
1040
1168
  return found;
1041
1169
  }
@@ -1060,7 +1188,7 @@ class StableBrowser {
1060
1188
  // if (world && world.screenshot && !world.screenshotPath) {
1061
1189
  // console.log(`Highlighting while running from recorder`);
1062
1190
  await this._highlightElements(state.element);
1063
- await state.element.setChecked(checked);
1191
+ await state.element.setChecked(checked, { timeout: 2000 });
1064
1192
  await new Promise((resolve) => setTimeout(resolve, 1000));
1065
1193
  // await this._unHighlightElements(element);
1066
1194
  // }
@@ -1072,11 +1200,28 @@ class StableBrowser {
1072
1200
  this.logger.info("element did not change its state, ignoring...");
1073
1201
  }
1074
1202
  else {
1203
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1075
1204
  //await this.closeUnexpectedPopups();
1076
1205
  state.info.log += "setCheck failed, will try again" + "\n";
1077
- state.element = await this._locate(selectors, state.info, _params);
1078
- await state.element.setChecked(checked, { timeout: 5000, force: true });
1079
- await new Promise((resolve) => setTimeout(resolve, 1000));
1206
+ state.element_found = false;
1207
+ try {
1208
+ state.element = await this._locate(selectors, state.info, _params, 100);
1209
+ state.element_found = true;
1210
+ // check the check state
1211
+ }
1212
+ catch (error) {
1213
+ // element dismissed
1214
+ }
1215
+ if (state.element_found) {
1216
+ const isChecked = await state.element.isChecked();
1217
+ if (isChecked !== checked) {
1218
+ // perform click
1219
+ await state.element.click({ timeout: 2000, force: true });
1220
+ }
1221
+ else {
1222
+ this.logger.info(`Element ${selectors.element_name} is already in the desired state (${checked})`);
1223
+ }
1224
+ }
1080
1225
  }
1081
1226
  }
1082
1227
  await this.waitForPageLoad();
@@ -1086,7 +1231,7 @@ class StableBrowser {
1086
1231
  await _commandError(state, e, this);
1087
1232
  }
1088
1233
  finally {
1089
- _commandFinally(state, this);
1234
+ await _commandFinally(state, this);
1090
1235
  }
1091
1236
  }
1092
1237
  async hover(selectors, _params, options = {}, world = null) {
@@ -1112,7 +1257,7 @@ class StableBrowser {
1112
1257
  await _commandError(state, e, this);
1113
1258
  }
1114
1259
  finally {
1115
- _commandFinally(state, this);
1260
+ await _commandFinally(state, this);
1116
1261
  }
1117
1262
  }
1118
1263
  async selectOption(selectors, values, _params = null, options = {}, world = null) {
@@ -1148,7 +1293,7 @@ class StableBrowser {
1148
1293
  await _commandError(state, e, this);
1149
1294
  }
1150
1295
  finally {
1151
- _commandFinally(state, this);
1296
+ await _commandFinally(state, this);
1152
1297
  }
1153
1298
  }
1154
1299
  async type(_value, _params = null, options = {}, world = null) {
@@ -1194,7 +1339,7 @@ class StableBrowser {
1194
1339
  await _commandError(state, e, this);
1195
1340
  }
1196
1341
  finally {
1197
- _commandFinally(state, this);
1342
+ await _commandFinally(state, this);
1198
1343
  }
1199
1344
  }
1200
1345
  async setInputValue(selectors, value, _params = null, options = {}, world = null) {
@@ -1230,7 +1375,7 @@ class StableBrowser {
1230
1375
  await _commandError(state, e, this);
1231
1376
  }
1232
1377
  finally {
1233
- _commandFinally(state, this);
1378
+ await _commandFinally(state, this);
1234
1379
  }
1235
1380
  }
1236
1381
  async setDateTime(selectors, value, format = null, enter = false, _params = null, options = {}, world = null) {
@@ -1299,7 +1444,7 @@ class StableBrowser {
1299
1444
  await _commandError(state, e, this);
1300
1445
  }
1301
1446
  finally {
1302
- _commandFinally(state, this);
1447
+ await _commandFinally(state, this);
1303
1448
  }
1304
1449
  }
1305
1450
  async clickType(selectors, _value, enter = false, _params = null, options = {}, world = null) {
@@ -1372,7 +1517,9 @@ class StableBrowser {
1372
1517
  await new Promise((resolve) => setTimeout(resolve, 500));
1373
1518
  }
1374
1519
  }
1520
+ //if (!this.fastMode) {
1375
1521
  await _screenshot(state, this);
1522
+ //}
1376
1523
  if (enter === true) {
1377
1524
  await new Promise((resolve) => setTimeout(resolve, 2000));
1378
1525
  await this.page.keyboard.press("Enter");
@@ -1399,7 +1546,7 @@ class StableBrowser {
1399
1546
  await _commandError(state, e, this);
1400
1547
  }
1401
1548
  finally {
1402
- _commandFinally(state, this);
1549
+ await _commandFinally(state, this);
1403
1550
  }
1404
1551
  }
1405
1552
  async fill(selectors, value, enter = false, _params = null, options = {}, world = null) {
@@ -1429,7 +1576,42 @@ class StableBrowser {
1429
1576
  await _commandError(state, e, this);
1430
1577
  }
1431
1578
  finally {
1432
- _commandFinally(state, this);
1579
+ await _commandFinally(state, this);
1580
+ }
1581
+ }
1582
+ async setInputFiles(selectors, files, _params = null, options = {}, world = null) {
1583
+ const state = {
1584
+ selectors,
1585
+ _params,
1586
+ files,
1587
+ value: '"' + files.join('", "') + '"',
1588
+ options,
1589
+ world,
1590
+ type: Types.SET_INPUT_FILES,
1591
+ text: `Set input files`,
1592
+ _text: `Set input files on ${selectors.element_name}`,
1593
+ operation: "setInputFiles",
1594
+ log: "***** set input files " + selectors.element_name + " *****\n",
1595
+ };
1596
+ const uploadsFolder = this.configuration.uploadsFolder ?? "data/uploads";
1597
+ try {
1598
+ await _preCommand(state, this);
1599
+ for (let i = 0; i < files.length; i++) {
1600
+ const file = files[i];
1601
+ const filePath = path.join(uploadsFolder, file);
1602
+ if (!fs.existsSync(filePath)) {
1603
+ throw new Error(`File not found: ${filePath}`);
1604
+ }
1605
+ state.files[i] = filePath;
1606
+ }
1607
+ await state.element.setInputFiles(files);
1608
+ return state.info;
1609
+ }
1610
+ catch (e) {
1611
+ await _commandError(state, e, this);
1612
+ }
1613
+ finally {
1614
+ await _commandFinally(state, this);
1433
1615
  }
1434
1616
  }
1435
1617
  async getText(selectors, _params = null, options = {}, info = {}, world = null) {
@@ -1545,7 +1727,7 @@ class StableBrowser {
1545
1727
  await _commandError(state, e, this);
1546
1728
  }
1547
1729
  finally {
1548
- _commandFinally(state, this);
1730
+ await _commandFinally(state, this);
1549
1731
  }
1550
1732
  }
1551
1733
  async containsText(selectors, text, climb, _params = null, options = {}, world = null) {
@@ -1622,7 +1804,84 @@ class StableBrowser {
1622
1804
  throw e;
1623
1805
  }
1624
1806
  finally {
1625
- _commandFinally(state, this);
1807
+ await _commandFinally(state, this);
1808
+ }
1809
+ }
1810
+ async snapshotValidation(frameSelectors, referanceSnapshot, _params = null, options = {}, world = null) {
1811
+ const timeout = this._getFindElementTimeout(options);
1812
+ const startTime = Date.now();
1813
+ const state = {
1814
+ _params,
1815
+ value: referanceSnapshot,
1816
+ options,
1817
+ world,
1818
+ locate: false,
1819
+ scroll: false,
1820
+ screenshot: true,
1821
+ highlight: false,
1822
+ type: Types.SNAPSHOT_VALIDATION,
1823
+ text: `verify snapshot: ${referanceSnapshot}`,
1824
+ operation: "snapshotValidation",
1825
+ log: "***** verify snapshot *****\n",
1826
+ };
1827
+ if (!referanceSnapshot) {
1828
+ throw new Error("referanceSnapshot is null");
1829
+ }
1830
+ let text = null;
1831
+ if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"))) {
1832
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"), "utf8");
1833
+ }
1834
+ else if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"))) {
1835
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"), "utf8");
1836
+ }
1837
+ else if (referanceSnapshot.startsWith("yaml:")) {
1838
+ text = referanceSnapshot.substring(5);
1839
+ }
1840
+ else {
1841
+ throw new Error("referenceSnapshot file not found: " + referanceSnapshot);
1842
+ }
1843
+ state.text = text;
1844
+ const newValue = await this._replaceWithLocalData(text, world);
1845
+ await _preCommand(state, this);
1846
+ let foundObj = null;
1847
+ try {
1848
+ let matchResult = null;
1849
+ while (Date.now() - startTime < timeout) {
1850
+ try {
1851
+ let scope = null;
1852
+ if (!frameSelectors) {
1853
+ scope = this.page;
1854
+ }
1855
+ else {
1856
+ scope = await this._findFrameScope(frameSelectors, timeout, state.info);
1857
+ }
1858
+ const snapshot = await scope.locator("body").ariaSnapshot({ timeout });
1859
+ matchResult = snapshotValidation(snapshot, newValue, referanceSnapshot);
1860
+ if (matchResult.errorLine !== -1) {
1861
+ throw new Error("Snapshot validation failed at line " + matchResult.errorLineText);
1862
+ }
1863
+ // highlight and screenshot
1864
+ try {
1865
+ await await highlightSnapshot(newValue, scope);
1866
+ await _screenshot(state, this);
1867
+ }
1868
+ catch (e) { }
1869
+ return state.info;
1870
+ }
1871
+ catch (e) {
1872
+ // Log error but continue retrying until timeout is reached
1873
+ //this.logger.warn("Retrying snapshot validation due to: " + e.message);
1874
+ }
1875
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 1 second before retrying
1876
+ }
1877
+ throw new Error("No snapshot match " + matchResult?.errorLineText);
1878
+ }
1879
+ catch (e) {
1880
+ await _commandError(state, e, this);
1881
+ throw e;
1882
+ }
1883
+ finally {
1884
+ await _commandFinally(state, this);
1626
1885
  }
1627
1886
  }
1628
1887
  async waitForUserInput(message, world = null) {
@@ -1765,12 +2024,7 @@ class StableBrowser {
1765
2024
  }
1766
2025
  }
1767
2026
  getTestData(world = null) {
1768
- const dataFile = _getDataFile(world, this.context, this);
1769
- let data = {};
1770
- if (fs.existsSync(dataFile)) {
1771
- data = JSON.parse(fs.readFileSync(dataFile, "utf8"));
1772
- }
1773
- return data;
2027
+ return _getTestData(world, this.context, this);
1774
2028
  }
1775
2029
  async _screenShot(options = {}, world = null, info = null) {
1776
2030
  // collect url/path/title
@@ -1921,7 +2175,7 @@ class StableBrowser {
1921
2175
  await _commandError(state, e, this);
1922
2176
  }
1923
2177
  finally {
1924
- _commandFinally(state, this);
2178
+ await _commandFinally(state, this);
1925
2179
  }
1926
2180
  }
1927
2181
  async extractAttribute(selectors, attribute, variable, _params = null, options = {}, world = null) {
@@ -1952,10 +2206,31 @@ class StableBrowser {
1952
2206
  case "value":
1953
2207
  state.value = await state.element.inputValue();
1954
2208
  break;
2209
+ case "text":
2210
+ state.value = await state.element.textContent();
2211
+ break;
1955
2212
  default:
1956
2213
  state.value = await state.element.getAttribute(attribute);
1957
2214
  break;
1958
2215
  }
2216
+ if (options !== null) {
2217
+ if (options.regex && options.regex !== "") {
2218
+ // Construct a regex pattern from the provided string
2219
+ const regex = options.regex.slice(1, -1);
2220
+ const regexPattern = new RegExp(regex, "g");
2221
+ const matches = state.value.match(regexPattern);
2222
+ if (matches) {
2223
+ let newValue = "";
2224
+ for (const match of matches) {
2225
+ newValue += match;
2226
+ }
2227
+ state.value = newValue;
2228
+ }
2229
+ }
2230
+ if (options.trimSpaces && options.trimSpaces === true) {
2231
+ state.value = state.value.trim();
2232
+ }
2233
+ }
1959
2234
  state.info.value = state.value;
1960
2235
  this.setTestData({ [variable]: state.value }, world);
1961
2236
  this.logger.info("set test data: " + variable + "=" + state.value);
@@ -1966,7 +2241,78 @@ class StableBrowser {
1966
2241
  await _commandError(state, e, this);
1967
2242
  }
1968
2243
  finally {
1969
- _commandFinally(state, this);
2244
+ await _commandFinally(state, this);
2245
+ }
2246
+ }
2247
+ async extractProperty(selectors, property, variable, _params = null, options = {}, world = null) {
2248
+ const state = {
2249
+ selectors,
2250
+ _params,
2251
+ property,
2252
+ variable,
2253
+ options,
2254
+ world,
2255
+ type: Types.EXTRACT_PROPERTY,
2256
+ text: `Extract property from element`,
2257
+ _text: `Extract property ${property} from ${selectors.element_name}`,
2258
+ operation: "extractProperty",
2259
+ log: "***** extract property " + property + " from " + selectors.element_name + " *****\n",
2260
+ allowDisabled: true,
2261
+ };
2262
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2263
+ try {
2264
+ await _preCommand(state, this);
2265
+ switch (property) {
2266
+ case "inner_text":
2267
+ state.value = await state.element.innerText();
2268
+ break;
2269
+ case "href":
2270
+ state.value = await state.element.getAttribute("href");
2271
+ break;
2272
+ case "value":
2273
+ state.value = await state.element.inputValue();
2274
+ break;
2275
+ case "text":
2276
+ state.value = await state.element.textContent();
2277
+ break;
2278
+ default:
2279
+ if (property.startsWith("dataset.")) {
2280
+ const dataAttribute = property.substring(8);
2281
+ state.value = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2282
+ }
2283
+ else {
2284
+ state.value = String(await state.element.evaluate((element, prop) => element[prop], property));
2285
+ }
2286
+ }
2287
+ if (options !== null) {
2288
+ if (options.regex && options.regex !== "") {
2289
+ // Construct a regex pattern from the provided string
2290
+ const regex = options.regex.slice(1, -1);
2291
+ const regexPattern = new RegExp(regex, "g");
2292
+ const matches = state.value.match(regexPattern);
2293
+ if (matches) {
2294
+ let newValue = "";
2295
+ for (const match of matches) {
2296
+ newValue += match;
2297
+ }
2298
+ state.value = newValue;
2299
+ }
2300
+ }
2301
+ if (options.trimSpaces && options.trimSpaces === true) {
2302
+ state.value = state.value.trim();
2303
+ }
2304
+ }
2305
+ state.info.value = state.value;
2306
+ this.setTestData({ [variable]: state.value }, world);
2307
+ this.logger.info("set test data: " + variable + "=" + state.value);
2308
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2309
+ return state.info;
2310
+ }
2311
+ catch (e) {
2312
+ await _commandError(state, e, this);
2313
+ }
2314
+ finally {
2315
+ await _commandFinally(state, this);
1970
2316
  }
1971
2317
  }
1972
2318
  async verifyAttribute(selectors, attribute, value, _params = null, options = {}, world = null) {
@@ -1991,12 +2337,15 @@ class StableBrowser {
1991
2337
  let expectedValue;
1992
2338
  try {
1993
2339
  await _preCommand(state, this);
1994
- expectedValue = state.value;
2340
+ expectedValue = await replaceWithLocalTestData(state.value, world);
1995
2341
  state.info.expectedValue = expectedValue;
1996
2342
  switch (attribute) {
1997
2343
  case "innerText":
1998
2344
  val = String(await state.element.innerText());
1999
2345
  break;
2346
+ case "text":
2347
+ val = String(await state.element.textContent());
2348
+ break;
2000
2349
  case "value":
2001
2350
  val = String(await state.element.inputValue());
2002
2351
  break;
@@ -2018,17 +2367,42 @@ class StableBrowser {
2018
2367
  let regex;
2019
2368
  if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2020
2369
  const patternBody = expectedValue.slice(1, -1);
2021
- regex = new RegExp(patternBody, "g");
2370
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2371
+ regex = new RegExp(processedPattern, "gs");
2372
+ state.info.regex = true;
2022
2373
  }
2023
2374
  else {
2024
2375
  const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2025
2376
  regex = new RegExp(escapedPattern, "g");
2026
2377
  }
2027
- if (!val.match(regex)) {
2028
- let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2029
- state.info.failCause.assertionFailed = true;
2030
- state.info.failCause.lastError = errorMessage;
2031
- throw new Error(errorMessage);
2378
+ if (attribute === "innerText") {
2379
+ if (state.info.regex) {
2380
+ if (!regex.test(val)) {
2381
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2382
+ state.info.failCause.assertionFailed = true;
2383
+ state.info.failCause.lastError = errorMessage;
2384
+ throw new Error(errorMessage);
2385
+ }
2386
+ }
2387
+ else {
2388
+ const valLines = val.split("\n");
2389
+ const expectedLines = expectedValue.split("\n");
2390
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine === expectedLine));
2391
+ if (!isPart) {
2392
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2393
+ state.info.failCause.assertionFailed = true;
2394
+ state.info.failCause.lastError = errorMessage;
2395
+ throw new Error(errorMessage);
2396
+ }
2397
+ }
2398
+ }
2399
+ else {
2400
+ if (!val.match(regex)) {
2401
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2402
+ state.info.failCause.assertionFailed = true;
2403
+ state.info.failCause.lastError = errorMessage;
2404
+ throw new Error(errorMessage);
2405
+ }
2032
2406
  }
2033
2407
  return state.info;
2034
2408
  }
@@ -2036,7 +2410,128 @@ class StableBrowser {
2036
2410
  await _commandError(state, e, this);
2037
2411
  }
2038
2412
  finally {
2039
- _commandFinally(state, this);
2413
+ await _commandFinally(state, this);
2414
+ }
2415
+ }
2416
+ async verifyProperty(selectors, property, value, _params = null, options = {}, world = null) {
2417
+ const state = {
2418
+ selectors,
2419
+ _params,
2420
+ property,
2421
+ value,
2422
+ options,
2423
+ world,
2424
+ type: Types.VERIFY_PROPERTY,
2425
+ highlight: true,
2426
+ screenshot: true,
2427
+ text: `Verify element property`,
2428
+ _text: `Verify property ${property} from ${selectors.element_name} is ${value}`,
2429
+ operation: "verifyProperty",
2430
+ log: "***** verify property " + property + " from " + selectors.element_name + " *****\n",
2431
+ allowDisabled: true,
2432
+ };
2433
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2434
+ let val;
2435
+ let expectedValue;
2436
+ try {
2437
+ await _preCommand(state, this);
2438
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2439
+ state.info.expectedValue = expectedValue;
2440
+ switch (property) {
2441
+ case "innerText":
2442
+ val = String(await state.element.innerText());
2443
+ break;
2444
+ case "text":
2445
+ val = String(await state.element.textContent());
2446
+ break;
2447
+ case "value":
2448
+ val = String(await state.element.inputValue());
2449
+ break;
2450
+ case "checked":
2451
+ val = String(await state.element.isChecked());
2452
+ break;
2453
+ case "disabled":
2454
+ val = String(await state.element.isDisabled());
2455
+ break;
2456
+ case "readOnly":
2457
+ const isEditable = await state.element.isEditable();
2458
+ val = String(!isEditable);
2459
+ break;
2460
+ case "innerHTML":
2461
+ val = String(await state.element.innerHTML());
2462
+ break;
2463
+ case "outerHTML":
2464
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2465
+ break;
2466
+ default:
2467
+ if (property.startsWith("dataset.")) {
2468
+ const dataAttribute = property.substring(8);
2469
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2470
+ }
2471
+ else {
2472
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2473
+ }
2474
+ }
2475
+ // Helper function to remove all style="" attributes
2476
+ const removeStyleAttributes = (htmlString) => {
2477
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2478
+ };
2479
+ // Remove style attributes for innerHTML and outerHTML properties
2480
+ if (property === "innerHTML" || property === "outerHTML") {
2481
+ val = removeStyleAttributes(val);
2482
+ expectedValue = removeStyleAttributes(expectedValue);
2483
+ }
2484
+ state.info.value = val;
2485
+ let regex;
2486
+ if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2487
+ const patternBody = expectedValue.slice(1, -1);
2488
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2489
+ regex = new RegExp(processedPattern, "gs");
2490
+ state.info.regex = true;
2491
+ }
2492
+ else {
2493
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2494
+ regex = new RegExp(escapedPattern, "g");
2495
+ }
2496
+ if (property === "innerText") {
2497
+ if (state.info.regex) {
2498
+ if (!regex.test(val)) {
2499
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2500
+ state.info.failCause.assertionFailed = true;
2501
+ state.info.failCause.lastError = errorMessage;
2502
+ throw new Error(errorMessage);
2503
+ }
2504
+ }
2505
+ else {
2506
+ // Fix: Replace escaped newlines with actual newlines before splitting
2507
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2508
+ const valLines = val.split("\n");
2509
+ const expectedLines = normalizedExpectedValue.split("\n");
2510
+ // Check if all expected lines are present in the actual lines
2511
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2512
+ if (!isPart) {
2513
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2514
+ state.info.failCause.assertionFailed = true;
2515
+ state.info.failCause.lastError = errorMessage;
2516
+ throw new Error(errorMessage);
2517
+ }
2518
+ }
2519
+ }
2520
+ else {
2521
+ if (!val.match(regex)) {
2522
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2523
+ state.info.failCause.assertionFailed = true;
2524
+ state.info.failCause.lastError = errorMessage;
2525
+ throw new Error(errorMessage);
2526
+ }
2527
+ }
2528
+ return state.info;
2529
+ }
2530
+ catch (e) {
2531
+ await _commandError(state, e, this);
2532
+ }
2533
+ finally {
2534
+ await _commandFinally(state, this);
2040
2535
  }
2041
2536
  }
2042
2537
  async extractEmailData(emailAddress, options, world) {
@@ -2196,56 +2691,49 @@ class StableBrowser {
2196
2691
  console.debug(error);
2197
2692
  }
2198
2693
  }
2199
- // async _unhighlightElements(scope, css) {
2200
- // try {
2201
- // if (!scope) {
2202
- // return;
2203
- // }
2204
- // if (!css) {
2205
- // scope
2206
- // .evaluate((node) => {
2207
- // if (node && node.style) {
2208
- // if (!node.__previousOutline) {
2209
- // node.style.outline = "";
2210
- // } else {
2211
- // node.style.outline = node.__previousOutline;
2212
- // }
2213
- // }
2214
- // })
2215
- // .then(() => {})
2216
- // .catch((e) => {
2217
- // // console.log(`Error while unhighlighting node ${JSON.stringify(scope)}: ${e}`);
2218
- // });
2219
- // } else {
2220
- // scope
2221
- // .evaluate(([css]) => {
2222
- // if (!css) {
2223
- // return;
2224
- // }
2225
- // let elements = Array.from(document.querySelectorAll(css));
2226
- // for (i = 0; i < elements.length; i++) {
2227
- // let element = elements[i];
2228
- // if (!element.style) {
2229
- // return;
2230
- // }
2231
- // if (!element.__previousOutline) {
2232
- // element.style.outline = "";
2233
- // } else {
2234
- // element.style.outline = element.__previousOutline;
2235
- // }
2236
- // }
2237
- // })
2238
- // .then(() => {})
2239
- // .catch((e) => {
2240
- // // console.error(`Error while unhighlighting element in css: ${e}`);
2241
- // });
2242
- // }
2243
- // } catch (error) {
2244
- // // console.debug(error);
2245
- // }
2246
- // }
2694
+ _matcher(text) {
2695
+ if (!text) {
2696
+ return { matcher: "contains", queryText: "" };
2697
+ }
2698
+ if (text.length < 2) {
2699
+ return { matcher: "contains", queryText: text };
2700
+ }
2701
+ const split = text.split(":");
2702
+ const matcher = split[0].toLowerCase();
2703
+ const queryText = split.slice(1).join(":").trim();
2704
+ return { matcher, queryText };
2705
+ }
2706
+ _getDomain(url) {
2707
+ if (url.length === 0 || (!url.startsWith("http://") && !url.startsWith("https://"))) {
2708
+ return "";
2709
+ }
2710
+ let hostnameFragments = url.split("/")[2].split(".");
2711
+ if (hostnameFragments.some((fragment) => fragment.includes(":"))) {
2712
+ return hostnameFragments.join("-").split(":").join("-");
2713
+ }
2714
+ let n = hostnameFragments.length;
2715
+ let fragments = [...hostnameFragments];
2716
+ while (n > 0 && hostnameFragments[n - 1].length <= 3) {
2717
+ hostnameFragments.pop();
2718
+ n = hostnameFragments.length;
2719
+ }
2720
+ if (n == 0) {
2721
+ if (fragments[0] === "www")
2722
+ fragments = fragments.slice(1);
2723
+ return fragments.length > 1 ? fragments.slice(0, fragments.length - 1).join("-") : fragments.join("-");
2724
+ }
2725
+ if (hostnameFragments[0] === "www")
2726
+ hostnameFragments = hostnameFragments.slice(1);
2727
+ return hostnameFragments.join(".");
2728
+ }
2729
+ /**
2730
+ * Verify the page path matches the given path.
2731
+ * @param {string} pathPart - The path to verify.
2732
+ * @param {object} options - Options for verification.
2733
+ * @param {object} world - The world context.
2734
+ * @returns {Promise<object>} - The state info after verification.
2735
+ */
2247
2736
  async verifyPagePath(pathPart, options = {}, world = null) {
2248
- const startTime = Date.now();
2249
2737
  let error = null;
2250
2738
  let screenshotId = null;
2251
2739
  let screenshotPath = null;
@@ -2259,113 +2747,212 @@ class StableBrowser {
2259
2747
  pathPart = newValue;
2260
2748
  }
2261
2749
  info.pathPart = pathPart;
2750
+ const { matcher, queryText } = this._matcher(pathPart);
2751
+ const state = {
2752
+ text_search: queryText,
2753
+ options,
2754
+ world,
2755
+ locate: false,
2756
+ scroll: false,
2757
+ highlight: false,
2758
+ type: Types.VERIFY_PAGE_PATH,
2759
+ text: `Verify the page url is ${queryText}`,
2760
+ _text: `Verify the page url is ${queryText}`,
2761
+ operation: "verifyPagePath",
2762
+ log: "***** verify page url is " + queryText + " *****\n",
2763
+ };
2262
2764
  try {
2765
+ await _preCommand(state, this);
2766
+ state.info.text = queryText;
2263
2767
  for (let i = 0; i < 30; i++) {
2264
2768
  const url = await this.page.url();
2265
- if (!url.includes(pathPart)) {
2266
- if (i === 29) {
2267
- throw new Error(`url ${url} doesn't contain ${pathPart}`);
2268
- }
2269
- await new Promise((resolve) => setTimeout(resolve, 1000));
2270
- continue;
2769
+ switch (matcher) {
2770
+ case "exact":
2771
+ if (url !== queryText) {
2772
+ if (i === 29) {
2773
+ throw new Error(`Page URL ${url} is not equal to ${queryText}`);
2774
+ }
2775
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2776
+ continue;
2777
+ }
2778
+ break;
2779
+ case "contains":
2780
+ if (!url.includes(queryText)) {
2781
+ if (i === 29) {
2782
+ throw new Error(`Page URL ${url} doesn't contain ${queryText}`);
2783
+ }
2784
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2785
+ continue;
2786
+ }
2787
+ break;
2788
+ case "starts-with":
2789
+ {
2790
+ const domain = this._getDomain(url);
2791
+ if (domain.length > 0 && domain !== queryText) {
2792
+ if (i === 29) {
2793
+ throw new Error(`Page URL ${url} doesn't start with ${queryText}`);
2794
+ }
2795
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2796
+ continue;
2797
+ }
2798
+ }
2799
+ break;
2800
+ case "ends-with":
2801
+ {
2802
+ const urlObj = new URL(url);
2803
+ let route = "/";
2804
+ if (urlObj.pathname !== "/") {
2805
+ route = urlObj.pathname.split("/").slice(-1)[0].trim();
2806
+ }
2807
+ else {
2808
+ route = "/";
2809
+ }
2810
+ if (route !== queryText) {
2811
+ if (i === 29) {
2812
+ throw new Error(`Page URL ${url} doesn't end with ${queryText}`);
2813
+ }
2814
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2815
+ continue;
2816
+ }
2817
+ }
2818
+ break;
2819
+ case "regex":
2820
+ const regex = new RegExp(queryText.slice(1, -1), "g");
2821
+ if (!regex.test(url)) {
2822
+ if (i === 29) {
2823
+ throw new Error(`Page URL ${url} doesn't match regex ${queryText}`);
2824
+ }
2825
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2826
+ continue;
2827
+ }
2828
+ break;
2829
+ default:
2830
+ console.log("Unknown matching type, defaulting to contains matching");
2831
+ if (!url.includes(pathPart)) {
2832
+ if (i === 29) {
2833
+ throw new Error(`Page URL ${url} does not contain ${pathPart}`);
2834
+ }
2835
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2836
+ continue;
2837
+ }
2271
2838
  }
2272
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2273
- return info;
2839
+ await _screenshot(state, this);
2840
+ return state.info;
2274
2841
  }
2275
2842
  }
2276
2843
  catch (e) {
2277
- //await this.closeUnexpectedPopups();
2278
- this.logger.error("verify page path failed " + info.log);
2279
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2280
- info.screenshotPath = screenshotPath;
2281
- Object.assign(e, { info: info });
2282
- error = e;
2283
- // throw e;
2284
- await _commandError({ text: "verifyPagePath", operation: "verifyPagePath", pathPart, info }, e, this);
2844
+ state.info.failCause.lastError = e.message;
2845
+ state.info.failCause.assertionFailed = true;
2846
+ await _commandError(state, e, this);
2285
2847
  }
2286
2848
  finally {
2287
- const endTime = Date.now();
2288
- _reportToWorld(world, {
2289
- type: Types.VERIFY_PAGE_PATH,
2290
- text: "Verify page path",
2291
- _text: "Verify the page path contains " + pathPart,
2292
- screenshotId,
2293
- result: error
2294
- ? {
2295
- status: "FAILED",
2296
- startTime,
2297
- endTime,
2298
- message: error?.message,
2299
- }
2300
- : {
2301
- status: "PASSED",
2302
- startTime,
2303
- endTime,
2304
- },
2305
- info: info,
2306
- });
2849
+ await _commandFinally(state, this);
2307
2850
  }
2308
2851
  }
2852
+ /**
2853
+ * Verify the page title matches the given title.
2854
+ * @param {string} title - The title to verify.
2855
+ * @param {object} options - Options for verification.
2856
+ * @param {object} world - The world context.
2857
+ * @returns {Promise<object>} - The state info after verification.
2858
+ */
2309
2859
  async verifyPageTitle(title, options = {}, world = null) {
2310
- const startTime = Date.now();
2311
2860
  let error = null;
2312
2861
  let screenshotId = null;
2313
2862
  let screenshotPath = null;
2314
2863
  await new Promise((resolve) => setTimeout(resolve, 2000));
2315
- const info = {};
2316
- info.log = "***** verify page title " + title + " *****\n";
2317
- info.operation = "verifyPageTitle";
2318
2864
  const newValue = await this._replaceWithLocalData(title, world);
2319
2865
  if (newValue !== title) {
2320
2866
  this.logger.info(title + "=" + newValue);
2321
2867
  title = newValue;
2322
2868
  }
2323
- info.title = title;
2869
+ const { matcher, queryText } = this._matcher(title);
2870
+ const state = {
2871
+ text_search: queryText,
2872
+ options,
2873
+ world,
2874
+ locate: false,
2875
+ scroll: false,
2876
+ highlight: false,
2877
+ type: Types.VERIFY_PAGE_TITLE,
2878
+ text: `Verify the page title is ${queryText}`,
2879
+ _text: `Verify the page title is ${queryText}`,
2880
+ operation: "verifyPageTitle",
2881
+ log: "***** verify page title is " + queryText + " *****\n",
2882
+ };
2324
2883
  try {
2884
+ await _preCommand(state, this);
2885
+ state.info.text = queryText;
2325
2886
  for (let i = 0; i < 30; i++) {
2326
2887
  const foundTitle = await this.page.title();
2327
- if (!foundTitle.includes(title)) {
2328
- if (i === 29) {
2329
- throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2330
- }
2331
- await new Promise((resolve) => setTimeout(resolve, 1000));
2332
- continue;
2888
+ switch (matcher) {
2889
+ case "exact":
2890
+ if (foundTitle !== queryText) {
2891
+ if (i === 29) {
2892
+ throw new Error(`Page Title ${foundTitle} is not equal to ${queryText}`);
2893
+ }
2894
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2895
+ continue;
2896
+ }
2897
+ break;
2898
+ case "contains":
2899
+ if (!foundTitle.includes(queryText)) {
2900
+ if (i === 29) {
2901
+ throw new Error(`Page Title ${foundTitle} doesn't contain ${queryText}`);
2902
+ }
2903
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2904
+ continue;
2905
+ }
2906
+ break;
2907
+ case "starts-with":
2908
+ if (!foundTitle.startsWith(queryText)) {
2909
+ if (i === 29) {
2910
+ throw new Error(`Page title ${foundTitle} doesn't start with ${queryText}`);
2911
+ }
2912
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2913
+ continue;
2914
+ }
2915
+ break;
2916
+ case "ends-with":
2917
+ if (!foundTitle.endsWith(queryText)) {
2918
+ if (i === 29) {
2919
+ throw new Error(`Page Title ${foundTitle} doesn't end with ${queryText}`);
2920
+ }
2921
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2922
+ continue;
2923
+ }
2924
+ break;
2925
+ case "regex":
2926
+ const regex = new RegExp(queryText.slice(1, -1), "g");
2927
+ if (!regex.test(foundTitle)) {
2928
+ if (i === 29) {
2929
+ throw new Error(`Page Title ${foundTitle} doesn't match regex ${queryText}`);
2930
+ }
2931
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2932
+ continue;
2933
+ }
2934
+ break;
2935
+ default:
2936
+ console.log("Unknown matching type, defaulting to contains matching");
2937
+ if (!foundTitle.includes(title)) {
2938
+ if (i === 29) {
2939
+ throw new Error(`Page Title ${foundTitle} does not contain ${title}`);
2940
+ }
2941
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2942
+ continue;
2943
+ }
2333
2944
  }
2334
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2335
- return info;
2945
+ await _screenshot(state, this);
2946
+ return state.info;
2336
2947
  }
2337
2948
  }
2338
2949
  catch (e) {
2339
- //await this.closeUnexpectedPopups();
2340
- this.logger.error("verify page title failed " + info.log);
2341
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2342
- info.screenshotPath = screenshotPath;
2343
- Object.assign(e, { info: info });
2344
- error = e;
2345
- // throw e;
2346
- await _commandError({ text: "verifyPageTitle", operation: "verifyPageTitle", title, info, throwError: true }, e, this);
2950
+ state.info.failCause.lastError = e.message;
2951
+ state.info.failCause.assertionFailed = true;
2952
+ await _commandError(state, e, this);
2347
2953
  }
2348
2954
  finally {
2349
- const endTime = Date.now();
2350
- _reportToWorld(world, {
2351
- type: Types.VERIFY_PAGE_PATH,
2352
- text: "Verify page title",
2353
- _text: "Verify the page title contains " + title,
2354
- screenshotId,
2355
- result: error
2356
- ? {
2357
- status: "FAILED",
2358
- startTime,
2359
- endTime,
2360
- message: error?.message,
2361
- }
2362
- : {
2363
- status: "PASSED",
2364
- startTime,
2365
- endTime,
2366
- },
2367
- info: info,
2368
- });
2955
+ await _commandFinally(state, this);
2369
2956
  }
2370
2957
  }
2371
2958
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2407,7 +2994,7 @@ class StableBrowser {
2407
2994
  scroll: false,
2408
2995
  highlight: false,
2409
2996
  type: Types.VERIFY_PAGE_CONTAINS_TEXT,
2410
- text: `Verify the text '${text}' exists in page`,
2997
+ text: `Verify the text '${maskValue(text)}' exists in page`,
2411
2998
  _text: `Verify the text '${text}' exists in page`,
2412
2999
  operation: "verifyTextExistInPage",
2413
3000
  log: "***** verify text " + text + " exists in page *****\n",
@@ -2449,27 +3036,10 @@ class StableBrowser {
2449
3036
  const frame = resultWithElementsFound[0].frame;
2450
3037
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2451
3038
  await this._highlightElements(frame, dataAttribute);
2452
- // if (world && world.screenshot && !world.screenshotPath) {
2453
- // console.log(`Highlighting for verify text is found while running from recorder`);
2454
- // this._highlightElements(frame, dataAttribute).then(async () => {
2455
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2456
- // this._unhighlightElements(frame, dataAttribute)
2457
- // .then(async () => {
2458
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2459
- // })
2460
- // .catch(
2461
- // (e) => {}
2462
- // console.error(e)
2463
- // );
2464
- // });
2465
- // }
2466
3039
  const element = await frame.locator(dataAttribute).first();
2467
- // await new Promise((resolve) => setTimeout(resolve, 100));
2468
- // await this._unhighlightElements(frame, dataAttribute);
2469
3040
  if (element) {
2470
3041
  await this.scrollIfNeeded(element, state.info);
2471
3042
  await element.dispatchEvent("bvt_verify_page_contains_text");
2472
- // await _screenshot(state, this, element);
2473
3043
  }
2474
3044
  }
2475
3045
  await _screenshot(state, this);
@@ -2479,13 +3049,12 @@ class StableBrowser {
2479
3049
  console.error(error);
2480
3050
  }
2481
3051
  }
2482
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2483
3052
  }
2484
3053
  catch (e) {
2485
3054
  await _commandError(state, e, this);
2486
3055
  }
2487
3056
  finally {
2488
- _commandFinally(state, this);
3057
+ await _commandFinally(state, this);
2489
3058
  }
2490
3059
  }
2491
3060
  async waitForTextToDisappear(text, options = {}, world = null) {
@@ -2498,7 +3067,7 @@ class StableBrowser {
2498
3067
  scroll: false,
2499
3068
  highlight: false,
2500
3069
  type: Types.WAIT_FOR_TEXT_TO_DISAPPEAR,
2501
- text: `Verify the text '${text}' does not exist in page`,
3070
+ text: `Verify the text '${maskValue(text)}' does not exist in page`,
2502
3071
  _text: `Verify the text '${text}' does not exist in page`,
2503
3072
  operation: "verifyTextNotExistInPage",
2504
3073
  log: "***** verify text " + text + " does not exist in page *****\n",
@@ -2542,7 +3111,7 @@ class StableBrowser {
2542
3111
  await _commandError(state, e, this);
2543
3112
  }
2544
3113
  finally {
2545
- _commandFinally(state, this);
3114
+ await _commandFinally(state, this);
2546
3115
  }
2547
3116
  }
2548
3117
  async verifyTextRelatedToText(textAnchor, climb, textToVerify, options = {}, world = null) {
@@ -2612,7 +3181,7 @@ class StableBrowser {
2612
3181
  const count = await frame.locator(css).count();
2613
3182
  for (let j = 0; j < count; j++) {
2614
3183
  const continer = await frame.locator(css).nth(j);
2615
- const result = await this._locateElementByText(continer, textToVerify, "*:not(script, style, head)", false, false, true, {});
3184
+ const result = await this._locateElementByText(continer, textToVerify, "*:not(script, style, head)", false, true, true, {});
2616
3185
  if (result.elementCount > 0) {
2617
3186
  const dataAttribute = "[data-blinq-id-" + result.randomToken + "]";
2618
3187
  await this._highlightElements(frame, dataAttribute);
@@ -2653,7 +3222,7 @@ class StableBrowser {
2653
3222
  await _commandError(state, e, this);
2654
3223
  }
2655
3224
  finally {
2656
- _commandFinally(state, this);
3225
+ await _commandFinally(state, this);
2657
3226
  }
2658
3227
  }
2659
3228
  async findRelatedTextInAllFrames(textAnchor, climb, textToVerify, params = {}, options = {}, world = null) {
@@ -2995,8 +3564,51 @@ class StableBrowser {
2995
3564
  });
2996
3565
  }
2997
3566
  }
3567
+ /**
3568
+ * Explicit wait/sleep function that pauses execution for a specified duration
3569
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3570
+ * @param options - Optional configuration object
3571
+ * @param world - Optional world context
3572
+ * @returns Promise that resolves after the specified duration
3573
+ */
3574
+ async sleep(duration = 1000, options = {}, world = null) {
3575
+ const state = {
3576
+ duration,
3577
+ options,
3578
+ world,
3579
+ locate: false,
3580
+ scroll: false,
3581
+ screenshot: false,
3582
+ highlight: false,
3583
+ type: Types.SLEEP,
3584
+ text: `Sleep for ${duration} ms`,
3585
+ _text: `Sleep for ${duration} ms`,
3586
+ operation: "sleep",
3587
+ log: `***** Sleep for ${duration} ms *****\n`,
3588
+ };
3589
+ try {
3590
+ await _preCommand(state, this);
3591
+ if (duration < 0) {
3592
+ throw new Error("Sleep duration cannot be negative");
3593
+ }
3594
+ await new Promise((resolve) => setTimeout(resolve, duration));
3595
+ return state.info;
3596
+ }
3597
+ catch (e) {
3598
+ await _commandError(state, e, this);
3599
+ }
3600
+ finally {
3601
+ await _commandFinally(state, this);
3602
+ }
3603
+ }
2998
3604
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
2999
- return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3605
+ try {
3606
+ return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3607
+ }
3608
+ catch (error) {
3609
+ this.logger.debug(error);
3610
+ throw error;
3611
+ }
3000
3612
  }
3001
3613
  _getLoadTimeout(options) {
3002
3614
  let timeout = 15000;
@@ -3019,6 +3631,7 @@ class StableBrowser {
3019
3631
  }
3020
3632
  async saveStoreState(path = null, world = null) {
3021
3633
  const storageState = await this.page.context().storageState();
3634
+ path = await this._replaceWithLocalData(path, this.world);
3022
3635
  //const testDataFile = _getDataFile(world, this.context, this);
3023
3636
  if (path) {
3024
3637
  // save { storageState: storageState } into the path
@@ -3029,10 +3642,14 @@ class StableBrowser {
3029
3642
  }
3030
3643
  }
3031
3644
  async restoreSaveState(path = null, world = null) {
3645
+ path = await this._replaceWithLocalData(path, this.world);
3032
3646
  await refreshBrowser(this, path, world);
3033
3647
  this.registerEventListeners(this.context);
3034
3648
  registerNetworkEvents(this.world, this, this.context, this.page);
3035
3649
  registerDownloadEvent(this.page, this.world, this.context);
3650
+ if (this.onRestoreSaveState) {
3651
+ this.onRestoreSaveState(path);
3652
+ }
3036
3653
  }
3037
3654
  async waitForPageLoad(options = {}, world = null) {
3038
3655
  let timeout = this._getLoadTimeout(options);
@@ -3115,7 +3732,7 @@ class StableBrowser {
3115
3732
  await _commandError(state, e, this);
3116
3733
  }
3117
3734
  finally {
3118
- _commandFinally(state, this);
3735
+ await _commandFinally(state, this);
3119
3736
  }
3120
3737
  }
3121
3738
  async tableCellOperation(headerText, rowText, options, _params, world = null) {
@@ -3202,7 +3819,7 @@ class StableBrowser {
3202
3819
  await _commandError(state, e, this);
3203
3820
  }
3204
3821
  finally {
3205
- _commandFinally(state, this);
3822
+ await _commandFinally(state, this);
3206
3823
  }
3207
3824
  }
3208
3825
  saveTestDataAsGlobal(options, world) {
@@ -3307,7 +3924,39 @@ class StableBrowser {
3307
3924
  console.log("#-#");
3308
3925
  }
3309
3926
  }
3927
+ async beforeScenario(world, scenario) {
3928
+ this.beforeScenarioCalled = true;
3929
+ if (scenario && scenario.pickle && scenario.pickle.name) {
3930
+ this.scenarioName = scenario.pickle.name;
3931
+ }
3932
+ if (scenario && scenario.gherkinDocument && scenario.gherkinDocument.feature) {
3933
+ this.featureName = scenario.gherkinDocument.feature.name;
3934
+ }
3935
+ if (this.context) {
3936
+ this.context.examplesRow = extractStepExampleParameters(scenario);
3937
+ }
3938
+ if (this.tags === null && scenario && scenario.pickle && scenario.pickle.tags) {
3939
+ this.tags = scenario.pickle.tags.map((tag) => tag.name);
3940
+ // check if @global_test_data tag is present
3941
+ if (this.tags.includes("@global_test_data")) {
3942
+ this.saveTestDataAsGlobal({}, world);
3943
+ }
3944
+ }
3945
+ // update test data based on feature/scenario
3946
+ let envName = null;
3947
+ if (this.context && this.context.environment) {
3948
+ envName = this.context.environment.name;
3949
+ }
3950
+ if (!process.env.TEMP_RUN) {
3951
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
3952
+ }
3953
+ await loadBrunoParams(this.context, this.context.environment.name);
3954
+ }
3955
+ async afterScenario(world, scenario) { }
3310
3956
  async beforeStep(world, step) {
3957
+ if (!this.beforeScenarioCalled) {
3958
+ this.beforeScenario(world, step);
3959
+ }
3311
3960
  if (this.stepIndex === undefined) {
3312
3961
  this.stepIndex = 0;
3313
3962
  }
@@ -3324,30 +3973,22 @@ class StableBrowser {
3324
3973
  else {
3325
3974
  this.stepName = "step " + this.stepIndex;
3326
3975
  }
3327
- if (this.context) {
3328
- this.context.examplesRow = extractStepExampleParameters(step);
3329
- }
3330
3976
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
3331
3977
  if (this.context.browserObject.context) {
3332
3978
  await this.context.browserObject.context.tracing.startChunk({ title: this.stepName });
3333
3979
  }
3334
3980
  }
3335
- if (this.tags === null && step && step.pickle && step.pickle.tags) {
3336
- this.tags = step.pickle.tags.map((tag) => tag.name);
3337
- // check if @global_test_data tag is present
3338
- if (this.tags.includes("@global_test_data")) {
3339
- this.saveTestDataAsGlobal({}, world);
3340
- }
3341
- }
3342
3981
  if (this.initSnapshotTaken === false) {
3343
3982
  this.initSnapshotTaken = true;
3344
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
3983
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3345
3984
  const snapshot = await this.getAriaSnapshot();
3346
3985
  if (snapshot) {
3347
3986
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3348
3987
  }
3349
3988
  }
3350
3989
  }
3990
+ this.context.routeResults = null;
3991
+ await registerBeforeStepRoutes(this.context, this.stepName);
3351
3992
  }
3352
3993
  async getAriaSnapshot() {
3353
3994
  try {
@@ -3363,18 +4004,68 @@ class StableBrowser {
3363
4004
  const content = [`- path: ${path}`, `- title: ${title}`];
3364
4005
  const timeout = this.configuration.ariaSnapshotTimeout ? this.configuration.ariaSnapshotTimeout : 3000;
3365
4006
  for (let i = 0; i < frames.length; i++) {
3366
- content.push(`- frame: ${i}`);
3367
4007
  const frame = frames[i];
3368
- const snapshot = await frame.locator("body").ariaSnapshot({ timeout });
3369
- content.push(snapshot);
4008
+ try {
4009
+ // Ensure frame is attached and has body
4010
+ const body = frame.locator("body");
4011
+ await body.waitFor({ timeout: 200 }); // wait explicitly
4012
+ const snapshot = await body.ariaSnapshot({ timeout });
4013
+ content.push(`- frame: ${i}`);
4014
+ content.push(snapshot);
4015
+ }
4016
+ catch (innerErr) { }
3370
4017
  }
3371
4018
  return content.join("\n");
3372
4019
  }
3373
4020
  catch (e) {
3374
- console.error(e);
4021
+ console.log("Error in getAriaSnapshot");
4022
+ //console.debug(e);
3375
4023
  }
3376
4024
  return null;
3377
4025
  }
4026
+ /**
4027
+ * Sends command with custom payload to report.
4028
+ * @param commandText - Title of the command to be shown in the report.
4029
+ * @param commandStatus - Status of the command (e.g. "PASSED", "FAILED").
4030
+ * @param content - Content of the command to be shown in the report.
4031
+ * @param options - Options for the command. Example: { type: "json", screenshot: true }
4032
+ * @param world - Optional world context.
4033
+ * @public
4034
+ */
4035
+ async addCommandToReport(commandText, commandStatus, content, options = {}, world = null) {
4036
+ const state = {
4037
+ options,
4038
+ world,
4039
+ locate: false,
4040
+ scroll: false,
4041
+ screenshot: options.screenshot ?? false,
4042
+ highlight: options.highlight ?? false,
4043
+ type: Types.REPORT_COMMAND,
4044
+ text: commandText,
4045
+ _text: commandText,
4046
+ operation: "report_command",
4047
+ log: "***** " + commandText + " *****\n",
4048
+ };
4049
+ try {
4050
+ await _preCommand(state, this);
4051
+ const payload = {
4052
+ type: options.type ?? "text",
4053
+ content: content,
4054
+ screenshotId: null,
4055
+ };
4056
+ state.payload = payload;
4057
+ if (commandStatus === "FAILED") {
4058
+ state.throwError = true;
4059
+ throw new Error("Command failed");
4060
+ }
4061
+ }
4062
+ catch (e) {
4063
+ await _commandError(state, e, this);
4064
+ }
4065
+ finally {
4066
+ await _commandFinally(state, this);
4067
+ }
4068
+ }
3378
4069
  async afterStep(world, step) {
3379
4070
  this.stepName = null;
3380
4071
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3382,10 +4073,12 @@ class StableBrowser {
3382
4073
  await this.context.browserObject.context.tracing.stopChunk({
3383
4074
  path: path.join(this.context.browserObject.traceFolder, `trace-${this.stepIndex}.zip`),
3384
4075
  });
3385
- await world.attach(JSON.stringify({
3386
- type: "trace",
3387
- traceFilePath: `trace-${this.stepIndex}.zip`,
3388
- }), "application/json+trace");
4076
+ if (world && world.attach) {
4077
+ await world.attach(JSON.stringify({
4078
+ type: "trace",
4079
+ traceFilePath: `trace-${this.stepIndex}.zip`,
4080
+ }), "application/json+trace");
4081
+ }
3389
4082
  // console.log("trace file created", `trace-${this.stepIndex}.zip`);
3390
4083
  }
3391
4084
  }
@@ -3399,6 +4092,30 @@ class StableBrowser {
3399
4092
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3400
4093
  }
3401
4094
  }
4095
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4096
+ if (!process.env.TEMP_RUN) {
4097
+ const state = {
4098
+ world,
4099
+ locate: false,
4100
+ scroll: false,
4101
+ screenshot: true,
4102
+ highlight: true,
4103
+ type: Types.STEP_COMPLETE,
4104
+ text: "end of scenario",
4105
+ _text: "end of scenario",
4106
+ operation: "step_complete",
4107
+ log: "***** " + "end of scenario" + " *****\n",
4108
+ };
4109
+ try {
4110
+ await _preCommand(state, this);
4111
+ }
4112
+ catch (e) {
4113
+ await _commandError(state, e, this);
4114
+ }
4115
+ finally {
4116
+ await _commandFinally(state, this);
4117
+ }
4118
+ }
3402
4119
  }
3403
4120
  }
3404
4121
  function createTimedPromise(promise, label) {