automation_model 1.0.657-dev → 1.0.657-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 +249 -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 +58 -24
  46. package/lib/stable_browser.js +904 -180
  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,27 @@ 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
- NAVIGATE: "navigate",
32
+ NAVIGATE: "navigate", ///
29
33
  FILL: "fill_element",
30
- EXECUTE: "execute_page_method",
31
- OPEN: "open_environment",
34
+ EXECUTE: "execute_page_method", //
35
+ OPEN: "open_environment", //
32
36
  COMPLETE: "step_complete",
33
37
  ASK: "information_needed",
34
- GET_PAGE_STATUS: "get_page_status",
35
- CLICK_ROW_ACTION: "click_row_action",
38
+ GET_PAGE_STATUS: "get_page_status", ///
39
+ CLICK_ROW_ACTION: "click_row_action", //
36
40
  VERIFY_ELEMENT_CONTAINS_TEXT: "verify_element_contains_text",
37
41
  VERIFY_PAGE_CONTAINS_TEXT: "verify_page_contains_text",
38
42
  VERIFY_PAGE_CONTAINS_NO_TEXT: "verify_page_contains_no_text",
39
43
  ANALYZE_TABLE: "analyze_table",
40
- SELECT: "select_combobox",
44
+ SELECT: "select_combobox", //
41
45
  VERIFY_PAGE_PATH: "verify_page_path",
46
+ VERIFY_PAGE_TITLE: "verify_page_title",
42
47
  TYPE_PRESS: "type_press",
43
48
  PRESS: "press_key",
44
49
  HOVER: "hover_element",
@@ -55,6 +60,13 @@ export const Types = {
55
60
  WAIT_FOR_TEXT_TO_DISAPPEAR: "wait_for_text_to_disappear",
56
61
  VERIFY_ATTRIBUTE: "verify_element_attribute",
57
62
  VERIFY_TEXT_WITH_RELATION: "verify_text_with_relation",
63
+ BRUNO: "bruno",
64
+ VERIFY_FILE_EXISTS: "verify_file_exists",
65
+ SET_INPUT_FILES: "set_input_files",
66
+ SNAPSHOT_VALIDATION: "snapshot_validation",
67
+ REPORT_COMMAND: "report_command",
68
+ STEP_COMPLETE: "step_complete",
69
+ SLEEP: "sleep",
58
70
  };
59
71
  export const apps = {};
60
72
  const formatElementName = (elementName) => {
@@ -66,6 +78,7 @@ class StableBrowser {
66
78
  logger;
67
79
  context;
68
80
  world;
81
+ fastMode;
69
82
  project_path = null;
70
83
  webLogFile = null;
71
84
  networkLogger = null;
@@ -74,12 +87,13 @@ class StableBrowser {
74
87
  tags = null;
75
88
  isRecording = false;
76
89
  initSnapshotTaken = false;
77
- constructor(browser, page, logger = null, context = null, world = null) {
90
+ constructor(browser, page, logger = null, context = null, world = null, fastMode = false) {
78
91
  this.browser = browser;
79
92
  this.page = page;
80
93
  this.logger = logger;
81
94
  this.context = context;
82
95
  this.world = world;
96
+ this.fastMode = fastMode;
83
97
  if (!this.logger) {
84
98
  this.logger = console;
85
99
  }
@@ -108,6 +122,18 @@ class StableBrowser {
108
122
  context.pages = [this.page];
109
123
  const logFolder = path.join(this.project_path, "logs", "web");
110
124
  this.world = world;
125
+ if (this.configuration && this.configuration.fastMode === true) {
126
+ this.fastMode = true;
127
+ }
128
+ if (process.env.FAST_MODE === "true") {
129
+ this.fastMode = true;
130
+ }
131
+ if (process.env.FAST_MODE === "false") {
132
+ this.fastMode = false;
133
+ }
134
+ if (this.context) {
135
+ this.context.fastMode = this.fastMode;
136
+ }
111
137
  this.registerEventListeners(this.context);
112
138
  registerNetworkEvents(this.world, this, this.context, this.page);
113
139
  registerDownloadEvent(this.page, this.world, this.context);
@@ -118,6 +144,9 @@ class StableBrowser {
118
144
  if (!context.pageLoading) {
119
145
  context.pageLoading = { status: false };
120
146
  }
147
+ if (this.configuration && this.configuration.acceptDialog && this.page) {
148
+ this.page.on("dialog", (dialog) => dialog.accept());
149
+ }
121
150
  context.playContext.on("page", async function (page) {
122
151
  if (this.configuration && this.configuration.closePopups === true) {
123
152
  console.log("close unexpected popups");
@@ -126,6 +155,14 @@ class StableBrowser {
126
155
  }
127
156
  context.pageLoading.status = true;
128
157
  this.page = page;
158
+ try {
159
+ if (this.configuration && this.configuration.acceptDialog) {
160
+ await page.on("dialog", (dialog) => dialog.accept());
161
+ }
162
+ }
163
+ catch (error) {
164
+ console.error("Error on dialog accept registration", error);
165
+ }
129
166
  context.page = page;
130
167
  context.pages.push(page);
131
168
  registerNetworkEvents(this.world, this, context, this.page);
@@ -177,9 +214,35 @@ class StableBrowser {
177
214
  if (newContextCreated) {
178
215
  this.registerEventListeners(this.context);
179
216
  await this.goto(this.context.environment.baseUrl);
180
- await this.waitForPageLoad();
217
+ if (!this.fastMode) {
218
+ await this.waitForPageLoad();
219
+ }
181
220
  }
182
221
  }
222
+ async switchTab(tabTitleOrIndex) {
223
+ // first check if the tabNameOrIndex is a number
224
+ let index = parseInt(tabTitleOrIndex);
225
+ if (!isNaN(index)) {
226
+ if (index >= 0 && index < this.context.pages.length) {
227
+ this.page = this.context.pages[index];
228
+ this.context.page = this.page;
229
+ await this.page.bringToFront();
230
+ return;
231
+ }
232
+ }
233
+ // if the tabNameOrIndex is a string, find the tab by name
234
+ for (let i = 0; i < this.context.pages.length; i++) {
235
+ let page = this.context.pages[i];
236
+ let title = await page.title();
237
+ if (title.includes(tabTitleOrIndex)) {
238
+ this.page = page;
239
+ this.context.page = this.page;
240
+ await this.page.bringToFront();
241
+ return;
242
+ }
243
+ }
244
+ throw new Error("Tab not found: " + tabTitleOrIndex);
245
+ }
183
246
  registerConsoleLogListener(page, context) {
184
247
  if (!this.context.webLogger) {
185
248
  this.context.webLogger = [];
@@ -247,6 +310,7 @@ class StableBrowser {
247
310
  if (!url) {
248
311
  throw new Error("url is null, verify that the environment file is correct");
249
312
  }
313
+ url = await this._replaceWithLocalData(url, this.world);
250
314
  if (!url.startsWith("http")) {
251
315
  url = "https://" + url;
252
316
  }
@@ -275,7 +339,7 @@ class StableBrowser {
275
339
  _commandError(state, error, this);
276
340
  }
277
341
  finally {
278
- _commandFinally(state, this);
342
+ await _commandFinally(state, this);
279
343
  }
280
344
  }
281
345
  async _getLocator(locator, scope, _params) {
@@ -391,7 +455,7 @@ class StableBrowser {
391
455
  }
392
456
  return { elementCount: tagCount, randomToken };
393
457
  }
394
- async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null) {
458
+ async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null, logErrors = false) {
395
459
  if (!info) {
396
460
  info = {};
397
461
  }
@@ -458,7 +522,7 @@ class StableBrowser {
458
522
  }
459
523
  return;
460
524
  }
461
- if (info.locatorLog && count === 0) {
525
+ if (info.locatorLog && count === 0 && logErrors) {
462
526
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "NOT_FOUND");
463
527
  }
464
528
  for (let j = 0; j < count; j++) {
@@ -473,7 +537,7 @@ class StableBrowser {
473
537
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "FOUND");
474
538
  }
475
539
  }
476
- else {
540
+ else if (logErrors) {
477
541
  info.failCause.visible = visible;
478
542
  info.failCause.enabled = enabled;
479
543
  if (!info.printMessages) {
@@ -565,7 +629,7 @@ class StableBrowser {
565
629
  let element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
566
630
  if (!element.rerun) {
567
631
  const randomToken = Math.random().toString(36).substring(7);
568
- element.evaluate((el, randomToken) => {
632
+ await element.evaluate((el, randomToken) => {
569
633
  el.setAttribute("data-blinq-id-" + randomToken, "");
570
634
  }, randomToken);
571
635
  // if (element._frame) {
@@ -579,7 +643,7 @@ class StableBrowser {
579
643
  if (frameSelectorIndex !== -1) {
580
644
  // remove everything after the >> internal:control=enter-frame
581
645
  const frameSelector = element._selector.substring(0, frameSelectorIndex);
582
- prefixSelector = frameSelector + " >> internal:control=enter-frame";
646
+ prefixSelector = frameSelector + " >> internal:control=enter-frame >>";
583
647
  }
584
648
  // if (element?._frame?._selector) {
585
649
  // prefixSelector = element._frame._selector + " >> " + prefixSelector;
@@ -814,7 +878,7 @@ class StableBrowser {
814
878
  }
815
879
  throw new Error("failed to locate first element no elements found, " + info.log);
816
880
  }
817
- async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name) {
881
+ async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name, logErrors = false) {
818
882
  let foundElements = [];
819
883
  const result = {
820
884
  foundElements: foundElements,
@@ -833,7 +897,9 @@ class StableBrowser {
833
897
  await this._collectLocatorInformation(locatorsGroup, i, this.page, foundLocators, _params, info, visibleOnly, allowDisabled, element_name);
834
898
  }
835
899
  catch (e) {
836
- this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
900
+ if (logErrors) {
901
+ this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
902
+ }
837
903
  }
838
904
  }
839
905
  if (foundLocators.length === 1) {
@@ -874,7 +940,7 @@ class StableBrowser {
874
940
  });
875
941
  result.locatorIndex = i;
876
942
  }
877
- else {
943
+ else if (logErrors) {
878
944
  info.failCause.foundMultiple = true;
879
945
  if (info.locatorLog) {
880
946
  info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
@@ -926,7 +992,7 @@ class StableBrowser {
926
992
  await _commandError(state, "timeout looking for " + elementDescription, this);
927
993
  }
928
994
  finally {
929
- _commandFinally(state, this);
995
+ await _commandFinally(state, this);
930
996
  }
931
997
  }
932
998
  }
@@ -975,7 +1041,7 @@ class StableBrowser {
975
1041
  await _commandError(state, "timeout looking for " + elementDescription, this);
976
1042
  }
977
1043
  finally {
978
- _commandFinally(state, this);
1044
+ await _commandFinally(state, this);
979
1045
  }
980
1046
  }
981
1047
  }
@@ -997,14 +1063,16 @@ class StableBrowser {
997
1063
  try {
998
1064
  await _preCommand(state, this);
999
1065
  await performAction("click", state.element, options, this, state, _params);
1000
- await this.waitForPageLoad();
1066
+ if (!this.fastMode) {
1067
+ await this.waitForPageLoad();
1068
+ }
1001
1069
  return state.info;
1002
1070
  }
1003
1071
  catch (e) {
1004
1072
  await _commandError(state, e, this);
1005
1073
  }
1006
1074
  finally {
1007
- _commandFinally(state, this);
1075
+ await _commandFinally(state, this);
1008
1076
  }
1009
1077
  }
1010
1078
  async waitForElement(selectors, _params, options = {}, world = null) {
@@ -1035,7 +1103,7 @@ class StableBrowser {
1035
1103
  // await _commandError(state, e, this);
1036
1104
  }
1037
1105
  finally {
1038
- _commandFinally(state, this);
1106
+ await _commandFinally(state, this);
1039
1107
  }
1040
1108
  return found;
1041
1109
  }
@@ -1060,7 +1128,7 @@ class StableBrowser {
1060
1128
  // if (world && world.screenshot && !world.screenshotPath) {
1061
1129
  // console.log(`Highlighting while running from recorder`);
1062
1130
  await this._highlightElements(state.element);
1063
- await state.element.setChecked(checked);
1131
+ await state.element.setChecked(checked, { timeout: 2000 });
1064
1132
  await new Promise((resolve) => setTimeout(resolve, 1000));
1065
1133
  // await this._unHighlightElements(element);
1066
1134
  // }
@@ -1072,11 +1140,28 @@ class StableBrowser {
1072
1140
  this.logger.info("element did not change its state, ignoring...");
1073
1141
  }
1074
1142
  else {
1143
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1075
1144
  //await this.closeUnexpectedPopups();
1076
1145
  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));
1146
+ state.element_found = false;
1147
+ try {
1148
+ state.element = await this._locate(selectors, state.info, _params, 100);
1149
+ state.element_found = true;
1150
+ // check the check state
1151
+ }
1152
+ catch (error) {
1153
+ // element dismissed
1154
+ }
1155
+ if (state.element_found) {
1156
+ const isChecked = await state.element.isChecked();
1157
+ if (isChecked !== checked) {
1158
+ // perform click
1159
+ await state.element.click({ timeout: 2000, force: true });
1160
+ }
1161
+ else {
1162
+ this.logger.info(`Element ${selectors.element_name} is already in the desired state (${checked})`);
1163
+ }
1164
+ }
1080
1165
  }
1081
1166
  }
1082
1167
  await this.waitForPageLoad();
@@ -1086,7 +1171,7 @@ class StableBrowser {
1086
1171
  await _commandError(state, e, this);
1087
1172
  }
1088
1173
  finally {
1089
- _commandFinally(state, this);
1174
+ await _commandFinally(state, this);
1090
1175
  }
1091
1176
  }
1092
1177
  async hover(selectors, _params, options = {}, world = null) {
@@ -1112,7 +1197,7 @@ class StableBrowser {
1112
1197
  await _commandError(state, e, this);
1113
1198
  }
1114
1199
  finally {
1115
- _commandFinally(state, this);
1200
+ await _commandFinally(state, this);
1116
1201
  }
1117
1202
  }
1118
1203
  async selectOption(selectors, values, _params = null, options = {}, world = null) {
@@ -1148,7 +1233,7 @@ class StableBrowser {
1148
1233
  await _commandError(state, e, this);
1149
1234
  }
1150
1235
  finally {
1151
- _commandFinally(state, this);
1236
+ await _commandFinally(state, this);
1152
1237
  }
1153
1238
  }
1154
1239
  async type(_value, _params = null, options = {}, world = null) {
@@ -1194,7 +1279,7 @@ class StableBrowser {
1194
1279
  await _commandError(state, e, this);
1195
1280
  }
1196
1281
  finally {
1197
- _commandFinally(state, this);
1282
+ await _commandFinally(state, this);
1198
1283
  }
1199
1284
  }
1200
1285
  async setInputValue(selectors, value, _params = null, options = {}, world = null) {
@@ -1230,7 +1315,7 @@ class StableBrowser {
1230
1315
  await _commandError(state, e, this);
1231
1316
  }
1232
1317
  finally {
1233
- _commandFinally(state, this);
1318
+ await _commandFinally(state, this);
1234
1319
  }
1235
1320
  }
1236
1321
  async setDateTime(selectors, value, format = null, enter = false, _params = null, options = {}, world = null) {
@@ -1299,7 +1384,7 @@ class StableBrowser {
1299
1384
  await _commandError(state, e, this);
1300
1385
  }
1301
1386
  finally {
1302
- _commandFinally(state, this);
1387
+ await _commandFinally(state, this);
1303
1388
  }
1304
1389
  }
1305
1390
  async clickType(selectors, _value, enter = false, _params = null, options = {}, world = null) {
@@ -1372,7 +1457,9 @@ class StableBrowser {
1372
1457
  await new Promise((resolve) => setTimeout(resolve, 500));
1373
1458
  }
1374
1459
  }
1460
+ //if (!this.fastMode) {
1375
1461
  await _screenshot(state, this);
1462
+ //}
1376
1463
  if (enter === true) {
1377
1464
  await new Promise((resolve) => setTimeout(resolve, 2000));
1378
1465
  await this.page.keyboard.press("Enter");
@@ -1399,7 +1486,7 @@ class StableBrowser {
1399
1486
  await _commandError(state, e, this);
1400
1487
  }
1401
1488
  finally {
1402
- _commandFinally(state, this);
1489
+ await _commandFinally(state, this);
1403
1490
  }
1404
1491
  }
1405
1492
  async fill(selectors, value, enter = false, _params = null, options = {}, world = null) {
@@ -1429,7 +1516,42 @@ class StableBrowser {
1429
1516
  await _commandError(state, e, this);
1430
1517
  }
1431
1518
  finally {
1432
- _commandFinally(state, this);
1519
+ await _commandFinally(state, this);
1520
+ }
1521
+ }
1522
+ async setInputFiles(selectors, files, _params = null, options = {}, world = null) {
1523
+ const state = {
1524
+ selectors,
1525
+ _params,
1526
+ files,
1527
+ value: '"' + files.join('", "') + '"',
1528
+ options,
1529
+ world,
1530
+ type: Types.SET_INPUT_FILES,
1531
+ text: `Set input files`,
1532
+ _text: `Set input files on ${selectors.element_name}`,
1533
+ operation: "setInputFiles",
1534
+ log: "***** set input files " + selectors.element_name + " *****\n",
1535
+ };
1536
+ const uploadsFolder = this.configuration.uploadsFolder ?? "data/uploads";
1537
+ try {
1538
+ await _preCommand(state, this);
1539
+ for (let i = 0; i < files.length; i++) {
1540
+ const file = files[i];
1541
+ const filePath = path.join(uploadsFolder, file);
1542
+ if (!fs.existsSync(filePath)) {
1543
+ throw new Error(`File not found: ${filePath}`);
1544
+ }
1545
+ state.files[i] = filePath;
1546
+ }
1547
+ await state.element.setInputFiles(files);
1548
+ return state.info;
1549
+ }
1550
+ catch (e) {
1551
+ await _commandError(state, e, this);
1552
+ }
1553
+ finally {
1554
+ await _commandFinally(state, this);
1433
1555
  }
1434
1556
  }
1435
1557
  async getText(selectors, _params = null, options = {}, info = {}, world = null) {
@@ -1545,7 +1667,7 @@ class StableBrowser {
1545
1667
  await _commandError(state, e, this);
1546
1668
  }
1547
1669
  finally {
1548
- _commandFinally(state, this);
1670
+ await _commandFinally(state, this);
1549
1671
  }
1550
1672
  }
1551
1673
  async containsText(selectors, text, climb, _params = null, options = {}, world = null) {
@@ -1622,7 +1744,84 @@ class StableBrowser {
1622
1744
  throw e;
1623
1745
  }
1624
1746
  finally {
1625
- _commandFinally(state, this);
1747
+ await _commandFinally(state, this);
1748
+ }
1749
+ }
1750
+ async snapshotValidation(frameSelectors, referanceSnapshot, _params = null, options = {}, world = null) {
1751
+ const timeout = this._getFindElementTimeout(options);
1752
+ const startTime = Date.now();
1753
+ const state = {
1754
+ _params,
1755
+ value: referanceSnapshot,
1756
+ options,
1757
+ world,
1758
+ locate: false,
1759
+ scroll: false,
1760
+ screenshot: true,
1761
+ highlight: false,
1762
+ type: Types.SNAPSHOT_VALIDATION,
1763
+ text: `verify snapshot: ${referanceSnapshot}`,
1764
+ operation: "snapshotValidation",
1765
+ log: "***** verify snapshot *****\n",
1766
+ };
1767
+ if (!referanceSnapshot) {
1768
+ throw new Error("referanceSnapshot is null");
1769
+ }
1770
+ let text = null;
1771
+ if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"))) {
1772
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"), "utf8");
1773
+ }
1774
+ else if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"))) {
1775
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"), "utf8");
1776
+ }
1777
+ else if (referanceSnapshot.startsWith("yaml:")) {
1778
+ text = referanceSnapshot.substring(5);
1779
+ }
1780
+ else {
1781
+ throw new Error("referenceSnapshot file not found: " + referanceSnapshot);
1782
+ }
1783
+ state.text = text;
1784
+ const newValue = await this._replaceWithLocalData(text, world);
1785
+ await _preCommand(state, this);
1786
+ let foundObj = null;
1787
+ try {
1788
+ let matchResult = null;
1789
+ while (Date.now() - startTime < timeout) {
1790
+ try {
1791
+ let scope = null;
1792
+ if (!frameSelectors) {
1793
+ scope = this.page;
1794
+ }
1795
+ else {
1796
+ scope = await this._findFrameScope(frameSelectors, timeout, state.info);
1797
+ }
1798
+ const snapshot = await scope.locator("body").ariaSnapshot({ timeout });
1799
+ matchResult = snapshotValidation(snapshot, newValue, referanceSnapshot);
1800
+ if (matchResult.errorLine !== -1) {
1801
+ throw new Error("Snapshot validation failed at line " + matchResult.errorLineText);
1802
+ }
1803
+ // highlight and screenshot
1804
+ try {
1805
+ await await highlightSnapshot(newValue, scope);
1806
+ await _screenshot(state, this);
1807
+ }
1808
+ catch (e) { }
1809
+ return state.info;
1810
+ }
1811
+ catch (e) {
1812
+ // Log error but continue retrying until timeout is reached
1813
+ //this.logger.warn("Retrying snapshot validation due to: " + e.message);
1814
+ }
1815
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 1 second before retrying
1816
+ }
1817
+ throw new Error("No snapshot match " + matchResult?.errorLineText);
1818
+ }
1819
+ catch (e) {
1820
+ await _commandError(state, e, this);
1821
+ throw e;
1822
+ }
1823
+ finally {
1824
+ await _commandFinally(state, this);
1626
1825
  }
1627
1826
  }
1628
1827
  async waitForUserInput(message, world = null) {
@@ -1765,12 +1964,7 @@ class StableBrowser {
1765
1964
  }
1766
1965
  }
1767
1966
  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;
1967
+ return _getTestData(world, this.context, this);
1774
1968
  }
1775
1969
  async _screenShot(options = {}, world = null, info = null) {
1776
1970
  // collect url/path/title
@@ -1921,7 +2115,7 @@ class StableBrowser {
1921
2115
  await _commandError(state, e, this);
1922
2116
  }
1923
2117
  finally {
1924
- _commandFinally(state, this);
2118
+ await _commandFinally(state, this);
1925
2119
  }
1926
2120
  }
1927
2121
  async extractAttribute(selectors, attribute, variable, _params = null, options = {}, world = null) {
@@ -1952,10 +2146,31 @@ class StableBrowser {
1952
2146
  case "value":
1953
2147
  state.value = await state.element.inputValue();
1954
2148
  break;
2149
+ case "text":
2150
+ state.value = await state.element.textContent();
2151
+ break;
1955
2152
  default:
1956
2153
  state.value = await state.element.getAttribute(attribute);
1957
2154
  break;
1958
2155
  }
2156
+ if (options !== null) {
2157
+ if (options.regex && options.regex !== "") {
2158
+ // Construct a regex pattern from the provided string
2159
+ const regex = options.regex.slice(1, -1);
2160
+ const regexPattern = new RegExp(regex, "g");
2161
+ const matches = state.value.match(regexPattern);
2162
+ if (matches) {
2163
+ let newValue = "";
2164
+ for (const match of matches) {
2165
+ newValue += match;
2166
+ }
2167
+ state.value = newValue;
2168
+ }
2169
+ }
2170
+ if (options.trimSpaces && options.trimSpaces === true) {
2171
+ state.value = state.value.trim();
2172
+ }
2173
+ }
1959
2174
  state.info.value = state.value;
1960
2175
  this.setTestData({ [variable]: state.value }, world);
1961
2176
  this.logger.info("set test data: " + variable + "=" + state.value);
@@ -1966,7 +2181,78 @@ class StableBrowser {
1966
2181
  await _commandError(state, e, this);
1967
2182
  }
1968
2183
  finally {
1969
- _commandFinally(state, this);
2184
+ await _commandFinally(state, this);
2185
+ }
2186
+ }
2187
+ async extractProperty(selectors, property, variable, _params = null, options = {}, world = null) {
2188
+ const state = {
2189
+ selectors,
2190
+ _params,
2191
+ property,
2192
+ variable,
2193
+ options,
2194
+ world,
2195
+ type: Types.EXTRACT_PROPERTY,
2196
+ text: `Extract property from element`,
2197
+ _text: `Extract property ${property} from ${selectors.element_name}`,
2198
+ operation: "extractProperty",
2199
+ log: "***** extract property " + property + " from " + selectors.element_name + " *****\n",
2200
+ allowDisabled: true,
2201
+ };
2202
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2203
+ try {
2204
+ await _preCommand(state, this);
2205
+ switch (property) {
2206
+ case "inner_text":
2207
+ state.value = await state.element.innerText();
2208
+ break;
2209
+ case "href":
2210
+ state.value = await state.element.getAttribute("href");
2211
+ break;
2212
+ case "value":
2213
+ state.value = await state.element.inputValue();
2214
+ break;
2215
+ case "text":
2216
+ state.value = await state.element.textContent();
2217
+ break;
2218
+ default:
2219
+ if (property.startsWith("dataset.")) {
2220
+ const dataAttribute = property.substring(8);
2221
+ state.value = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2222
+ }
2223
+ else {
2224
+ state.value = String(await state.element.evaluate((element, prop) => element[prop], property));
2225
+ }
2226
+ }
2227
+ if (options !== null) {
2228
+ if (options.regex && options.regex !== "") {
2229
+ // Construct a regex pattern from the provided string
2230
+ const regex = options.regex.slice(1, -1);
2231
+ const regexPattern = new RegExp(regex, "g");
2232
+ const matches = state.value.match(regexPattern);
2233
+ if (matches) {
2234
+ let newValue = "";
2235
+ for (const match of matches) {
2236
+ newValue += match;
2237
+ }
2238
+ state.value = newValue;
2239
+ }
2240
+ }
2241
+ if (options.trimSpaces && options.trimSpaces === true) {
2242
+ state.value = state.value.trim();
2243
+ }
2244
+ }
2245
+ state.info.value = state.value;
2246
+ this.setTestData({ [variable]: state.value }, world);
2247
+ this.logger.info("set test data: " + variable + "=" + state.value);
2248
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2249
+ return state.info;
2250
+ }
2251
+ catch (e) {
2252
+ await _commandError(state, e, this);
2253
+ }
2254
+ finally {
2255
+ await _commandFinally(state, this);
1970
2256
  }
1971
2257
  }
1972
2258
  async verifyAttribute(selectors, attribute, value, _params = null, options = {}, world = null) {
@@ -1991,12 +2277,15 @@ class StableBrowser {
1991
2277
  let expectedValue;
1992
2278
  try {
1993
2279
  await _preCommand(state, this);
1994
- expectedValue = state.value;
2280
+ expectedValue = await replaceWithLocalTestData(state.value, world);
1995
2281
  state.info.expectedValue = expectedValue;
1996
2282
  switch (attribute) {
1997
2283
  case "innerText":
1998
2284
  val = String(await state.element.innerText());
1999
2285
  break;
2286
+ case "text":
2287
+ val = String(await state.element.textContent());
2288
+ break;
2000
2289
  case "value":
2001
2290
  val = String(await state.element.inputValue());
2002
2291
  break;
@@ -2018,17 +2307,42 @@ class StableBrowser {
2018
2307
  let regex;
2019
2308
  if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2020
2309
  const patternBody = expectedValue.slice(1, -1);
2021
- regex = new RegExp(patternBody, "g");
2310
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2311
+ regex = new RegExp(processedPattern, "gs");
2312
+ state.info.regex = true;
2022
2313
  }
2023
2314
  else {
2024
2315
  const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2025
2316
  regex = new RegExp(escapedPattern, "g");
2026
2317
  }
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);
2318
+ if (attribute === "innerText") {
2319
+ if (state.info.regex) {
2320
+ if (!regex.test(val)) {
2321
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2322
+ state.info.failCause.assertionFailed = true;
2323
+ state.info.failCause.lastError = errorMessage;
2324
+ throw new Error(errorMessage);
2325
+ }
2326
+ }
2327
+ else {
2328
+ const valLines = val.split("\n");
2329
+ const expectedLines = expectedValue.split("\n");
2330
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine === expectedLine));
2331
+ if (!isPart) {
2332
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2333
+ state.info.failCause.assertionFailed = true;
2334
+ state.info.failCause.lastError = errorMessage;
2335
+ throw new Error(errorMessage);
2336
+ }
2337
+ }
2338
+ }
2339
+ else {
2340
+ if (!val.match(regex)) {
2341
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2342
+ state.info.failCause.assertionFailed = true;
2343
+ state.info.failCause.lastError = errorMessage;
2344
+ throw new Error(errorMessage);
2345
+ }
2032
2346
  }
2033
2347
  return state.info;
2034
2348
  }
@@ -2036,7 +2350,128 @@ class StableBrowser {
2036
2350
  await _commandError(state, e, this);
2037
2351
  }
2038
2352
  finally {
2039
- _commandFinally(state, this);
2353
+ await _commandFinally(state, this);
2354
+ }
2355
+ }
2356
+ async verifyProperty(selectors, property, value, _params = null, options = {}, world = null) {
2357
+ const state = {
2358
+ selectors,
2359
+ _params,
2360
+ property,
2361
+ value,
2362
+ options,
2363
+ world,
2364
+ type: Types.VERIFY_PROPERTY,
2365
+ highlight: true,
2366
+ screenshot: true,
2367
+ text: `Verify element property`,
2368
+ _text: `Verify property ${property} from ${selectors.element_name} is ${value}`,
2369
+ operation: "verifyProperty",
2370
+ log: "***** verify property " + property + " from " + selectors.element_name + " *****\n",
2371
+ allowDisabled: true,
2372
+ };
2373
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2374
+ let val;
2375
+ let expectedValue;
2376
+ try {
2377
+ await _preCommand(state, this);
2378
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2379
+ state.info.expectedValue = expectedValue;
2380
+ switch (property) {
2381
+ case "innerText":
2382
+ val = String(await state.element.innerText());
2383
+ break;
2384
+ case "text":
2385
+ val = String(await state.element.textContent());
2386
+ break;
2387
+ case "value":
2388
+ val = String(await state.element.inputValue());
2389
+ break;
2390
+ case "checked":
2391
+ val = String(await state.element.isChecked());
2392
+ break;
2393
+ case "disabled":
2394
+ val = String(await state.element.isDisabled());
2395
+ break;
2396
+ case "readOnly":
2397
+ const isEditable = await state.element.isEditable();
2398
+ val = String(!isEditable);
2399
+ break;
2400
+ case "innerHTML":
2401
+ val = String(await state.element.innerHTML());
2402
+ break;
2403
+ case "outerHTML":
2404
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2405
+ break;
2406
+ default:
2407
+ if (property.startsWith("dataset.")) {
2408
+ const dataAttribute = property.substring(8);
2409
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2410
+ }
2411
+ else {
2412
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2413
+ }
2414
+ }
2415
+ // Helper function to remove all style="" attributes
2416
+ const removeStyleAttributes = (htmlString) => {
2417
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2418
+ };
2419
+ // Remove style attributes for innerHTML and outerHTML properties
2420
+ if (property === "innerHTML" || property === "outerHTML") {
2421
+ val = removeStyleAttributes(val);
2422
+ expectedValue = removeStyleAttributes(expectedValue);
2423
+ }
2424
+ state.info.value = val;
2425
+ let regex;
2426
+ if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2427
+ const patternBody = expectedValue.slice(1, -1);
2428
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2429
+ regex = new RegExp(processedPattern, "gs");
2430
+ state.info.regex = true;
2431
+ }
2432
+ else {
2433
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2434
+ regex = new RegExp(escapedPattern, "g");
2435
+ }
2436
+ if (property === "innerText") {
2437
+ if (state.info.regex) {
2438
+ if (!regex.test(val)) {
2439
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2440
+ state.info.failCause.assertionFailed = true;
2441
+ state.info.failCause.lastError = errorMessage;
2442
+ throw new Error(errorMessage);
2443
+ }
2444
+ }
2445
+ else {
2446
+ // Fix: Replace escaped newlines with actual newlines before splitting
2447
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2448
+ const valLines = val.split("\n");
2449
+ const expectedLines = normalizedExpectedValue.split("\n");
2450
+ // Check if all expected lines are present in the actual lines
2451
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2452
+ if (!isPart) {
2453
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2454
+ state.info.failCause.assertionFailed = true;
2455
+ state.info.failCause.lastError = errorMessage;
2456
+ throw new Error(errorMessage);
2457
+ }
2458
+ }
2459
+ }
2460
+ else {
2461
+ if (!val.match(regex)) {
2462
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2463
+ state.info.failCause.assertionFailed = true;
2464
+ state.info.failCause.lastError = errorMessage;
2465
+ throw new Error(errorMessage);
2466
+ }
2467
+ }
2468
+ return state.info;
2469
+ }
2470
+ catch (e) {
2471
+ await _commandError(state, e, this);
2472
+ }
2473
+ finally {
2474
+ await _commandFinally(state, this);
2040
2475
  }
2041
2476
  }
2042
2477
  async extractEmailData(emailAddress, options, world) {
@@ -2196,56 +2631,49 @@ class StableBrowser {
2196
2631
  console.debug(error);
2197
2632
  }
2198
2633
  }
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
- // }
2634
+ _matcher(text) {
2635
+ if (!text) {
2636
+ return { matcher: "contains", queryText: "" };
2637
+ }
2638
+ if (text.length < 2) {
2639
+ return { matcher: "contains", queryText: text };
2640
+ }
2641
+ const split = text.split(":");
2642
+ const matcher = split[0].toLowerCase();
2643
+ const queryText = split.slice(1).join(":").trim();
2644
+ return { matcher, queryText };
2645
+ }
2646
+ _getDomain(url) {
2647
+ if (url.length === 0 || (!url.startsWith("http://") && !url.startsWith("https://"))) {
2648
+ return "";
2649
+ }
2650
+ let hostnameFragments = url.split("/")[2].split(".");
2651
+ if (hostnameFragments.some((fragment) => fragment.includes(":"))) {
2652
+ return hostnameFragments.join("-").split(":").join("-");
2653
+ }
2654
+ let n = hostnameFragments.length;
2655
+ let fragments = [...hostnameFragments];
2656
+ while (n > 0 && hostnameFragments[n - 1].length <= 3) {
2657
+ hostnameFragments.pop();
2658
+ n = hostnameFragments.length;
2659
+ }
2660
+ if (n == 0) {
2661
+ if (fragments[0] === "www")
2662
+ fragments = fragments.slice(1);
2663
+ return fragments.length > 1 ? fragments.slice(0, fragments.length - 1).join("-") : fragments.join("-");
2664
+ }
2665
+ if (hostnameFragments[0] === "www")
2666
+ hostnameFragments = hostnameFragments.slice(1);
2667
+ return hostnameFragments.join(".");
2668
+ }
2669
+ /**
2670
+ * Verify the page path matches the given path.
2671
+ * @param {string} pathPart - The path to verify.
2672
+ * @param {object} options - Options for verification.
2673
+ * @param {object} world - The world context.
2674
+ * @returns {Promise<object>} - The state info after verification.
2675
+ */
2247
2676
  async verifyPagePath(pathPart, options = {}, world = null) {
2248
- const startTime = Date.now();
2249
2677
  let error = null;
2250
2678
  let screenshotId = null;
2251
2679
  let screenshotPath = null;
@@ -2259,51 +2687,212 @@ class StableBrowser {
2259
2687
  pathPart = newValue;
2260
2688
  }
2261
2689
  info.pathPart = pathPart;
2690
+ const { matcher, queryText } = this._matcher(pathPart);
2691
+ const state = {
2692
+ text_search: queryText,
2693
+ options,
2694
+ world,
2695
+ locate: false,
2696
+ scroll: false,
2697
+ highlight: false,
2698
+ type: Types.VERIFY_PAGE_PATH,
2699
+ text: `Verify the page url is ${queryText}`,
2700
+ _text: `Verify the page url is ${queryText}`,
2701
+ operation: "verifyPagePath",
2702
+ log: "***** verify page url is " + queryText + " *****\n",
2703
+ };
2262
2704
  try {
2705
+ await _preCommand(state, this);
2706
+ state.info.text = queryText;
2263
2707
  for (let i = 0; i < 30; i++) {
2264
2708
  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;
2709
+ switch (matcher) {
2710
+ case "exact":
2711
+ if (url !== queryText) {
2712
+ if (i === 29) {
2713
+ throw new Error(`Page URL ${url} is not equal to ${queryText}`);
2714
+ }
2715
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2716
+ continue;
2717
+ }
2718
+ break;
2719
+ case "contains":
2720
+ if (!url.includes(queryText)) {
2721
+ if (i === 29) {
2722
+ throw new Error(`Page URL ${url} doesn't contain ${queryText}`);
2723
+ }
2724
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2725
+ continue;
2726
+ }
2727
+ break;
2728
+ case "starts-with":
2729
+ {
2730
+ const domain = this._getDomain(url);
2731
+ if (domain.length > 0 && domain !== queryText) {
2732
+ if (i === 29) {
2733
+ throw new Error(`Page URL ${url} doesn't start with ${queryText}`);
2734
+ }
2735
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2736
+ continue;
2737
+ }
2738
+ }
2739
+ break;
2740
+ case "ends-with":
2741
+ {
2742
+ const urlObj = new URL(url);
2743
+ let route = "/";
2744
+ if (urlObj.pathname !== "/") {
2745
+ route = urlObj.pathname.split("/").slice(-1)[0].trim();
2746
+ }
2747
+ else {
2748
+ route = "/";
2749
+ }
2750
+ if (route !== queryText) {
2751
+ if (i === 29) {
2752
+ throw new Error(`Page URL ${url} doesn't end with ${queryText}`);
2753
+ }
2754
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2755
+ continue;
2756
+ }
2757
+ }
2758
+ break;
2759
+ case "regex":
2760
+ const regex = new RegExp(queryText.slice(1, -1), "g");
2761
+ if (!regex.test(url)) {
2762
+ if (i === 29) {
2763
+ throw new Error(`Page URL ${url} doesn't match regex ${queryText}`);
2764
+ }
2765
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2766
+ continue;
2767
+ }
2768
+ break;
2769
+ default:
2770
+ console.log("Unknown matching type, defaulting to contains matching");
2771
+ if (!url.includes(pathPart)) {
2772
+ if (i === 29) {
2773
+ throw new Error(`Page URL ${url} does not contain ${pathPart}`);
2774
+ }
2775
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2776
+ continue;
2777
+ }
2271
2778
  }
2272
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2273
- return info;
2779
+ await _screenshot(state, this);
2780
+ return state.info;
2274
2781
  }
2275
2782
  }
2276
2783
  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);
2784
+ state.info.failCause.lastError = e.message;
2785
+ state.info.failCause.assertionFailed = true;
2786
+ await _commandError(state, e, this);
2285
2787
  }
2286
2788
  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
- });
2789
+ await _commandFinally(state, this);
2790
+ }
2791
+ }
2792
+ /**
2793
+ * Verify the page title matches the given title.
2794
+ * @param {string} title - The title to verify.
2795
+ * @param {object} options - Options for verification.
2796
+ * @param {object} world - The world context.
2797
+ * @returns {Promise<object>} - The state info after verification.
2798
+ */
2799
+ async verifyPageTitle(title, options = {}, world = null) {
2800
+ let error = null;
2801
+ let screenshotId = null;
2802
+ let screenshotPath = null;
2803
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2804
+ const newValue = await this._replaceWithLocalData(title, world);
2805
+ if (newValue !== title) {
2806
+ this.logger.info(title + "=" + newValue);
2807
+ title = newValue;
2808
+ }
2809
+ const { matcher, queryText } = this._matcher(title);
2810
+ const state = {
2811
+ text_search: queryText,
2812
+ options,
2813
+ world,
2814
+ locate: false,
2815
+ scroll: false,
2816
+ highlight: false,
2817
+ type: Types.VERIFY_PAGE_TITLE,
2818
+ text: `Verify the page title is ${queryText}`,
2819
+ _text: `Verify the page title is ${queryText}`,
2820
+ operation: "verifyPageTitle",
2821
+ log: "***** verify page title is " + queryText + " *****\n",
2822
+ };
2823
+ try {
2824
+ await _preCommand(state, this);
2825
+ state.info.text = queryText;
2826
+ for (let i = 0; i < 30; i++) {
2827
+ const foundTitle = await this.page.title();
2828
+ switch (matcher) {
2829
+ case "exact":
2830
+ if (foundTitle !== queryText) {
2831
+ if (i === 29) {
2832
+ throw new Error(`Page Title ${foundTitle} is not equal to ${queryText}`);
2833
+ }
2834
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2835
+ continue;
2836
+ }
2837
+ break;
2838
+ case "contains":
2839
+ if (!foundTitle.includes(queryText)) {
2840
+ if (i === 29) {
2841
+ throw new Error(`Page Title ${foundTitle} doesn't contain ${queryText}`);
2842
+ }
2843
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2844
+ continue;
2845
+ }
2846
+ break;
2847
+ case "starts-with":
2848
+ if (!foundTitle.startsWith(queryText)) {
2849
+ if (i === 29) {
2850
+ throw new Error(`Page title ${foundTitle} doesn't start with ${queryText}`);
2851
+ }
2852
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2853
+ continue;
2854
+ }
2855
+ break;
2856
+ case "ends-with":
2857
+ if (!foundTitle.endsWith(queryText)) {
2858
+ if (i === 29) {
2859
+ throw new Error(`Page Title ${foundTitle} doesn't end with ${queryText}`);
2860
+ }
2861
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2862
+ continue;
2863
+ }
2864
+ break;
2865
+ case "regex":
2866
+ const regex = new RegExp(queryText.slice(1, -1), "g");
2867
+ if (!regex.test(foundTitle)) {
2868
+ if (i === 29) {
2869
+ throw new Error(`Page Title ${foundTitle} doesn't match regex ${queryText}`);
2870
+ }
2871
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2872
+ continue;
2873
+ }
2874
+ break;
2875
+ default:
2876
+ console.log("Unknown matching type, defaulting to contains matching");
2877
+ if (!foundTitle.includes(title)) {
2878
+ if (i === 29) {
2879
+ throw new Error(`Page Title ${foundTitle} does not contain ${title}`);
2880
+ }
2881
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2882
+ continue;
2883
+ }
2884
+ }
2885
+ await _screenshot(state, this);
2886
+ return state.info;
2887
+ }
2888
+ }
2889
+ catch (e) {
2890
+ state.info.failCause.lastError = e.message;
2891
+ state.info.failCause.assertionFailed = true;
2892
+ await _commandError(state, e, this);
2893
+ }
2894
+ finally {
2895
+ await _commandFinally(state, this);
2307
2896
  }
2308
2897
  }
2309
2898
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2345,7 +2934,7 @@ class StableBrowser {
2345
2934
  scroll: false,
2346
2935
  highlight: false,
2347
2936
  type: Types.VERIFY_PAGE_CONTAINS_TEXT,
2348
- text: `Verify the text '${text}' exists in page`,
2937
+ text: `Verify the text '${maskValue(text)}' exists in page`,
2349
2938
  _text: `Verify the text '${text}' exists in page`,
2350
2939
  operation: "verifyTextExistInPage",
2351
2940
  log: "***** verify text " + text + " exists in page *****\n",
@@ -2387,27 +2976,10 @@ class StableBrowser {
2387
2976
  const frame = resultWithElementsFound[0].frame;
2388
2977
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2389
2978
  await this._highlightElements(frame, dataAttribute);
2390
- // if (world && world.screenshot && !world.screenshotPath) {
2391
- // console.log(`Highlighting for verify text is found while running from recorder`);
2392
- // this._highlightElements(frame, dataAttribute).then(async () => {
2393
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2394
- // this._unhighlightElements(frame, dataAttribute)
2395
- // .then(async () => {
2396
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2397
- // })
2398
- // .catch(
2399
- // (e) => {}
2400
- // console.error(e)
2401
- // );
2402
- // });
2403
- // }
2404
2979
  const element = await frame.locator(dataAttribute).first();
2405
- // await new Promise((resolve) => setTimeout(resolve, 100));
2406
- // await this._unhighlightElements(frame, dataAttribute);
2407
2980
  if (element) {
2408
2981
  await this.scrollIfNeeded(element, state.info);
2409
2982
  await element.dispatchEvent("bvt_verify_page_contains_text");
2410
- // await _screenshot(state, this, element);
2411
2983
  }
2412
2984
  }
2413
2985
  await _screenshot(state, this);
@@ -2417,13 +2989,12 @@ class StableBrowser {
2417
2989
  console.error(error);
2418
2990
  }
2419
2991
  }
2420
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2421
2992
  }
2422
2993
  catch (e) {
2423
2994
  await _commandError(state, e, this);
2424
2995
  }
2425
2996
  finally {
2426
- _commandFinally(state, this);
2997
+ await _commandFinally(state, this);
2427
2998
  }
2428
2999
  }
2429
3000
  async waitForTextToDisappear(text, options = {}, world = null) {
@@ -2436,7 +3007,7 @@ class StableBrowser {
2436
3007
  scroll: false,
2437
3008
  highlight: false,
2438
3009
  type: Types.WAIT_FOR_TEXT_TO_DISAPPEAR,
2439
- text: `Verify the text '${text}' does not exist in page`,
3010
+ text: `Verify the text '${maskValue(text)}' does not exist in page`,
2440
3011
  _text: `Verify the text '${text}' does not exist in page`,
2441
3012
  operation: "verifyTextNotExistInPage",
2442
3013
  log: "***** verify text " + text + " does not exist in page *****\n",
@@ -2480,7 +3051,7 @@ class StableBrowser {
2480
3051
  await _commandError(state, e, this);
2481
3052
  }
2482
3053
  finally {
2483
- _commandFinally(state, this);
3054
+ await _commandFinally(state, this);
2484
3055
  }
2485
3056
  }
2486
3057
  async verifyTextRelatedToText(textAnchor, climb, textToVerify, options = {}, world = null) {
@@ -2550,7 +3121,7 @@ class StableBrowser {
2550
3121
  const count = await frame.locator(css).count();
2551
3122
  for (let j = 0; j < count; j++) {
2552
3123
  const continer = await frame.locator(css).nth(j);
2553
- const result = await this._locateElementByText(continer, textToVerify, "*:not(script, style, head)", false, false, true, {});
3124
+ const result = await this._locateElementByText(continer, textToVerify, "*:not(script, style, head)", false, true, true, {});
2554
3125
  if (result.elementCount > 0) {
2555
3126
  const dataAttribute = "[data-blinq-id-" + result.randomToken + "]";
2556
3127
  await this._highlightElements(frame, dataAttribute);
@@ -2591,7 +3162,7 @@ class StableBrowser {
2591
3162
  await _commandError(state, e, this);
2592
3163
  }
2593
3164
  finally {
2594
- _commandFinally(state, this);
3165
+ await _commandFinally(state, this);
2595
3166
  }
2596
3167
  }
2597
3168
  async findRelatedTextInAllFrames(textAnchor, climb, textToVerify, params = {}, options = {}, world = null) {
@@ -2933,8 +3504,51 @@ class StableBrowser {
2933
3504
  });
2934
3505
  }
2935
3506
  }
3507
+ /**
3508
+ * Explicit wait/sleep function that pauses execution for a specified duration
3509
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3510
+ * @param options - Optional configuration object
3511
+ * @param world - Optional world context
3512
+ * @returns Promise that resolves after the specified duration
3513
+ */
3514
+ async sleep(duration = 1000, options = {}, world = null) {
3515
+ const state = {
3516
+ duration,
3517
+ options,
3518
+ world,
3519
+ locate: false,
3520
+ scroll: false,
3521
+ screenshot: false,
3522
+ highlight: false,
3523
+ type: Types.SLEEP,
3524
+ text: `Sleep for ${duration} ms`,
3525
+ _text: `Sleep for ${duration} ms`,
3526
+ operation: "sleep",
3527
+ log: `***** Sleep for ${duration} ms *****\n`,
3528
+ };
3529
+ try {
3530
+ await _preCommand(state, this);
3531
+ if (duration < 0) {
3532
+ throw new Error("Sleep duration cannot be negative");
3533
+ }
3534
+ await new Promise((resolve) => setTimeout(resolve, duration));
3535
+ return state.info;
3536
+ }
3537
+ catch (e) {
3538
+ await _commandError(state, e, this);
3539
+ }
3540
+ finally {
3541
+ await _commandFinally(state, this);
3542
+ }
3543
+ }
2936
3544
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
2937
- return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3545
+ try {
3546
+ return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3547
+ }
3548
+ catch (error) {
3549
+ this.logger.debug(error);
3550
+ throw error;
3551
+ }
2938
3552
  }
2939
3553
  _getLoadTimeout(options) {
2940
3554
  let timeout = 15000;
@@ -2957,6 +3571,7 @@ class StableBrowser {
2957
3571
  }
2958
3572
  async saveStoreState(path = null, world = null) {
2959
3573
  const storageState = await this.page.context().storageState();
3574
+ path = await this._replaceWithLocalData(path, this.world);
2960
3575
  //const testDataFile = _getDataFile(world, this.context, this);
2961
3576
  if (path) {
2962
3577
  // save { storageState: storageState } into the path
@@ -2967,10 +3582,14 @@ class StableBrowser {
2967
3582
  }
2968
3583
  }
2969
3584
  async restoreSaveState(path = null, world = null) {
3585
+ path = await this._replaceWithLocalData(path, this.world);
2970
3586
  await refreshBrowser(this, path, world);
2971
3587
  this.registerEventListeners(this.context);
2972
3588
  registerNetworkEvents(this.world, this, this.context, this.page);
2973
3589
  registerDownloadEvent(this.page, this.world, this.context);
3590
+ if (this.onRestoreSaveState) {
3591
+ this.onRestoreSaveState(path);
3592
+ }
2974
3593
  }
2975
3594
  async waitForPageLoad(options = {}, world = null) {
2976
3595
  let timeout = this._getLoadTimeout(options);
@@ -3053,7 +3672,7 @@ class StableBrowser {
3053
3672
  await _commandError(state, e, this);
3054
3673
  }
3055
3674
  finally {
3056
- _commandFinally(state, this);
3675
+ await _commandFinally(state, this);
3057
3676
  }
3058
3677
  }
3059
3678
  async tableCellOperation(headerText, rowText, options, _params, world = null) {
@@ -3140,7 +3759,7 @@ class StableBrowser {
3140
3759
  await _commandError(state, e, this);
3141
3760
  }
3142
3761
  finally {
3143
- _commandFinally(state, this);
3762
+ await _commandFinally(state, this);
3144
3763
  }
3145
3764
  }
3146
3765
  saveTestDataAsGlobal(options, world) {
@@ -3245,7 +3864,39 @@ class StableBrowser {
3245
3864
  console.log("#-#");
3246
3865
  }
3247
3866
  }
3867
+ async beforeScenario(world, scenario) {
3868
+ this.beforeScenarioCalled = true;
3869
+ if (scenario && scenario.pickle && scenario.pickle.name) {
3870
+ this.scenarioName = scenario.pickle.name;
3871
+ }
3872
+ if (scenario && scenario.gherkinDocument && scenario.gherkinDocument.feature) {
3873
+ this.featureName = scenario.gherkinDocument.feature.name;
3874
+ }
3875
+ if (this.context) {
3876
+ this.context.examplesRow = extractStepExampleParameters(scenario);
3877
+ }
3878
+ if (this.tags === null && scenario && scenario.pickle && scenario.pickle.tags) {
3879
+ this.tags = scenario.pickle.tags.map((tag) => tag.name);
3880
+ // check if @global_test_data tag is present
3881
+ if (this.tags.includes("@global_test_data")) {
3882
+ this.saveTestDataAsGlobal({}, world);
3883
+ }
3884
+ }
3885
+ // update test data based on feature/scenario
3886
+ let envName = null;
3887
+ if (this.context && this.context.environment) {
3888
+ envName = this.context.environment.name;
3889
+ }
3890
+ if (!process.env.TEMP_RUN) {
3891
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
3892
+ }
3893
+ await loadBrunoParams(this.context, this.context.environment.name);
3894
+ }
3895
+ async afterScenario(world, scenario) { }
3248
3896
  async beforeStep(world, step) {
3897
+ if (!this.beforeScenarioCalled) {
3898
+ this.beforeScenario(world, step);
3899
+ }
3249
3900
  if (this.stepIndex === undefined) {
3250
3901
  this.stepIndex = 0;
3251
3902
  }
@@ -3262,30 +3913,22 @@ class StableBrowser {
3262
3913
  else {
3263
3914
  this.stepName = "step " + this.stepIndex;
3264
3915
  }
3265
- if (this.context) {
3266
- this.context.examplesRow = extractStepExampleParameters(step);
3267
- }
3268
3916
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
3269
3917
  if (this.context.browserObject.context) {
3270
3918
  await this.context.browserObject.context.tracing.startChunk({ title: this.stepName });
3271
3919
  }
3272
3920
  }
3273
- if (this.tags === null && step && step.pickle && step.pickle.tags) {
3274
- this.tags = step.pickle.tags.map((tag) => tag.name);
3275
- // check if @global_test_data tag is present
3276
- if (this.tags.includes("@global_test_data")) {
3277
- this.saveTestDataAsGlobal({}, world);
3278
- }
3279
- }
3280
3921
  if (this.initSnapshotTaken === false) {
3281
3922
  this.initSnapshotTaken = true;
3282
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
3923
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3283
3924
  const snapshot = await this.getAriaSnapshot();
3284
3925
  if (snapshot) {
3285
3926
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3286
3927
  }
3287
3928
  }
3288
3929
  }
3930
+ this.context.routeResults = null;
3931
+ await registerBeforeStepRoutes(this.context, this.stepName);
3289
3932
  }
3290
3933
  async getAriaSnapshot() {
3291
3934
  try {
@@ -3301,18 +3944,68 @@ class StableBrowser {
3301
3944
  const content = [`- path: ${path}`, `- title: ${title}`];
3302
3945
  const timeout = this.configuration.ariaSnapshotTimeout ? this.configuration.ariaSnapshotTimeout : 3000;
3303
3946
  for (let i = 0; i < frames.length; i++) {
3304
- content.push(`- frame: ${i}`);
3305
3947
  const frame = frames[i];
3306
- const snapshot = await frame.locator("body").ariaSnapshot({ timeout });
3307
- content.push(snapshot);
3948
+ try {
3949
+ // Ensure frame is attached and has body
3950
+ const body = frame.locator("body");
3951
+ await body.waitFor({ timeout: 200 }); // wait explicitly
3952
+ const snapshot = await body.ariaSnapshot({ timeout });
3953
+ content.push(`- frame: ${i}`);
3954
+ content.push(snapshot);
3955
+ }
3956
+ catch (innerErr) { }
3308
3957
  }
3309
3958
  return content.join("\n");
3310
3959
  }
3311
3960
  catch (e) {
3312
- console.error(e);
3961
+ console.log("Error in getAriaSnapshot");
3962
+ //console.debug(e);
3313
3963
  }
3314
3964
  return null;
3315
3965
  }
3966
+ /**
3967
+ * Sends command with custom payload to report.
3968
+ * @param commandText - Title of the command to be shown in the report.
3969
+ * @param commandStatus - Status of the command (e.g. "PASSED", "FAILED").
3970
+ * @param content - Content of the command to be shown in the report.
3971
+ * @param options - Options for the command. Example: { type: "json", screenshot: true }
3972
+ * @param world - Optional world context.
3973
+ * @public
3974
+ */
3975
+ async addCommandToReport(commandText, commandStatus, content, options = {}, world = null) {
3976
+ const state = {
3977
+ options,
3978
+ world,
3979
+ locate: false,
3980
+ scroll: false,
3981
+ screenshot: options.screenshot ?? false,
3982
+ highlight: options.highlight ?? false,
3983
+ type: Types.REPORT_COMMAND,
3984
+ text: commandText,
3985
+ _text: commandText,
3986
+ operation: "report_command",
3987
+ log: "***** " + commandText + " *****\n",
3988
+ };
3989
+ try {
3990
+ await _preCommand(state, this);
3991
+ const payload = {
3992
+ type: options.type ?? "text",
3993
+ content: content,
3994
+ screenshotId: null,
3995
+ };
3996
+ state.payload = payload;
3997
+ if (commandStatus === "FAILED") {
3998
+ state.throwError = true;
3999
+ throw new Error("Command failed");
4000
+ }
4001
+ }
4002
+ catch (e) {
4003
+ await _commandError(state, e, this);
4004
+ }
4005
+ finally {
4006
+ await _commandFinally(state, this);
4007
+ }
4008
+ }
3316
4009
  async afterStep(world, step) {
3317
4010
  this.stepName = null;
3318
4011
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3320,6 +4013,13 @@ class StableBrowser {
3320
4013
  await this.context.browserObject.context.tracing.stopChunk({
3321
4014
  path: path.join(this.context.browserObject.traceFolder, `trace-${this.stepIndex}.zip`),
3322
4015
  });
4016
+ if (world && world.attach) {
4017
+ await world.attach(JSON.stringify({
4018
+ type: "trace",
4019
+ traceFilePath: `trace-${this.stepIndex}.zip`,
4020
+ }), "application/json+trace");
4021
+ }
4022
+ // console.log("trace file created", `trace-${this.stepIndex}.zip`);
3323
4023
  }
3324
4024
  }
3325
4025
  if (this.context) {
@@ -3332,6 +4032,30 @@ class StableBrowser {
3332
4032
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3333
4033
  }
3334
4034
  }
4035
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4036
+ if (!process.env.TEMP_RUN) {
4037
+ const state = {
4038
+ world,
4039
+ locate: false,
4040
+ scroll: false,
4041
+ screenshot: true,
4042
+ highlight: true,
4043
+ type: Types.STEP_COMPLETE,
4044
+ text: "end of scenario",
4045
+ _text: "end of scenario",
4046
+ operation: "step_complete",
4047
+ log: "***** " + "end of scenario" + " *****\n",
4048
+ };
4049
+ try {
4050
+ await _preCommand(state, this);
4051
+ }
4052
+ catch (e) {
4053
+ await _commandError(state, e, this);
4054
+ }
4055
+ finally {
4056
+ await _commandFinally(state, this);
4057
+ }
4058
+ }
3335
4059
  }
3336
4060
  }
3337
4061
  function createTimedPromise(promise, label) {