automation_model 1.0.730-dev → 1.0.730-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 (47) hide show
  1. package/README.md +4 -1
  2. package/lib/api.js +4 -3
  3. package/lib/api.js.map +1 -1
  4. package/lib/auto_page.d.ts +4 -2
  5. package/lib/auto_page.js +153 -86
  6. package/lib/auto_page.js.map +1 -1
  7. package/lib/browser_manager.js +19 -25
  8. package/lib/browser_manager.js.map +1 -1
  9. package/lib/bruno.js.map +1 -1
  10. package/lib/check_performance.d.ts +1 -0
  11. package/lib/check_performance.js +57 -0
  12. package/lib/check_performance.js.map +1 -0
  13. package/lib/command_common.js +18 -2
  14. package/lib/command_common.js.map +1 -1
  15. package/lib/file_checker.js +129 -25
  16. package/lib/file_checker.js.map +1 -1
  17. package/lib/index.js +1 -0
  18. package/lib/index.js.map +1 -1
  19. package/lib/init_browser.d.ts +1 -2
  20. package/lib/init_browser.js +121 -125
  21. package/lib/init_browser.js.map +1 -1
  22. package/lib/locator.d.ts +1 -0
  23. package/lib/locator.js +9 -2
  24. package/lib/locator.js.map +1 -1
  25. package/lib/network.d.ts +2 -0
  26. package/lib/network.js +374 -86
  27. package/lib/network.js.map +1 -1
  28. package/lib/route.d.ts +21 -0
  29. package/lib/route.js +533 -0
  30. package/lib/route.js.map +1 -0
  31. package/lib/scripts/axe.mini.js +3 -3
  32. package/lib/snapshot_validation.js.map +1 -1
  33. package/lib/stable_browser.d.ts +27 -2
  34. package/lib/stable_browser.js +811 -76
  35. package/lib/stable_browser.js.map +1 -1
  36. package/lib/table.d.ts +9 -7
  37. package/lib/table.js +82 -12
  38. package/lib/table.js.map +1 -1
  39. package/lib/table_helper.js +14 -0
  40. package/lib/table_helper.js.map +1 -1
  41. package/lib/test_context.d.ts +1 -0
  42. package/lib/test_context.js +1 -0
  43. package/lib/test_context.js.map +1 -1
  44. package/lib/utils.d.ts +3 -1
  45. package/lib/utils.js +38 -6
  46. package/lib/utils.js.map +1 -1
  47. package/package.json +11 -9
@@ -1,4 +1,5 @@
1
1
  // @ts-nocheck
2
+ import { check_performance } from "./check_performance.js";
2
3
  import { expect } from "@playwright/test";
3
4
  import dayjs from "dayjs";
4
5
  import fs from "fs";
@@ -10,7 +11,8 @@ import { getDateTimeValue } from "./date_time.js";
10
11
  import drawRectangle from "./drawRect.js";
11
12
  //import { closeUnexpectedPopups } from "./popups.js";
12
13
  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";
14
+ import errorStackParser from "error-stack-parser";
15
+ import { _convertToRegexQuery, _copyContext, _fixLocatorUsingParams, _fixUsingParams, _getServerUrl, extractStepExampleParameters, KEYBOARD_EVENTS, maskValue, replaceWithLocalTestData, scrollPageToLoadLazyElements, unEscapeString, _getDataFile, testForRegex, performAction, _getTestData, } from "./utils.js";
14
16
  import csv from "csv-parser";
15
17
  import { Readable } from "node:stream";
16
18
  import readline from "readline";
@@ -19,16 +21,20 @@ import { getTestData } from "./auto_page.js";
19
21
  import { locate_element } from "./locate_element.js";
20
22
  import { randomUUID } from "crypto";
21
23
  import { _commandError, _commandFinally, _preCommand, _validateSelectors, _screenshot, _reportToWorld, } from "./command_common.js";
22
- import { registerDownloadEvent, registerNetworkEvents } from "./network.js";
24
+ import { networkAfterStep, networkBeforeStep, registerDownloadEvent, registerNetworkEvents } from "./network.js";
23
25
  import { LocatorLog } from "./locator_log.js";
24
26
  import axios from "axios";
25
27
  import { _findCellArea, findElementsInArea } from "./table_helper.js";
26
- import { snapshotValidation } from "./snapshot_validation.js";
28
+ import { highlightSnapshot, snapshotValidation } from "./snapshot_validation.js";
27
29
  import { loadBrunoParams } from "./bruno.js";
30
+ import { registerAfterStepRoutes, registerBeforeStepRoutes } from "./route.js";
31
+ import { existsSync } from "node:fs";
28
32
  export const Types = {
29
33
  CLICK: "click_element",
30
34
  WAIT_ELEMENT: "wait_element",
31
- NAVIGATE: "navigate", ///
35
+ NAVIGATE: "navigate",
36
+ GO_BACK: "go_back",
37
+ GO_FORWARD: "go_forward",
32
38
  FILL: "fill_element",
33
39
  EXECUTE: "execute_page_method", //
34
40
  OPEN: "open_environment", //
@@ -41,6 +47,7 @@ export const Types = {
41
47
  VERIFY_PAGE_CONTAINS_NO_TEXT: "verify_page_contains_no_text",
42
48
  ANALYZE_TABLE: "analyze_table",
43
49
  SELECT: "select_combobox", //
50
+ VERIFY_PROPERTY: "verify_element_property",
44
51
  VERIFY_PAGE_PATH: "verify_page_path",
45
52
  VERIFY_PAGE_TITLE: "verify_page_title",
46
53
  TYPE_PRESS: "type_press",
@@ -49,6 +56,7 @@ export const Types = {
49
56
  CHECK: "check_element",
50
57
  UNCHECK: "uncheck_element",
51
58
  EXTRACT: "extract_attribute",
59
+ EXTRACT_PROPERTY: "extract_property",
52
60
  CLOSE_PAGE: "close_page",
53
61
  TABLE_OPERATION: "table_operation",
54
62
  SET_DATE_TIME: "set_date_time",
@@ -60,11 +68,13 @@ export const Types = {
60
68
  VERIFY_ATTRIBUTE: "verify_element_attribute",
61
69
  VERIFY_TEXT_WITH_RELATION: "verify_text_with_relation",
62
70
  BRUNO: "bruno",
63
- SNAPSHOT_VALIDATION: "snapshot_validation",
64
71
  VERIFY_FILE_EXISTS: "verify_file_exists",
65
72
  SET_INPUT_FILES: "set_input_files",
73
+ SNAPSHOT_VALIDATION: "snapshot_validation",
66
74
  REPORT_COMMAND: "report_command",
67
75
  STEP_COMPLETE: "step_complete",
76
+ SLEEP: "sleep",
77
+ CONDITIONAL_WAIT: "conditional_wait",
68
78
  };
69
79
  export const apps = {};
70
80
  const formatElementName = (elementName) => {
@@ -76,6 +86,8 @@ class StableBrowser {
76
86
  logger;
77
87
  context;
78
88
  world;
89
+ fastMode;
90
+ stepTags;
79
91
  project_path = null;
80
92
  webLogFile = null;
81
93
  networkLogger = null;
@@ -84,12 +96,15 @@ class StableBrowser {
84
96
  tags = null;
85
97
  isRecording = false;
86
98
  initSnapshotTaken = false;
87
- constructor(browser, page, logger = null, context = null, world = null) {
99
+ onlyFailuresScreenshot = process.env.SCREENSHOT_ON_FAILURE_ONLY === "true";
100
+ constructor(browser, page, logger = null, context = null, world = null, fastMode = false, stepTags = []) {
88
101
  this.browser = browser;
89
102
  this.page = page;
90
103
  this.logger = logger;
91
104
  this.context = context;
92
105
  this.world = world;
106
+ this.fastMode = fastMode;
107
+ this.stepTags = stepTags;
93
108
  if (!this.logger) {
94
109
  this.logger = console;
95
110
  }
@@ -118,6 +133,19 @@ class StableBrowser {
118
133
  context.pages = [this.page];
119
134
  const logFolder = path.join(this.project_path, "logs", "web");
120
135
  this.world = world;
136
+ if (this.configuration && this.configuration.fastMode === true) {
137
+ this.fastMode = true;
138
+ }
139
+ if (process.env.FAST_MODE === "true") {
140
+ // console.log("Fast mode enabled from environment variable");
141
+ this.fastMode = true;
142
+ }
143
+ if (process.env.FAST_MODE === "false") {
144
+ this.fastMode = false;
145
+ }
146
+ if (this.context) {
147
+ this.context.fastMode = this.fastMode;
148
+ }
121
149
  this.registerEventListeners(this.context);
122
150
  registerNetworkEvents(this.world, this, this.context, this.page);
123
151
  registerDownloadEvent(this.page, this.world, this.context);
@@ -128,6 +156,9 @@ class StableBrowser {
128
156
  if (!context.pageLoading) {
129
157
  context.pageLoading = { status: false };
130
158
  }
159
+ if (this.configuration && this.configuration.acceptDialog && this.page) {
160
+ this.page.on("dialog", (dialog) => dialog.accept());
161
+ }
131
162
  context.playContext.on("page", async function (page) {
132
163
  if (this.configuration && this.configuration.closePopups === true) {
133
164
  console.log("close unexpected popups");
@@ -136,11 +167,20 @@ class StableBrowser {
136
167
  }
137
168
  context.pageLoading.status = true;
138
169
  this.page = page;
170
+ try {
171
+ if (this.configuration && this.configuration.acceptDialog) {
172
+ await page.on("dialog", (dialog) => dialog.accept());
173
+ }
174
+ }
175
+ catch (error) {
176
+ console.error("Error on dialog accept registration", error);
177
+ }
139
178
  context.page = page;
140
179
  context.pages.push(page);
141
180
  registerNetworkEvents(this.world, this, context, this.page);
142
181
  registerDownloadEvent(this.page, this.world, context);
143
182
  page.on("close", async () => {
183
+ // return if browser context is already closed
144
184
  if (this.context && this.context.pages && this.context.pages.length > 1) {
145
185
  this.context.pages.pop();
146
186
  this.page = this.context.pages[this.context.pages.length - 1];
@@ -150,7 +190,12 @@ class StableBrowser {
150
190
  console.log("Switched to page " + title);
151
191
  }
152
192
  catch (error) {
153
- console.error("Error on page close", error);
193
+ if (error?.message?.includes("Target page, context or browser has been closed")) {
194
+ // Ignore this error
195
+ }
196
+ else {
197
+ console.error("Error on page close", error);
198
+ }
154
199
  }
155
200
  }
156
201
  });
@@ -159,7 +204,12 @@ class StableBrowser {
159
204
  console.log("Switch page: " + (await page.title()));
160
205
  }
161
206
  catch (e) {
162
- this.logger.error("error on page load " + e);
207
+ if (e?.message?.includes("Target page, context or browser has been closed")) {
208
+ // Ignore this error
209
+ }
210
+ else {
211
+ this.logger.error("error on page load " + e);
212
+ }
163
213
  }
164
214
  context.pageLoading.status = false;
165
215
  }.bind(this));
@@ -187,7 +237,9 @@ class StableBrowser {
187
237
  if (newContextCreated) {
188
238
  this.registerEventListeners(this.context);
189
239
  await this.goto(this.context.environment.baseUrl);
190
- await this.waitForPageLoad();
240
+ if (!this.fastMode && !this.stepTags.includes("fast-mode")) {
241
+ await this.waitForPageLoad();
242
+ }
191
243
  }
192
244
  }
193
245
  async switchTab(tabTitleOrIndex) {
@@ -313,6 +365,64 @@ class StableBrowser {
313
365
  await _commandFinally(state, this);
314
366
  }
315
367
  }
368
+ async goBack(options, world = null) {
369
+ const state = {
370
+ value: "",
371
+ world: world,
372
+ type: Types.GO_BACK,
373
+ text: `Browser navigate back`,
374
+ operation: "goBack",
375
+ log: "***** navigate back *****\n",
376
+ info: {},
377
+ locate: false,
378
+ scroll: false,
379
+ screenshot: false,
380
+ highlight: false,
381
+ };
382
+ try {
383
+ await _preCommand(state, this);
384
+ await this.page.goBack({
385
+ waitUntil: "load",
386
+ });
387
+ await _screenshot(state, this);
388
+ }
389
+ catch (error) {
390
+ console.error("Error on goBack", error);
391
+ _commandError(state, error, this);
392
+ }
393
+ finally {
394
+ await _commandFinally(state, this);
395
+ }
396
+ }
397
+ async goForward(options, world = null) {
398
+ const state = {
399
+ value: "",
400
+ world: world,
401
+ type: Types.GO_FORWARD,
402
+ text: `Browser navigate forward`,
403
+ operation: "goForward",
404
+ log: "***** navigate forward *****\n",
405
+ info: {},
406
+ locate: false,
407
+ scroll: false,
408
+ screenshot: false,
409
+ highlight: false,
410
+ };
411
+ try {
412
+ await _preCommand(state, this);
413
+ await this.page.goForward({
414
+ waitUntil: "load",
415
+ });
416
+ await _screenshot(state, this);
417
+ }
418
+ catch (error) {
419
+ console.error("Error on goForward", error);
420
+ _commandError(state, error, this);
421
+ }
422
+ finally {
423
+ await _commandFinally(state, this);
424
+ }
425
+ }
316
426
  async _getLocator(locator, scope, _params) {
317
427
  locator = _fixLocatorUsingParams(locator, _params);
318
428
  // locator = await this._replaceWithLocalData(locator);
@@ -411,12 +521,6 @@ class StableBrowser {
411
521
  if (!el.setAttribute) {
412
522
  el = el.parentElement;
413
523
  }
414
- // remove any attributes start with data-blinq-id
415
- // for (let i = 0; i < el.attributes.length; i++) {
416
- // if (el.attributes[i].name.startsWith("data-blinq-id")) {
417
- // el.removeAttribute(el.attributes[i].name);
418
- // }
419
- // }
420
524
  el.setAttribute("data-blinq-id-" + randomToken, "");
421
525
  return true;
422
526
  }, [tag1, randomToken]))) {
@@ -438,14 +542,13 @@ class StableBrowser {
438
542
  info.locatorLog = new LocatorLog(selectorHierarchy);
439
543
  }
440
544
  let locatorSearch = selectorHierarchy[index];
441
- let originalLocatorSearch = "";
442
545
  try {
443
- originalLocatorSearch = _fixUsingParams(JSON.stringify(locatorSearch), _params);
444
- locatorSearch = JSON.parse(originalLocatorSearch);
546
+ locatorSearch = _fixLocatorUsingParams(locatorSearch, _params);
445
547
  }
446
548
  catch (e) {
447
549
  console.error(e);
448
550
  }
551
+ let originalLocatorSearch = JSON.stringify(locatorSearch);
449
552
  //info.log += "searching for locator " + JSON.stringify(locatorSearch) + "\n";
450
553
  let locator = null;
451
554
  if (locatorSearch.climb && locatorSearch.climb >= 0) {
@@ -587,34 +690,183 @@ class StableBrowser {
587
690
  }
588
691
  return { rerun: false };
589
692
  }
693
+ getFilePath() {
694
+ const stackFrames = errorStackParser.parse(new Error());
695
+ const stackFrame = stackFrames.findLast((frame) => frame.fileName && frame.fileName.endsWith(".mjs"));
696
+ // return stackFrame?.fileName || null;
697
+ const filepath = stackFrame?.fileName;
698
+ if (filepath) {
699
+ let jsonFilePath = filepath.replace(".mjs", ".json");
700
+ if (existsSync(jsonFilePath)) {
701
+ return jsonFilePath;
702
+ }
703
+ const config = this.configuration ?? {};
704
+ if (!config?.locatorsMetadataDir) {
705
+ config.locatorsMetadataDir = "features/step_definitions/locators";
706
+ }
707
+ if (config && config.locatorsMetadataDir) {
708
+ jsonFilePath = path.join(config.locatorsMetadataDir, path.basename(jsonFilePath));
709
+ }
710
+ if (existsSync(jsonFilePath)) {
711
+ return jsonFilePath;
712
+ }
713
+ return null;
714
+ }
715
+ return null;
716
+ }
717
+ getFullElementLocators(selectors, filePath) {
718
+ if (!filePath || !existsSync(filePath)) {
719
+ return null;
720
+ }
721
+ const content = fs.readFileSync(filePath, "utf8");
722
+ try {
723
+ const allElements = JSON.parse(content);
724
+ const element_key = selectors?.element_key;
725
+ if (element_key && allElements[element_key]) {
726
+ return allElements[element_key];
727
+ }
728
+ for (const elementKey in allElements) {
729
+ const element = allElements[elementKey];
730
+ let foundStrategy = null;
731
+ for (const key in element) {
732
+ if (key === "strategy") {
733
+ continue;
734
+ }
735
+ const locators = element[key];
736
+ if (!locators || !locators.length) {
737
+ continue;
738
+ }
739
+ for (const locator of locators) {
740
+ delete locator.score;
741
+ }
742
+ if (JSON.stringify(locators) === JSON.stringify(selectors.locators)) {
743
+ foundStrategy = key;
744
+ break;
745
+ }
746
+ }
747
+ if (foundStrategy) {
748
+ return element;
749
+ }
750
+ }
751
+ }
752
+ catch (error) {
753
+ console.error("Error parsing locators from file: " + filePath, error);
754
+ }
755
+ return null;
756
+ }
590
757
  async _locate(selectors, info, _params, timeout, allowDisabled = false) {
591
758
  if (!timeout) {
592
759
  timeout = 30000;
593
760
  }
761
+ let element = null;
762
+ let allStrategyLocators = null;
763
+ let selectedStrategy = null;
764
+ if (this.tryAllStrategies) {
765
+ allStrategyLocators = this.getFullElementLocators(selectors, this.getFilePath());
766
+ selectedStrategy = allStrategyLocators?.strategy;
767
+ }
594
768
  for (let i = 0; i < 3; i++) {
595
769
  info.log += "attempt " + i + ": total locators " + selectors.locators.length + "\n";
596
770
  for (let j = 0; j < selectors.locators.length; j++) {
597
771
  let selector = selectors.locators[j];
598
772
  info.log += "searching for locator " + j + ":" + JSON.stringify(selector) + "\n";
599
773
  }
600
- let element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
774
+ if (this.tryAllStrategies && selectedStrategy) {
775
+ const strategyLocators = allStrategyLocators[selectedStrategy];
776
+ let err;
777
+ if (strategyLocators && strategyLocators.length) {
778
+ try {
779
+ selectors.locators = strategyLocators;
780
+ element = await this._locate_internal(selectors, info, _params, 10_000, allowDisabled);
781
+ info.selectedStrategy = selectedStrategy;
782
+ info.log += "element found using strategy " + selectedStrategy + "\n";
783
+ }
784
+ catch (error) {
785
+ err = error;
786
+ }
787
+ }
788
+ if (!element) {
789
+ for (const key in allStrategyLocators) {
790
+ if (key === "strategy" || key === selectedStrategy) {
791
+ continue;
792
+ }
793
+ const strategyLocators = allStrategyLocators[key];
794
+ if (strategyLocators && strategyLocators.length) {
795
+ try {
796
+ info.log += "using strategy " + key + " with locators " + JSON.stringify(strategyLocators) + "\n";
797
+ selectors.locators = strategyLocators;
798
+ element = await this._locate_internal(selectors, info, _params, 10_000, allowDisabled);
799
+ err = null;
800
+ info.selectedStrategy = key;
801
+ info.log += "element found using strategy " + key + "\n";
802
+ break;
803
+ }
804
+ catch (error) {
805
+ err = error;
806
+ }
807
+ }
808
+ }
809
+ }
810
+ if (err) {
811
+ throw err;
812
+ }
813
+ }
814
+ else {
815
+ element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
816
+ }
601
817
  if (!element.rerun) {
602
- const randomToken = Math.random().toString(36).substring(7);
603
- await element.evaluate((el, randomToken) => {
604
- el.setAttribute("data-blinq-id-" + randomToken, "");
605
- }, randomToken);
606
- // if (element._frame) {
607
- // return element;
608
- // }
818
+ let newElementSelector = "";
819
+ if (this.configuration && this.configuration.stableLocatorStrategy === "csschain") {
820
+ const cssSelector = await element.evaluate((el) => {
821
+ function getCssSelector(el) {
822
+ if (!el || el.nodeType !== 1 || el === document.body)
823
+ return el.tagName.toLowerCase();
824
+ const parent = el.parentElement;
825
+ const tag = el.tagName.toLowerCase();
826
+ // Find the index of the element among its siblings of the same tag
827
+ let index = 1;
828
+ for (let sibling = el.previousElementSibling; sibling; sibling = sibling.previousElementSibling) {
829
+ if (sibling.tagName === el.tagName) {
830
+ index++;
831
+ }
832
+ }
833
+ // Use nth-child if necessary (i.e., if there's more than one of the same tag)
834
+ const siblings = Array.from(parent.children).filter((child) => child.tagName === el.tagName);
835
+ const needsNthChild = siblings.length > 1;
836
+ const selector = needsNthChild ? `${tag}:nth-child(${[...parent.children].indexOf(el) + 1})` : tag;
837
+ return getCssSelector(parent) + " > " + selector;
838
+ }
839
+ const cssSelector = getCssSelector(el);
840
+ return cssSelector;
841
+ });
842
+ newElementSelector = cssSelector;
843
+ }
844
+ else {
845
+ const randomToken = "blinq_" + Math.random().toString(36).substring(7);
846
+ const id = await element.evaluate((el, randomToken) => {
847
+ // check if the element has id attribute
848
+ if (el.id) {
849
+ return el.id;
850
+ }
851
+ el.setAttribute("id", randomToken);
852
+ console.log("set id=" + randomToken + " on element", el);
853
+ return randomToken;
854
+ }, randomToken);
855
+ newElementSelector = "#" + id;
856
+ // check if the id contains :
857
+ if (id.includes(":")) {
858
+ // //*[@id="radix-:r0:"]
859
+ newElementSelector = `//*[@id="${id}"]`;
860
+ }
861
+ }
609
862
  const scope = element._frame ?? element.page();
610
- let newElementSelector = "[data-blinq-id-" + randomToken + "]";
611
863
  let prefixSelector = "";
612
864
  const frameControlSelector = " >> internal:control=enter-frame";
613
865
  const frameSelectorIndex = element._selector.lastIndexOf(frameControlSelector);
614
866
  if (frameSelectorIndex !== -1) {
615
867
  // remove everything after the >> internal:control=enter-frame
616
868
  const frameSelector = element._selector.substring(0, frameSelectorIndex);
617
- prefixSelector = frameSelector + " >> internal:control=enter-frame >>";
869
+ prefixSelector = frameSelector + " >> internal:control=enter-frame >> ";
618
870
  }
619
871
  // if (element?._frame?._selector) {
620
872
  // prefixSelector = element._frame._selector + " >> " + prefixSelector;
@@ -653,7 +905,7 @@ class StableBrowser {
653
905
  break;
654
906
  }
655
907
  catch (error) {
656
- console.error("frame not found " + frameLocator.css);
908
+ // console.error("frame not found " + frameLocator.css);
657
909
  }
658
910
  }
659
911
  }
@@ -731,7 +983,6 @@ class StableBrowser {
731
983
  let locatorsCount = 0;
732
984
  let lazy_scroll = false;
733
985
  //let arrayMode = Array.isArray(selectors);
734
- let scope = await this._findFrameScope(selectors, timeout, info);
735
986
  let selectorsLocators = null;
736
987
  selectorsLocators = selectors.locators;
737
988
  // group selectors by priority
@@ -759,6 +1010,7 @@ class StableBrowser {
759
1010
  let highPriorityOnly = true;
760
1011
  let visibleOnly = true;
761
1012
  while (true) {
1013
+ let scope = await this._findFrameScope(selectors, timeout, info);
762
1014
  locatorsCount = 0;
763
1015
  let result = [];
764
1016
  let popupResult = await this.closeUnexpectedPopups(info, _params);
@@ -874,9 +1126,13 @@ class StableBrowser {
874
1126
  }
875
1127
  }
876
1128
  if (foundLocators.length === 1) {
1129
+ let box = null;
1130
+ if (!this.onlyFailuresScreenshot) {
1131
+ box = await foundLocators[0].boundingBox();
1132
+ }
877
1133
  result.foundElements.push({
878
1134
  locator: foundLocators[0],
879
- box: await foundLocators[0].boundingBox(),
1135
+ box: box,
880
1136
  unique: true,
881
1137
  });
882
1138
  result.locatorIndex = i;
@@ -1031,17 +1287,30 @@ class StableBrowser {
1031
1287
  operation: "click",
1032
1288
  log: "***** click on " + selectors.element_name + " *****\n",
1033
1289
  };
1290
+ check_performance("click_all ***", this.context, true);
1034
1291
  try {
1292
+ check_performance("click_preCommand", this.context, true);
1035
1293
  await _preCommand(state, this);
1294
+ check_performance("click_preCommand", this.context, false);
1036
1295
  await performAction("click", state.element, options, this, state, _params);
1037
- await this.waitForPageLoad();
1296
+ if (!this.fastMode && !this.stepTags.includes("fast-mode")) {
1297
+ check_performance("click_waitForPageLoad", this.context, true);
1298
+ await this.waitForPageLoad({ noSleep: true });
1299
+ check_performance("click_waitForPageLoad", this.context, false);
1300
+ }
1038
1301
  return state.info;
1039
1302
  }
1040
1303
  catch (e) {
1041
1304
  await _commandError(state, e, this);
1042
1305
  }
1043
1306
  finally {
1307
+ check_performance("click_commandFinally", this.context, true);
1044
1308
  await _commandFinally(state, this);
1309
+ check_performance("click_commandFinally", this.context, false);
1310
+ check_performance("click_all ***", this.context, false);
1311
+ if (this.context.profile) {
1312
+ console.log(JSON.stringify(this.context.profile, null, 2));
1313
+ }
1045
1314
  }
1046
1315
  }
1047
1316
  async waitForElement(selectors, _params, options = {}, world = null) {
@@ -1097,7 +1366,7 @@ class StableBrowser {
1097
1366
  // if (world && world.screenshot && !world.screenshotPath) {
1098
1367
  // console.log(`Highlighting while running from recorder`);
1099
1368
  await this._highlightElements(state.element);
1100
- await state.element.setChecked(checked);
1369
+ await state.element.setChecked(checked, { timeout: 2000 });
1101
1370
  await new Promise((resolve) => setTimeout(resolve, 1000));
1102
1371
  // await this._unHighlightElements(element);
1103
1372
  // }
@@ -1109,14 +1378,31 @@ class StableBrowser {
1109
1378
  this.logger.info("element did not change its state, ignoring...");
1110
1379
  }
1111
1380
  else {
1381
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1112
1382
  //await this.closeUnexpectedPopups();
1113
1383
  state.info.log += "setCheck failed, will try again" + "\n";
1114
- state.element = await this._locate(selectors, state.info, _params);
1115
- await state.element.setChecked(checked, { timeout: 5000, force: true });
1116
- await new Promise((resolve) => setTimeout(resolve, 1000));
1384
+ state.element_found = false;
1385
+ try {
1386
+ state.element = await this._locate(selectors, state.info, _params, 100);
1387
+ state.element_found = true;
1388
+ // check the check state
1389
+ }
1390
+ catch (error) {
1391
+ // element dismissed
1392
+ }
1393
+ if (state.element_found) {
1394
+ const isChecked = await state.element.isChecked();
1395
+ if (isChecked !== checked) {
1396
+ // perform click
1397
+ await state.element.click({ timeout: 2000, force: true });
1398
+ }
1399
+ else {
1400
+ this.logger.info(`Element ${selectors.element_name} is already in the desired state (${checked})`);
1401
+ }
1402
+ }
1117
1403
  }
1118
1404
  }
1119
- await this.waitForPageLoad();
1405
+ //await this.waitForPageLoad();
1120
1406
  return state.info;
1121
1407
  }
1122
1408
  catch (e) {
@@ -1142,7 +1428,7 @@ class StableBrowser {
1142
1428
  await _preCommand(state, this);
1143
1429
  await performAction("hover", state.element, options, this, state, _params);
1144
1430
  await _screenshot(state, this);
1145
- await this.waitForPageLoad();
1431
+ //await this.waitForPageLoad();
1146
1432
  return state.info;
1147
1433
  }
1148
1434
  catch (e) {
@@ -1178,7 +1464,7 @@ class StableBrowser {
1178
1464
  state.info.log += "selectOption failed, will try force" + "\n";
1179
1465
  await state.element.selectOption(values, { timeout: 10000, force: true });
1180
1466
  }
1181
- await this.waitForPageLoad();
1467
+ //await this.waitForPageLoad();
1182
1468
  return state.info;
1183
1469
  }
1184
1470
  catch (e) {
@@ -1409,7 +1695,9 @@ class StableBrowser {
1409
1695
  await new Promise((resolve) => setTimeout(resolve, 500));
1410
1696
  }
1411
1697
  }
1698
+ //if (!this.fastMode) {
1412
1699
  await _screenshot(state, this);
1700
+ //}
1413
1701
  if (enter === true) {
1414
1702
  await new Promise((resolve) => setTimeout(resolve, 2000));
1415
1703
  await this.page.keyboard.press("Enter");
@@ -1458,8 +1746,8 @@ class StableBrowser {
1458
1746
  if (enter) {
1459
1747
  await new Promise((resolve) => setTimeout(resolve, 2000));
1460
1748
  await this.page.keyboard.press("Enter");
1749
+ await this.waitForPageLoad();
1461
1750
  }
1462
- await this.waitForPageLoad();
1463
1751
  return state.info;
1464
1752
  }
1465
1753
  catch (e) {
@@ -1751,6 +2039,11 @@ class StableBrowser {
1751
2039
  throw new Error("Snapshot validation failed at line " + matchResult.errorLineText);
1752
2040
  }
1753
2041
  // highlight and screenshot
2042
+ try {
2043
+ await await highlightSnapshot(newValue, scope);
2044
+ await _screenshot(state, this);
2045
+ }
2046
+ catch (e) { }
1754
2047
  return state.info;
1755
2048
  }
1756
2049
  catch (e) {
@@ -1909,12 +2202,7 @@ class StableBrowser {
1909
2202
  }
1910
2203
  }
1911
2204
  getTestData(world = null) {
1912
- const dataFile = _getDataFile(world, this.context, this);
1913
- let data = {};
1914
- if (fs.existsSync(dataFile)) {
1915
- data = JSON.parse(fs.readFileSync(dataFile, "utf8"));
1916
- }
1917
- return data;
2205
+ return _getTestData(world, this.context, this);
1918
2206
  }
1919
2207
  async _screenShot(options = {}, world = null, info = null) {
1920
2208
  // collect url/path/title
@@ -2134,6 +2422,77 @@ class StableBrowser {
2134
2422
  await _commandFinally(state, this);
2135
2423
  }
2136
2424
  }
2425
+ async extractProperty(selectors, property, variable, _params = null, options = {}, world = null) {
2426
+ const state = {
2427
+ selectors,
2428
+ _params,
2429
+ property,
2430
+ variable,
2431
+ options,
2432
+ world,
2433
+ type: Types.EXTRACT_PROPERTY,
2434
+ text: `Extract property from element`,
2435
+ _text: `Extract property ${property} from ${selectors.element_name}`,
2436
+ operation: "extractProperty",
2437
+ log: "***** extract property " + property + " from " + selectors.element_name + " *****\n",
2438
+ allowDisabled: true,
2439
+ };
2440
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2441
+ try {
2442
+ await _preCommand(state, this);
2443
+ switch (property) {
2444
+ case "inner_text":
2445
+ state.value = await state.element.innerText();
2446
+ break;
2447
+ case "href":
2448
+ state.value = await state.element.getAttribute("href");
2449
+ break;
2450
+ case "value":
2451
+ state.value = await state.element.inputValue();
2452
+ break;
2453
+ case "text":
2454
+ state.value = await state.element.textContent();
2455
+ break;
2456
+ default:
2457
+ if (property.startsWith("dataset.")) {
2458
+ const dataAttribute = property.substring(8);
2459
+ state.value = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2460
+ }
2461
+ else {
2462
+ state.value = String(await state.element.evaluate((element, prop) => element[prop], property));
2463
+ }
2464
+ }
2465
+ if (options !== null) {
2466
+ if (options.regex && options.regex !== "") {
2467
+ // Construct a regex pattern from the provided string
2468
+ const regex = options.regex.slice(1, -1);
2469
+ const regexPattern = new RegExp(regex, "g");
2470
+ const matches = state.value.match(regexPattern);
2471
+ if (matches) {
2472
+ let newValue = "";
2473
+ for (const match of matches) {
2474
+ newValue += match;
2475
+ }
2476
+ state.value = newValue;
2477
+ }
2478
+ }
2479
+ if (options.trimSpaces && options.trimSpaces === true) {
2480
+ state.value = state.value.trim();
2481
+ }
2482
+ }
2483
+ state.info.value = state.value;
2484
+ this.setTestData({ [variable]: state.value }, world);
2485
+ this.logger.info("set test data: " + variable + "=" + state.value);
2486
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2487
+ return state.info;
2488
+ }
2489
+ catch (e) {
2490
+ await _commandError(state, e, this);
2491
+ }
2492
+ finally {
2493
+ await _commandFinally(state, this);
2494
+ }
2495
+ }
2137
2496
  async verifyAttribute(selectors, attribute, value, _params = null, options = {}, world = null) {
2138
2497
  const state = {
2139
2498
  selectors,
@@ -2232,6 +2591,261 @@ class StableBrowser {
2232
2591
  await _commandFinally(state, this);
2233
2592
  }
2234
2593
  }
2594
+ async verifyProperty(selectors, property, value, _params = null, options = {}, world = null) {
2595
+ const state = {
2596
+ selectors,
2597
+ _params,
2598
+ property,
2599
+ value,
2600
+ options,
2601
+ world,
2602
+ type: Types.VERIFY_PROPERTY,
2603
+ highlight: true,
2604
+ screenshot: true,
2605
+ text: `Verify element property`,
2606
+ _text: `Verify property ${property} from ${selectors.element_name} is ${value}`,
2607
+ operation: "verifyProperty",
2608
+ log: "***** verify property " + property + " from " + selectors.element_name + " *****\n",
2609
+ allowDisabled: true,
2610
+ };
2611
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2612
+ let val;
2613
+ let expectedValue;
2614
+ try {
2615
+ await _preCommand(state, this);
2616
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2617
+ state.info.expectedValue = expectedValue;
2618
+ switch (property) {
2619
+ case "innerText":
2620
+ val = String(await state.element.innerText());
2621
+ break;
2622
+ case "text":
2623
+ val = String(await state.element.textContent());
2624
+ break;
2625
+ case "value":
2626
+ val = String(await state.element.inputValue());
2627
+ break;
2628
+ case "checked":
2629
+ val = String(await state.element.isChecked());
2630
+ break;
2631
+ case "disabled":
2632
+ val = String(await state.element.isDisabled());
2633
+ break;
2634
+ case "readOnly":
2635
+ const isEditable = await state.element.isEditable();
2636
+ val = String(!isEditable);
2637
+ break;
2638
+ case "innerHTML":
2639
+ val = String(await state.element.innerHTML());
2640
+ break;
2641
+ case "outerHTML":
2642
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2643
+ break;
2644
+ default:
2645
+ if (property.startsWith("dataset.")) {
2646
+ const dataAttribute = property.substring(8);
2647
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2648
+ }
2649
+ else {
2650
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2651
+ }
2652
+ }
2653
+ // Helper function to remove all style="" attributes
2654
+ const removeStyleAttributes = (htmlString) => {
2655
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2656
+ };
2657
+ // Remove style attributes for innerHTML and outerHTML properties
2658
+ if (property === "innerHTML" || property === "outerHTML") {
2659
+ val = removeStyleAttributes(val);
2660
+ expectedValue = removeStyleAttributes(expectedValue);
2661
+ }
2662
+ state.info.value = val;
2663
+ let regex;
2664
+ state.info.value = val;
2665
+ const isRegex = expectedValue.startsWith("regex:");
2666
+ const isContains = expectedValue.startsWith("contains:");
2667
+ const isExact = expectedValue.startsWith("exact:");
2668
+ let matchPassed = false;
2669
+ if (isRegex) {
2670
+ const rawPattern = expectedValue.slice(6); // remove "regex:"
2671
+ const lastSlashIndex = rawPattern.lastIndexOf("/");
2672
+ if (rawPattern.startsWith("/") && lastSlashIndex > 0) {
2673
+ const patternBody = rawPattern.slice(1, lastSlashIndex).replace(/\n/g, ".*");
2674
+ const flags = rawPattern.slice(lastSlashIndex + 1) || "gs";
2675
+ const regex = new RegExp(patternBody, flags);
2676
+ state.info.regex = true;
2677
+ matchPassed = regex.test(val);
2678
+ }
2679
+ else {
2680
+ // Fallback: treat as literal
2681
+ const escapedPattern = rawPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2682
+ const regex = new RegExp(escapedPattern, "g");
2683
+ matchPassed = regex.test(val);
2684
+ }
2685
+ }
2686
+ else if (isContains) {
2687
+ const containsValue = expectedValue.slice(9); // remove "contains:"
2688
+ matchPassed = val.includes(containsValue);
2689
+ }
2690
+ else if (isExact) {
2691
+ const exactValue = expectedValue.slice(6); // remove "exact:"
2692
+ matchPassed = val === exactValue;
2693
+ }
2694
+ else if (property === "innerText") {
2695
+ // Default innerText logic
2696
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2697
+ const valLines = val.split("\n");
2698
+ const expectedLines = normalizedExpectedValue.split("\n");
2699
+ matchPassed = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2700
+ }
2701
+ else {
2702
+ // Fallback exact or loose match
2703
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2704
+ const regex = new RegExp(escapedPattern, "g");
2705
+ matchPassed = regex.test(val);
2706
+ }
2707
+ if (!matchPassed) {
2708
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2709
+ state.info.failCause.assertionFailed = true;
2710
+ state.info.failCause.lastError = errorMessage;
2711
+ throw new Error(errorMessage);
2712
+ }
2713
+ return state.info;
2714
+ }
2715
+ catch (e) {
2716
+ await _commandError(state, e, this);
2717
+ }
2718
+ finally {
2719
+ await _commandFinally(state, this);
2720
+ }
2721
+ }
2722
+ async conditionalWait(selectors, condition, timeout = 1000, _params = null, options = {}, world = null) {
2723
+ // Convert timeout from seconds to milliseconds
2724
+ const timeoutMs = timeout * 1000;
2725
+ const state = {
2726
+ selectors,
2727
+ _params,
2728
+ condition,
2729
+ timeout: timeoutMs, // Store as milliseconds for internal use
2730
+ options,
2731
+ world,
2732
+ type: Types.CONDITIONAL_WAIT,
2733
+ highlight: true,
2734
+ screenshot: true,
2735
+ text: `Conditional wait for element`,
2736
+ _text: `Wait for ${selectors.element_name} to be ${condition} (timeout: ${timeout}s)`, // Display original seconds
2737
+ operation: "conditionalWait",
2738
+ log: `***** conditional wait for ${condition} on ${selectors.element_name} *****\n`,
2739
+ allowDisabled: true,
2740
+ info: {},
2741
+ };
2742
+ state.options ??= { timeout: timeoutMs };
2743
+ // Initialize startTime outside try block to ensure it's always accessible
2744
+ const startTime = Date.now();
2745
+ let conditionMet = false;
2746
+ let currentValue = null;
2747
+ let lastError = null;
2748
+ // Main retry loop - continues until timeout or condition is met
2749
+ while (Date.now() - startTime < timeoutMs) {
2750
+ const elapsedTime = Date.now() - startTime;
2751
+ const remainingTime = timeoutMs - elapsedTime;
2752
+ try {
2753
+ // Try to execute _preCommand (element location)
2754
+ await _preCommand(state, this);
2755
+ // If _preCommand succeeds, start condition checking
2756
+ const checkCondition = async () => {
2757
+ try {
2758
+ switch (condition.toLowerCase()) {
2759
+ case "checked":
2760
+ currentValue = await state.element.isChecked();
2761
+ return currentValue === true;
2762
+ case "unchecked":
2763
+ currentValue = await state.element.isChecked();
2764
+ return currentValue === false;
2765
+ case "visible":
2766
+ currentValue = await state.element.isVisible();
2767
+ return currentValue === true;
2768
+ case "hidden":
2769
+ currentValue = await state.element.isVisible();
2770
+ return currentValue === false;
2771
+ case "enabled":
2772
+ currentValue = await state.element.isDisabled();
2773
+ return currentValue === false;
2774
+ case "disabled":
2775
+ currentValue = await state.element.isDisabled();
2776
+ return currentValue === true;
2777
+ case "editable":
2778
+ // currentValue = await String(await state.element.evaluate((element, prop) => element[prop], "isContentEditable"));
2779
+ currentValue = await state.element.isContentEditable();
2780
+ return currentValue === true;
2781
+ default:
2782
+ state.info.message = `Unsupported condition: '${condition}'. Supported conditions are: checked, unchecked, visible, hidden, enabled, disabled, editable.`;
2783
+ state.info.success = false;
2784
+ return false;
2785
+ }
2786
+ }
2787
+ catch (error) {
2788
+ // Don't throw here, just return false to continue retrying
2789
+ return false;
2790
+ }
2791
+ };
2792
+ // Inner loop for condition checking (once element is located)
2793
+ while (Date.now() - startTime < timeoutMs) {
2794
+ const currentElapsedTime = Date.now() - startTime;
2795
+ conditionMet = await checkCondition();
2796
+ if (conditionMet) {
2797
+ break;
2798
+ }
2799
+ // Check if we still have time for another attempt
2800
+ if (Date.now() - startTime + 50 < timeoutMs) {
2801
+ await new Promise((res) => setTimeout(res, 50));
2802
+ }
2803
+ else {
2804
+ break;
2805
+ }
2806
+ }
2807
+ // If we got here and condition is met, break out of main loop
2808
+ if (conditionMet) {
2809
+ break;
2810
+ }
2811
+ // If condition not met but no exception, we've timed out
2812
+ break;
2813
+ }
2814
+ catch (e) {
2815
+ lastError = e;
2816
+ const currentElapsedTime = Date.now() - startTime;
2817
+ const timeLeft = timeoutMs - currentElapsedTime;
2818
+ // Check if we have enough time left to retry
2819
+ if (timeLeft > 100) {
2820
+ await new Promise((resolve) => setTimeout(resolve, 50));
2821
+ }
2822
+ else {
2823
+ break;
2824
+ }
2825
+ }
2826
+ }
2827
+ const actualWaitTime = Date.now() - startTime;
2828
+ state.info = {
2829
+ success: conditionMet,
2830
+ conditionMet,
2831
+ actualWaitTime,
2832
+ currentValue,
2833
+ lastError: lastError?.message || null,
2834
+ message: conditionMet
2835
+ ? `Condition '${condition}' met after ${(actualWaitTime / 1000).toFixed(2)}s`
2836
+ : `Condition '${condition}' not met within ${timeout}s timeout`,
2837
+ };
2838
+ if (lastError) {
2839
+ state.log += `Last error: ${lastError.message}\n`;
2840
+ }
2841
+ try {
2842
+ await _commandFinally(state, this);
2843
+ }
2844
+ catch (finallyError) {
2845
+ state.log += `Error in _commandFinally: ${finallyError.message}\n`;
2846
+ }
2847
+ return state.info;
2848
+ }
2235
2849
  async extractEmailData(emailAddress, options, world) {
2236
2850
  if (!emailAddress) {
2237
2851
  throw new Error("email address is null");
@@ -2828,6 +3442,8 @@ class StableBrowser {
2828
3442
  operation: "verify_text_with_relation",
2829
3443
  log: "***** search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found *****\n",
2830
3444
  };
3445
+ const cmdStartTime = Date.now();
3446
+ let cmdEndTime = null;
2831
3447
  const timeout = this._getFindElementTimeout(options);
2832
3448
  await new Promise((resolve) => setTimeout(resolve, 2000));
2833
3449
  let newValue = await this._replaceWithLocalData(textAnchor, world);
@@ -2863,6 +3479,17 @@ class StableBrowser {
2863
3479
  await new Promise((resolve) => setTimeout(resolve, 1000));
2864
3480
  continue;
2865
3481
  }
3482
+ else {
3483
+ cmdEndTime = Date.now();
3484
+ if (cmdEndTime - cmdStartTime > 55000) {
3485
+ if (foundAncore) {
3486
+ throw new Error(`Text ${textToVerify} not found in page`);
3487
+ }
3488
+ else {
3489
+ throw new Error(`Text ${textAnchor} not found in page`);
3490
+ }
3491
+ }
3492
+ }
2866
3493
  try {
2867
3494
  for (let i = 0; i < resultWithElementsFound.length; i++) {
2868
3495
  foundAncore = true;
@@ -3262,6 +3889,43 @@ class StableBrowser {
3262
3889
  });
3263
3890
  }
3264
3891
  }
3892
+ /**
3893
+ * Explicit wait/sleep function that pauses execution for a specified duration
3894
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3895
+ * @param options - Optional configuration object
3896
+ * @param world - Optional world context
3897
+ * @returns Promise that resolves after the specified duration
3898
+ */
3899
+ async sleep(duration = 1000, options = {}, world = null) {
3900
+ const state = {
3901
+ duration,
3902
+ options,
3903
+ world,
3904
+ locate: false,
3905
+ scroll: false,
3906
+ screenshot: false,
3907
+ highlight: false,
3908
+ type: Types.SLEEP,
3909
+ text: `Sleep for ${duration} ms`,
3910
+ _text: `Sleep for ${duration} ms`,
3911
+ operation: "sleep",
3912
+ log: `***** Sleep for ${duration} ms *****\n`,
3913
+ };
3914
+ try {
3915
+ await _preCommand(state, this);
3916
+ if (duration < 0) {
3917
+ throw new Error("Sleep duration cannot be negative");
3918
+ }
3919
+ await new Promise((resolve) => setTimeout(resolve, duration));
3920
+ return state.info;
3921
+ }
3922
+ catch (e) {
3923
+ await _commandError(state, e, this);
3924
+ }
3925
+ finally {
3926
+ await _commandFinally(state, this);
3927
+ }
3928
+ }
3265
3929
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3266
3930
  try {
3267
3931
  return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
@@ -3313,6 +3977,22 @@ class StableBrowser {
3313
3977
  }
3314
3978
  }
3315
3979
  async waitForPageLoad(options = {}, world = null) {
3980
+ // try {
3981
+ // let currentPagePath = null;
3982
+ // currentPagePath = new URL(this.page.url()).pathname;
3983
+ // if (this.latestPagePath) {
3984
+ // // get the currect page path and compare with the latest page path
3985
+ // if (this.latestPagePath === currentPagePath) {
3986
+ // // if the page path is the same, do not wait for page load
3987
+ // console.log("No page change: " + currentPagePath);
3988
+ // return;
3989
+ // }
3990
+ // }
3991
+ // this.latestPagePath = currentPagePath;
3992
+ // } catch (e) {
3993
+ // console.debug("Error getting current page path: ", e);
3994
+ // }
3995
+ //console.log("Waiting for page load");
3316
3996
  let timeout = this._getLoadTimeout(options);
3317
3997
  const promiseArray = [];
3318
3998
  // let waitForNetworkIdle = true;
@@ -3345,10 +4025,12 @@ class StableBrowser {
3345
4025
  else if (e.label === "domcontentloaded") {
3346
4026
  console.log("waited for the domcontent loaded timeout");
3347
4027
  }
3348
- console.log(".");
3349
4028
  }
3350
4029
  finally {
3351
- await new Promise((resolve) => setTimeout(resolve, 2000));
4030
+ await new Promise((resolve) => setTimeout(resolve, 500));
4031
+ if (options && !options.noSleep) {
4032
+ await new Promise((resolve) => setTimeout(resolve, 1500));
4033
+ }
3352
4034
  ({ screenshotId, screenshotPath } = await this._screenShot(options, world));
3353
4035
  const endTime = Date.now();
3354
4036
  _reportToWorld(world, {
@@ -3389,7 +4071,6 @@ class StableBrowser {
3389
4071
  await this.page.close();
3390
4072
  }
3391
4073
  catch (e) {
3392
- console.log(".");
3393
4074
  await _commandError(state, e, this);
3394
4075
  }
3395
4076
  finally {
@@ -3403,7 +4084,7 @@ class StableBrowser {
3403
4084
  }
3404
4085
  operation = options.operation;
3405
4086
  // validate operation is one of the supported operations
3406
- if (operation != "click" && operation != "hover+click") {
4087
+ if (operation != "click" && operation != "hover+click" && operation != "hover") {
3407
4088
  throw new Error("operation is not supported");
3408
4089
  }
3409
4090
  const state = {
@@ -3472,6 +4153,17 @@ class StableBrowser {
3472
4153
  state.element = results[0];
3473
4154
  await performAction("hover+click", state.element, options, this, state, _params);
3474
4155
  break;
4156
+ case "hover":
4157
+ if (!options.css) {
4158
+ throw new Error("css is not defined");
4159
+ }
4160
+ const result1 = await findElementsInArea(options.css, cellArea, this, options);
4161
+ if (result1.length === 0) {
4162
+ throw new Error(`Element not found in cell area`);
4163
+ }
4164
+ state.element = result1[0];
4165
+ await performAction("hover", state.element, options, this, state, _params);
4166
+ break;
3475
4167
  default:
3476
4168
  throw new Error("operation is not supported");
3477
4169
  }
@@ -3504,7 +4196,6 @@ class StableBrowser {
3504
4196
  await this.page.setViewportSize({ width: width, height: hight });
3505
4197
  }
3506
4198
  catch (e) {
3507
- console.log(".");
3508
4199
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3509
4200
  }
3510
4201
  finally {
@@ -3542,7 +4233,6 @@ class StableBrowser {
3542
4233
  await this.page.reload();
3543
4234
  }
3544
4235
  catch (e) {
3545
- console.log(".");
3546
4236
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3547
4237
  }
3548
4238
  finally {
@@ -3586,6 +4276,10 @@ class StableBrowser {
3586
4276
  }
3587
4277
  }
3588
4278
  async beforeScenario(world, scenario) {
4279
+ if (world && world.attach) {
4280
+ world.attach(this.context.reportFolder, { mediaType: "text/plain" });
4281
+ }
4282
+ this.context.loadedRoutes = null;
3589
4283
  this.beforeScenarioCalled = true;
3590
4284
  if (scenario && scenario.pickle && scenario.pickle.name) {
3591
4285
  this.scenarioName = scenario.pickle.name;
@@ -3609,14 +4303,16 @@ class StableBrowser {
3609
4303
  envName = this.context.environment.name;
3610
4304
  }
3611
4305
  if (!process.env.TEMP_RUN) {
3612
- await getTestData(envName, world, undefined, this.featureName, this.scenarioName);
4306
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
3613
4307
  }
3614
4308
  await loadBrunoParams(this.context, this.context.environment.name);
3615
4309
  }
3616
4310
  async afterScenario(world, scenario) { }
3617
4311
  async beforeStep(world, step) {
4312
+ this.stepTags = [];
3618
4313
  if (!this.beforeScenarioCalled) {
3619
4314
  this.beforeScenario(world, step);
4315
+ this.context.loadedRoutes = null;
3620
4316
  }
3621
4317
  if (this.stepIndex === undefined) {
3622
4318
  this.stepIndex = 0;
@@ -3626,7 +4322,12 @@ class StableBrowser {
3626
4322
  }
3627
4323
  if (step && step.pickleStep && step.pickleStep.text) {
3628
4324
  this.stepName = step.pickleStep.text;
3629
- this.logger.info("step: " + this.stepName);
4325
+ let printableStepName = this.stepName;
4326
+ // take the printableStepName and replace quated value with \x1b[33m and \x1b[0m
4327
+ printableStepName = printableStepName.replace(/"([^"]*)"/g, (match, p1) => {
4328
+ return `\x1b[33m"${p1}"\x1b[0m`;
4329
+ });
4330
+ this.logger.info("\x1b[38;5;208mstep:\x1b[0m " + printableStepName);
3630
4331
  }
3631
4332
  else if (step && step.text) {
3632
4333
  this.stepName = step.text;
@@ -3641,13 +4342,22 @@ class StableBrowser {
3641
4342
  }
3642
4343
  if (this.initSnapshotTaken === false) {
3643
4344
  this.initSnapshotTaken = true;
3644
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4345
+ if (world &&
4346
+ world.attach &&
4347
+ !process.env.DISABLE_SNAPSHOT &&
4348
+ (!this.fastMode || this.stepTags.includes("fast-mode"))) {
3645
4349
  const snapshot = await this.getAriaSnapshot();
3646
4350
  if (snapshot) {
3647
4351
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3648
4352
  }
3649
4353
  }
3650
4354
  }
4355
+ this.context.routeResults = null;
4356
+ await registerBeforeStepRoutes(this.context, this.stepName);
4357
+ networkBeforeStep(this.stepName);
4358
+ }
4359
+ setStepTags(tags) {
4360
+ this.stepTags = tags;
3651
4361
  }
3652
4362
  async getAriaSnapshot() {
3653
4363
  try {
@@ -3667,12 +4377,18 @@ class StableBrowser {
3667
4377
  try {
3668
4378
  // Ensure frame is attached and has body
3669
4379
  const body = frame.locator("body");
3670
- await body.waitFor({ timeout: 200 }); // wait explicitly
4380
+ //await body.waitFor({ timeout: 2000 }); // wait explicitly
3671
4381
  const snapshot = await body.ariaSnapshot({ timeout });
4382
+ if (!snapshot) {
4383
+ continue;
4384
+ }
3672
4385
  content.push(`- frame: ${i}`);
3673
4386
  content.push(snapshot);
3674
4387
  }
3675
- catch (innerErr) { }
4388
+ catch (innerErr) {
4389
+ console.warn(`Frame ${i} snapshot failed:`, innerErr);
4390
+ content.push(`- frame: ${i} - error: ${innerErr.message}`);
4391
+ }
3676
4392
  }
3677
4393
  return content.join("\n");
3678
4394
  }
@@ -3744,33 +4460,52 @@ class StableBrowser {
3744
4460
  if (this.context) {
3745
4461
  this.context.examplesRow = null;
3746
4462
  }
3747
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4463
+ if (world &&
4464
+ world.attach &&
4465
+ !process.env.DISABLE_SNAPSHOT &&
4466
+ !this.fastMode &&
4467
+ !this.stepTags.includes("fast-mode")) {
3748
4468
  const snapshot = await this.getAriaSnapshot();
3749
4469
  if (snapshot) {
3750
4470
  const obj = {};
3751
4471
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3752
4472
  }
3753
4473
  }
3754
- const state = {
3755
- world,
3756
- locate: false,
3757
- scroll: false,
3758
- screenshot: true,
3759
- highlight: true,
3760
- type: Types.STEP_COMPLETE,
3761
- text: "end of scenario",
3762
- _text: "end of scenario",
3763
- operation: "step_complete",
3764
- log: "***** " + "end of scenario" + " *****\n",
3765
- };
3766
- try {
3767
- await _preCommand(state, this);
4474
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4475
+ if (this.context.routeResults) {
4476
+ if (world && world.attach) {
4477
+ await world.attach(JSON.stringify(this.context.routeResults), "application/json+intercept-results");
4478
+ }
3768
4479
  }
3769
- catch (e) {
3770
- await _commandError(state, e, this);
4480
+ if (!process.env.TEMP_RUN) {
4481
+ const state = {
4482
+ world,
4483
+ locate: false,
4484
+ scroll: false,
4485
+ screenshot: true,
4486
+ highlight: true,
4487
+ type: Types.STEP_COMPLETE,
4488
+ text: "end of scenario",
4489
+ _text: "end of scenario",
4490
+ operation: "step_complete",
4491
+ log: "***** " + "end of scenario" + " *****\n",
4492
+ };
4493
+ try {
4494
+ await _preCommand(state, this);
4495
+ }
4496
+ catch (e) {
4497
+ await _commandError(state, e, this);
4498
+ }
4499
+ finally {
4500
+ await _commandFinally(state, this);
4501
+ }
3771
4502
  }
3772
- finally {
3773
- await _commandFinally(state, this);
4503
+ networkAfterStep(this.stepName);
4504
+ if (process.env.TEMP_RUN === "true") {
4505
+ // Put a sleep for some time to allow the browser to finish processing
4506
+ if (!this.stepTags.includes("fast-mode")) {
4507
+ await new Promise((resolve) => setTimeout(resolve, 3000));
4508
+ }
3774
4509
  }
3775
4510
  }
3776
4511
  }