automation_model 1.0.739-dev → 1.0.739-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 (46) 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 +3 -1
  5. package/lib/auto_page.js +60 -9
  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 +398 -87
  27. package/lib/network.js.map +1 -1
  28. package/lib/route.d.ts +21 -0
  29. package/lib/route.js +575 -0
  30. package/lib/route.js.map +1 -0
  31. package/lib/snapshot_validation.js.map +1 -1
  32. package/lib/stable_browser.d.ts +26 -2
  33. package/lib/stable_browser.js +752 -56
  34. package/lib/stable_browser.js.map +1 -1
  35. package/lib/table.d.ts +9 -7
  36. package/lib/table.js +82 -12
  37. package/lib/table.js.map +1 -1
  38. package/lib/table_helper.js +14 -0
  39. package/lib/table_helper.js.map +1 -1
  40. package/lib/test_context.d.ts +1 -0
  41. package/lib/test_context.js +1 -0
  42. package/lib/test_context.js.map +1 -1
  43. package/lib/utils.d.ts +3 -1
  44. package/lib/utils.js +35 -6
  45. package/lib/utils.js.map +1 -1
  46. 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
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) => {
@@ -77,6 +87,7 @@ class StableBrowser {
77
87
  context;
78
88
  world;
79
89
  fastMode;
90
+ stepTags;
80
91
  project_path = null;
81
92
  webLogFile = null;
82
93
  networkLogger = null;
@@ -85,13 +96,15 @@ class StableBrowser {
85
96
  tags = null;
86
97
  isRecording = false;
87
98
  initSnapshotTaken = false;
88
- constructor(browser, page, logger = null, context = null, world = null, fastMode = false) {
99
+ onlyFailuresScreenshot = process.env.SCREENSHOT_ON_FAILURE_ONLY === "true";
100
+ constructor(browser, page, logger = null, context = null, world = null, fastMode = false, stepTags = []) {
89
101
  this.browser = browser;
90
102
  this.page = page;
91
103
  this.logger = logger;
92
104
  this.context = context;
93
105
  this.world = world;
94
106
  this.fastMode = fastMode;
107
+ this.stepTags = stepTags;
95
108
  if (!this.logger) {
96
109
  this.logger = console;
97
110
  }
@@ -120,9 +133,16 @@ class StableBrowser {
120
133
  context.pages = [this.page];
121
134
  const logFolder = path.join(this.project_path, "logs", "web");
122
135
  this.world = world;
136
+ if (this.configuration && this.configuration.fastMode === true) {
137
+ this.fastMode = true;
138
+ }
123
139
  if (process.env.FAST_MODE === "true") {
140
+ // console.log("Fast mode enabled from environment variable");
124
141
  this.fastMode = true;
125
142
  }
143
+ if (process.env.FAST_MODE === "false") {
144
+ this.fastMode = false;
145
+ }
126
146
  if (this.context) {
127
147
  this.context.fastMode = this.fastMode;
128
148
  }
@@ -160,6 +180,7 @@ class StableBrowser {
160
180
  registerNetworkEvents(this.world, this, context, this.page);
161
181
  registerDownloadEvent(this.page, this.world, context);
162
182
  page.on("close", async () => {
183
+ // return if browser context is already closed
163
184
  if (this.context && this.context.pages && this.context.pages.length > 1) {
164
185
  this.context.pages.pop();
165
186
  this.page = this.context.pages[this.context.pages.length - 1];
@@ -169,7 +190,12 @@ class StableBrowser {
169
190
  console.log("Switched to page " + title);
170
191
  }
171
192
  catch (error) {
172
- 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
+ }
173
199
  }
174
200
  }
175
201
  });
@@ -178,7 +204,12 @@ class StableBrowser {
178
204
  console.log("Switch page: " + (await page.title()));
179
205
  }
180
206
  catch (e) {
181
- 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
+ }
182
213
  }
183
214
  context.pageLoading.status = false;
184
215
  }.bind(this));
@@ -206,7 +237,7 @@ class StableBrowser {
206
237
  if (newContextCreated) {
207
238
  this.registerEventListeners(this.context);
208
239
  await this.goto(this.context.environment.baseUrl);
209
- if (!this.fastMode) {
240
+ if (!this.fastMode && !this.stepTags.includes("fast-mode")) {
210
241
  await this.waitForPageLoad();
211
242
  }
212
243
  }
@@ -334,6 +365,64 @@ class StableBrowser {
334
365
  await _commandFinally(state, this);
335
366
  }
336
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
+ }
337
426
  async _getLocator(locator, scope, _params) {
338
427
  locator = _fixLocatorUsingParams(locator, _params);
339
428
  // locator = await this._replaceWithLocalData(locator);
@@ -432,12 +521,6 @@ class StableBrowser {
432
521
  if (!el.setAttribute) {
433
522
  el = el.parentElement;
434
523
  }
435
- // remove any attributes start with data-blinq-id
436
- // for (let i = 0; i < el.attributes.length; i++) {
437
- // if (el.attributes[i].name.startsWith("data-blinq-id")) {
438
- // el.removeAttribute(el.attributes[i].name);
439
- // }
440
- // }
441
524
  el.setAttribute("data-blinq-id-" + randomToken, "");
442
525
  return true;
443
526
  }, [tag1, randomToken]))) {
@@ -459,14 +542,13 @@ class StableBrowser {
459
542
  info.locatorLog = new LocatorLog(selectorHierarchy);
460
543
  }
461
544
  let locatorSearch = selectorHierarchy[index];
462
- let originalLocatorSearch = "";
463
545
  try {
464
- originalLocatorSearch = _fixUsingParams(JSON.stringify(locatorSearch), _params);
465
- locatorSearch = JSON.parse(originalLocatorSearch);
546
+ locatorSearch = _fixLocatorUsingParams(locatorSearch, _params);
466
547
  }
467
548
  catch (e) {
468
549
  console.error(e);
469
550
  }
551
+ let originalLocatorSearch = JSON.stringify(locatorSearch);
470
552
  //info.log += "searching for locator " + JSON.stringify(locatorSearch) + "\n";
471
553
  let locator = null;
472
554
  if (locatorSearch.climb && locatorSearch.climb >= 0) {
@@ -608,34 +690,192 @@ class StableBrowser {
608
690
  }
609
691
  return { rerun: false };
610
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
+ }
611
757
  async _locate(selectors, info, _params, timeout, allowDisabled = false) {
612
758
  if (!timeout) {
613
759
  timeout = 30000;
614
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
+ }
615
768
  for (let i = 0; i < 3; i++) {
616
769
  info.log += "attempt " + i + ": total locators " + selectors.locators.length + "\n";
617
770
  for (let j = 0; j < selectors.locators.length; j++) {
618
771
  let selector = selectors.locators[j];
619
772
  info.log += "searching for locator " + j + ":" + JSON.stringify(selector) + "\n";
620
773
  }
621
- 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
+ }
622
817
  if (!element.rerun) {
623
- const randomToken = Math.random().toString(36).substring(7);
624
- await element.evaluate((el, randomToken) => {
625
- el.setAttribute("data-blinq-id-" + randomToken, "");
626
- }, randomToken);
627
- // if (element._frame) {
628
- // return element;
629
- // }
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
+ if (this.configuration && this.configuration.stableLocatorStrategy === "data-attribute") {
847
+ const dataAttribute = "data-blinq-id";
848
+ await element.evaluate((el, [dataAttribute, randomToken]) => {
849
+ el.setAttribute(dataAttribute, randomToken);
850
+ }, [dataAttribute, randomToken]);
851
+ newElementSelector = `[${dataAttribute}="${randomToken}"]`;
852
+ }
853
+ else {
854
+ const id = await element.evaluate((el, randomToken) => {
855
+ // check if the element has id attribute
856
+ if (el.id) {
857
+ return el.id;
858
+ }
859
+ el.setAttribute("id", randomToken);
860
+ console.log("set id=" + randomToken + " on element", el);
861
+ return randomToken;
862
+ }, randomToken);
863
+ newElementSelector = "#" + id;
864
+ // check if the id contains :
865
+ if (id.includes(":") || id.includes(".") || id.includes("[") || id.includes("]")) {
866
+ // //*[@id="radix-:r0:"]
867
+ newElementSelector = `//*[@id="${id}"]`;
868
+ }
869
+ }
870
+ }
630
871
  const scope = element._frame ?? element.page();
631
- let newElementSelector = "[data-blinq-id-" + randomToken + "]";
632
872
  let prefixSelector = "";
633
873
  const frameControlSelector = " >> internal:control=enter-frame";
634
874
  const frameSelectorIndex = element._selector.lastIndexOf(frameControlSelector);
635
875
  if (frameSelectorIndex !== -1) {
636
876
  // remove everything after the >> internal:control=enter-frame
637
877
  const frameSelector = element._selector.substring(0, frameSelectorIndex);
638
- prefixSelector = frameSelector + " >> internal:control=enter-frame >>";
878
+ prefixSelector = frameSelector + " >> internal:control=enter-frame >> ";
639
879
  }
640
880
  // if (element?._frame?._selector) {
641
881
  // prefixSelector = element._frame._selector + " >> " + prefixSelector;
@@ -674,7 +914,7 @@ class StableBrowser {
674
914
  break;
675
915
  }
676
916
  catch (error) {
677
- console.error("frame not found " + frameLocator.css);
917
+ // console.error("frame not found " + frameLocator.css);
678
918
  }
679
919
  }
680
920
  }
@@ -752,7 +992,6 @@ class StableBrowser {
752
992
  let locatorsCount = 0;
753
993
  let lazy_scroll = false;
754
994
  //let arrayMode = Array.isArray(selectors);
755
- let scope = await this._findFrameScope(selectors, timeout, info);
756
995
  let selectorsLocators = null;
757
996
  selectorsLocators = selectors.locators;
758
997
  // group selectors by priority
@@ -780,6 +1019,7 @@ class StableBrowser {
780
1019
  let highPriorityOnly = true;
781
1020
  let visibleOnly = true;
782
1021
  while (true) {
1022
+ let scope = await this._findFrameScope(selectors, timeout, info);
783
1023
  locatorsCount = 0;
784
1024
  let result = [];
785
1025
  let popupResult = await this.closeUnexpectedPopups(info, _params);
@@ -895,9 +1135,13 @@ class StableBrowser {
895
1135
  }
896
1136
  }
897
1137
  if (foundLocators.length === 1) {
1138
+ let box = null;
1139
+ if (!this.onlyFailuresScreenshot) {
1140
+ box = await foundLocators[0].boundingBox();
1141
+ }
898
1142
  result.foundElements.push({
899
1143
  locator: foundLocators[0],
900
- box: await foundLocators[0].boundingBox(),
1144
+ box: box,
901
1145
  unique: true,
902
1146
  });
903
1147
  result.locatorIndex = i;
@@ -1052,11 +1296,16 @@ class StableBrowser {
1052
1296
  operation: "click",
1053
1297
  log: "***** click on " + selectors.element_name + " *****\n",
1054
1298
  };
1299
+ check_performance("click_all ***", this.context, true);
1055
1300
  try {
1301
+ check_performance("click_preCommand", this.context, true);
1056
1302
  await _preCommand(state, this);
1303
+ check_performance("click_preCommand", this.context, false);
1057
1304
  await performAction("click", state.element, options, this, state, _params);
1058
- if (!this.fastMode) {
1059
- await this.waitForPageLoad();
1305
+ if (!this.fastMode && !this.stepTags.includes("fast-mode")) {
1306
+ check_performance("click_waitForPageLoad", this.context, true);
1307
+ await this.waitForPageLoad({ noSleep: true });
1308
+ check_performance("click_waitForPageLoad", this.context, false);
1060
1309
  }
1061
1310
  return state.info;
1062
1311
  }
@@ -1064,7 +1313,13 @@ class StableBrowser {
1064
1313
  await _commandError(state, e, this);
1065
1314
  }
1066
1315
  finally {
1316
+ check_performance("click_commandFinally", this.context, true);
1067
1317
  await _commandFinally(state, this);
1318
+ check_performance("click_commandFinally", this.context, false);
1319
+ check_performance("click_all ***", this.context, false);
1320
+ if (this.context.profile) {
1321
+ console.log(JSON.stringify(this.context.profile, null, 2));
1322
+ }
1068
1323
  }
1069
1324
  }
1070
1325
  async waitForElement(selectors, _params, options = {}, world = null) {
@@ -1156,7 +1411,7 @@ class StableBrowser {
1156
1411
  }
1157
1412
  }
1158
1413
  }
1159
- await this.waitForPageLoad();
1414
+ //await this.waitForPageLoad();
1160
1415
  return state.info;
1161
1416
  }
1162
1417
  catch (e) {
@@ -1182,7 +1437,7 @@ class StableBrowser {
1182
1437
  await _preCommand(state, this);
1183
1438
  await performAction("hover", state.element, options, this, state, _params);
1184
1439
  await _screenshot(state, this);
1185
- await this.waitForPageLoad();
1440
+ //await this.waitForPageLoad();
1186
1441
  return state.info;
1187
1442
  }
1188
1443
  catch (e) {
@@ -1218,7 +1473,7 @@ class StableBrowser {
1218
1473
  state.info.log += "selectOption failed, will try force" + "\n";
1219
1474
  await state.element.selectOption(values, { timeout: 10000, force: true });
1220
1475
  }
1221
- await this.waitForPageLoad();
1476
+ //await this.waitForPageLoad();
1222
1477
  return state.info;
1223
1478
  }
1224
1479
  catch (e) {
@@ -1449,9 +1704,9 @@ class StableBrowser {
1449
1704
  await new Promise((resolve) => setTimeout(resolve, 500));
1450
1705
  }
1451
1706
  }
1452
- if (!this.fastMode) {
1453
- await _screenshot(state, this);
1454
- }
1707
+ //if (!this.fastMode) {
1708
+ await _screenshot(state, this);
1709
+ //}
1455
1710
  if (enter === true) {
1456
1711
  await new Promise((resolve) => setTimeout(resolve, 2000));
1457
1712
  await this.page.keyboard.press("Enter");
@@ -1500,8 +1755,8 @@ class StableBrowser {
1500
1755
  if (enter) {
1501
1756
  await new Promise((resolve) => setTimeout(resolve, 2000));
1502
1757
  await this.page.keyboard.press("Enter");
1758
+ await this.waitForPageLoad();
1503
1759
  }
1504
- await this.waitForPageLoad();
1505
1760
  return state.info;
1506
1761
  }
1507
1762
  catch (e) {
@@ -1956,12 +2211,7 @@ class StableBrowser {
1956
2211
  }
1957
2212
  }
1958
2213
  getTestData(world = null) {
1959
- const dataFile = _getDataFile(world, this.context, this);
1960
- let data = {};
1961
- if (fs.existsSync(dataFile)) {
1962
- data = JSON.parse(fs.readFileSync(dataFile, "utf8"));
1963
- }
1964
- return data;
2214
+ return _getTestData(world, this.context, this);
1965
2215
  }
1966
2216
  async _screenShot(options = {}, world = null, info = null) {
1967
2217
  // collect url/path/title
@@ -2181,6 +2431,77 @@ class StableBrowser {
2181
2431
  await _commandFinally(state, this);
2182
2432
  }
2183
2433
  }
2434
+ async extractProperty(selectors, property, variable, _params = null, options = {}, world = null) {
2435
+ const state = {
2436
+ selectors,
2437
+ _params,
2438
+ property,
2439
+ variable,
2440
+ options,
2441
+ world,
2442
+ type: Types.EXTRACT_PROPERTY,
2443
+ text: `Extract property from element`,
2444
+ _text: `Extract property ${property} from ${selectors.element_name}`,
2445
+ operation: "extractProperty",
2446
+ log: "***** extract property " + property + " from " + selectors.element_name + " *****\n",
2447
+ allowDisabled: true,
2448
+ };
2449
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2450
+ try {
2451
+ await _preCommand(state, this);
2452
+ switch (property) {
2453
+ case "inner_text":
2454
+ state.value = await state.element.innerText();
2455
+ break;
2456
+ case "href":
2457
+ state.value = await state.element.getAttribute("href");
2458
+ break;
2459
+ case "value":
2460
+ state.value = await state.element.inputValue();
2461
+ break;
2462
+ case "text":
2463
+ state.value = await state.element.textContent();
2464
+ break;
2465
+ default:
2466
+ if (property.startsWith("dataset.")) {
2467
+ const dataAttribute = property.substring(8);
2468
+ state.value = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2469
+ }
2470
+ else {
2471
+ state.value = String(await state.element.evaluate((element, prop) => element[prop], property));
2472
+ }
2473
+ }
2474
+ if (options !== null) {
2475
+ if (options.regex && options.regex !== "") {
2476
+ // Construct a regex pattern from the provided string
2477
+ const regex = options.regex.slice(1, -1);
2478
+ const regexPattern = new RegExp(regex, "g");
2479
+ const matches = state.value.match(regexPattern);
2480
+ if (matches) {
2481
+ let newValue = "";
2482
+ for (const match of matches) {
2483
+ newValue += match;
2484
+ }
2485
+ state.value = newValue;
2486
+ }
2487
+ }
2488
+ if (options.trimSpaces && options.trimSpaces === true) {
2489
+ state.value = state.value.trim();
2490
+ }
2491
+ }
2492
+ state.info.value = state.value;
2493
+ this.setTestData({ [variable]: state.value }, world);
2494
+ this.logger.info("set test data: " + variable + "=" + state.value);
2495
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2496
+ return state.info;
2497
+ }
2498
+ catch (e) {
2499
+ await _commandError(state, e, this);
2500
+ }
2501
+ finally {
2502
+ await _commandFinally(state, this);
2503
+ }
2504
+ }
2184
2505
  async verifyAttribute(selectors, attribute, value, _params = null, options = {}, world = null) {
2185
2506
  const state = {
2186
2507
  selectors,
@@ -2279,6 +2600,261 @@ class StableBrowser {
2279
2600
  await _commandFinally(state, this);
2280
2601
  }
2281
2602
  }
2603
+ async verifyProperty(selectors, property, value, _params = null, options = {}, world = null) {
2604
+ const state = {
2605
+ selectors,
2606
+ _params,
2607
+ property,
2608
+ value,
2609
+ options,
2610
+ world,
2611
+ type: Types.VERIFY_PROPERTY,
2612
+ highlight: true,
2613
+ screenshot: true,
2614
+ text: `Verify element property`,
2615
+ _text: `Verify property ${property} from ${selectors.element_name} is ${value}`,
2616
+ operation: "verifyProperty",
2617
+ log: "***** verify property " + property + " from " + selectors.element_name + " *****\n",
2618
+ allowDisabled: true,
2619
+ };
2620
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2621
+ let val;
2622
+ let expectedValue;
2623
+ try {
2624
+ await _preCommand(state, this);
2625
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2626
+ state.info.expectedValue = expectedValue;
2627
+ switch (property) {
2628
+ case "innerText":
2629
+ val = String(await state.element.innerText());
2630
+ break;
2631
+ case "text":
2632
+ val = String(await state.element.textContent());
2633
+ break;
2634
+ case "value":
2635
+ val = String(await state.element.inputValue());
2636
+ break;
2637
+ case "checked":
2638
+ val = String(await state.element.isChecked());
2639
+ break;
2640
+ case "disabled":
2641
+ val = String(await state.element.isDisabled());
2642
+ break;
2643
+ case "readOnly":
2644
+ const isEditable = await state.element.isEditable();
2645
+ val = String(!isEditable);
2646
+ break;
2647
+ case "innerHTML":
2648
+ val = String(await state.element.innerHTML());
2649
+ break;
2650
+ case "outerHTML":
2651
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2652
+ break;
2653
+ default:
2654
+ if (property.startsWith("dataset.")) {
2655
+ const dataAttribute = property.substring(8);
2656
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2657
+ }
2658
+ else {
2659
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2660
+ }
2661
+ }
2662
+ // Helper function to remove all style="" attributes
2663
+ const removeStyleAttributes = (htmlString) => {
2664
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2665
+ };
2666
+ // Remove style attributes for innerHTML and outerHTML properties
2667
+ if (property === "innerHTML" || property === "outerHTML") {
2668
+ val = removeStyleAttributes(val);
2669
+ expectedValue = removeStyleAttributes(expectedValue);
2670
+ }
2671
+ state.info.value = val;
2672
+ let regex;
2673
+ state.info.value = val;
2674
+ const isRegex = expectedValue.startsWith("regex:");
2675
+ const isContains = expectedValue.startsWith("contains:");
2676
+ const isExact = expectedValue.startsWith("exact:");
2677
+ let matchPassed = false;
2678
+ if (isRegex) {
2679
+ const rawPattern = expectedValue.slice(6); // remove "regex:"
2680
+ const lastSlashIndex = rawPattern.lastIndexOf("/");
2681
+ if (rawPattern.startsWith("/") && lastSlashIndex > 0) {
2682
+ const patternBody = rawPattern.slice(1, lastSlashIndex).replace(/\n/g, ".*");
2683
+ const flags = rawPattern.slice(lastSlashIndex + 1) || "gs";
2684
+ const regex = new RegExp(patternBody, flags);
2685
+ state.info.regex = true;
2686
+ matchPassed = regex.test(val);
2687
+ }
2688
+ else {
2689
+ // Fallback: treat as literal
2690
+ const escapedPattern = rawPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2691
+ const regex = new RegExp(escapedPattern, "g");
2692
+ matchPassed = regex.test(val);
2693
+ }
2694
+ }
2695
+ else if (isContains) {
2696
+ const containsValue = expectedValue.slice(9); // remove "contains:"
2697
+ matchPassed = val.includes(containsValue);
2698
+ }
2699
+ else if (isExact) {
2700
+ const exactValue = expectedValue.slice(6); // remove "exact:"
2701
+ matchPassed = val === exactValue;
2702
+ }
2703
+ else if (property === "innerText") {
2704
+ // Default innerText logic
2705
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2706
+ const valLines = val.split("\n");
2707
+ const expectedLines = normalizedExpectedValue.split("\n");
2708
+ matchPassed = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2709
+ }
2710
+ else {
2711
+ // Fallback exact or loose match
2712
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2713
+ const regex = new RegExp(escapedPattern, "g");
2714
+ matchPassed = regex.test(val);
2715
+ }
2716
+ if (!matchPassed) {
2717
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2718
+ state.info.failCause.assertionFailed = true;
2719
+ state.info.failCause.lastError = errorMessage;
2720
+ throw new Error(errorMessage);
2721
+ }
2722
+ return state.info;
2723
+ }
2724
+ catch (e) {
2725
+ await _commandError(state, e, this);
2726
+ }
2727
+ finally {
2728
+ await _commandFinally(state, this);
2729
+ }
2730
+ }
2731
+ async conditionalWait(selectors, condition, timeout = 1000, _params = null, options = {}, world = null) {
2732
+ // Convert timeout from seconds to milliseconds
2733
+ const timeoutMs = timeout * 1000;
2734
+ const state = {
2735
+ selectors,
2736
+ _params,
2737
+ condition,
2738
+ timeout: timeoutMs, // Store as milliseconds for internal use
2739
+ options,
2740
+ world,
2741
+ type: Types.CONDITIONAL_WAIT,
2742
+ highlight: true,
2743
+ screenshot: true,
2744
+ text: `Conditional wait for element`,
2745
+ _text: `Wait for ${selectors.element_name} to be ${condition} (timeout: ${timeout}s)`, // Display original seconds
2746
+ operation: "conditionalWait",
2747
+ log: `***** conditional wait for ${condition} on ${selectors.element_name} *****\n`,
2748
+ allowDisabled: true,
2749
+ info: {},
2750
+ };
2751
+ state.options ??= { timeout: timeoutMs };
2752
+ // Initialize startTime outside try block to ensure it's always accessible
2753
+ const startTime = Date.now();
2754
+ let conditionMet = false;
2755
+ let currentValue = null;
2756
+ let lastError = null;
2757
+ // Main retry loop - continues until timeout or condition is met
2758
+ while (Date.now() - startTime < timeoutMs) {
2759
+ const elapsedTime = Date.now() - startTime;
2760
+ const remainingTime = timeoutMs - elapsedTime;
2761
+ try {
2762
+ // Try to execute _preCommand (element location)
2763
+ await _preCommand(state, this);
2764
+ // If _preCommand succeeds, start condition checking
2765
+ const checkCondition = async () => {
2766
+ try {
2767
+ switch (condition.toLowerCase()) {
2768
+ case "checked":
2769
+ currentValue = await state.element.isChecked();
2770
+ return currentValue === true;
2771
+ case "unchecked":
2772
+ currentValue = await state.element.isChecked();
2773
+ return currentValue === false;
2774
+ case "visible":
2775
+ currentValue = await state.element.isVisible();
2776
+ return currentValue === true;
2777
+ case "hidden":
2778
+ currentValue = await state.element.isVisible();
2779
+ return currentValue === false;
2780
+ case "enabled":
2781
+ currentValue = await state.element.isDisabled();
2782
+ return currentValue === false;
2783
+ case "disabled":
2784
+ currentValue = await state.element.isDisabled();
2785
+ return currentValue === true;
2786
+ case "editable":
2787
+ // currentValue = await String(await state.element.evaluate((element, prop) => element[prop], "isContentEditable"));
2788
+ currentValue = await state.element.isContentEditable();
2789
+ return currentValue === true;
2790
+ default:
2791
+ state.info.message = `Unsupported condition: '${condition}'. Supported conditions are: checked, unchecked, visible, hidden, enabled, disabled, editable.`;
2792
+ state.info.success = false;
2793
+ return false;
2794
+ }
2795
+ }
2796
+ catch (error) {
2797
+ // Don't throw here, just return false to continue retrying
2798
+ return false;
2799
+ }
2800
+ };
2801
+ // Inner loop for condition checking (once element is located)
2802
+ while (Date.now() - startTime < timeoutMs) {
2803
+ const currentElapsedTime = Date.now() - startTime;
2804
+ conditionMet = await checkCondition();
2805
+ if (conditionMet) {
2806
+ break;
2807
+ }
2808
+ // Check if we still have time for another attempt
2809
+ if (Date.now() - startTime + 50 < timeoutMs) {
2810
+ await new Promise((res) => setTimeout(res, 50));
2811
+ }
2812
+ else {
2813
+ break;
2814
+ }
2815
+ }
2816
+ // If we got here and condition is met, break out of main loop
2817
+ if (conditionMet) {
2818
+ break;
2819
+ }
2820
+ // If condition not met but no exception, we've timed out
2821
+ break;
2822
+ }
2823
+ catch (e) {
2824
+ lastError = e;
2825
+ const currentElapsedTime = Date.now() - startTime;
2826
+ const timeLeft = timeoutMs - currentElapsedTime;
2827
+ // Check if we have enough time left to retry
2828
+ if (timeLeft > 100) {
2829
+ await new Promise((resolve) => setTimeout(resolve, 50));
2830
+ }
2831
+ else {
2832
+ break;
2833
+ }
2834
+ }
2835
+ }
2836
+ const actualWaitTime = Date.now() - startTime;
2837
+ state.info = {
2838
+ success: conditionMet,
2839
+ conditionMet,
2840
+ actualWaitTime,
2841
+ currentValue,
2842
+ lastError: lastError?.message || null,
2843
+ message: conditionMet
2844
+ ? `Condition '${condition}' met after ${(actualWaitTime / 1000).toFixed(2)}s`
2845
+ : `Condition '${condition}' not met within ${timeout}s timeout`,
2846
+ };
2847
+ if (lastError) {
2848
+ state.log += `Last error: ${lastError.message}\n`;
2849
+ }
2850
+ try {
2851
+ await _commandFinally(state, this);
2852
+ }
2853
+ catch (finallyError) {
2854
+ state.log += `Error in _commandFinally: ${finallyError.message}\n`;
2855
+ }
2856
+ return state.info;
2857
+ }
2282
2858
  async extractEmailData(emailAddress, options, world) {
2283
2859
  if (!emailAddress) {
2284
2860
  throw new Error("email address is null");
@@ -2875,6 +3451,8 @@ class StableBrowser {
2875
3451
  operation: "verify_text_with_relation",
2876
3452
  log: "***** search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found *****\n",
2877
3453
  };
3454
+ const cmdStartTime = Date.now();
3455
+ let cmdEndTime = null;
2878
3456
  const timeout = this._getFindElementTimeout(options);
2879
3457
  await new Promise((resolve) => setTimeout(resolve, 2000));
2880
3458
  let newValue = await this._replaceWithLocalData(textAnchor, world);
@@ -2910,6 +3488,17 @@ class StableBrowser {
2910
3488
  await new Promise((resolve) => setTimeout(resolve, 1000));
2911
3489
  continue;
2912
3490
  }
3491
+ else {
3492
+ cmdEndTime = Date.now();
3493
+ if (cmdEndTime - cmdStartTime > 55000) {
3494
+ if (foundAncore) {
3495
+ throw new Error(`Text ${textToVerify} not found in page`);
3496
+ }
3497
+ else {
3498
+ throw new Error(`Text ${textAnchor} not found in page`);
3499
+ }
3500
+ }
3501
+ }
2913
3502
  try {
2914
3503
  for (let i = 0; i < resultWithElementsFound.length; i++) {
2915
3504
  foundAncore = true;
@@ -3309,6 +3898,43 @@ class StableBrowser {
3309
3898
  });
3310
3899
  }
3311
3900
  }
3901
+ /**
3902
+ * Explicit wait/sleep function that pauses execution for a specified duration
3903
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3904
+ * @param options - Optional configuration object
3905
+ * @param world - Optional world context
3906
+ * @returns Promise that resolves after the specified duration
3907
+ */
3908
+ async sleep(duration = 1000, options = {}, world = null) {
3909
+ const state = {
3910
+ duration,
3911
+ options,
3912
+ world,
3913
+ locate: false,
3914
+ scroll: false,
3915
+ screenshot: false,
3916
+ highlight: false,
3917
+ type: Types.SLEEP,
3918
+ text: `Sleep for ${duration} ms`,
3919
+ _text: `Sleep for ${duration} ms`,
3920
+ operation: "sleep",
3921
+ log: `***** Sleep for ${duration} ms *****\n`,
3922
+ };
3923
+ try {
3924
+ await _preCommand(state, this);
3925
+ if (duration < 0) {
3926
+ throw new Error("Sleep duration cannot be negative");
3927
+ }
3928
+ await new Promise((resolve) => setTimeout(resolve, duration));
3929
+ return state.info;
3930
+ }
3931
+ catch (e) {
3932
+ await _commandError(state, e, this);
3933
+ }
3934
+ finally {
3935
+ await _commandFinally(state, this);
3936
+ }
3937
+ }
3312
3938
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3313
3939
  try {
3314
3940
  return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
@@ -3360,6 +3986,22 @@ class StableBrowser {
3360
3986
  }
3361
3987
  }
3362
3988
  async waitForPageLoad(options = {}, world = null) {
3989
+ // try {
3990
+ // let currentPagePath = null;
3991
+ // currentPagePath = new URL(this.page.url()).pathname;
3992
+ // if (this.latestPagePath) {
3993
+ // // get the currect page path and compare with the latest page path
3994
+ // if (this.latestPagePath === currentPagePath) {
3995
+ // // if the page path is the same, do not wait for page load
3996
+ // console.log("No page change: " + currentPagePath);
3997
+ // return;
3998
+ // }
3999
+ // }
4000
+ // this.latestPagePath = currentPagePath;
4001
+ // } catch (e) {
4002
+ // console.debug("Error getting current page path: ", e);
4003
+ // }
4004
+ //console.log("Waiting for page load");
3363
4005
  let timeout = this._getLoadTimeout(options);
3364
4006
  const promiseArray = [];
3365
4007
  // let waitForNetworkIdle = true;
@@ -3392,10 +4034,12 @@ class StableBrowser {
3392
4034
  else if (e.label === "domcontentloaded") {
3393
4035
  console.log("waited for the domcontent loaded timeout");
3394
4036
  }
3395
- console.log(".");
3396
4037
  }
3397
4038
  finally {
3398
- await new Promise((resolve) => setTimeout(resolve, 2000));
4039
+ await new Promise((resolve) => setTimeout(resolve, 500));
4040
+ if (options && !options.noSleep) {
4041
+ await new Promise((resolve) => setTimeout(resolve, 1500));
4042
+ }
3399
4043
  ({ screenshotId, screenshotPath } = await this._screenShot(options, world));
3400
4044
  const endTime = Date.now();
3401
4045
  _reportToWorld(world, {
@@ -3436,7 +4080,6 @@ class StableBrowser {
3436
4080
  await this.page.close();
3437
4081
  }
3438
4082
  catch (e) {
3439
- console.log(".");
3440
4083
  await _commandError(state, e, this);
3441
4084
  }
3442
4085
  finally {
@@ -3450,7 +4093,7 @@ class StableBrowser {
3450
4093
  }
3451
4094
  operation = options.operation;
3452
4095
  // validate operation is one of the supported operations
3453
- if (operation != "click" && operation != "hover+click") {
4096
+ if (operation != "click" && operation != "hover+click" && operation != "hover") {
3454
4097
  throw new Error("operation is not supported");
3455
4098
  }
3456
4099
  const state = {
@@ -3519,6 +4162,17 @@ class StableBrowser {
3519
4162
  state.element = results[0];
3520
4163
  await performAction("hover+click", state.element, options, this, state, _params);
3521
4164
  break;
4165
+ case "hover":
4166
+ if (!options.css) {
4167
+ throw new Error("css is not defined");
4168
+ }
4169
+ const result1 = await findElementsInArea(options.css, cellArea, this, options);
4170
+ if (result1.length === 0) {
4171
+ throw new Error(`Element not found in cell area`);
4172
+ }
4173
+ state.element = result1[0];
4174
+ await performAction("hover", state.element, options, this, state, _params);
4175
+ break;
3522
4176
  default:
3523
4177
  throw new Error("operation is not supported");
3524
4178
  }
@@ -3551,7 +4205,6 @@ class StableBrowser {
3551
4205
  await this.page.setViewportSize({ width: width, height: hight });
3552
4206
  }
3553
4207
  catch (e) {
3554
- console.log(".");
3555
4208
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3556
4209
  }
3557
4210
  finally {
@@ -3589,7 +4242,6 @@ class StableBrowser {
3589
4242
  await this.page.reload();
3590
4243
  }
3591
4244
  catch (e) {
3592
- console.log(".");
3593
4245
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3594
4246
  }
3595
4247
  finally {
@@ -3633,6 +4285,10 @@ class StableBrowser {
3633
4285
  }
3634
4286
  }
3635
4287
  async beforeScenario(world, scenario) {
4288
+ if (world && world.attach) {
4289
+ world.attach(this.context.reportFolder, { mediaType: "text/plain" });
4290
+ }
4291
+ this.context.loadedRoutes = null;
3636
4292
  this.beforeScenarioCalled = true;
3637
4293
  if (scenario && scenario.pickle && scenario.pickle.name) {
3638
4294
  this.scenarioName = scenario.pickle.name;
@@ -3662,8 +4318,10 @@ class StableBrowser {
3662
4318
  }
3663
4319
  async afterScenario(world, scenario) { }
3664
4320
  async beforeStep(world, step) {
4321
+ this.stepTags = [];
3665
4322
  if (!this.beforeScenarioCalled) {
3666
4323
  this.beforeScenario(world, step);
4324
+ this.context.loadedRoutes = null;
3667
4325
  }
3668
4326
  if (this.stepIndex === undefined) {
3669
4327
  this.stepIndex = 0;
@@ -3673,7 +4331,12 @@ class StableBrowser {
3673
4331
  }
3674
4332
  if (step && step.pickleStep && step.pickleStep.text) {
3675
4333
  this.stepName = step.pickleStep.text;
3676
- this.logger.info("step: " + this.stepName);
4334
+ let printableStepName = this.stepName;
4335
+ // take the printableStepName and replace quated value with \x1b[33m and \x1b[0m
4336
+ printableStepName = printableStepName.replace(/"([^"]*)"/g, (match, p1) => {
4337
+ return `\x1b[33m"${p1}"\x1b[0m`;
4338
+ });
4339
+ this.logger.info("\x1b[38;5;208mstep:\x1b[0m " + printableStepName);
3677
4340
  }
3678
4341
  else if (step && step.text) {
3679
4342
  this.stepName = step.text;
@@ -3688,13 +4351,23 @@ class StableBrowser {
3688
4351
  }
3689
4352
  if (this.initSnapshotTaken === false) {
3690
4353
  this.initSnapshotTaken = true;
3691
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
4354
+ if (world &&
4355
+ world.attach &&
4356
+ !process.env.DISABLE_SNAPSHOT &&
4357
+ (!this.fastMode || this.stepTags.includes("fast-mode"))) {
3692
4358
  const snapshot = await this.getAriaSnapshot();
3693
4359
  if (snapshot) {
3694
4360
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3695
4361
  }
3696
4362
  }
3697
4363
  }
4364
+ this.context.routeResults = null;
4365
+ this.context.loadedRoutes = null;
4366
+ await registerBeforeStepRoutes(this.context, this.stepName, world);
4367
+ networkBeforeStep(this.stepName, this.context);
4368
+ }
4369
+ setStepTags(tags) {
4370
+ this.stepTags = tags;
3698
4371
  }
3699
4372
  async getAriaSnapshot() {
3700
4373
  try {
@@ -3714,12 +4387,18 @@ class StableBrowser {
3714
4387
  try {
3715
4388
  // Ensure frame is attached and has body
3716
4389
  const body = frame.locator("body");
3717
- await body.waitFor({ timeout: 200 }); // wait explicitly
4390
+ //await body.waitFor({ timeout: 2000 }); // wait explicitly
3718
4391
  const snapshot = await body.ariaSnapshot({ timeout });
4392
+ if (!snapshot) {
4393
+ continue;
4394
+ }
3719
4395
  content.push(`- frame: ${i}`);
3720
4396
  content.push(snapshot);
3721
4397
  }
3722
- catch (innerErr) { }
4398
+ catch (innerErr) {
4399
+ console.warn(`Frame ${i} snapshot failed:`, innerErr);
4400
+ content.push(`- frame: ${i} - error: ${innerErr.message}`);
4401
+ }
3723
4402
  }
3724
4403
  return content.join("\n");
3725
4404
  }
@@ -3791,13 +4470,23 @@ class StableBrowser {
3791
4470
  if (this.context) {
3792
4471
  this.context.examplesRow = null;
3793
4472
  }
3794
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4473
+ if (world &&
4474
+ world.attach &&
4475
+ !process.env.DISABLE_SNAPSHOT &&
4476
+ !this.fastMode &&
4477
+ !this.stepTags.includes("fast-mode")) {
3795
4478
  const snapshot = await this.getAriaSnapshot();
3796
4479
  if (snapshot) {
3797
4480
  const obj = {};
3798
4481
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3799
4482
  }
3800
4483
  }
4484
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4485
+ if (this.context.routeResults) {
4486
+ if (world && world.attach) {
4487
+ await world.attach(JSON.stringify(this.context.routeResults), "application/json+intercept-results");
4488
+ }
4489
+ }
3801
4490
  if (!process.env.TEMP_RUN) {
3802
4491
  const state = {
3803
4492
  world,
@@ -3821,6 +4510,13 @@ class StableBrowser {
3821
4510
  await _commandFinally(state, this);
3822
4511
  }
3823
4512
  }
4513
+ networkAfterStep(this.stepName, this.context);
4514
+ if (process.env.TEMP_RUN === "true") {
4515
+ // Put a sleep for some time to allow the browser to finish processing
4516
+ if (!this.stepTags.includes("fast-mode")) {
4517
+ await new Promise((resolve) => setTimeout(resolve, 3000));
4518
+ }
4519
+ }
3824
4520
  }
3825
4521
  }
3826
4522
  function createTimedPromise(promise, label) {