automation_model 1.0.693-dev → 1.0.693-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 (55) hide show
  1. package/README.md +4 -1
  2. package/lib/analyze_helper.js.map +1 -1
  3. package/lib/api.d.ts +0 -1
  4. package/lib/api.js.map +1 -1
  5. package/lib/auto_page.d.ts +4 -2
  6. package/lib/auto_page.js +178 -88
  7. package/lib/auto_page.js.map +1 -1
  8. package/lib/browser_manager.js +35 -9
  9. package/lib/browser_manager.js.map +1 -1
  10. package/lib/bruno.js +8 -1
  11. package/lib/bruno.js.map +1 -1
  12. package/lib/command_common.d.ts +1 -1
  13. package/lib/command_common.js +18 -1
  14. package/lib/command_common.js.map +1 -1
  15. package/lib/date_time.js.map +1 -1
  16. package/lib/drawRect.js.map +1 -1
  17. package/lib/environment.d.ts +1 -0
  18. package/lib/environment.js +1 -0
  19. package/lib/environment.js.map +1 -1
  20. package/lib/error-messages.js.map +1 -1
  21. package/lib/file_checker.js +129 -25
  22. package/lib/file_checker.js.map +1 -1
  23. package/lib/find_function.js.map +1 -1
  24. package/lib/init_browser.js +4 -4
  25. package/lib/init_browser.js.map +1 -1
  26. package/lib/locate_element.js.map +1 -1
  27. package/lib/locator.d.ts +1 -0
  28. package/lib/locator.js +10 -3
  29. package/lib/locator.js.map +1 -1
  30. package/lib/locator_log.js.map +1 -1
  31. package/lib/network.d.ts +2 -0
  32. package/lib/network.js +232 -4
  33. package/lib/network.js.map +1 -1
  34. package/lib/route.d.ts +21 -0
  35. package/lib/route.js +392 -0
  36. package/lib/route.js.map +1 -0
  37. package/lib/scripts/axe.mini.js +3 -3
  38. package/lib/snapshot_validation.d.ts +4 -2
  39. package/lib/snapshot_validation.js +160 -42
  40. package/lib/snapshot_validation.js.map +1 -1
  41. package/lib/stable_browser.d.ts +59 -26
  42. package/lib/stable_browser.js +956 -202
  43. package/lib/stable_browser.js.map +1 -1
  44. package/lib/table.d.ts +9 -7
  45. package/lib/table.js +82 -12
  46. package/lib/table.js.map +1 -1
  47. package/lib/table_analyze.js.map +1 -1
  48. package/lib/table_helper.js.map +1 -1
  49. package/lib/test_context.d.ts +1 -0
  50. package/lib/test_context.js +1 -0
  51. package/lib/test_context.js.map +1 -1
  52. package/lib/utils.d.ts +2 -1
  53. package/lib/utils.js +77 -63
  54. package/lib/utils.js.map +1 -1
  55. package/package.json +12 -7
@@ -10,7 +10,7 @@ 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";
@@ -19,29 +19,33 @@ import { getTestData } from "./auto_page.js";
19
19
  import { locate_element } from "./locate_element.js";
20
20
  import { randomUUID } from "crypto";
21
21
  import { _commandError, _commandFinally, _preCommand, _validateSelectors, _screenshot, _reportToWorld, } from "./command_common.js";
22
- import { registerDownloadEvent, registerNetworkEvents } from "./network.js";
22
+ import { networkAfterStep, networkBeforeStep, registerDownloadEvent, registerNetworkEvents } from "./network.js";
23
23
  import { LocatorLog } from "./locator_log.js";
24
24
  import axios from "axios";
25
25
  import { _findCellArea, findElementsInArea } from "./table_helper.js";
26
- import { snapshotValidation } from "./snapshot_validation.js";
26
+ import { highlightSnapshot, snapshotValidation } from "./snapshot_validation.js";
27
27
  import { loadBrunoParams } from "./bruno.js";
28
+ import { registerAfterStepRoutes, registerBeforeStepRoutes } from "./route.js";
28
29
  export const Types = {
29
30
  CLICK: "click_element",
30
31
  WAIT_ELEMENT: "wait_element",
31
32
  NAVIGATE: "navigate",
33
+ GO_BACK: "go_back",
34
+ GO_FORWARD: "go_forward",
32
35
  FILL: "fill_element",
33
- EXECUTE: "execute_page_method",
34
- OPEN: "open_environment",
36
+ EXECUTE: "execute_page_method", //
37
+ OPEN: "open_environment", //
35
38
  COMPLETE: "step_complete",
36
39
  ASK: "information_needed",
37
- GET_PAGE_STATUS: "get_page_status",
38
- CLICK_ROW_ACTION: "click_row_action",
40
+ GET_PAGE_STATUS: "get_page_status", ///
41
+ CLICK_ROW_ACTION: "click_row_action", //
39
42
  VERIFY_ELEMENT_CONTAINS_TEXT: "verify_element_contains_text",
40
43
  VERIFY_PAGE_CONTAINS_TEXT: "verify_page_contains_text",
41
44
  VERIFY_PAGE_CONTAINS_NO_TEXT: "verify_page_contains_no_text",
42
45
  ANALYZE_TABLE: "analyze_table",
43
- SELECT: "select_combobox",
46
+ SELECT: "select_combobox", //
44
47
  VERIFY_PAGE_PATH: "verify_page_path",
48
+ VERIFY_PAGE_TITLE: "verify_page_title",
45
49
  TYPE_PRESS: "type_press",
46
50
  PRESS: "press_key",
47
51
  HOVER: "hover_element",
@@ -59,8 +63,13 @@ export const Types = {
59
63
  VERIFY_ATTRIBUTE: "verify_element_attribute",
60
64
  VERIFY_TEXT_WITH_RELATION: "verify_text_with_relation",
61
65
  BRUNO: "bruno",
62
- SNAPSHOT_VALIDATION: "snapshot_validation",
63
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",
72
+ CONDITIONAL_WAIT: "conditional_wait",
64
73
  };
65
74
  export const apps = {};
66
75
  const formatElementName = (elementName) => {
@@ -72,6 +81,7 @@ class StableBrowser {
72
81
  logger;
73
82
  context;
74
83
  world;
84
+ fastMode;
75
85
  project_path = null;
76
86
  webLogFile = null;
77
87
  networkLogger = null;
@@ -80,12 +90,14 @@ class StableBrowser {
80
90
  tags = null;
81
91
  isRecording = false;
82
92
  initSnapshotTaken = false;
83
- constructor(browser, page, logger = null, context = null, world = null) {
93
+ abortedExecution = false;
94
+ constructor(browser, page, logger = null, context = null, world = null, fastMode = false) {
84
95
  this.browser = browser;
85
96
  this.page = page;
86
97
  this.logger = logger;
87
98
  this.context = context;
88
99
  this.world = world;
100
+ this.fastMode = fastMode;
89
101
  if (!this.logger) {
90
102
  this.logger = console;
91
103
  }
@@ -114,6 +126,19 @@ class StableBrowser {
114
126
  context.pages = [this.page];
115
127
  const logFolder = path.join(this.project_path, "logs", "web");
116
128
  this.world = world;
129
+ if (this.configuration && this.configuration.fastMode === true) {
130
+ this.fastMode = true;
131
+ }
132
+ if (process.env.FAST_MODE === "true") {
133
+ // console.log("Fast mode enabled from environment variable");
134
+ this.fastMode = true;
135
+ }
136
+ if (process.env.FAST_MODE === "false") {
137
+ this.fastMode = false;
138
+ }
139
+ if (this.context) {
140
+ this.context.fastMode = this.fastMode;
141
+ }
117
142
  this.registerEventListeners(this.context);
118
143
  registerNetworkEvents(this.world, this, this.context, this.page);
119
144
  registerDownloadEvent(this.page, this.world, this.context);
@@ -124,6 +149,9 @@ class StableBrowser {
124
149
  if (!context.pageLoading) {
125
150
  context.pageLoading = { status: false };
126
151
  }
152
+ if (this.configuration && this.configuration.acceptDialog && this.page) {
153
+ this.page.on("dialog", (dialog) => dialog.accept());
154
+ }
127
155
  context.playContext.on("page", async function (page) {
128
156
  if (this.configuration && this.configuration.closePopups === true) {
129
157
  console.log("close unexpected popups");
@@ -132,6 +160,14 @@ class StableBrowser {
132
160
  }
133
161
  context.pageLoading.status = true;
134
162
  this.page = page;
163
+ try {
164
+ if (this.configuration && this.configuration.acceptDialog) {
165
+ await page.on("dialog", (dialog) => dialog.accept());
166
+ }
167
+ }
168
+ catch (error) {
169
+ console.error("Error on dialog accept registration", error);
170
+ }
135
171
  context.page = page;
136
172
  context.pages.push(page);
137
173
  registerNetworkEvents(this.world, this, context, this.page);
@@ -183,7 +219,9 @@ class StableBrowser {
183
219
  if (newContextCreated) {
184
220
  this.registerEventListeners(this.context);
185
221
  await this.goto(this.context.environment.baseUrl);
186
- await this.waitForPageLoad();
222
+ if (!this.fastMode) {
223
+ await this.waitForPageLoad();
224
+ }
187
225
  }
188
226
  }
189
227
  async switchTab(tabTitleOrIndex) {
@@ -277,6 +315,7 @@ class StableBrowser {
277
315
  if (!url) {
278
316
  throw new Error("url is null, verify that the environment file is correct");
279
317
  }
318
+ url = await this._replaceWithLocalData(url, this.world);
280
319
  if (!url.startsWith("http")) {
281
320
  url = "https://" + url;
282
321
  }
@@ -308,6 +347,64 @@ class StableBrowser {
308
347
  await _commandFinally(state, this);
309
348
  }
310
349
  }
350
+ async goBack(options, world = null) {
351
+ const state = {
352
+ value: "",
353
+ world: world,
354
+ type: Types.GO_BACK,
355
+ text: `Browser navigate back`,
356
+ operation: "goBack",
357
+ log: "***** navigate back *****\n",
358
+ info: {},
359
+ locate: false,
360
+ scroll: false,
361
+ screenshot: false,
362
+ highlight: false,
363
+ };
364
+ try {
365
+ await _preCommand(state, this);
366
+ await this.page.goBack({
367
+ waitUntil: "load",
368
+ });
369
+ await _screenshot(state, this);
370
+ }
371
+ catch (error) {
372
+ console.error("Error on goBack", error);
373
+ _commandError(state, error, this);
374
+ }
375
+ finally {
376
+ await _commandFinally(state, this);
377
+ }
378
+ }
379
+ async goForward(options, world = null) {
380
+ const state = {
381
+ value: "",
382
+ world: world,
383
+ type: Types.GO_FORWARD,
384
+ text: `Browser navigate forward`,
385
+ operation: "goForward",
386
+ log: "***** navigate forward *****\n",
387
+ info: {},
388
+ locate: false,
389
+ scroll: false,
390
+ screenshot: false,
391
+ highlight: false,
392
+ };
393
+ try {
394
+ await _preCommand(state, this);
395
+ await this.page.goForward({
396
+ waitUntil: "load",
397
+ });
398
+ await _screenshot(state, this);
399
+ }
400
+ catch (error) {
401
+ console.error("Error on goForward", error);
402
+ _commandError(state, error, this);
403
+ }
404
+ finally {
405
+ await _commandFinally(state, this);
406
+ }
407
+ }
311
408
  async _getLocator(locator, scope, _params) {
312
409
  locator = _fixLocatorUsingParams(locator, _params);
313
410
  // locator = await this._replaceWithLocalData(locator);
@@ -421,7 +518,7 @@ class StableBrowser {
421
518
  }
422
519
  return { elementCount: tagCount, randomToken };
423
520
  }
424
- async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null) {
521
+ async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null, logErrors = false) {
425
522
  if (!info) {
426
523
  info = {};
427
524
  }
@@ -433,14 +530,13 @@ class StableBrowser {
433
530
  info.locatorLog = new LocatorLog(selectorHierarchy);
434
531
  }
435
532
  let locatorSearch = selectorHierarchy[index];
436
- let originalLocatorSearch = "";
437
533
  try {
438
- originalLocatorSearch = _fixUsingParams(JSON.stringify(locatorSearch), _params);
439
- locatorSearch = JSON.parse(originalLocatorSearch);
534
+ locatorSearch = _fixLocatorUsingParams(locatorSearch, _params);
440
535
  }
441
536
  catch (e) {
442
537
  console.error(e);
443
538
  }
539
+ let originalLocatorSearch = JSON.stringify(locatorSearch);
444
540
  //info.log += "searching for locator " + JSON.stringify(locatorSearch) + "\n";
445
541
  let locator = null;
446
542
  if (locatorSearch.climb && locatorSearch.climb >= 0) {
@@ -488,7 +584,7 @@ class StableBrowser {
488
584
  }
489
585
  return;
490
586
  }
491
- if (info.locatorLog && count === 0) {
587
+ if (info.locatorLog && count === 0 && logErrors) {
492
588
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "NOT_FOUND");
493
589
  }
494
590
  for (let j = 0; j < count; j++) {
@@ -503,7 +599,7 @@ class StableBrowser {
503
599
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "FOUND");
504
600
  }
505
601
  }
506
- else {
602
+ else if (logErrors) {
507
603
  info.failCause.visible = visible;
508
604
  info.failCause.enabled = enabled;
509
605
  if (!info.printMessages) {
@@ -595,7 +691,7 @@ class StableBrowser {
595
691
  let element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
596
692
  if (!element.rerun) {
597
693
  const randomToken = Math.random().toString(36).substring(7);
598
- element.evaluate((el, randomToken) => {
694
+ await element.evaluate((el, randomToken) => {
599
695
  el.setAttribute("data-blinq-id-" + randomToken, "");
600
696
  }, randomToken);
601
697
  // if (element._frame) {
@@ -648,7 +744,7 @@ class StableBrowser {
648
744
  break;
649
745
  }
650
746
  catch (error) {
651
- console.error("frame not found " + frameLocator.css);
747
+ // console.error("frame not found " + frameLocator.css);
652
748
  }
653
749
  }
654
750
  }
@@ -726,7 +822,6 @@ class StableBrowser {
726
822
  let locatorsCount = 0;
727
823
  let lazy_scroll = false;
728
824
  //let arrayMode = Array.isArray(selectors);
729
- let scope = await this._findFrameScope(selectors, timeout, info);
730
825
  let selectorsLocators = null;
731
826
  selectorsLocators = selectors.locators;
732
827
  // group selectors by priority
@@ -754,6 +849,7 @@ class StableBrowser {
754
849
  let highPriorityOnly = true;
755
850
  let visibleOnly = true;
756
851
  while (true) {
852
+ let scope = await this._findFrameScope(selectors, timeout, info);
757
853
  locatorsCount = 0;
758
854
  let result = [];
759
855
  let popupResult = await this.closeUnexpectedPopups(info, _params);
@@ -844,7 +940,7 @@ class StableBrowser {
844
940
  }
845
941
  throw new Error("failed to locate first element no elements found, " + info.log);
846
942
  }
847
- async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name) {
943
+ async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name, logErrors = false) {
848
944
  let foundElements = [];
849
945
  const result = {
850
946
  foundElements: foundElements,
@@ -863,7 +959,9 @@ class StableBrowser {
863
959
  await this._collectLocatorInformation(locatorsGroup, i, this.page, foundLocators, _params, info, visibleOnly, allowDisabled, element_name);
864
960
  }
865
961
  catch (e) {
866
- this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
962
+ if (logErrors) {
963
+ this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
964
+ }
867
965
  }
868
966
  }
869
967
  if (foundLocators.length === 1) {
@@ -904,7 +1002,7 @@ class StableBrowser {
904
1002
  });
905
1003
  result.locatorIndex = i;
906
1004
  }
907
- else {
1005
+ else if (logErrors) {
908
1006
  info.failCause.foundMultiple = true;
909
1007
  if (info.locatorLog) {
910
1008
  info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
@@ -1027,7 +1125,9 @@ class StableBrowser {
1027
1125
  try {
1028
1126
  await _preCommand(state, this);
1029
1127
  await performAction("click", state.element, options, this, state, _params);
1030
- await this.waitForPageLoad();
1128
+ if (!this.fastMode) {
1129
+ await this.waitForPageLoad();
1130
+ }
1031
1131
  return state.info;
1032
1132
  }
1033
1133
  catch (e) {
@@ -1090,7 +1190,7 @@ class StableBrowser {
1090
1190
  // if (world && world.screenshot && !world.screenshotPath) {
1091
1191
  // console.log(`Highlighting while running from recorder`);
1092
1192
  await this._highlightElements(state.element);
1093
- await state.element.setChecked(checked);
1193
+ await state.element.setChecked(checked, { timeout: 2000 });
1094
1194
  await new Promise((resolve) => setTimeout(resolve, 1000));
1095
1195
  // await this._unHighlightElements(element);
1096
1196
  // }
@@ -1102,11 +1202,28 @@ class StableBrowser {
1102
1202
  this.logger.info("element did not change its state, ignoring...");
1103
1203
  }
1104
1204
  else {
1205
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1105
1206
  //await this.closeUnexpectedPopups();
1106
1207
  state.info.log += "setCheck failed, will try again" + "\n";
1107
- state.element = await this._locate(selectors, state.info, _params);
1108
- await state.element.setChecked(checked, { timeout: 5000, force: true });
1109
- await new Promise((resolve) => setTimeout(resolve, 1000));
1208
+ state.element_found = false;
1209
+ try {
1210
+ state.element = await this._locate(selectors, state.info, _params, 100);
1211
+ state.element_found = true;
1212
+ // check the check state
1213
+ }
1214
+ catch (error) {
1215
+ // element dismissed
1216
+ }
1217
+ if (state.element_found) {
1218
+ const isChecked = await state.element.isChecked();
1219
+ if (isChecked !== checked) {
1220
+ // perform click
1221
+ await state.element.click({ timeout: 2000, force: true });
1222
+ }
1223
+ else {
1224
+ this.logger.info(`Element ${selectors.element_name} is already in the desired state (${checked})`);
1225
+ }
1226
+ }
1110
1227
  }
1111
1228
  }
1112
1229
  await this.waitForPageLoad();
@@ -1402,7 +1519,9 @@ class StableBrowser {
1402
1519
  await new Promise((resolve) => setTimeout(resolve, 500));
1403
1520
  }
1404
1521
  }
1522
+ //if (!this.fastMode) {
1405
1523
  await _screenshot(state, this);
1524
+ //}
1406
1525
  if (enter === true) {
1407
1526
  await new Promise((resolve) => setTimeout(resolve, 2000));
1408
1527
  await this.page.keyboard.press("Enter");
@@ -1462,6 +1581,41 @@ class StableBrowser {
1462
1581
  await _commandFinally(state, this);
1463
1582
  }
1464
1583
  }
1584
+ async setInputFiles(selectors, files, _params = null, options = {}, world = null) {
1585
+ const state = {
1586
+ selectors,
1587
+ _params,
1588
+ files,
1589
+ value: '"' + files.join('", "') + '"',
1590
+ options,
1591
+ world,
1592
+ type: Types.SET_INPUT_FILES,
1593
+ text: `Set input files`,
1594
+ _text: `Set input files on ${selectors.element_name}`,
1595
+ operation: "setInputFiles",
1596
+ log: "***** set input files " + selectors.element_name + " *****\n",
1597
+ };
1598
+ const uploadsFolder = this.configuration.uploadsFolder ?? "data/uploads";
1599
+ try {
1600
+ await _preCommand(state, this);
1601
+ for (let i = 0; i < files.length; i++) {
1602
+ const file = files[i];
1603
+ const filePath = path.join(uploadsFolder, file);
1604
+ if (!fs.existsSync(filePath)) {
1605
+ throw new Error(`File not found: ${filePath}`);
1606
+ }
1607
+ state.files[i] = filePath;
1608
+ }
1609
+ await state.element.setInputFiles(files);
1610
+ return state.info;
1611
+ }
1612
+ catch (e) {
1613
+ await _commandError(state, e, this);
1614
+ }
1615
+ finally {
1616
+ await _commandFinally(state, this);
1617
+ }
1618
+ }
1465
1619
  async getText(selectors, _params = null, options = {}, info = {}, world = null) {
1466
1620
  return await this._getText(selectors, 0, _params, options, info, world);
1467
1621
  }
@@ -1676,14 +1830,17 @@ class StableBrowser {
1676
1830
  throw new Error("referanceSnapshot is null");
1677
1831
  }
1678
1832
  let text = null;
1679
- if (fs.existsSync(path.join(this.project_path, "snapshots", referanceSnapshot + ".yml"))) {
1680
- text = fs.readFileSync(path.join(this.project_path, "snapshots", referanceSnapshot + ".yml"), "utf8");
1833
+ if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"))) {
1834
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"), "utf8");
1835
+ }
1836
+ else if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"))) {
1837
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"), "utf8");
1681
1838
  }
1682
1839
  else if (referanceSnapshot.startsWith("yaml:")) {
1683
1840
  text = referanceSnapshot.substring(5);
1684
1841
  }
1685
1842
  else {
1686
- throw new Error("referanceSnapshot file not found: " + referanceSnapshot);
1843
+ throw new Error("referenceSnapshot file not found: " + referanceSnapshot);
1687
1844
  }
1688
1845
  state.text = text;
1689
1846
  const newValue = await this._replaceWithLocalData(text, world);
@@ -1701,18 +1858,23 @@ class StableBrowser {
1701
1858
  scope = await this._findFrameScope(frameSelectors, timeout, state.info);
1702
1859
  }
1703
1860
  const snapshot = await scope.locator("body").ariaSnapshot({ timeout });
1704
- matchResult = snapshotValidation(snapshot, newValue);
1861
+ matchResult = snapshotValidation(snapshot, newValue, referanceSnapshot);
1705
1862
  if (matchResult.errorLine !== -1) {
1706
1863
  throw new Error("Snapshot validation failed at line " + matchResult.errorLineText);
1707
1864
  }
1708
1865
  // highlight and screenshot
1866
+ try {
1867
+ await await highlightSnapshot(newValue, scope);
1868
+ await _screenshot(state, this);
1869
+ }
1870
+ catch (e) { }
1709
1871
  return state.info;
1710
1872
  }
1711
1873
  catch (e) {
1712
1874
  // Log error but continue retrying until timeout is reached
1713
- this.logger.warn("Retrying containsText due to: " + e.message);
1875
+ //this.logger.warn("Retrying snapshot validation due to: " + e.message);
1714
1876
  }
1715
- await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1 second before retrying
1877
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 1 second before retrying
1716
1878
  }
1717
1879
  throw new Error("No snapshot match " + matchResult?.errorLineText);
1718
1880
  }
@@ -1864,12 +2026,7 @@ class StableBrowser {
1864
2026
  }
1865
2027
  }
1866
2028
  getTestData(world = null) {
1867
- const dataFile = _getDataFile(world, this.context, this);
1868
- let data = {};
1869
- if (fs.existsSync(dataFile)) {
1870
- data = JSON.parse(fs.readFileSync(dataFile, "utf8"));
1871
- }
1872
- return data;
2029
+ return _getTestData(world, this.context, this);
1873
2030
  }
1874
2031
  async _screenShot(options = {}, world = null, info = null) {
1875
2032
  // collect url/path/title
@@ -2058,6 +2215,95 @@ class StableBrowser {
2058
2215
  state.value = await state.element.getAttribute(attribute);
2059
2216
  break;
2060
2217
  }
2218
+ if (options !== null) {
2219
+ if (options.regex && options.regex !== "") {
2220
+ // Construct a regex pattern from the provided string
2221
+ const regex = options.regex.slice(1, -1);
2222
+ const regexPattern = new RegExp(regex, "g");
2223
+ const matches = state.value.match(regexPattern);
2224
+ if (matches) {
2225
+ let newValue = "";
2226
+ for (const match of matches) {
2227
+ newValue += match;
2228
+ }
2229
+ state.value = newValue;
2230
+ }
2231
+ }
2232
+ if (options.trimSpaces && options.trimSpaces === true) {
2233
+ state.value = state.value.trim();
2234
+ }
2235
+ }
2236
+ state.info.value = state.value;
2237
+ this.setTestData({ [variable]: state.value }, world);
2238
+ this.logger.info("set test data: " + variable + "=" + state.value);
2239
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2240
+ return state.info;
2241
+ }
2242
+ catch (e) {
2243
+ await _commandError(state, e, this);
2244
+ }
2245
+ finally {
2246
+ await _commandFinally(state, this);
2247
+ }
2248
+ }
2249
+ async extractProperty(selectors, property, variable, _params = null, options = {}, world = null) {
2250
+ const state = {
2251
+ selectors,
2252
+ _params,
2253
+ property,
2254
+ variable,
2255
+ options,
2256
+ world,
2257
+ type: Types.EXTRACT_PROPERTY,
2258
+ text: `Extract property from element`,
2259
+ _text: `Extract property ${property} from ${selectors.element_name}`,
2260
+ operation: "extractProperty",
2261
+ log: "***** extract property " + property + " from " + selectors.element_name + " *****\n",
2262
+ allowDisabled: true,
2263
+ };
2264
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2265
+ try {
2266
+ await _preCommand(state, this);
2267
+ switch (property) {
2268
+ case "inner_text":
2269
+ state.value = await state.element.innerText();
2270
+ break;
2271
+ case "href":
2272
+ state.value = await state.element.getAttribute("href");
2273
+ break;
2274
+ case "value":
2275
+ state.value = await state.element.inputValue();
2276
+ break;
2277
+ case "text":
2278
+ state.value = await state.element.textContent();
2279
+ break;
2280
+ default:
2281
+ if (property.startsWith("dataset.")) {
2282
+ const dataAttribute = property.substring(8);
2283
+ state.value = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2284
+ }
2285
+ else {
2286
+ state.value = String(await state.element.evaluate((element, prop) => element[prop], property));
2287
+ }
2288
+ }
2289
+ if (options !== null) {
2290
+ if (options.regex && options.regex !== "") {
2291
+ // Construct a regex pattern from the provided string
2292
+ const regex = options.regex.slice(1, -1);
2293
+ const regexPattern = new RegExp(regex, "g");
2294
+ const matches = state.value.match(regexPattern);
2295
+ if (matches) {
2296
+ let newValue = "";
2297
+ for (const match of matches) {
2298
+ newValue += match;
2299
+ }
2300
+ state.value = newValue;
2301
+ }
2302
+ }
2303
+ if (options.trimSpaces && options.trimSpaces === true) {
2304
+ state.value = state.value.trim();
2305
+ }
2306
+ }
2061
2307
  state.info.value = state.value;
2062
2308
  this.setTestData({ [variable]: state.value }, world);
2063
2309
  this.logger.info("set test data: " + variable + "=" + state.value);
@@ -2123,14 +2369,167 @@ class StableBrowser {
2123
2369
  let regex;
2124
2370
  if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2125
2371
  const patternBody = expectedValue.slice(1, -1);
2126
- regex = new RegExp(patternBody, "g");
2372
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2373
+ regex = new RegExp(processedPattern, "gs");
2374
+ state.info.regex = true;
2127
2375
  }
2128
2376
  else {
2129
2377
  const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2130
2378
  regex = new RegExp(escapedPattern, "g");
2131
2379
  }
2132
- if (!val.match(regex)) {
2133
- let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2380
+ if (attribute === "innerText") {
2381
+ if (state.info.regex) {
2382
+ if (!regex.test(val)) {
2383
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2384
+ state.info.failCause.assertionFailed = true;
2385
+ state.info.failCause.lastError = errorMessage;
2386
+ throw new Error(errorMessage);
2387
+ }
2388
+ }
2389
+ else {
2390
+ const valLines = val.split("\n");
2391
+ const expectedLines = expectedValue.split("\n");
2392
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine === expectedLine));
2393
+ if (!isPart) {
2394
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2395
+ state.info.failCause.assertionFailed = true;
2396
+ state.info.failCause.lastError = errorMessage;
2397
+ throw new Error(errorMessage);
2398
+ }
2399
+ }
2400
+ }
2401
+ else {
2402
+ if (!val.match(regex)) {
2403
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2404
+ state.info.failCause.assertionFailed = true;
2405
+ state.info.failCause.lastError = errorMessage;
2406
+ throw new Error(errorMessage);
2407
+ }
2408
+ }
2409
+ return state.info;
2410
+ }
2411
+ catch (e) {
2412
+ await _commandError(state, e, this);
2413
+ }
2414
+ finally {
2415
+ await _commandFinally(state, this);
2416
+ }
2417
+ }
2418
+ async verifyProperty(selectors, property, value, _params = null, options = {}, world = null) {
2419
+ const state = {
2420
+ selectors,
2421
+ _params,
2422
+ property,
2423
+ value,
2424
+ options,
2425
+ world,
2426
+ type: Types.VERIFY_PROPERTY,
2427
+ highlight: true,
2428
+ screenshot: true,
2429
+ text: `Verify element property`,
2430
+ _text: `Verify property ${property} from ${selectors.element_name} is ${value}`,
2431
+ operation: "verifyProperty",
2432
+ log: "***** verify property " + property + " from " + selectors.element_name + " *****\n",
2433
+ allowDisabled: true,
2434
+ };
2435
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2436
+ let val;
2437
+ let expectedValue;
2438
+ try {
2439
+ await _preCommand(state, this);
2440
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2441
+ state.info.expectedValue = expectedValue;
2442
+ switch (property) {
2443
+ case "innerText":
2444
+ val = String(await state.element.innerText());
2445
+ break;
2446
+ case "text":
2447
+ val = String(await state.element.textContent());
2448
+ break;
2449
+ case "value":
2450
+ val = String(await state.element.inputValue());
2451
+ break;
2452
+ case "checked":
2453
+ val = String(await state.element.isChecked());
2454
+ break;
2455
+ case "disabled":
2456
+ val = String(await state.element.isDisabled());
2457
+ break;
2458
+ case "readOnly":
2459
+ const isEditable = await state.element.isEditable();
2460
+ val = String(!isEditable);
2461
+ break;
2462
+ case "innerHTML":
2463
+ val = String(await state.element.innerHTML());
2464
+ break;
2465
+ case "outerHTML":
2466
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2467
+ break;
2468
+ default:
2469
+ if (property.startsWith("dataset.")) {
2470
+ const dataAttribute = property.substring(8);
2471
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2472
+ }
2473
+ else {
2474
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2475
+ }
2476
+ }
2477
+ // Helper function to remove all style="" attributes
2478
+ const removeStyleAttributes = (htmlString) => {
2479
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2480
+ };
2481
+ // Remove style attributes for innerHTML and outerHTML properties
2482
+ if (property === "innerHTML" || property === "outerHTML") {
2483
+ val = removeStyleAttributes(val);
2484
+ expectedValue = removeStyleAttributes(expectedValue);
2485
+ }
2486
+ state.info.value = val;
2487
+ let regex;
2488
+ state.info.value = val;
2489
+ const isRegex = expectedValue.startsWith("regex:");
2490
+ const isContains = expectedValue.startsWith("contains:");
2491
+ const isExact = expectedValue.startsWith("exact:");
2492
+ let matchPassed = false;
2493
+ if (isRegex) {
2494
+ const rawPattern = expectedValue.slice(6); // remove "regex:"
2495
+ const lastSlashIndex = rawPattern.lastIndexOf("/");
2496
+ if (rawPattern.startsWith("/") && lastSlashIndex > 0) {
2497
+ const patternBody = rawPattern.slice(1, lastSlashIndex).replace(/\n/g, ".*");
2498
+ const flags = rawPattern.slice(lastSlashIndex + 1) || "gs";
2499
+ const regex = new RegExp(patternBody, flags);
2500
+ state.info.regex = true;
2501
+ matchPassed = regex.test(val);
2502
+ }
2503
+ else {
2504
+ // Fallback: treat as literal
2505
+ const escapedPattern = rawPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2506
+ const regex = new RegExp(escapedPattern, "g");
2507
+ matchPassed = regex.test(val);
2508
+ }
2509
+ }
2510
+ else if (isContains) {
2511
+ const containsValue = expectedValue.slice(9); // remove "contains:"
2512
+ matchPassed = val.includes(containsValue);
2513
+ }
2514
+ else if (isExact) {
2515
+ const exactValue = expectedValue.slice(6); // remove "exact:"
2516
+ matchPassed = val === exactValue;
2517
+ }
2518
+ else if (property === "innerText") {
2519
+ // Default innerText logic
2520
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2521
+ const valLines = val.split("\n");
2522
+ const expectedLines = normalizedExpectedValue.split("\n");
2523
+ matchPassed = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2524
+ }
2525
+ else {
2526
+ // Fallback exact or loose match
2527
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2528
+ const regex = new RegExp(escapedPattern, "g");
2529
+ matchPassed = regex.test(val);
2530
+ }
2531
+ if (!matchPassed) {
2532
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2134
2533
  state.info.failCause.assertionFailed = true;
2135
2534
  state.info.failCause.lastError = errorMessage;
2136
2535
  throw new Error(errorMessage);
@@ -2144,6 +2543,132 @@ class StableBrowser {
2144
2543
  await _commandFinally(state, this);
2145
2544
  }
2146
2545
  }
2546
+ async conditionalWait(selectors, condition, timeout = 1000, _params = null, options = {}, world = null) {
2547
+ // Convert timeout from seconds to milliseconds
2548
+ const timeoutMs = timeout * 1000;
2549
+ const state = {
2550
+ selectors,
2551
+ _params,
2552
+ condition,
2553
+ timeout: timeoutMs, // Store as milliseconds for internal use
2554
+ options,
2555
+ world,
2556
+ type: Types.CONDITIONAL_WAIT,
2557
+ highlight: true,
2558
+ screenshot: true,
2559
+ text: `Conditional wait for element`,
2560
+ _text: `Wait for ${selectors.element_name} to be ${condition} (timeout: ${timeout}s)`, // Display original seconds
2561
+ operation: "conditionalWait",
2562
+ log: `***** conditional wait for ${condition} on ${selectors.element_name} *****\n`,
2563
+ allowDisabled: true,
2564
+ info: {},
2565
+ };
2566
+ // Initialize startTime outside try block to ensure it's always accessible
2567
+ const startTime = Date.now();
2568
+ let conditionMet = false;
2569
+ let currentValue = null;
2570
+ let lastError = null;
2571
+ // Main retry loop - continues until timeout or condition is met
2572
+ while (Date.now() - startTime < timeoutMs) {
2573
+ const elapsedTime = Date.now() - startTime;
2574
+ const remainingTime = timeoutMs - elapsedTime;
2575
+ try {
2576
+ // Try to execute _preCommand (element location)
2577
+ await _preCommand(state, this);
2578
+ // If _preCommand succeeds, start condition checking
2579
+ const checkCondition = async () => {
2580
+ try {
2581
+ switch (condition.toLowerCase()) {
2582
+ case "checked":
2583
+ currentValue = await state.element.isChecked();
2584
+ return currentValue === true;
2585
+ case "unchecked":
2586
+ currentValue = await state.element.isChecked();
2587
+ return currentValue === false;
2588
+ case "visible":
2589
+ currentValue = await state.element.isVisible();
2590
+ return currentValue === true;
2591
+ case "hidden":
2592
+ currentValue = await state.element.isVisible();
2593
+ return currentValue === false;
2594
+ case "enabled":
2595
+ currentValue = await state.element.isDisabled();
2596
+ return currentValue === false;
2597
+ case "disabled":
2598
+ currentValue = await state.element.isDisabled();
2599
+ return currentValue === true;
2600
+ case "editable":
2601
+ // currentValue = await String(await state.element.evaluate((element, prop) => element[prop], "isContentEditable"));
2602
+ currentValue = await state.element.isContentEditable();
2603
+ return currentValue === true;
2604
+ default:
2605
+ state.info.message = `Unsupported condition: '${condition}'. Supported conditions are: checked, unchecked, visible, hidden, enabled, disabled, editable.`;
2606
+ state.info.success = false;
2607
+ return false;
2608
+ }
2609
+ }
2610
+ catch (error) {
2611
+ // Don't throw here, just return false to continue retrying
2612
+ return false;
2613
+ }
2614
+ };
2615
+ // Inner loop for condition checking (once element is located)
2616
+ while (Date.now() - startTime < timeoutMs) {
2617
+ const currentElapsedTime = Date.now() - startTime;
2618
+ conditionMet = await checkCondition();
2619
+ if (conditionMet) {
2620
+ break;
2621
+ }
2622
+ // Check if we still have time for another attempt
2623
+ if (Date.now() - startTime + 50 < timeoutMs) {
2624
+ await new Promise((res) => setTimeout(res, 50));
2625
+ }
2626
+ else {
2627
+ break;
2628
+ }
2629
+ }
2630
+ // If we got here and condition is met, break out of main loop
2631
+ if (conditionMet) {
2632
+ break;
2633
+ }
2634
+ // If condition not met but no exception, we've timed out
2635
+ break;
2636
+ }
2637
+ catch (e) {
2638
+ lastError = e;
2639
+ const currentElapsedTime = Date.now() - startTime;
2640
+ const timeLeft = timeoutMs - currentElapsedTime;
2641
+ // Check if we have enough time left to retry
2642
+ if (timeLeft > 100) {
2643
+ await new Promise((resolve) => setTimeout(resolve, 50));
2644
+ }
2645
+ else {
2646
+ break;
2647
+ }
2648
+ }
2649
+ }
2650
+ const actualWaitTime = Date.now() - startTime;
2651
+ state.info = {
2652
+ success: conditionMet,
2653
+ conditionMet,
2654
+ actualWaitTime,
2655
+ currentValue,
2656
+ lastError: lastError?.message || null,
2657
+ message: conditionMet
2658
+ ? `Condition '${condition}' met after ${(actualWaitTime / 1000).toFixed(2)}s`
2659
+ : `Condition '${condition}' not met within ${timeout}s timeout`,
2660
+ };
2661
+ if (lastError) {
2662
+ state.log += `Last error: ${lastError.message}\n`;
2663
+ }
2664
+ try {
2665
+ await _commandFinally(state, this);
2666
+ }
2667
+ catch (finallyError) {
2668
+ state.log += `Error in _commandFinally: ${finallyError.message}\n`;
2669
+ }
2670
+ return state.info;
2671
+ }
2147
2672
  async extractEmailData(emailAddress, options, world) {
2148
2673
  if (!emailAddress) {
2149
2674
  throw new Error("email address is null");
@@ -2301,56 +2826,49 @@ class StableBrowser {
2301
2826
  console.debug(error);
2302
2827
  }
2303
2828
  }
2304
- // async _unhighlightElements(scope, css) {
2305
- // try {
2306
- // if (!scope) {
2307
- // return;
2308
- // }
2309
- // if (!css) {
2310
- // scope
2311
- // .evaluate((node) => {
2312
- // if (node && node.style) {
2313
- // if (!node.__previousOutline) {
2314
- // node.style.outline = "";
2315
- // } else {
2316
- // node.style.outline = node.__previousOutline;
2317
- // }
2318
- // }
2319
- // })
2320
- // .then(() => {})
2321
- // .catch((e) => {
2322
- // // console.log(`Error while unhighlighting node ${JSON.stringify(scope)}: ${e}`);
2323
- // });
2324
- // } else {
2325
- // scope
2326
- // .evaluate(([css]) => {
2327
- // if (!css) {
2328
- // return;
2329
- // }
2330
- // let elements = Array.from(document.querySelectorAll(css));
2331
- // for (i = 0; i < elements.length; i++) {
2332
- // let element = elements[i];
2333
- // if (!element.style) {
2334
- // return;
2335
- // }
2336
- // if (!element.__previousOutline) {
2337
- // element.style.outline = "";
2338
- // } else {
2339
- // element.style.outline = element.__previousOutline;
2340
- // }
2341
- // }
2342
- // })
2343
- // .then(() => {})
2344
- // .catch((e) => {
2345
- // // console.error(`Error while unhighlighting element in css: ${e}`);
2346
- // });
2347
- // }
2348
- // } catch (error) {
2349
- // // console.debug(error);
2350
- // }
2351
- // }
2829
+ _matcher(text) {
2830
+ if (!text) {
2831
+ return { matcher: "contains", queryText: "" };
2832
+ }
2833
+ if (text.length < 2) {
2834
+ return { matcher: "contains", queryText: text };
2835
+ }
2836
+ const split = text.split(":");
2837
+ const matcher = split[0].toLowerCase();
2838
+ const queryText = split.slice(1).join(":").trim();
2839
+ return { matcher, queryText };
2840
+ }
2841
+ _getDomain(url) {
2842
+ if (url.length === 0 || (!url.startsWith("http://") && !url.startsWith("https://"))) {
2843
+ return "";
2844
+ }
2845
+ let hostnameFragments = url.split("/")[2].split(".");
2846
+ if (hostnameFragments.some((fragment) => fragment.includes(":"))) {
2847
+ return hostnameFragments.join("-").split(":").join("-");
2848
+ }
2849
+ let n = hostnameFragments.length;
2850
+ let fragments = [...hostnameFragments];
2851
+ while (n > 0 && hostnameFragments[n - 1].length <= 3) {
2852
+ hostnameFragments.pop();
2853
+ n = hostnameFragments.length;
2854
+ }
2855
+ if (n == 0) {
2856
+ if (fragments[0] === "www")
2857
+ fragments = fragments.slice(1);
2858
+ return fragments.length > 1 ? fragments.slice(0, fragments.length - 1).join("-") : fragments.join("-");
2859
+ }
2860
+ if (hostnameFragments[0] === "www")
2861
+ hostnameFragments = hostnameFragments.slice(1);
2862
+ return hostnameFragments.join(".");
2863
+ }
2864
+ /**
2865
+ * Verify the page path matches the given path.
2866
+ * @param {string} pathPart - The path to verify.
2867
+ * @param {object} options - Options for verification.
2868
+ * @param {object} world - The world context.
2869
+ * @returns {Promise<object>} - The state info after verification.
2870
+ */
2352
2871
  async verifyPagePath(pathPart, options = {}, world = null) {
2353
- const startTime = Date.now();
2354
2872
  let error = null;
2355
2873
  let screenshotId = null;
2356
2874
  let screenshotPath = null;
@@ -2364,113 +2882,212 @@ class StableBrowser {
2364
2882
  pathPart = newValue;
2365
2883
  }
2366
2884
  info.pathPart = pathPart;
2885
+ const { matcher, queryText } = this._matcher(pathPart);
2886
+ const state = {
2887
+ text_search: queryText,
2888
+ options,
2889
+ world,
2890
+ locate: false,
2891
+ scroll: false,
2892
+ highlight: false,
2893
+ type: Types.VERIFY_PAGE_PATH,
2894
+ text: `Verify the page url is ${queryText}`,
2895
+ _text: `Verify the page url is ${queryText}`,
2896
+ operation: "verifyPagePath",
2897
+ log: "***** verify page url is " + queryText + " *****\n",
2898
+ };
2367
2899
  try {
2900
+ await _preCommand(state, this);
2901
+ state.info.text = queryText;
2368
2902
  for (let i = 0; i < 30; i++) {
2369
2903
  const url = await this.page.url();
2370
- if (!url.includes(pathPart)) {
2371
- if (i === 29) {
2372
- throw new Error(`url ${url} doesn't contain ${pathPart}`);
2373
- }
2374
- await new Promise((resolve) => setTimeout(resolve, 1000));
2375
- continue;
2904
+ switch (matcher) {
2905
+ case "exact":
2906
+ if (url !== queryText) {
2907
+ if (i === 29) {
2908
+ throw new Error(`Page URL ${url} is not equal to ${queryText}`);
2909
+ }
2910
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2911
+ continue;
2912
+ }
2913
+ break;
2914
+ case "contains":
2915
+ if (!url.includes(queryText)) {
2916
+ if (i === 29) {
2917
+ throw new Error(`Page URL ${url} doesn't contain ${queryText}`);
2918
+ }
2919
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2920
+ continue;
2921
+ }
2922
+ break;
2923
+ case "starts-with":
2924
+ {
2925
+ const domain = this._getDomain(url);
2926
+ if (domain.length > 0 && domain !== queryText) {
2927
+ if (i === 29) {
2928
+ throw new Error(`Page URL ${url} doesn't start with ${queryText}`);
2929
+ }
2930
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2931
+ continue;
2932
+ }
2933
+ }
2934
+ break;
2935
+ case "ends-with":
2936
+ {
2937
+ const urlObj = new URL(url);
2938
+ let route = "/";
2939
+ if (urlObj.pathname !== "/") {
2940
+ route = urlObj.pathname.split("/").slice(-1)[0].trim();
2941
+ }
2942
+ else {
2943
+ route = "/";
2944
+ }
2945
+ if (route !== queryText) {
2946
+ if (i === 29) {
2947
+ throw new Error(`Page URL ${url} doesn't end with ${queryText}`);
2948
+ }
2949
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2950
+ continue;
2951
+ }
2952
+ }
2953
+ break;
2954
+ case "regex":
2955
+ const regex = new RegExp(queryText.slice(1, -1), "g");
2956
+ if (!regex.test(url)) {
2957
+ if (i === 29) {
2958
+ throw new Error(`Page URL ${url} doesn't match regex ${queryText}`);
2959
+ }
2960
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2961
+ continue;
2962
+ }
2963
+ break;
2964
+ default:
2965
+ console.log("Unknown matching type, defaulting to contains matching");
2966
+ if (!url.includes(pathPart)) {
2967
+ if (i === 29) {
2968
+ throw new Error(`Page URL ${url} does not contain ${pathPart}`);
2969
+ }
2970
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2971
+ continue;
2972
+ }
2376
2973
  }
2377
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2378
- return info;
2974
+ await _screenshot(state, this);
2975
+ return state.info;
2379
2976
  }
2380
2977
  }
2381
2978
  catch (e) {
2382
- //await this.closeUnexpectedPopups();
2383
- this.logger.error("verify page path failed " + info.log);
2384
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2385
- info.screenshotPath = screenshotPath;
2386
- Object.assign(e, { info: info });
2387
- error = e;
2388
- // throw e;
2389
- await _commandError({ text: "verifyPagePath", operation: "verifyPagePath", pathPart, info }, e, this);
2979
+ state.info.failCause.lastError = e.message;
2980
+ state.info.failCause.assertionFailed = true;
2981
+ await _commandError(state, e, this);
2390
2982
  }
2391
2983
  finally {
2392
- const endTime = Date.now();
2393
- _reportToWorld(world, {
2394
- type: Types.VERIFY_PAGE_PATH,
2395
- text: "Verify page path",
2396
- _text: "Verify the page path contains " + pathPart,
2397
- screenshotId,
2398
- result: error
2399
- ? {
2400
- status: "FAILED",
2401
- startTime,
2402
- endTime,
2403
- message: error?.message,
2404
- }
2405
- : {
2406
- status: "PASSED",
2407
- startTime,
2408
- endTime,
2409
- },
2410
- info: info,
2411
- });
2984
+ await _commandFinally(state, this);
2412
2985
  }
2413
2986
  }
2987
+ /**
2988
+ * Verify the page title matches the given title.
2989
+ * @param {string} title - The title to verify.
2990
+ * @param {object} options - Options for verification.
2991
+ * @param {object} world - The world context.
2992
+ * @returns {Promise<object>} - The state info after verification.
2993
+ */
2414
2994
  async verifyPageTitle(title, options = {}, world = null) {
2415
- const startTime = Date.now();
2416
2995
  let error = null;
2417
2996
  let screenshotId = null;
2418
2997
  let screenshotPath = null;
2419
2998
  await new Promise((resolve) => setTimeout(resolve, 2000));
2420
- const info = {};
2421
- info.log = "***** verify page title " + title + " *****\n";
2422
- info.operation = "verifyPageTitle";
2423
2999
  const newValue = await this._replaceWithLocalData(title, world);
2424
3000
  if (newValue !== title) {
2425
3001
  this.logger.info(title + "=" + newValue);
2426
3002
  title = newValue;
2427
3003
  }
2428
- info.title = title;
3004
+ const { matcher, queryText } = this._matcher(title);
3005
+ const state = {
3006
+ text_search: queryText,
3007
+ options,
3008
+ world,
3009
+ locate: false,
3010
+ scroll: false,
3011
+ highlight: false,
3012
+ type: Types.VERIFY_PAGE_TITLE,
3013
+ text: `Verify the page title is ${queryText}`,
3014
+ _text: `Verify the page title is ${queryText}`,
3015
+ operation: "verifyPageTitle",
3016
+ log: "***** verify page title is " + queryText + " *****\n",
3017
+ };
2429
3018
  try {
3019
+ await _preCommand(state, this);
3020
+ state.info.text = queryText;
2430
3021
  for (let i = 0; i < 30; i++) {
2431
3022
  const foundTitle = await this.page.title();
2432
- if (!foundTitle.includes(title)) {
2433
- if (i === 29) {
2434
- throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2435
- }
2436
- await new Promise((resolve) => setTimeout(resolve, 1000));
2437
- continue;
3023
+ switch (matcher) {
3024
+ case "exact":
3025
+ if (foundTitle !== queryText) {
3026
+ if (i === 29) {
3027
+ throw new Error(`Page Title ${foundTitle} is not equal to ${queryText}`);
3028
+ }
3029
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3030
+ continue;
3031
+ }
3032
+ break;
3033
+ case "contains":
3034
+ if (!foundTitle.includes(queryText)) {
3035
+ if (i === 29) {
3036
+ throw new Error(`Page Title ${foundTitle} doesn't contain ${queryText}`);
3037
+ }
3038
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3039
+ continue;
3040
+ }
3041
+ break;
3042
+ case "starts-with":
3043
+ if (!foundTitle.startsWith(queryText)) {
3044
+ if (i === 29) {
3045
+ throw new Error(`Page title ${foundTitle} doesn't start with ${queryText}`);
3046
+ }
3047
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3048
+ continue;
3049
+ }
3050
+ break;
3051
+ case "ends-with":
3052
+ if (!foundTitle.endsWith(queryText)) {
3053
+ if (i === 29) {
3054
+ throw new Error(`Page Title ${foundTitle} doesn't end with ${queryText}`);
3055
+ }
3056
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3057
+ continue;
3058
+ }
3059
+ break;
3060
+ case "regex":
3061
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3062
+ if (!regex.test(foundTitle)) {
3063
+ if (i === 29) {
3064
+ throw new Error(`Page Title ${foundTitle} doesn't match regex ${queryText}`);
3065
+ }
3066
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3067
+ continue;
3068
+ }
3069
+ break;
3070
+ default:
3071
+ console.log("Unknown matching type, defaulting to contains matching");
3072
+ if (!foundTitle.includes(title)) {
3073
+ if (i === 29) {
3074
+ throw new Error(`Page Title ${foundTitle} does not contain ${title}`);
3075
+ }
3076
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3077
+ continue;
3078
+ }
2438
3079
  }
2439
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2440
- return info;
3080
+ await _screenshot(state, this);
3081
+ return state.info;
2441
3082
  }
2442
3083
  }
2443
3084
  catch (e) {
2444
- //await this.closeUnexpectedPopups();
2445
- this.logger.error("verify page title failed " + info.log);
2446
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2447
- info.screenshotPath = screenshotPath;
2448
- Object.assign(e, { info: info });
2449
- error = e;
2450
- // throw e;
2451
- await _commandError({ text: "verifyPageTitle", operation: "verifyPageTitle", title, info, throwError: true }, e, this);
3085
+ state.info.failCause.lastError = e.message;
3086
+ state.info.failCause.assertionFailed = true;
3087
+ await _commandError(state, e, this);
2452
3088
  }
2453
3089
  finally {
2454
- const endTime = Date.now();
2455
- _reportToWorld(world, {
2456
- type: Types.VERIFY_PAGE_PATH,
2457
- text: "Verify page title",
2458
- _text: "Verify the page title contains " + title,
2459
- screenshotId,
2460
- result: error
2461
- ? {
2462
- status: "FAILED",
2463
- startTime,
2464
- endTime,
2465
- message: error?.message,
2466
- }
2467
- : {
2468
- status: "PASSED",
2469
- startTime,
2470
- endTime,
2471
- },
2472
- info: info,
2473
- });
3090
+ await _commandFinally(state, this);
2474
3091
  }
2475
3092
  }
2476
3093
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2554,27 +3171,10 @@ class StableBrowser {
2554
3171
  const frame = resultWithElementsFound[0].frame;
2555
3172
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2556
3173
  await this._highlightElements(frame, dataAttribute);
2557
- // if (world && world.screenshot && !world.screenshotPath) {
2558
- // console.log(`Highlighting for verify text is found while running from recorder`);
2559
- // this._highlightElements(frame, dataAttribute).then(async () => {
2560
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2561
- // this._unhighlightElements(frame, dataAttribute)
2562
- // .then(async () => {
2563
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2564
- // })
2565
- // .catch(
2566
- // (e) => {}
2567
- // console.error(e)
2568
- // );
2569
- // });
2570
- // }
2571
3174
  const element = await frame.locator(dataAttribute).first();
2572
- // await new Promise((resolve) => setTimeout(resolve, 100));
2573
- // await this._unhighlightElements(frame, dataAttribute);
2574
3175
  if (element) {
2575
3176
  await this.scrollIfNeeded(element, state.info);
2576
3177
  await element.dispatchEvent("bvt_verify_page_contains_text");
2577
- // await _screenshot(state, this, element);
2578
3178
  }
2579
3179
  }
2580
3180
  await _screenshot(state, this);
@@ -2584,7 +3184,6 @@ class StableBrowser {
2584
3184
  console.error(error);
2585
3185
  }
2586
3186
  }
2587
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2588
3187
  }
2589
3188
  catch (e) {
2590
3189
  await _commandError(state, e, this);
@@ -2666,6 +3265,8 @@ class StableBrowser {
2666
3265
  operation: "verify_text_with_relation",
2667
3266
  log: "***** search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found *****\n",
2668
3267
  };
3268
+ const cmdStartTime = Date.now();
3269
+ let cmdEndTime = null;
2669
3270
  const timeout = this._getFindElementTimeout(options);
2670
3271
  await new Promise((resolve) => setTimeout(resolve, 2000));
2671
3272
  let newValue = await this._replaceWithLocalData(textAnchor, world);
@@ -2701,6 +3302,17 @@ class StableBrowser {
2701
3302
  await new Promise((resolve) => setTimeout(resolve, 1000));
2702
3303
  continue;
2703
3304
  }
3305
+ else {
3306
+ cmdEndTime = Date.now();
3307
+ if (cmdEndTime - cmdStartTime > 55000) {
3308
+ if (foundAncore) {
3309
+ throw new Error(`Text ${textToVerify} not found in page`);
3310
+ }
3311
+ else {
3312
+ throw new Error(`Text ${textAnchor} not found in page`);
3313
+ }
3314
+ }
3315
+ }
2704
3316
  try {
2705
3317
  for (let i = 0; i < resultWithElementsFound.length; i++) {
2706
3318
  foundAncore = true;
@@ -3100,8 +3712,51 @@ class StableBrowser {
3100
3712
  });
3101
3713
  }
3102
3714
  }
3715
+ /**
3716
+ * Explicit wait/sleep function that pauses execution for a specified duration
3717
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3718
+ * @param options - Optional configuration object
3719
+ * @param world - Optional world context
3720
+ * @returns Promise that resolves after the specified duration
3721
+ */
3722
+ async sleep(duration = 1000, options = {}, world = null) {
3723
+ const state = {
3724
+ duration,
3725
+ options,
3726
+ world,
3727
+ locate: false,
3728
+ scroll: false,
3729
+ screenshot: false,
3730
+ highlight: false,
3731
+ type: Types.SLEEP,
3732
+ text: `Sleep for ${duration} ms`,
3733
+ _text: `Sleep for ${duration} ms`,
3734
+ operation: "sleep",
3735
+ log: `***** Sleep for ${duration} ms *****\n`,
3736
+ };
3737
+ try {
3738
+ await _preCommand(state, this);
3739
+ if (duration < 0) {
3740
+ throw new Error("Sleep duration cannot be negative");
3741
+ }
3742
+ await new Promise((resolve) => setTimeout(resolve, duration));
3743
+ return state.info;
3744
+ }
3745
+ catch (e) {
3746
+ await _commandError(state, e, this);
3747
+ }
3748
+ finally {
3749
+ await _commandFinally(state, this);
3750
+ }
3751
+ }
3103
3752
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3104
- return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3753
+ try {
3754
+ return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
3755
+ }
3756
+ catch (error) {
3757
+ this.logger.debug(error);
3758
+ throw error;
3759
+ }
3105
3760
  }
3106
3761
  _getLoadTimeout(options) {
3107
3762
  let timeout = 15000;
@@ -3124,6 +3779,7 @@ class StableBrowser {
3124
3779
  }
3125
3780
  async saveStoreState(path = null, world = null) {
3126
3781
  const storageState = await this.page.context().storageState();
3782
+ path = await this._replaceWithLocalData(path, this.world);
3127
3783
  //const testDataFile = _getDataFile(world, this.context, this);
3128
3784
  if (path) {
3129
3785
  // save { storageState: storageState } into the path
@@ -3134,10 +3790,14 @@ class StableBrowser {
3134
3790
  }
3135
3791
  }
3136
3792
  async restoreSaveState(path = null, world = null) {
3793
+ path = await this._replaceWithLocalData(path, this.world);
3137
3794
  await refreshBrowser(this, path, world);
3138
3795
  this.registerEventListeners(this.context);
3139
3796
  registerNetworkEvents(this.world, this, this.context, this.page);
3140
3797
  registerDownloadEvent(this.page, this.world, this.context);
3798
+ if (this.onRestoreSaveState) {
3799
+ this.onRestoreSaveState(path);
3800
+ }
3141
3801
  }
3142
3802
  async waitForPageLoad(options = {}, world = null) {
3143
3803
  let timeout = this._getLoadTimeout(options);
@@ -3172,7 +3832,6 @@ class StableBrowser {
3172
3832
  else if (e.label === "domcontentloaded") {
3173
3833
  console.log("waited for the domcontent loaded timeout");
3174
3834
  }
3175
- console.log(".");
3176
3835
  }
3177
3836
  finally {
3178
3837
  await new Promise((resolve) => setTimeout(resolve, 2000));
@@ -3216,7 +3875,6 @@ class StableBrowser {
3216
3875
  await this.page.close();
3217
3876
  }
3218
3877
  catch (e) {
3219
- console.log(".");
3220
3878
  await _commandError(state, e, this);
3221
3879
  }
3222
3880
  finally {
@@ -3331,7 +3989,6 @@ class StableBrowser {
3331
3989
  await this.page.setViewportSize({ width: width, height: hight });
3332
3990
  }
3333
3991
  catch (e) {
3334
- console.log(".");
3335
3992
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3336
3993
  }
3337
3994
  finally {
@@ -3369,7 +4026,6 @@ class StableBrowser {
3369
4026
  await this.page.reload();
3370
4027
  }
3371
4028
  catch (e) {
3372
- console.log(".");
3373
4029
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3374
4030
  }
3375
4031
  finally {
@@ -3413,6 +4069,10 @@ class StableBrowser {
3413
4069
  }
3414
4070
  }
3415
4071
  async beforeScenario(world, scenario) {
4072
+ if (world && world.attach) {
4073
+ world.attach(this.context.reportFolder, { mediaType: "text/plain" });
4074
+ }
4075
+ this.context.loadedRoutes = null;
3416
4076
  this.beforeScenarioCalled = true;
3417
4077
  if (scenario && scenario.pickle && scenario.pickle.name) {
3418
4078
  this.scenarioName = scenario.pickle.name;
@@ -3436,14 +4096,18 @@ class StableBrowser {
3436
4096
  envName = this.context.environment.name;
3437
4097
  }
3438
4098
  if (!process.env.TEMP_RUN) {
3439
- await getTestData(envName, world, undefined, this.featureName, this.scenarioName);
4099
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
3440
4100
  }
3441
4101
  await loadBrunoParams(this.context, this.context.environment.name);
3442
4102
  }
3443
4103
  async afterScenario(world, scenario) { }
3444
4104
  async beforeStep(world, step) {
4105
+ if (this.abortedExecution) {
4106
+ throw new Error("Aborted");
4107
+ }
3445
4108
  if (!this.beforeScenarioCalled) {
3446
4109
  this.beforeScenario(world, step);
4110
+ this.context.loadedRoutes = null;
3447
4111
  }
3448
4112
  if (this.stepIndex === undefined) {
3449
4113
  this.stepIndex = 0;
@@ -3468,13 +4132,16 @@ class StableBrowser {
3468
4132
  }
3469
4133
  if (this.initSnapshotTaken === false) {
3470
4134
  this.initSnapshotTaken = true;
3471
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4135
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3472
4136
  const snapshot = await this.getAriaSnapshot();
3473
4137
  if (snapshot) {
3474
4138
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3475
4139
  }
3476
4140
  }
3477
4141
  }
4142
+ this.context.routeResults = null;
4143
+ await registerBeforeStepRoutes(this.context, this.stepName);
4144
+ networkBeforeStep(this.stepName);
3478
4145
  }
3479
4146
  async getAriaSnapshot() {
3480
4147
  try {
@@ -3490,19 +4157,74 @@ class StableBrowser {
3490
4157
  const content = [`- path: ${path}`, `- title: ${title}`];
3491
4158
  const timeout = this.configuration.ariaSnapshotTimeout ? this.configuration.ariaSnapshotTimeout : 3000;
3492
4159
  for (let i = 0; i < frames.length; i++) {
3493
- content.push(`- frame: ${i}`);
3494
4160
  const frame = frames[i];
3495
- const snapshot = await frame.locator("body").ariaSnapshot({ timeout });
3496
- content.push(snapshot);
4161
+ try {
4162
+ // Ensure frame is attached and has body
4163
+ const body = frame.locator("body");
4164
+ //await body.waitFor({ timeout: 2000 }); // wait explicitly
4165
+ const snapshot = await body.ariaSnapshot({ timeout });
4166
+ if (!snapshot) {
4167
+ continue;
4168
+ }
4169
+ content.push(`- frame: ${i}`);
4170
+ content.push(snapshot);
4171
+ }
4172
+ catch (innerErr) {
4173
+ console.warn(`Frame ${i} snapshot failed:`, innerErr);
4174
+ content.push(`- frame: ${i} - error: ${innerErr.message}`);
4175
+ }
3497
4176
  }
3498
4177
  return content.join("\n");
3499
4178
  }
3500
4179
  catch (e) {
3501
4180
  console.log("Error in getAriaSnapshot");
3502
- console.debug(e);
4181
+ //console.debug(e);
3503
4182
  }
3504
4183
  return null;
3505
4184
  }
4185
+ /**
4186
+ * Sends command with custom payload to report.
4187
+ * @param commandText - Title of the command to be shown in the report.
4188
+ * @param commandStatus - Status of the command (e.g. "PASSED", "FAILED").
4189
+ * @param content - Content of the command to be shown in the report.
4190
+ * @param options - Options for the command. Example: { type: "json", screenshot: true }
4191
+ * @param world - Optional world context.
4192
+ * @public
4193
+ */
4194
+ async addCommandToReport(commandText, commandStatus, content, options = {}, world = null) {
4195
+ const state = {
4196
+ options,
4197
+ world,
4198
+ locate: false,
4199
+ scroll: false,
4200
+ screenshot: options.screenshot ?? false,
4201
+ highlight: options.highlight ?? false,
4202
+ type: Types.REPORT_COMMAND,
4203
+ text: commandText,
4204
+ _text: commandText,
4205
+ operation: "report_command",
4206
+ log: "***** " + commandText + " *****\n",
4207
+ };
4208
+ try {
4209
+ await _preCommand(state, this);
4210
+ const payload = {
4211
+ type: options.type ?? "text",
4212
+ content: content,
4213
+ screenshotId: null,
4214
+ };
4215
+ state.payload = payload;
4216
+ if (commandStatus === "FAILED") {
4217
+ state.throwError = true;
4218
+ throw new Error("Command failed");
4219
+ }
4220
+ }
4221
+ catch (e) {
4222
+ await _commandError(state, e, this);
4223
+ }
4224
+ finally {
4225
+ await _commandFinally(state, this);
4226
+ }
4227
+ }
3506
4228
  async afterStep(world, step) {
3507
4229
  this.stepName = null;
3508
4230
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3510,10 +4232,12 @@ class StableBrowser {
3510
4232
  await this.context.browserObject.context.tracing.stopChunk({
3511
4233
  path: path.join(this.context.browserObject.traceFolder, `trace-${this.stepIndex}.zip`),
3512
4234
  });
3513
- await world.attach(JSON.stringify({
3514
- type: "trace",
3515
- traceFilePath: `trace-${this.stepIndex}.zip`,
3516
- }), "application/json+trace");
4235
+ if (world && world.attach) {
4236
+ await world.attach(JSON.stringify({
4237
+ type: "trace",
4238
+ traceFilePath: `trace-${this.stepIndex}.zip`,
4239
+ }), "application/json+trace");
4240
+ }
3517
4241
  // console.log("trace file created", `trace-${this.stepIndex}.zip`);
3518
4242
  }
3519
4243
  }
@@ -3527,6 +4251,36 @@ class StableBrowser {
3527
4251
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3528
4252
  }
3529
4253
  }
4254
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4255
+ if (this.context.routeResults) {
4256
+ if (world && world.attach) {
4257
+ await world.attach(JSON.stringify(this.context.routeResults), "application/json+intercept-results");
4258
+ }
4259
+ }
4260
+ if (!process.env.TEMP_RUN) {
4261
+ const state = {
4262
+ world,
4263
+ locate: false,
4264
+ scroll: false,
4265
+ screenshot: true,
4266
+ highlight: true,
4267
+ type: Types.STEP_COMPLETE,
4268
+ text: "end of scenario",
4269
+ _text: "end of scenario",
4270
+ operation: "step_complete",
4271
+ log: "***** " + "end of scenario" + " *****\n",
4272
+ };
4273
+ try {
4274
+ await _preCommand(state, this);
4275
+ }
4276
+ catch (e) {
4277
+ await _commandError(state, e, this);
4278
+ }
4279
+ finally {
4280
+ await _commandFinally(state, this);
4281
+ }
4282
+ }
4283
+ networkAfterStep(this.stepName);
3530
4284
  }
3531
4285
  }
3532
4286
  function createTimedPromise(promise, label) {