automation_model 1.0.713-dev → 1.0.713-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 (53) hide show
  1. package/README.md +4 -1
  2. package/lib/analyze_helper.js.map +1 -1
  3. package/lib/api.d.ts +0 -1
  4. package/lib/api.js +4 -3
  5. package/lib/api.js.map +1 -1
  6. package/lib/auto_page.d.ts +4 -2
  7. package/lib/auto_page.js +141 -85
  8. package/lib/auto_page.js.map +1 -1
  9. package/lib/browser_manager.js +22 -25
  10. package/lib/browser_manager.js.map +1 -1
  11. package/lib/bruno.js.map +1 -1
  12. package/lib/check_performance.d.ts +1 -0
  13. package/lib/check_performance.js +57 -0
  14. package/lib/check_performance.js.map +1 -0
  15. package/lib/command_common.js +22 -2
  16. package/lib/command_common.js.map +1 -1
  17. package/lib/date_time.js.map +1 -1
  18. package/lib/drawRect.js.map +1 -1
  19. package/lib/error-messages.js.map +1 -1
  20. package/lib/file_checker.js +129 -25
  21. package/lib/file_checker.js.map +1 -1
  22. package/lib/find_function.js.map +1 -1
  23. package/lib/index.js +1 -0
  24. package/lib/index.js.map +1 -1
  25. package/lib/init_browser.js +115 -125
  26. package/lib/init_browser.js.map +1 -1
  27. package/lib/locate_element.js.map +1 -1
  28. package/lib/locator.d.ts +1 -0
  29. package/lib/locator.js +10 -3
  30. package/lib/locator.js.map +1 -1
  31. package/lib/locator_log.js +0 -3
  32. package/lib/locator_log.js.map +1 -1
  33. package/lib/network.d.ts +2 -0
  34. package/lib/network.js +334 -86
  35. package/lib/network.js.map +1 -1
  36. package/lib/route.d.ts +21 -0
  37. package/lib/route.js +521 -0
  38. package/lib/route.js.map +1 -0
  39. package/lib/scripts/axe.mini.js +3 -3
  40. package/lib/snapshot_validation.js +149 -38
  41. package/lib/snapshot_validation.js.map +1 -1
  42. package/lib/stable_browser.d.ts +61 -26
  43. package/lib/stable_browser.js +1015 -223
  44. package/lib/stable_browser.js.map +1 -1
  45. package/lib/table.d.ts +9 -7
  46. package/lib/table.js +82 -12
  47. package/lib/table.js.map +1 -1
  48. package/lib/table_analyze.js.map +1 -1
  49. package/lib/table_helper.js.map +1 -1
  50. package/lib/utils.d.ts +3 -1
  51. package/lib/utils.js +92 -63
  52. package/lib/utils.js.map +1 -1
  53. package/package.json +15 -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,35 +21,42 @@ 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
35
  NAVIGATE: "navigate",
36
+ GO_BACK: "go_back",
37
+ GO_FORWARD: "go_forward",
32
38
  FILL: "fill_element",
33
- EXECUTE: "execute_page_method",
34
- OPEN: "open_environment",
39
+ EXECUTE: "execute_page_method", //
40
+ OPEN: "open_environment", //
35
41
  COMPLETE: "step_complete",
36
42
  ASK: "information_needed",
37
- GET_PAGE_STATUS: "get_page_status",
38
- CLICK_ROW_ACTION: "click_row_action",
43
+ GET_PAGE_STATUS: "get_page_status", ///
44
+ CLICK_ROW_ACTION: "click_row_action", //
39
45
  VERIFY_ELEMENT_CONTAINS_TEXT: "verify_element_contains_text",
40
46
  VERIFY_PAGE_CONTAINS_TEXT: "verify_page_contains_text",
41
47
  VERIFY_PAGE_CONTAINS_NO_TEXT: "verify_page_contains_no_text",
42
48
  ANALYZE_TABLE: "analyze_table",
43
- SELECT: "select_combobox",
49
+ SELECT: "select_combobox", //
50
+ VERIFY_PROPERTY: "verify_element_property",
44
51
  VERIFY_PAGE_PATH: "verify_page_path",
52
+ VERIFY_PAGE_TITLE: "verify_page_title",
45
53
  TYPE_PRESS: "type_press",
46
54
  PRESS: "press_key",
47
55
  HOVER: "hover_element",
48
56
  CHECK: "check_element",
49
57
  UNCHECK: "uncheck_element",
50
58
  EXTRACT: "extract_attribute",
59
+ EXTRACT_PROPERTY: "extract_property",
51
60
  CLOSE_PAGE: "close_page",
52
61
  TABLE_OPERATION: "table_operation",
53
62
  SET_DATE_TIME: "set_date_time",
@@ -59,9 +68,13 @@ export const Types = {
59
68
  VERIFY_ATTRIBUTE: "verify_element_attribute",
60
69
  VERIFY_TEXT_WITH_RELATION: "verify_text_with_relation",
61
70
  BRUNO: "bruno",
62
- SNAPSHOT_VALIDATION: "snapshot_validation",
63
71
  VERIFY_FILE_EXISTS: "verify_file_exists",
64
72
  SET_INPUT_FILES: "set_input_files",
73
+ SNAPSHOT_VALIDATION: "snapshot_validation",
74
+ REPORT_COMMAND: "report_command",
75
+ STEP_COMPLETE: "step_complete",
76
+ SLEEP: "sleep",
77
+ CONDITIONAL_WAIT: "conditional_wait",
65
78
  };
66
79
  export const apps = {};
67
80
  const formatElementName = (elementName) => {
@@ -73,6 +86,7 @@ class StableBrowser {
73
86
  logger;
74
87
  context;
75
88
  world;
89
+ fastMode;
76
90
  project_path = null;
77
91
  webLogFile = null;
78
92
  networkLogger = null;
@@ -81,12 +95,14 @@ class StableBrowser {
81
95
  tags = null;
82
96
  isRecording = false;
83
97
  initSnapshotTaken = false;
84
- constructor(browser, page, logger = null, context = null, world = null) {
98
+ onlyFailuresScreenshot = process.env.SCREENSHOT_ON_FAILURE_ONLY === "true";
99
+ constructor(browser, page, logger = null, context = null, world = null, fastMode = false) {
85
100
  this.browser = browser;
86
101
  this.page = page;
87
102
  this.logger = logger;
88
103
  this.context = context;
89
104
  this.world = world;
105
+ this.fastMode = fastMode;
90
106
  if (!this.logger) {
91
107
  this.logger = console;
92
108
  }
@@ -115,6 +131,19 @@ class StableBrowser {
115
131
  context.pages = [this.page];
116
132
  const logFolder = path.join(this.project_path, "logs", "web");
117
133
  this.world = world;
134
+ if (this.configuration && this.configuration.fastMode === true) {
135
+ this.fastMode = true;
136
+ }
137
+ if (process.env.FAST_MODE === "true") {
138
+ // console.log("Fast mode enabled from environment variable");
139
+ this.fastMode = true;
140
+ }
141
+ if (process.env.FAST_MODE === "false") {
142
+ this.fastMode = false;
143
+ }
144
+ if (this.context) {
145
+ this.context.fastMode = this.fastMode;
146
+ }
118
147
  this.registerEventListeners(this.context);
119
148
  registerNetworkEvents(this.world, this, this.context, this.page);
120
149
  registerDownloadEvent(this.page, this.world, this.context);
@@ -125,6 +154,9 @@ class StableBrowser {
125
154
  if (!context.pageLoading) {
126
155
  context.pageLoading = { status: false };
127
156
  }
157
+ if (this.configuration && this.configuration.acceptDialog && this.page) {
158
+ this.page.on("dialog", (dialog) => dialog.accept());
159
+ }
128
160
  context.playContext.on("page", async function (page) {
129
161
  if (this.configuration && this.configuration.closePopups === true) {
130
162
  console.log("close unexpected popups");
@@ -133,6 +165,14 @@ class StableBrowser {
133
165
  }
134
166
  context.pageLoading.status = true;
135
167
  this.page = page;
168
+ try {
169
+ if (this.configuration && this.configuration.acceptDialog) {
170
+ await page.on("dialog", (dialog) => dialog.accept());
171
+ }
172
+ }
173
+ catch (error) {
174
+ console.error("Error on dialog accept registration", error);
175
+ }
136
176
  context.page = page;
137
177
  context.pages.push(page);
138
178
  registerNetworkEvents(this.world, this, context, this.page);
@@ -184,7 +224,9 @@ class StableBrowser {
184
224
  if (newContextCreated) {
185
225
  this.registerEventListeners(this.context);
186
226
  await this.goto(this.context.environment.baseUrl);
187
- await this.waitForPageLoad();
227
+ if (!this.fastMode) {
228
+ await this.waitForPageLoad();
229
+ }
188
230
  }
189
231
  }
190
232
  async switchTab(tabTitleOrIndex) {
@@ -278,6 +320,7 @@ class StableBrowser {
278
320
  if (!url) {
279
321
  throw new Error("url is null, verify that the environment file is correct");
280
322
  }
323
+ url = await this._replaceWithLocalData(url, this.world);
281
324
  if (!url.startsWith("http")) {
282
325
  url = "https://" + url;
283
326
  }
@@ -309,6 +352,64 @@ class StableBrowser {
309
352
  await _commandFinally(state, this);
310
353
  }
311
354
  }
355
+ async goBack(options, world = null) {
356
+ const state = {
357
+ value: "",
358
+ world: world,
359
+ type: Types.GO_BACK,
360
+ text: `Browser navigate back`,
361
+ operation: "goBack",
362
+ log: "***** navigate back *****\n",
363
+ info: {},
364
+ locate: false,
365
+ scroll: false,
366
+ screenshot: false,
367
+ highlight: false,
368
+ };
369
+ try {
370
+ await _preCommand(state, this);
371
+ await this.page.goBack({
372
+ waitUntil: "load",
373
+ });
374
+ await _screenshot(state, this);
375
+ }
376
+ catch (error) {
377
+ console.error("Error on goBack", error);
378
+ _commandError(state, error, this);
379
+ }
380
+ finally {
381
+ await _commandFinally(state, this);
382
+ }
383
+ }
384
+ async goForward(options, world = null) {
385
+ const state = {
386
+ value: "",
387
+ world: world,
388
+ type: Types.GO_FORWARD,
389
+ text: `Browser navigate forward`,
390
+ operation: "goForward",
391
+ log: "***** navigate forward *****\n",
392
+ info: {},
393
+ locate: false,
394
+ scroll: false,
395
+ screenshot: false,
396
+ highlight: false,
397
+ };
398
+ try {
399
+ await _preCommand(state, this);
400
+ await this.page.goForward({
401
+ waitUntil: "load",
402
+ });
403
+ await _screenshot(state, this);
404
+ }
405
+ catch (error) {
406
+ console.error("Error on goForward", error);
407
+ _commandError(state, error, this);
408
+ }
409
+ finally {
410
+ await _commandFinally(state, this);
411
+ }
412
+ }
312
413
  async _getLocator(locator, scope, _params) {
313
414
  locator = _fixLocatorUsingParams(locator, _params);
314
415
  // locator = await this._replaceWithLocalData(locator);
@@ -407,12 +508,6 @@ class StableBrowser {
407
508
  if (!el.setAttribute) {
408
509
  el = el.parentElement;
409
510
  }
410
- // remove any attributes start with data-blinq-id
411
- // for (let i = 0; i < el.attributes.length; i++) {
412
- // if (el.attributes[i].name.startsWith("data-blinq-id")) {
413
- // el.removeAttribute(el.attributes[i].name);
414
- // }
415
- // }
416
511
  el.setAttribute("data-blinq-id-" + randomToken, "");
417
512
  return true;
418
513
  }, [tag1, randomToken]))) {
@@ -422,7 +517,7 @@ class StableBrowser {
422
517
  }
423
518
  return { elementCount: tagCount, randomToken };
424
519
  }
425
- async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null) {
520
+ async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null, logErrors = false) {
426
521
  if (!info) {
427
522
  info = {};
428
523
  }
@@ -434,14 +529,13 @@ class StableBrowser {
434
529
  info.locatorLog = new LocatorLog(selectorHierarchy);
435
530
  }
436
531
  let locatorSearch = selectorHierarchy[index];
437
- let originalLocatorSearch = "";
438
532
  try {
439
- originalLocatorSearch = _fixUsingParams(JSON.stringify(locatorSearch), _params);
440
- locatorSearch = JSON.parse(originalLocatorSearch);
533
+ locatorSearch = _fixLocatorUsingParams(locatorSearch, _params);
441
534
  }
442
535
  catch (e) {
443
536
  console.error(e);
444
537
  }
538
+ let originalLocatorSearch = JSON.stringify(locatorSearch);
445
539
  //info.log += "searching for locator " + JSON.stringify(locatorSearch) + "\n";
446
540
  let locator = null;
447
541
  if (locatorSearch.climb && locatorSearch.climb >= 0) {
@@ -489,7 +583,7 @@ class StableBrowser {
489
583
  }
490
584
  return;
491
585
  }
492
- if (info.locatorLog && count === 0) {
586
+ if (info.locatorLog && count === 0 && logErrors) {
493
587
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "NOT_FOUND");
494
588
  }
495
589
  for (let j = 0; j < count; j++) {
@@ -504,7 +598,7 @@ class StableBrowser {
504
598
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "FOUND");
505
599
  }
506
600
  }
507
- else {
601
+ else if (logErrors) {
508
602
  info.failCause.visible = visible;
509
603
  info.failCause.enabled = enabled;
510
604
  if (!info.printMessages) {
@@ -583,31 +677,148 @@ class StableBrowser {
583
677
  }
584
678
  return { rerun: false };
585
679
  }
680
+ getFilePath() {
681
+ const stackFrames = errorStackParser.parse(new Error());
682
+ const stackFrame = stackFrames.findLast((frame) => frame.fileName && frame.fileName.endsWith(".mjs"));
683
+ // return stackFrame?.fileName || null;
684
+ const filepath = stackFrame?.fileName;
685
+ if (filepath) {
686
+ let jsonFilePath = filepath.replace(".mjs", ".json");
687
+ if (existsSync(jsonFilePath)) {
688
+ return jsonFilePath;
689
+ }
690
+ const config = this.configuration ?? {};
691
+ if (!config?.locatorsMetadataDir) {
692
+ config.locatorsMetadataDir = "features/step_definitions/locators";
693
+ }
694
+ if (config && config.locatorsMetadataDir) {
695
+ jsonFilePath = path.join(config.locatorsMetadataDir, path.basename(jsonFilePath));
696
+ }
697
+ if (existsSync(jsonFilePath)) {
698
+ return jsonFilePath;
699
+ }
700
+ return null;
701
+ }
702
+ return null;
703
+ }
704
+ getFullElementLocators(selectors, filePath) {
705
+ if (!filePath || !existsSync(filePath)) {
706
+ return null;
707
+ }
708
+ const content = fs.readFileSync(filePath, "utf8");
709
+ try {
710
+ const allElements = JSON.parse(content);
711
+ const element_key = selectors?.element_key;
712
+ if (element_key && allElements[element_key]) {
713
+ return allElements[element_key];
714
+ }
715
+ for (const elementKey in allElements) {
716
+ const element = allElements[elementKey];
717
+ let foundStrategy = null;
718
+ for (const key in element) {
719
+ if (key === "strategy") {
720
+ continue;
721
+ }
722
+ const locators = element[key];
723
+ if (!locators || !locators.length) {
724
+ continue;
725
+ }
726
+ for (const locator of locators) {
727
+ delete locator.score;
728
+ }
729
+ if (JSON.stringify(locators) === JSON.stringify(selectors.locators)) {
730
+ foundStrategy = key;
731
+ break;
732
+ }
733
+ }
734
+ if (foundStrategy) {
735
+ return element;
736
+ }
737
+ }
738
+ }
739
+ catch (error) {
740
+ console.error("Error parsing locators from file: " + filePath, error);
741
+ }
742
+ return null;
743
+ }
586
744
  async _locate(selectors, info, _params, timeout, allowDisabled = false) {
587
745
  if (!timeout) {
588
746
  timeout = 30000;
589
747
  }
748
+ let element = null;
749
+ let allStrategyLocators = null;
750
+ let selectedStrategy = null;
751
+ if (this.tryAllStrategies) {
752
+ allStrategyLocators = this.getFullElementLocators(selectors, this.getFilePath());
753
+ selectedStrategy = allStrategyLocators?.strategy;
754
+ }
590
755
  for (let i = 0; i < 3; i++) {
591
- if (process.env.SUPRESS_ERRORS === "true") {
592
- info.log += "attempt " + i + ": total locators " + selectors.locators.length + "\n";
593
- }
756
+ info.log += "attempt " + i + ": total locators " + selectors.locators.length + "\n";
594
757
  for (let j = 0; j < selectors.locators.length; j++) {
595
758
  let selector = selectors.locators[j];
596
- if (process.env.SUPRESS_ERRORS === "true") {
597
- info.log += "searching for locator " + j + ":" + JSON.stringify(selector) + "\n";
759
+ info.log += "searching for locator " + j + ":" + JSON.stringify(selector) + "\n";
760
+ }
761
+ if (this.tryAllStrategies && selectedStrategy) {
762
+ const strategyLocators = allStrategyLocators[selectedStrategy];
763
+ let err;
764
+ if (strategyLocators && strategyLocators.length) {
765
+ try {
766
+ selectors.locators = strategyLocators;
767
+ element = await this._locate_internal(selectors, info, _params, 10_000, allowDisabled);
768
+ info.selectedStrategy = selectedStrategy;
769
+ info.log += "element found using strategy " + selectedStrategy + "\n";
770
+ }
771
+ catch (error) {
772
+ err = error;
773
+ }
774
+ }
775
+ if (!element) {
776
+ for (const key in allStrategyLocators) {
777
+ if (key === "strategy" || key === selectedStrategy) {
778
+ continue;
779
+ }
780
+ const strategyLocators = allStrategyLocators[key];
781
+ if (strategyLocators && strategyLocators.length) {
782
+ try {
783
+ info.log += "using strategy " + key + " with locators " + JSON.stringify(strategyLocators) + "\n";
784
+ selectors.locators = strategyLocators;
785
+ element = await this._locate_internal(selectors, info, _params, 10_000, allowDisabled);
786
+ err = null;
787
+ info.selectedStrategy = key;
788
+ info.log += "element found using strategy " + key + "\n";
789
+ break;
790
+ }
791
+ catch (error) {
792
+ err = error;
793
+ }
794
+ }
795
+ }
796
+ }
797
+ if (err) {
798
+ throw err;
598
799
  }
599
800
  }
600
- let element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
801
+ else {
802
+ element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
803
+ }
601
804
  if (!element.rerun) {
602
- const randomToken = Math.random().toString(36).substring(7);
603
- element.evaluate((el, randomToken) => {
604
- el.setAttribute("data-blinq-id-" + randomToken, "");
805
+ const randomToken = "blinq_" + Math.random().toString(36).substring(7);
806
+ const id = await element.evaluate((el, randomToken) => {
807
+ // check if the element has id attribute
808
+ if (el.id) {
809
+ return el.id;
810
+ }
811
+ el.setAttribute("id", randomToken);
812
+ console.log("set id=" + randomToken + " on element", el);
813
+ return randomToken;
605
814
  }, randomToken);
606
- // if (element._frame) {
607
- // return element;
608
- // }
609
815
  const scope = element._frame ?? element.page();
610
- let newElementSelector = "[data-blinq-id-" + randomToken + "]";
816
+ let newElementSelector = "#" + id;
817
+ // check if the id contains :
818
+ if (id.includes(":")) {
819
+ // //*[@id="radix-:r0:"]
820
+ newElementSelector = `//*[@id="${id}"]`;
821
+ }
611
822
  let prefixSelector = "";
612
823
  const frameControlSelector = " >> internal:control=enter-frame";
613
824
  const frameSelectorIndex = element._selector.lastIndexOf(frameControlSelector);
@@ -623,12 +834,7 @@ class StableBrowser {
623
834
  return scope.locator(newSelector);
624
835
  }
625
836
  }
626
- if (process.env.SUPRESS_ERRORS === "true") {
627
- throw new Error("unable to locate the element");
628
- }
629
- else {
630
- throw new Error("unable to locate element " + JSON.stringify(selectors));
631
- }
837
+ throw new Error("unable to locate element " + JSON.stringify(selectors));
632
838
  }
633
839
  async _findFrameScope(selectors, timeout = 30000, info) {
634
840
  if (!info) {
@@ -658,7 +864,7 @@ class StableBrowser {
658
864
  break;
659
865
  }
660
866
  catch (error) {
661
- console.error("frame not found " + frameLocator.css);
867
+ // console.error("frame not found " + frameLocator.css);
662
868
  }
663
869
  }
664
870
  }
@@ -736,7 +942,6 @@ class StableBrowser {
736
942
  let locatorsCount = 0;
737
943
  let lazy_scroll = false;
738
944
  //let arrayMode = Array.isArray(selectors);
739
- let scope = await this._findFrameScope(selectors, timeout, info);
740
945
  let selectorsLocators = null;
741
946
  selectorsLocators = selectors.locators;
742
947
  // group selectors by priority
@@ -764,6 +969,7 @@ class StableBrowser {
764
969
  let highPriorityOnly = true;
765
970
  let visibleOnly = true;
766
971
  while (true) {
972
+ let scope = await this._findFrameScope(selectors, timeout, info);
767
973
  locatorsCount = 0;
768
974
  let result = [];
769
975
  let popupResult = await this.closeUnexpectedPopups(info, _params);
@@ -852,14 +1058,9 @@ class StableBrowser {
852
1058
  if (!info?.failCause?.lastError) {
853
1059
  info.failCause.lastError = `failed to locate ${formatElementName(selectors.element_name)}, ${locatorsCount > 0 ? `${locatorsCount} matching elements found` : "no matching elements found"}`;
854
1060
  }
855
- if (process.env.SUPRESS_ERRORS === "true") {
856
- throw new Error("failed to locate first element no elements found");
857
- }
858
- else {
859
- throw new Error("failed to locate first element no elements found, " + info.log);
860
- }
1061
+ throw new Error("failed to locate first element no elements found, " + info.log);
861
1062
  }
862
- async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name) {
1063
+ async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name, logErrors = false) {
863
1064
  let foundElements = [];
864
1065
  const result = {
865
1066
  foundElements: foundElements,
@@ -878,13 +1079,19 @@ class StableBrowser {
878
1079
  await this._collectLocatorInformation(locatorsGroup, i, this.page, foundLocators, _params, info, visibleOnly, allowDisabled, element_name);
879
1080
  }
880
1081
  catch (e) {
881
- this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
1082
+ if (logErrors) {
1083
+ this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
1084
+ }
882
1085
  }
883
1086
  }
884
1087
  if (foundLocators.length === 1) {
1088
+ let box = null;
1089
+ if (!this.onlyFailuresScreenshot) {
1090
+ box = await foundLocators[0].boundingBox();
1091
+ }
885
1092
  result.foundElements.push({
886
1093
  locator: foundLocators[0],
887
- box: await foundLocators[0].boundingBox(),
1094
+ box: box,
888
1095
  unique: true,
889
1096
  });
890
1097
  result.locatorIndex = i;
@@ -919,7 +1126,7 @@ class StableBrowser {
919
1126
  });
920
1127
  result.locatorIndex = i;
921
1128
  }
922
- else {
1129
+ else if (logErrors) {
923
1130
  info.failCause.foundMultiple = true;
924
1131
  if (info.locatorLog) {
925
1132
  info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
@@ -1039,17 +1246,30 @@ class StableBrowser {
1039
1246
  operation: "click",
1040
1247
  log: "***** click on " + selectors.element_name + " *****\n",
1041
1248
  };
1249
+ check_performance("click_all ***", this.context, true);
1042
1250
  try {
1251
+ check_performance("click_preCommand", this.context, true);
1043
1252
  await _preCommand(state, this);
1253
+ check_performance("click_preCommand", this.context, false);
1044
1254
  await performAction("click", state.element, options, this, state, _params);
1045
- await this.waitForPageLoad();
1255
+ if (!this.fastMode) {
1256
+ check_performance("click_waitForPageLoad", this.context, true);
1257
+ await this.waitForPageLoad({ noSleep: true });
1258
+ check_performance("click_waitForPageLoad", this.context, false);
1259
+ }
1046
1260
  return state.info;
1047
1261
  }
1048
1262
  catch (e) {
1049
1263
  await _commandError(state, e, this);
1050
1264
  }
1051
1265
  finally {
1266
+ check_performance("click_commandFinally", this.context, true);
1052
1267
  await _commandFinally(state, this);
1268
+ check_performance("click_commandFinally", this.context, false);
1269
+ check_performance("click_all ***", this.context, false);
1270
+ if (this.context.profile) {
1271
+ console.log(JSON.stringify(this.context.profile, null, 2));
1272
+ }
1053
1273
  }
1054
1274
  }
1055
1275
  async waitForElement(selectors, _params, options = {}, world = null) {
@@ -1105,7 +1325,7 @@ class StableBrowser {
1105
1325
  // if (world && world.screenshot && !world.screenshotPath) {
1106
1326
  // console.log(`Highlighting while running from recorder`);
1107
1327
  await this._highlightElements(state.element);
1108
- await state.element.setChecked(checked);
1328
+ await state.element.setChecked(checked, { timeout: 2000 });
1109
1329
  await new Promise((resolve) => setTimeout(resolve, 1000));
1110
1330
  // await this._unHighlightElements(element);
1111
1331
  // }
@@ -1117,14 +1337,31 @@ class StableBrowser {
1117
1337
  this.logger.info("element did not change its state, ignoring...");
1118
1338
  }
1119
1339
  else {
1340
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1120
1341
  //await this.closeUnexpectedPopups();
1121
1342
  state.info.log += "setCheck failed, will try again" + "\n";
1122
- state.element = await this._locate(selectors, state.info, _params);
1123
- await state.element.setChecked(checked, { timeout: 5000, force: true });
1124
- await new Promise((resolve) => setTimeout(resolve, 1000));
1343
+ state.element_found = false;
1344
+ try {
1345
+ state.element = await this._locate(selectors, state.info, _params, 100);
1346
+ state.element_found = true;
1347
+ // check the check state
1348
+ }
1349
+ catch (error) {
1350
+ // element dismissed
1351
+ }
1352
+ if (state.element_found) {
1353
+ const isChecked = await state.element.isChecked();
1354
+ if (isChecked !== checked) {
1355
+ // perform click
1356
+ await state.element.click({ timeout: 2000, force: true });
1357
+ }
1358
+ else {
1359
+ this.logger.info(`Element ${selectors.element_name} is already in the desired state (${checked})`);
1360
+ }
1361
+ }
1125
1362
  }
1126
1363
  }
1127
- await this.waitForPageLoad();
1364
+ //await this.waitForPageLoad();
1128
1365
  return state.info;
1129
1366
  }
1130
1367
  catch (e) {
@@ -1150,7 +1387,7 @@ class StableBrowser {
1150
1387
  await _preCommand(state, this);
1151
1388
  await performAction("hover", state.element, options, this, state, _params);
1152
1389
  await _screenshot(state, this);
1153
- await this.waitForPageLoad();
1390
+ //await this.waitForPageLoad();
1154
1391
  return state.info;
1155
1392
  }
1156
1393
  catch (e) {
@@ -1186,7 +1423,7 @@ class StableBrowser {
1186
1423
  state.info.log += "selectOption failed, will try force" + "\n";
1187
1424
  await state.element.selectOption(values, { timeout: 10000, force: true });
1188
1425
  }
1189
- await this.waitForPageLoad();
1426
+ //await this.waitForPageLoad();
1190
1427
  return state.info;
1191
1428
  }
1192
1429
  catch (e) {
@@ -1417,7 +1654,9 @@ class StableBrowser {
1417
1654
  await new Promise((resolve) => setTimeout(resolve, 500));
1418
1655
  }
1419
1656
  }
1657
+ //if (!this.fastMode) {
1420
1658
  await _screenshot(state, this);
1659
+ //}
1421
1660
  if (enter === true) {
1422
1661
  await new Promise((resolve) => setTimeout(resolve, 2000));
1423
1662
  await this.page.keyboard.press("Enter");
@@ -1466,8 +1705,8 @@ class StableBrowser {
1466
1705
  if (enter) {
1467
1706
  await new Promise((resolve) => setTimeout(resolve, 2000));
1468
1707
  await this.page.keyboard.press("Enter");
1708
+ await this.waitForPageLoad();
1469
1709
  }
1470
- await this.waitForPageLoad();
1471
1710
  return state.info;
1472
1711
  }
1473
1712
  catch (e) {
@@ -1759,6 +1998,11 @@ class StableBrowser {
1759
1998
  throw new Error("Snapshot validation failed at line " + matchResult.errorLineText);
1760
1999
  }
1761
2000
  // highlight and screenshot
2001
+ try {
2002
+ await await highlightSnapshot(newValue, scope);
2003
+ await _screenshot(state, this);
2004
+ }
2005
+ catch (e) { }
1762
2006
  return state.info;
1763
2007
  }
1764
2008
  catch (e) {
@@ -1917,12 +2161,7 @@ class StableBrowser {
1917
2161
  }
1918
2162
  }
1919
2163
  getTestData(world = null) {
1920
- const dataFile = _getDataFile(world, this.context, this);
1921
- let data = {};
1922
- if (fs.existsSync(dataFile)) {
1923
- data = JSON.parse(fs.readFileSync(dataFile, "utf8"));
1924
- }
1925
- return data;
2164
+ return _getTestData(world, this.context, this);
1926
2165
  }
1927
2166
  async _screenShot(options = {}, world = null, info = null) {
1928
2167
  // collect url/path/title
@@ -2142,6 +2381,77 @@ class StableBrowser {
2142
2381
  await _commandFinally(state, this);
2143
2382
  }
2144
2383
  }
2384
+ async extractProperty(selectors, property, variable, _params = null, options = {}, world = null) {
2385
+ const state = {
2386
+ selectors,
2387
+ _params,
2388
+ property,
2389
+ variable,
2390
+ options,
2391
+ world,
2392
+ type: Types.EXTRACT_PROPERTY,
2393
+ text: `Extract property from element`,
2394
+ _text: `Extract property ${property} from ${selectors.element_name}`,
2395
+ operation: "extractProperty",
2396
+ log: "***** extract property " + property + " from " + selectors.element_name + " *****\n",
2397
+ allowDisabled: true,
2398
+ };
2399
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2400
+ try {
2401
+ await _preCommand(state, this);
2402
+ switch (property) {
2403
+ case "inner_text":
2404
+ state.value = await state.element.innerText();
2405
+ break;
2406
+ case "href":
2407
+ state.value = await state.element.getAttribute("href");
2408
+ break;
2409
+ case "value":
2410
+ state.value = await state.element.inputValue();
2411
+ break;
2412
+ case "text":
2413
+ state.value = await state.element.textContent();
2414
+ break;
2415
+ default:
2416
+ if (property.startsWith("dataset.")) {
2417
+ const dataAttribute = property.substring(8);
2418
+ state.value = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2419
+ }
2420
+ else {
2421
+ state.value = String(await state.element.evaluate((element, prop) => element[prop], property));
2422
+ }
2423
+ }
2424
+ if (options !== null) {
2425
+ if (options.regex && options.regex !== "") {
2426
+ // Construct a regex pattern from the provided string
2427
+ const regex = options.regex.slice(1, -1);
2428
+ const regexPattern = new RegExp(regex, "g");
2429
+ const matches = state.value.match(regexPattern);
2430
+ if (matches) {
2431
+ let newValue = "";
2432
+ for (const match of matches) {
2433
+ newValue += match;
2434
+ }
2435
+ state.value = newValue;
2436
+ }
2437
+ }
2438
+ if (options.trimSpaces && options.trimSpaces === true) {
2439
+ state.value = state.value.trim();
2440
+ }
2441
+ }
2442
+ state.info.value = state.value;
2443
+ this.setTestData({ [variable]: state.value }, world);
2444
+ this.logger.info("set test data: " + variable + "=" + state.value);
2445
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2446
+ return state.info;
2447
+ }
2448
+ catch (e) {
2449
+ await _commandError(state, e, this);
2450
+ }
2451
+ finally {
2452
+ await _commandFinally(state, this);
2453
+ }
2454
+ }
2145
2455
  async verifyAttribute(selectors, attribute, value, _params = null, options = {}, world = null) {
2146
2456
  const state = {
2147
2457
  selectors,
@@ -2240,6 +2550,260 @@ class StableBrowser {
2240
2550
  await _commandFinally(state, this);
2241
2551
  }
2242
2552
  }
2553
+ async verifyProperty(selectors, property, value, _params = null, options = {}, world = null) {
2554
+ const state = {
2555
+ selectors,
2556
+ _params,
2557
+ property,
2558
+ value,
2559
+ options,
2560
+ world,
2561
+ type: Types.VERIFY_PROPERTY,
2562
+ highlight: true,
2563
+ screenshot: true,
2564
+ text: `Verify element property`,
2565
+ _text: `Verify property ${property} from ${selectors.element_name} is ${value}`,
2566
+ operation: "verifyProperty",
2567
+ log: "***** verify property " + property + " from " + selectors.element_name + " *****\n",
2568
+ allowDisabled: true,
2569
+ };
2570
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2571
+ let val;
2572
+ let expectedValue;
2573
+ try {
2574
+ await _preCommand(state, this);
2575
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2576
+ state.info.expectedValue = expectedValue;
2577
+ switch (property) {
2578
+ case "innerText":
2579
+ val = String(await state.element.innerText());
2580
+ break;
2581
+ case "text":
2582
+ val = String(await state.element.textContent());
2583
+ break;
2584
+ case "value":
2585
+ val = String(await state.element.inputValue());
2586
+ break;
2587
+ case "checked":
2588
+ val = String(await state.element.isChecked());
2589
+ break;
2590
+ case "disabled":
2591
+ val = String(await state.element.isDisabled());
2592
+ break;
2593
+ case "readOnly":
2594
+ const isEditable = await state.element.isEditable();
2595
+ val = String(!isEditable);
2596
+ break;
2597
+ case "innerHTML":
2598
+ val = String(await state.element.innerHTML());
2599
+ break;
2600
+ case "outerHTML":
2601
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2602
+ break;
2603
+ default:
2604
+ if (property.startsWith("dataset.")) {
2605
+ const dataAttribute = property.substring(8);
2606
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2607
+ }
2608
+ else {
2609
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2610
+ }
2611
+ }
2612
+ // Helper function to remove all style="" attributes
2613
+ const removeStyleAttributes = (htmlString) => {
2614
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2615
+ };
2616
+ // Remove style attributes for innerHTML and outerHTML properties
2617
+ if (property === "innerHTML" || property === "outerHTML") {
2618
+ val = removeStyleAttributes(val);
2619
+ expectedValue = removeStyleAttributes(expectedValue);
2620
+ }
2621
+ state.info.value = val;
2622
+ let regex;
2623
+ state.info.value = val;
2624
+ const isRegex = expectedValue.startsWith("regex:");
2625
+ const isContains = expectedValue.startsWith("contains:");
2626
+ const isExact = expectedValue.startsWith("exact:");
2627
+ let matchPassed = false;
2628
+ if (isRegex) {
2629
+ const rawPattern = expectedValue.slice(6); // remove "regex:"
2630
+ const lastSlashIndex = rawPattern.lastIndexOf("/");
2631
+ if (rawPattern.startsWith("/") && lastSlashIndex > 0) {
2632
+ const patternBody = rawPattern.slice(1, lastSlashIndex).replace(/\n/g, ".*");
2633
+ const flags = rawPattern.slice(lastSlashIndex + 1) || "gs";
2634
+ const regex = new RegExp(patternBody, flags);
2635
+ state.info.regex = true;
2636
+ matchPassed = regex.test(val);
2637
+ }
2638
+ else {
2639
+ // Fallback: treat as literal
2640
+ const escapedPattern = rawPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2641
+ const regex = new RegExp(escapedPattern, "g");
2642
+ matchPassed = regex.test(val);
2643
+ }
2644
+ }
2645
+ else if (isContains) {
2646
+ const containsValue = expectedValue.slice(9); // remove "contains:"
2647
+ matchPassed = val.includes(containsValue);
2648
+ }
2649
+ else if (isExact) {
2650
+ const exactValue = expectedValue.slice(6); // remove "exact:"
2651
+ matchPassed = val === exactValue;
2652
+ }
2653
+ else if (property === "innerText") {
2654
+ // Default innerText logic
2655
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2656
+ const valLines = val.split("\n");
2657
+ const expectedLines = normalizedExpectedValue.split("\n");
2658
+ matchPassed = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2659
+ }
2660
+ else {
2661
+ // Fallback exact or loose match
2662
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2663
+ const regex = new RegExp(escapedPattern, "g");
2664
+ matchPassed = regex.test(val);
2665
+ }
2666
+ if (!matchPassed) {
2667
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2668
+ state.info.failCause.assertionFailed = true;
2669
+ state.info.failCause.lastError = errorMessage;
2670
+ throw new Error(errorMessage);
2671
+ }
2672
+ return state.info;
2673
+ }
2674
+ catch (e) {
2675
+ await _commandError(state, e, this);
2676
+ }
2677
+ finally {
2678
+ await _commandFinally(state, this);
2679
+ }
2680
+ }
2681
+ async conditionalWait(selectors, condition, timeout = 1000, _params = null, options = {}, world = null) {
2682
+ // Convert timeout from seconds to milliseconds
2683
+ const timeoutMs = timeout * 1000;
2684
+ const state = {
2685
+ selectors,
2686
+ _params,
2687
+ condition,
2688
+ timeout: timeoutMs, // Store as milliseconds for internal use
2689
+ options,
2690
+ world,
2691
+ type: Types.CONDITIONAL_WAIT,
2692
+ highlight: true,
2693
+ screenshot: true,
2694
+ text: `Conditional wait for element`,
2695
+ _text: `Wait for ${selectors.element_name} to be ${condition} (timeout: ${timeout}s)`, // Display original seconds
2696
+ operation: "conditionalWait",
2697
+ log: `***** conditional wait for ${condition} on ${selectors.element_name} *****\n`,
2698
+ allowDisabled: true,
2699
+ info: {},
2700
+ };
2701
+ // Initialize startTime outside try block to ensure it's always accessible
2702
+ const startTime = Date.now();
2703
+ let conditionMet = false;
2704
+ let currentValue = null;
2705
+ let lastError = null;
2706
+ // Main retry loop - continues until timeout or condition is met
2707
+ while (Date.now() - startTime < timeoutMs) {
2708
+ const elapsedTime = Date.now() - startTime;
2709
+ const remainingTime = timeoutMs - elapsedTime;
2710
+ try {
2711
+ // Try to execute _preCommand (element location)
2712
+ await _preCommand(state, this);
2713
+ // If _preCommand succeeds, start condition checking
2714
+ const checkCondition = async () => {
2715
+ try {
2716
+ switch (condition.toLowerCase()) {
2717
+ case "checked":
2718
+ currentValue = await state.element.isChecked();
2719
+ return currentValue === true;
2720
+ case "unchecked":
2721
+ currentValue = await state.element.isChecked();
2722
+ return currentValue === false;
2723
+ case "visible":
2724
+ currentValue = await state.element.isVisible();
2725
+ return currentValue === true;
2726
+ case "hidden":
2727
+ currentValue = await state.element.isVisible();
2728
+ return currentValue === false;
2729
+ case "enabled":
2730
+ currentValue = await state.element.isDisabled();
2731
+ return currentValue === false;
2732
+ case "disabled":
2733
+ currentValue = await state.element.isDisabled();
2734
+ return currentValue === true;
2735
+ case "editable":
2736
+ // currentValue = await String(await state.element.evaluate((element, prop) => element[prop], "isContentEditable"));
2737
+ currentValue = await state.element.isContentEditable();
2738
+ return currentValue === true;
2739
+ default:
2740
+ state.info.message = `Unsupported condition: '${condition}'. Supported conditions are: checked, unchecked, visible, hidden, enabled, disabled, editable.`;
2741
+ state.info.success = false;
2742
+ return false;
2743
+ }
2744
+ }
2745
+ catch (error) {
2746
+ // Don't throw here, just return false to continue retrying
2747
+ return false;
2748
+ }
2749
+ };
2750
+ // Inner loop for condition checking (once element is located)
2751
+ while (Date.now() - startTime < timeoutMs) {
2752
+ const currentElapsedTime = Date.now() - startTime;
2753
+ conditionMet = await checkCondition();
2754
+ if (conditionMet) {
2755
+ break;
2756
+ }
2757
+ // Check if we still have time for another attempt
2758
+ if (Date.now() - startTime + 50 < timeoutMs) {
2759
+ await new Promise((res) => setTimeout(res, 50));
2760
+ }
2761
+ else {
2762
+ break;
2763
+ }
2764
+ }
2765
+ // If we got here and condition is met, break out of main loop
2766
+ if (conditionMet) {
2767
+ break;
2768
+ }
2769
+ // If condition not met but no exception, we've timed out
2770
+ break;
2771
+ }
2772
+ catch (e) {
2773
+ lastError = e;
2774
+ const currentElapsedTime = Date.now() - startTime;
2775
+ const timeLeft = timeoutMs - currentElapsedTime;
2776
+ // Check if we have enough time left to retry
2777
+ if (timeLeft > 100) {
2778
+ await new Promise((resolve) => setTimeout(resolve, 50));
2779
+ }
2780
+ else {
2781
+ break;
2782
+ }
2783
+ }
2784
+ }
2785
+ const actualWaitTime = Date.now() - startTime;
2786
+ state.info = {
2787
+ success: conditionMet,
2788
+ conditionMet,
2789
+ actualWaitTime,
2790
+ currentValue,
2791
+ lastError: lastError?.message || null,
2792
+ message: conditionMet
2793
+ ? `Condition '${condition}' met after ${(actualWaitTime / 1000).toFixed(2)}s`
2794
+ : `Condition '${condition}' not met within ${timeout}s timeout`,
2795
+ };
2796
+ if (lastError) {
2797
+ state.log += `Last error: ${lastError.message}\n`;
2798
+ }
2799
+ try {
2800
+ await _commandFinally(state, this);
2801
+ }
2802
+ catch (finallyError) {
2803
+ state.log += `Error in _commandFinally: ${finallyError.message}\n`;
2804
+ }
2805
+ return state.info;
2806
+ }
2243
2807
  async extractEmailData(emailAddress, options, world) {
2244
2808
  if (!emailAddress) {
2245
2809
  throw new Error("email address is null");
@@ -2397,56 +2961,49 @@ class StableBrowser {
2397
2961
  console.debug(error);
2398
2962
  }
2399
2963
  }
2400
- // async _unhighlightElements(scope, css) {
2401
- // try {
2402
- // if (!scope) {
2403
- // return;
2404
- // }
2405
- // if (!css) {
2406
- // scope
2407
- // .evaluate((node) => {
2408
- // if (node && node.style) {
2409
- // if (!node.__previousOutline) {
2410
- // node.style.outline = "";
2411
- // } else {
2412
- // node.style.outline = node.__previousOutline;
2413
- // }
2414
- // }
2415
- // })
2416
- // .then(() => {})
2417
- // .catch((e) => {
2418
- // // console.log(`Error while unhighlighting node ${JSON.stringify(scope)}: ${e}`);
2419
- // });
2420
- // } else {
2421
- // scope
2422
- // .evaluate(([css]) => {
2423
- // if (!css) {
2424
- // return;
2425
- // }
2426
- // let elements = Array.from(document.querySelectorAll(css));
2427
- // for (i = 0; i < elements.length; i++) {
2428
- // let element = elements[i];
2429
- // if (!element.style) {
2430
- // return;
2431
- // }
2432
- // if (!element.__previousOutline) {
2433
- // element.style.outline = "";
2434
- // } else {
2435
- // element.style.outline = element.__previousOutline;
2436
- // }
2437
- // }
2438
- // })
2439
- // .then(() => {})
2440
- // .catch((e) => {
2441
- // // console.error(`Error while unhighlighting element in css: ${e}`);
2442
- // });
2443
- // }
2444
- // } catch (error) {
2445
- // // console.debug(error);
2446
- // }
2447
- // }
2964
+ _matcher(text) {
2965
+ if (!text) {
2966
+ return { matcher: "contains", queryText: "" };
2967
+ }
2968
+ if (text.length < 2) {
2969
+ return { matcher: "contains", queryText: text };
2970
+ }
2971
+ const split = text.split(":");
2972
+ const matcher = split[0].toLowerCase();
2973
+ const queryText = split.slice(1).join(":").trim();
2974
+ return { matcher, queryText };
2975
+ }
2976
+ _getDomain(url) {
2977
+ if (url.length === 0 || (!url.startsWith("http://") && !url.startsWith("https://"))) {
2978
+ return "";
2979
+ }
2980
+ let hostnameFragments = url.split("/")[2].split(".");
2981
+ if (hostnameFragments.some((fragment) => fragment.includes(":"))) {
2982
+ return hostnameFragments.join("-").split(":").join("-");
2983
+ }
2984
+ let n = hostnameFragments.length;
2985
+ let fragments = [...hostnameFragments];
2986
+ while (n > 0 && hostnameFragments[n - 1].length <= 3) {
2987
+ hostnameFragments.pop();
2988
+ n = hostnameFragments.length;
2989
+ }
2990
+ if (n == 0) {
2991
+ if (fragments[0] === "www")
2992
+ fragments = fragments.slice(1);
2993
+ return fragments.length > 1 ? fragments.slice(0, fragments.length - 1).join("-") : fragments.join("-");
2994
+ }
2995
+ if (hostnameFragments[0] === "www")
2996
+ hostnameFragments = hostnameFragments.slice(1);
2997
+ return hostnameFragments.join(".");
2998
+ }
2999
+ /**
3000
+ * Verify the page path matches the given path.
3001
+ * @param {string} pathPart - The path to verify.
3002
+ * @param {object} options - Options for verification.
3003
+ * @param {object} world - The world context.
3004
+ * @returns {Promise<object>} - The state info after verification.
3005
+ */
2448
3006
  async verifyPagePath(pathPart, options = {}, world = null) {
2449
- const startTime = Date.now();
2450
3007
  let error = null;
2451
3008
  let screenshotId = null;
2452
3009
  let screenshotPath = null;
@@ -2460,113 +3017,212 @@ class StableBrowser {
2460
3017
  pathPart = newValue;
2461
3018
  }
2462
3019
  info.pathPart = pathPart;
3020
+ const { matcher, queryText } = this._matcher(pathPart);
3021
+ const state = {
3022
+ text_search: queryText,
3023
+ options,
3024
+ world,
3025
+ locate: false,
3026
+ scroll: false,
3027
+ highlight: false,
3028
+ type: Types.VERIFY_PAGE_PATH,
3029
+ text: `Verify the page url is ${queryText}`,
3030
+ _text: `Verify the page url is ${queryText}`,
3031
+ operation: "verifyPagePath",
3032
+ log: "***** verify page url is " + queryText + " *****\n",
3033
+ };
2463
3034
  try {
3035
+ await _preCommand(state, this);
3036
+ state.info.text = queryText;
2464
3037
  for (let i = 0; i < 30; i++) {
2465
3038
  const url = await this.page.url();
2466
- if (!url.includes(pathPart)) {
2467
- if (i === 29) {
2468
- throw new Error(`url ${url} doesn't contain ${pathPart}`);
2469
- }
2470
- await new Promise((resolve) => setTimeout(resolve, 1000));
2471
- continue;
3039
+ switch (matcher) {
3040
+ case "exact":
3041
+ if (url !== queryText) {
3042
+ if (i === 29) {
3043
+ throw new Error(`Page URL ${url} is not equal to ${queryText}`);
3044
+ }
3045
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3046
+ continue;
3047
+ }
3048
+ break;
3049
+ case "contains":
3050
+ if (!url.includes(queryText)) {
3051
+ if (i === 29) {
3052
+ throw new Error(`Page URL ${url} doesn't contain ${queryText}`);
3053
+ }
3054
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3055
+ continue;
3056
+ }
3057
+ break;
3058
+ case "starts-with":
3059
+ {
3060
+ const domain = this._getDomain(url);
3061
+ if (domain.length > 0 && domain !== queryText) {
3062
+ if (i === 29) {
3063
+ throw new Error(`Page URL ${url} doesn't start with ${queryText}`);
3064
+ }
3065
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3066
+ continue;
3067
+ }
3068
+ }
3069
+ break;
3070
+ case "ends-with":
3071
+ {
3072
+ const urlObj = new URL(url);
3073
+ let route = "/";
3074
+ if (urlObj.pathname !== "/") {
3075
+ route = urlObj.pathname.split("/").slice(-1)[0].trim();
3076
+ }
3077
+ else {
3078
+ route = "/";
3079
+ }
3080
+ if (route !== queryText) {
3081
+ if (i === 29) {
3082
+ throw new Error(`Page URL ${url} doesn't end with ${queryText}`);
3083
+ }
3084
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3085
+ continue;
3086
+ }
3087
+ }
3088
+ break;
3089
+ case "regex":
3090
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3091
+ if (!regex.test(url)) {
3092
+ if (i === 29) {
3093
+ throw new Error(`Page URL ${url} doesn't match regex ${queryText}`);
3094
+ }
3095
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3096
+ continue;
3097
+ }
3098
+ break;
3099
+ default:
3100
+ console.log("Unknown matching type, defaulting to contains matching");
3101
+ if (!url.includes(pathPart)) {
3102
+ if (i === 29) {
3103
+ throw new Error(`Page URL ${url} does not contain ${pathPart}`);
3104
+ }
3105
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3106
+ continue;
3107
+ }
2472
3108
  }
2473
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2474
- return info;
3109
+ await _screenshot(state, this);
3110
+ return state.info;
2475
3111
  }
2476
3112
  }
2477
3113
  catch (e) {
2478
- //await this.closeUnexpectedPopups();
2479
- this.logger.error("verify page path failed " + info.log);
2480
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2481
- info.screenshotPath = screenshotPath;
2482
- Object.assign(e, { info: info });
2483
- error = e;
2484
- // throw e;
2485
- await _commandError({ text: "verifyPagePath", operation: "verifyPagePath", pathPart, info, throwError: true }, e, this);
3114
+ state.info.failCause.lastError = e.message;
3115
+ state.info.failCause.assertionFailed = true;
3116
+ await _commandError(state, e, this);
2486
3117
  }
2487
3118
  finally {
2488
- const endTime = Date.now();
2489
- _reportToWorld(world, {
2490
- type: Types.VERIFY_PAGE_PATH,
2491
- text: "Verify page path",
2492
- _text: "Verify the page path contains " + pathPart,
2493
- screenshotId,
2494
- result: error
2495
- ? {
2496
- status: "FAILED",
2497
- startTime,
2498
- endTime,
2499
- message: error?.message,
2500
- }
2501
- : {
2502
- status: "PASSED",
2503
- startTime,
2504
- endTime,
2505
- },
2506
- info: info,
2507
- });
3119
+ await _commandFinally(state, this);
2508
3120
  }
2509
3121
  }
3122
+ /**
3123
+ * Verify the page title matches the given title.
3124
+ * @param {string} title - The title to verify.
3125
+ * @param {object} options - Options for verification.
3126
+ * @param {object} world - The world context.
3127
+ * @returns {Promise<object>} - The state info after verification.
3128
+ */
2510
3129
  async verifyPageTitle(title, options = {}, world = null) {
2511
- const startTime = Date.now();
2512
3130
  let error = null;
2513
3131
  let screenshotId = null;
2514
3132
  let screenshotPath = null;
2515
3133
  await new Promise((resolve) => setTimeout(resolve, 2000));
2516
- const info = {};
2517
- info.log = "***** verify page title " + title + " *****\n";
2518
- info.operation = "verifyPageTitle";
2519
3134
  const newValue = await this._replaceWithLocalData(title, world);
2520
3135
  if (newValue !== title) {
2521
3136
  this.logger.info(title + "=" + newValue);
2522
3137
  title = newValue;
2523
3138
  }
2524
- info.title = title;
3139
+ const { matcher, queryText } = this._matcher(title);
3140
+ const state = {
3141
+ text_search: queryText,
3142
+ options,
3143
+ world,
3144
+ locate: false,
3145
+ scroll: false,
3146
+ highlight: false,
3147
+ type: Types.VERIFY_PAGE_TITLE,
3148
+ text: `Verify the page title is ${queryText}`,
3149
+ _text: `Verify the page title is ${queryText}`,
3150
+ operation: "verifyPageTitle",
3151
+ log: "***** verify page title is " + queryText + " *****\n",
3152
+ };
2525
3153
  try {
3154
+ await _preCommand(state, this);
3155
+ state.info.text = queryText;
2526
3156
  for (let i = 0; i < 30; i++) {
2527
3157
  const foundTitle = await this.page.title();
2528
- if (!foundTitle.includes(title)) {
2529
- if (i === 29) {
2530
- throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2531
- }
2532
- await new Promise((resolve) => setTimeout(resolve, 1000));
2533
- continue;
3158
+ switch (matcher) {
3159
+ case "exact":
3160
+ if (foundTitle !== queryText) {
3161
+ if (i === 29) {
3162
+ throw new Error(`Page Title ${foundTitle} is not equal to ${queryText}`);
3163
+ }
3164
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3165
+ continue;
3166
+ }
3167
+ break;
3168
+ case "contains":
3169
+ if (!foundTitle.includes(queryText)) {
3170
+ if (i === 29) {
3171
+ throw new Error(`Page Title ${foundTitle} doesn't contain ${queryText}`);
3172
+ }
3173
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3174
+ continue;
3175
+ }
3176
+ break;
3177
+ case "starts-with":
3178
+ if (!foundTitle.startsWith(queryText)) {
3179
+ if (i === 29) {
3180
+ throw new Error(`Page title ${foundTitle} doesn't start with ${queryText}`);
3181
+ }
3182
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3183
+ continue;
3184
+ }
3185
+ break;
3186
+ case "ends-with":
3187
+ if (!foundTitle.endsWith(queryText)) {
3188
+ if (i === 29) {
3189
+ throw new Error(`Page Title ${foundTitle} doesn't end with ${queryText}`);
3190
+ }
3191
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3192
+ continue;
3193
+ }
3194
+ break;
3195
+ case "regex":
3196
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3197
+ if (!regex.test(foundTitle)) {
3198
+ if (i === 29) {
3199
+ throw new Error(`Page Title ${foundTitle} doesn't match regex ${queryText}`);
3200
+ }
3201
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3202
+ continue;
3203
+ }
3204
+ break;
3205
+ default:
3206
+ console.log("Unknown matching type, defaulting to contains matching");
3207
+ if (!foundTitle.includes(title)) {
3208
+ if (i === 29) {
3209
+ throw new Error(`Page Title ${foundTitle} does not contain ${title}`);
3210
+ }
3211
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3212
+ continue;
3213
+ }
2534
3214
  }
2535
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2536
- return info;
3215
+ await _screenshot(state, this);
3216
+ return state.info;
2537
3217
  }
2538
3218
  }
2539
3219
  catch (e) {
2540
- //await this.closeUnexpectedPopups();
2541
- this.logger.error("verify page title failed " + info.log);
2542
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2543
- info.screenshotPath = screenshotPath;
2544
- Object.assign(e, { info: info });
2545
- error = e;
2546
- // throw e;
2547
- await _commandError({ text: "verifyPageTitle", operation: "verifyPageTitle", title, info, throwError: true }, e, this);
3220
+ state.info.failCause.lastError = e.message;
3221
+ state.info.failCause.assertionFailed = true;
3222
+ await _commandError(state, e, this);
2548
3223
  }
2549
3224
  finally {
2550
- const endTime = Date.now();
2551
- _reportToWorld(world, {
2552
- type: Types.VERIFY_PAGE_PATH,
2553
- text: "Verify page title",
2554
- _text: "Verify the page title contains " + title,
2555
- screenshotId,
2556
- result: error
2557
- ? {
2558
- status: "FAILED",
2559
- startTime,
2560
- endTime,
2561
- message: error?.message,
2562
- }
2563
- : {
2564
- status: "PASSED",
2565
- startTime,
2566
- endTime,
2567
- },
2568
- info: info,
2569
- });
3225
+ await _commandFinally(state, this);
2570
3226
  }
2571
3227
  }
2572
3228
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2650,27 +3306,10 @@ class StableBrowser {
2650
3306
  const frame = resultWithElementsFound[0].frame;
2651
3307
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2652
3308
  await this._highlightElements(frame, dataAttribute);
2653
- // if (world && world.screenshot && !world.screenshotPath) {
2654
- // console.log(`Highlighting for verify text is found while running from recorder`);
2655
- // this._highlightElements(frame, dataAttribute).then(async () => {
2656
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2657
- // this._unhighlightElements(frame, dataAttribute)
2658
- // .then(async () => {
2659
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2660
- // })
2661
- // .catch(
2662
- // (e) => {}
2663
- // console.error(e)
2664
- // );
2665
- // });
2666
- // }
2667
3309
  const element = await frame.locator(dataAttribute).first();
2668
- // await new Promise((resolve) => setTimeout(resolve, 100));
2669
- // await this._unhighlightElements(frame, dataAttribute);
2670
3310
  if (element) {
2671
3311
  await this.scrollIfNeeded(element, state.info);
2672
3312
  await element.dispatchEvent("bvt_verify_page_contains_text");
2673
- // await _screenshot(state, this, element);
2674
3313
  }
2675
3314
  }
2676
3315
  await _screenshot(state, this);
@@ -2680,7 +3319,6 @@ class StableBrowser {
2680
3319
  console.error(error);
2681
3320
  }
2682
3321
  }
2683
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2684
3322
  }
2685
3323
  catch (e) {
2686
3324
  await _commandError(state, e, this);
@@ -2762,6 +3400,8 @@ class StableBrowser {
2762
3400
  operation: "verify_text_with_relation",
2763
3401
  log: "***** search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found *****\n",
2764
3402
  };
3403
+ const cmdStartTime = Date.now();
3404
+ let cmdEndTime = null;
2765
3405
  const timeout = this._getFindElementTimeout(options);
2766
3406
  await new Promise((resolve) => setTimeout(resolve, 2000));
2767
3407
  let newValue = await this._replaceWithLocalData(textAnchor, world);
@@ -2797,6 +3437,17 @@ class StableBrowser {
2797
3437
  await new Promise((resolve) => setTimeout(resolve, 1000));
2798
3438
  continue;
2799
3439
  }
3440
+ else {
3441
+ cmdEndTime = Date.now();
3442
+ if (cmdEndTime - cmdStartTime > 55000) {
3443
+ if (foundAncore) {
3444
+ throw new Error(`Text ${textToVerify} not found in page`);
3445
+ }
3446
+ else {
3447
+ throw new Error(`Text ${textAnchor} not found in page`);
3448
+ }
3449
+ }
3450
+ }
2800
3451
  try {
2801
3452
  for (let i = 0; i < resultWithElementsFound.length; i++) {
2802
3453
  foundAncore = true;
@@ -3196,6 +3847,43 @@ class StableBrowser {
3196
3847
  });
3197
3848
  }
3198
3849
  }
3850
+ /**
3851
+ * Explicit wait/sleep function that pauses execution for a specified duration
3852
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3853
+ * @param options - Optional configuration object
3854
+ * @param world - Optional world context
3855
+ * @returns Promise that resolves after the specified duration
3856
+ */
3857
+ async sleep(duration = 1000, options = {}, world = null) {
3858
+ const state = {
3859
+ duration,
3860
+ options,
3861
+ world,
3862
+ locate: false,
3863
+ scroll: false,
3864
+ screenshot: false,
3865
+ highlight: false,
3866
+ type: Types.SLEEP,
3867
+ text: `Sleep for ${duration} ms`,
3868
+ _text: `Sleep for ${duration} ms`,
3869
+ operation: "sleep",
3870
+ log: `***** Sleep for ${duration} ms *****\n`,
3871
+ };
3872
+ try {
3873
+ await _preCommand(state, this);
3874
+ if (duration < 0) {
3875
+ throw new Error("Sleep duration cannot be negative");
3876
+ }
3877
+ await new Promise((resolve) => setTimeout(resolve, duration));
3878
+ return state.info;
3879
+ }
3880
+ catch (e) {
3881
+ await _commandError(state, e, this);
3882
+ }
3883
+ finally {
3884
+ await _commandFinally(state, this);
3885
+ }
3886
+ }
3199
3887
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3200
3888
  try {
3201
3889
  return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
@@ -3226,6 +3914,7 @@ class StableBrowser {
3226
3914
  }
3227
3915
  async saveStoreState(path = null, world = null) {
3228
3916
  const storageState = await this.page.context().storageState();
3917
+ path = await this._replaceWithLocalData(path, this.world);
3229
3918
  //const testDataFile = _getDataFile(world, this.context, this);
3230
3919
  if (path) {
3231
3920
  // save { storageState: storageState } into the path
@@ -3236,6 +3925,7 @@ class StableBrowser {
3236
3925
  }
3237
3926
  }
3238
3927
  async restoreSaveState(path = null, world = null) {
3928
+ path = await this._replaceWithLocalData(path, this.world);
3239
3929
  await refreshBrowser(this, path, world);
3240
3930
  this.registerEventListeners(this.context);
3241
3931
  registerNetworkEvents(this.world, this, this.context, this.page);
@@ -3245,6 +3935,22 @@ class StableBrowser {
3245
3935
  }
3246
3936
  }
3247
3937
  async waitForPageLoad(options = {}, world = null) {
3938
+ // try {
3939
+ // let currentPagePath = null;
3940
+ // currentPagePath = new URL(this.page.url()).pathname;
3941
+ // if (this.latestPagePath) {
3942
+ // // get the currect page path and compare with the latest page path
3943
+ // if (this.latestPagePath === currentPagePath) {
3944
+ // // if the page path is the same, do not wait for page load
3945
+ // console.log("No page change: " + currentPagePath);
3946
+ // return;
3947
+ // }
3948
+ // }
3949
+ // this.latestPagePath = currentPagePath;
3950
+ // } catch (e) {
3951
+ // console.debug("Error getting current page path: ", e);
3952
+ // }
3953
+ //console.log("Waiting for page load");
3248
3954
  let timeout = this._getLoadTimeout(options);
3249
3955
  const promiseArray = [];
3250
3956
  // let waitForNetworkIdle = true;
@@ -3277,10 +3983,12 @@ class StableBrowser {
3277
3983
  else if (e.label === "domcontentloaded") {
3278
3984
  console.log("waited for the domcontent loaded timeout");
3279
3985
  }
3280
- console.log(".");
3281
3986
  }
3282
3987
  finally {
3283
- await new Promise((resolve) => setTimeout(resolve, 2000));
3988
+ await new Promise((resolve) => setTimeout(resolve, 500));
3989
+ if (options && !options.noSleep) {
3990
+ await new Promise((resolve) => setTimeout(resolve, 1500));
3991
+ }
3284
3992
  ({ screenshotId, screenshotPath } = await this._screenShot(options, world));
3285
3993
  const endTime = Date.now();
3286
3994
  _reportToWorld(world, {
@@ -3321,7 +4029,6 @@ class StableBrowser {
3321
4029
  await this.page.close();
3322
4030
  }
3323
4031
  catch (e) {
3324
- console.log(".");
3325
4032
  await _commandError(state, e, this);
3326
4033
  }
3327
4034
  finally {
@@ -3436,7 +4143,6 @@ class StableBrowser {
3436
4143
  await this.page.setViewportSize({ width: width, height: hight });
3437
4144
  }
3438
4145
  catch (e) {
3439
- console.log(".");
3440
4146
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3441
4147
  }
3442
4148
  finally {
@@ -3474,7 +4180,6 @@ class StableBrowser {
3474
4180
  await this.page.reload();
3475
4181
  }
3476
4182
  catch (e) {
3477
- console.log(".");
3478
4183
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3479
4184
  }
3480
4185
  finally {
@@ -3518,6 +4223,10 @@ class StableBrowser {
3518
4223
  }
3519
4224
  }
3520
4225
  async beforeScenario(world, scenario) {
4226
+ if (world && world.attach) {
4227
+ world.attach(this.context.reportFolder, { mediaType: "text/plain" });
4228
+ }
4229
+ this.context.loadedRoutes = null;
3521
4230
  this.beforeScenarioCalled = true;
3522
4231
  if (scenario && scenario.pickle && scenario.pickle.name) {
3523
4232
  this.scenarioName = scenario.pickle.name;
@@ -3541,7 +4250,7 @@ class StableBrowser {
3541
4250
  envName = this.context.environment.name;
3542
4251
  }
3543
4252
  if (!process.env.TEMP_RUN) {
3544
- await getTestData(envName, world, undefined, this.featureName, this.scenarioName);
4253
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
3545
4254
  }
3546
4255
  await loadBrunoParams(this.context, this.context.environment.name);
3547
4256
  }
@@ -3549,6 +4258,7 @@ class StableBrowser {
3549
4258
  async beforeStep(world, step) {
3550
4259
  if (!this.beforeScenarioCalled) {
3551
4260
  this.beforeScenario(world, step);
4261
+ this.context.loadedRoutes = null;
3552
4262
  }
3553
4263
  if (this.stepIndex === undefined) {
3554
4264
  this.stepIndex = 0;
@@ -3573,13 +4283,16 @@ class StableBrowser {
3573
4283
  }
3574
4284
  if (this.initSnapshotTaken === false) {
3575
4285
  this.initSnapshotTaken = true;
3576
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4286
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3577
4287
  const snapshot = await this.getAriaSnapshot();
3578
4288
  if (snapshot) {
3579
4289
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3580
4290
  }
3581
4291
  }
3582
4292
  }
4293
+ this.context.routeResults = null;
4294
+ await registerBeforeStepRoutes(this.context, this.stepName);
4295
+ networkBeforeStep(this.stepName);
3583
4296
  }
3584
4297
  async getAriaSnapshot() {
3585
4298
  try {
@@ -3599,12 +4312,18 @@ class StableBrowser {
3599
4312
  try {
3600
4313
  // Ensure frame is attached and has body
3601
4314
  const body = frame.locator("body");
3602
- await body.waitFor({ timeout: 200 }); // wait explicitly
4315
+ //await body.waitFor({ timeout: 2000 }); // wait explicitly
3603
4316
  const snapshot = await body.ariaSnapshot({ timeout });
4317
+ if (!snapshot) {
4318
+ continue;
4319
+ }
3604
4320
  content.push(`- frame: ${i}`);
3605
4321
  content.push(snapshot);
3606
4322
  }
3607
- catch (innerErr) { }
4323
+ catch (innerErr) {
4324
+ console.warn(`Frame ${i} snapshot failed:`, innerErr);
4325
+ content.push(`- frame: ${i} - error: ${innerErr.message}`);
4326
+ }
3608
4327
  }
3609
4328
  return content.join("\n");
3610
4329
  }
@@ -3614,6 +4333,49 @@ class StableBrowser {
3614
4333
  }
3615
4334
  return null;
3616
4335
  }
4336
+ /**
4337
+ * Sends command with custom payload to report.
4338
+ * @param commandText - Title of the command to be shown in the report.
4339
+ * @param commandStatus - Status of the command (e.g. "PASSED", "FAILED").
4340
+ * @param content - Content of the command to be shown in the report.
4341
+ * @param options - Options for the command. Example: { type: "json", screenshot: true }
4342
+ * @param world - Optional world context.
4343
+ * @public
4344
+ */
4345
+ async addCommandToReport(commandText, commandStatus, content, options = {}, world = null) {
4346
+ const state = {
4347
+ options,
4348
+ world,
4349
+ locate: false,
4350
+ scroll: false,
4351
+ screenshot: options.screenshot ?? false,
4352
+ highlight: options.highlight ?? false,
4353
+ type: Types.REPORT_COMMAND,
4354
+ text: commandText,
4355
+ _text: commandText,
4356
+ operation: "report_command",
4357
+ log: "***** " + commandText + " *****\n",
4358
+ };
4359
+ try {
4360
+ await _preCommand(state, this);
4361
+ const payload = {
4362
+ type: options.type ?? "text",
4363
+ content: content,
4364
+ screenshotId: null,
4365
+ };
4366
+ state.payload = payload;
4367
+ if (commandStatus === "FAILED") {
4368
+ state.throwError = true;
4369
+ throw new Error("Command failed");
4370
+ }
4371
+ }
4372
+ catch (e) {
4373
+ await _commandError(state, e, this);
4374
+ }
4375
+ finally {
4376
+ await _commandFinally(state, this);
4377
+ }
4378
+ }
3617
4379
  async afterStep(world, step) {
3618
4380
  this.stepName = null;
3619
4381
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3633,13 +4395,43 @@ class StableBrowser {
3633
4395
  if (this.context) {
3634
4396
  this.context.examplesRow = null;
3635
4397
  }
3636
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4398
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3637
4399
  const snapshot = await this.getAriaSnapshot();
3638
4400
  if (snapshot) {
3639
4401
  const obj = {};
3640
4402
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3641
4403
  }
3642
4404
  }
4405
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4406
+ if (this.context.routeResults) {
4407
+ if (world && world.attach) {
4408
+ await world.attach(JSON.stringify(this.context.routeResults), "application/json+intercept-results");
4409
+ }
4410
+ }
4411
+ if (!process.env.TEMP_RUN) {
4412
+ const state = {
4413
+ world,
4414
+ locate: false,
4415
+ scroll: false,
4416
+ screenshot: true,
4417
+ highlight: true,
4418
+ type: Types.STEP_COMPLETE,
4419
+ text: "end of scenario",
4420
+ _text: "end of scenario",
4421
+ operation: "step_complete",
4422
+ log: "***** " + "end of scenario" + " *****\n",
4423
+ };
4424
+ try {
4425
+ await _preCommand(state, this);
4426
+ }
4427
+ catch (e) {
4428
+ await _commandError(state, e, this);
4429
+ }
4430
+ finally {
4431
+ await _commandFinally(state, this);
4432
+ }
4433
+ }
4434
+ networkAfterStep(this.stepName);
3643
4435
  }
3644
4436
  }
3645
4437
  function createTimedPromise(promise, label) {