automation_model 1.0.703-dev → 1.0.703-stage

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +4 -1
  2. package/lib/analyze_helper.js.map +1 -1
  3. package/lib/api.d.ts +0 -1
  4. package/lib/api.js.map +1 -1
  5. package/lib/auto_page.d.ts +4 -2
  6. package/lib/auto_page.js +210 -126
  7. package/lib/auto_page.js.map +1 -1
  8. package/lib/browser_manager.d.ts +1 -0
  9. package/lib/browser_manager.js +54 -9
  10. package/lib/browser_manager.js.map +1 -1
  11. package/lib/bruno.js.map +1 -1
  12. package/lib/command_common.d.ts +1 -1
  13. package/lib/command_common.js +18 -1
  14. package/lib/command_common.js.map +1 -1
  15. package/lib/date_time.js.map +1 -1
  16. package/lib/drawRect.js.map +1 -1
  17. package/lib/environment.d.ts +1 -0
  18. package/lib/environment.js +1 -0
  19. package/lib/environment.js.map +1 -1
  20. package/lib/error-messages.js.map +1 -1
  21. package/lib/file_checker.js +129 -25
  22. package/lib/file_checker.js.map +1 -1
  23. package/lib/find_function.js.map +1 -1
  24. package/lib/init_browser.js +4 -4
  25. package/lib/init_browser.js.map +1 -1
  26. package/lib/locate_element.js.map +1 -1
  27. package/lib/locator.d.ts +1 -0
  28. package/lib/locator.js +10 -3
  29. package/lib/locator.js.map +1 -1
  30. package/lib/locator_log.js.map +1 -1
  31. package/lib/network.d.ts +2 -0
  32. package/lib/network.js +334 -86
  33. package/lib/network.js.map +1 -1
  34. package/lib/route.d.ts +21 -0
  35. package/lib/route.js +450 -0
  36. package/lib/route.js.map +1 -0
  37. package/lib/scripts/axe.mini.js +3 -3
  38. package/lib/snapshot_validation.d.ts +4 -2
  39. package/lib/snapshot_validation.js +160 -42
  40. package/lib/snapshot_validation.js.map +1 -1
  41. package/lib/stable_browser.d.ts +61 -26
  42. package/lib/stable_browser.js +1004 -201
  43. package/lib/stable_browser.js.map +1 -1
  44. package/lib/table.d.ts +9 -7
  45. package/lib/table.js +82 -12
  46. package/lib/table.js.map +1 -1
  47. package/lib/table_analyze.js.map +1 -1
  48. package/lib/table_helper.js.map +1 -1
  49. package/lib/test_context.d.ts +1 -0
  50. package/lib/test_context.js +1 -0
  51. package/lib/test_context.js.map +1 -1
  52. package/lib/utils.d.ts +3 -1
  53. package/lib/utils.js +88 -63
  54. package/lib/utils.js.map +1 -1
  55. package/package.json +13 -7
@@ -10,7 +10,8 @@ import { getDateTimeValue } from "./date_time.js";
10
10
  import drawRectangle from "./drawRect.js";
11
11
  //import { closeUnexpectedPopups } from "./popups.js";
12
12
  import { getTableCells, getTableData } from "./table_analyze.js";
13
- import { _convertToRegexQuery, _copyContext, _fixLocatorUsingParams, _fixUsingParams, _getServerUrl, extractStepExampleParameters, KEYBOARD_EVENTS, maskValue, replaceWithLocalTestData, scrollPageToLoadLazyElements, unEscapeString, _getDataFile, testForRegex, performAction, } from "./utils.js";
13
+ import errorStackParser from "error-stack-parser";
14
+ import { _convertToRegexQuery, _copyContext, _fixLocatorUsingParams, _fixUsingParams, _getServerUrl, extractStepExampleParameters, KEYBOARD_EVENTS, maskValue, replaceWithLocalTestData, scrollPageToLoadLazyElements, unEscapeString, _getDataFile, testForRegex, performAction, _getTestData, } from "./utils.js";
14
15
  import csv from "csv-parser";
15
16
  import { Readable } from "node:stream";
16
17
  import readline from "readline";
@@ -19,35 +20,42 @@ import { getTestData } from "./auto_page.js";
19
20
  import { locate_element } from "./locate_element.js";
20
21
  import { randomUUID } from "crypto";
21
22
  import { _commandError, _commandFinally, _preCommand, _validateSelectors, _screenshot, _reportToWorld, } from "./command_common.js";
22
- import { registerDownloadEvent, registerNetworkEvents } from "./network.js";
23
+ import { networkAfterStep, networkBeforeStep, registerDownloadEvent, registerNetworkEvents } from "./network.js";
23
24
  import { LocatorLog } from "./locator_log.js";
24
25
  import axios from "axios";
25
26
  import { _findCellArea, findElementsInArea } from "./table_helper.js";
26
- import { snapshotValidation } from "./snapshot_validation.js";
27
+ import { highlightSnapshot, snapshotValidation } from "./snapshot_validation.js";
27
28
  import { loadBrunoParams } from "./bruno.js";
29
+ import { registerAfterStepRoutes, registerBeforeStepRoutes } from "./route.js";
30
+ import { existsSync } from "node:fs";
28
31
  export const Types = {
29
32
  CLICK: "click_element",
30
33
  WAIT_ELEMENT: "wait_element",
31
34
  NAVIGATE: "navigate",
35
+ GO_BACK: "go_back",
36
+ GO_FORWARD: "go_forward",
32
37
  FILL: "fill_element",
33
- EXECUTE: "execute_page_method",
34
- OPEN: "open_environment",
38
+ EXECUTE: "execute_page_method", //
39
+ OPEN: "open_environment", //
35
40
  COMPLETE: "step_complete",
36
41
  ASK: "information_needed",
37
- GET_PAGE_STATUS: "get_page_status",
38
- CLICK_ROW_ACTION: "click_row_action",
42
+ GET_PAGE_STATUS: "get_page_status", ///
43
+ CLICK_ROW_ACTION: "click_row_action", //
39
44
  VERIFY_ELEMENT_CONTAINS_TEXT: "verify_element_contains_text",
40
45
  VERIFY_PAGE_CONTAINS_TEXT: "verify_page_contains_text",
41
46
  VERIFY_PAGE_CONTAINS_NO_TEXT: "verify_page_contains_no_text",
42
47
  ANALYZE_TABLE: "analyze_table",
43
- SELECT: "select_combobox",
48
+ SELECT: "select_combobox", //
49
+ VERIFY_PROPERTY: "verify_element_property",
44
50
  VERIFY_PAGE_PATH: "verify_page_path",
51
+ VERIFY_PAGE_TITLE: "verify_page_title",
45
52
  TYPE_PRESS: "type_press",
46
53
  PRESS: "press_key",
47
54
  HOVER: "hover_element",
48
55
  CHECK: "check_element",
49
56
  UNCHECK: "uncheck_element",
50
57
  EXTRACT: "extract_attribute",
58
+ EXTRACT_PROPERTY: "extract_property",
51
59
  CLOSE_PAGE: "close_page",
52
60
  TABLE_OPERATION: "table_operation",
53
61
  SET_DATE_TIME: "set_date_time",
@@ -59,9 +67,13 @@ export const Types = {
59
67
  VERIFY_ATTRIBUTE: "verify_element_attribute",
60
68
  VERIFY_TEXT_WITH_RELATION: "verify_text_with_relation",
61
69
  BRUNO: "bruno",
62
- SNAPSHOT_VALIDATION: "snapshot_validation",
63
70
  VERIFY_FILE_EXISTS: "verify_file_exists",
64
71
  SET_INPUT_FILES: "set_input_files",
72
+ SNAPSHOT_VALIDATION: "snapshot_validation",
73
+ REPORT_COMMAND: "report_command",
74
+ STEP_COMPLETE: "step_complete",
75
+ SLEEP: "sleep",
76
+ CONDITIONAL_WAIT: "conditional_wait",
65
77
  };
66
78
  export const apps = {};
67
79
  const formatElementName = (elementName) => {
@@ -73,6 +85,7 @@ class StableBrowser {
73
85
  logger;
74
86
  context;
75
87
  world;
88
+ fastMode;
76
89
  project_path = null;
77
90
  webLogFile = null;
78
91
  networkLogger = null;
@@ -81,12 +94,14 @@ class StableBrowser {
81
94
  tags = null;
82
95
  isRecording = false;
83
96
  initSnapshotTaken = false;
84
- constructor(browser, page, logger = null, context = null, world = null) {
97
+ abortedExecution = false;
98
+ constructor(browser, page, logger = null, context = null, world = null, fastMode = false) {
85
99
  this.browser = browser;
86
100
  this.page = page;
87
101
  this.logger = logger;
88
102
  this.context = context;
89
103
  this.world = world;
104
+ this.fastMode = fastMode;
90
105
  if (!this.logger) {
91
106
  this.logger = console;
92
107
  }
@@ -115,6 +130,19 @@ class StableBrowser {
115
130
  context.pages = [this.page];
116
131
  const logFolder = path.join(this.project_path, "logs", "web");
117
132
  this.world = world;
133
+ if (this.configuration && this.configuration.fastMode === true) {
134
+ this.fastMode = true;
135
+ }
136
+ if (process.env.FAST_MODE === "true") {
137
+ // console.log("Fast mode enabled from environment variable");
138
+ this.fastMode = true;
139
+ }
140
+ if (process.env.FAST_MODE === "false") {
141
+ this.fastMode = false;
142
+ }
143
+ if (this.context) {
144
+ this.context.fastMode = this.fastMode;
145
+ }
118
146
  this.registerEventListeners(this.context);
119
147
  registerNetworkEvents(this.world, this, this.context, this.page);
120
148
  registerDownloadEvent(this.page, this.world, this.context);
@@ -125,6 +153,9 @@ class StableBrowser {
125
153
  if (!context.pageLoading) {
126
154
  context.pageLoading = { status: false };
127
155
  }
156
+ if (this.configuration && this.configuration.acceptDialog && this.page) {
157
+ this.page.on("dialog", (dialog) => dialog.accept());
158
+ }
128
159
  context.playContext.on("page", async function (page) {
129
160
  if (this.configuration && this.configuration.closePopups === true) {
130
161
  console.log("close unexpected popups");
@@ -133,6 +164,14 @@ class StableBrowser {
133
164
  }
134
165
  context.pageLoading.status = true;
135
166
  this.page = page;
167
+ try {
168
+ if (this.configuration && this.configuration.acceptDialog) {
169
+ await page.on("dialog", (dialog) => dialog.accept());
170
+ }
171
+ }
172
+ catch (error) {
173
+ console.error("Error on dialog accept registration", error);
174
+ }
136
175
  context.page = page;
137
176
  context.pages.push(page);
138
177
  registerNetworkEvents(this.world, this, context, this.page);
@@ -184,7 +223,9 @@ class StableBrowser {
184
223
  if (newContextCreated) {
185
224
  this.registerEventListeners(this.context);
186
225
  await this.goto(this.context.environment.baseUrl);
187
- await this.waitForPageLoad();
226
+ if (!this.fastMode) {
227
+ await this.waitForPageLoad();
228
+ }
188
229
  }
189
230
  }
190
231
  async switchTab(tabTitleOrIndex) {
@@ -278,6 +319,7 @@ class StableBrowser {
278
319
  if (!url) {
279
320
  throw new Error("url is null, verify that the environment file is correct");
280
321
  }
322
+ url = await this._replaceWithLocalData(url, this.world);
281
323
  if (!url.startsWith("http")) {
282
324
  url = "https://" + url;
283
325
  }
@@ -309,6 +351,64 @@ class StableBrowser {
309
351
  await _commandFinally(state, this);
310
352
  }
311
353
  }
354
+ async goBack(options, world = null) {
355
+ const state = {
356
+ value: "",
357
+ world: world,
358
+ type: Types.GO_BACK,
359
+ text: `Browser navigate back`,
360
+ operation: "goBack",
361
+ log: "***** navigate back *****\n",
362
+ info: {},
363
+ locate: false,
364
+ scroll: false,
365
+ screenshot: false,
366
+ highlight: false,
367
+ };
368
+ try {
369
+ await _preCommand(state, this);
370
+ await this.page.goBack({
371
+ waitUntil: "load",
372
+ });
373
+ await _screenshot(state, this);
374
+ }
375
+ catch (error) {
376
+ console.error("Error on goBack", error);
377
+ _commandError(state, error, this);
378
+ }
379
+ finally {
380
+ await _commandFinally(state, this);
381
+ }
382
+ }
383
+ async goForward(options, world = null) {
384
+ const state = {
385
+ value: "",
386
+ world: world,
387
+ type: Types.GO_FORWARD,
388
+ text: `Browser navigate forward`,
389
+ operation: "goForward",
390
+ log: "***** navigate forward *****\n",
391
+ info: {},
392
+ locate: false,
393
+ scroll: false,
394
+ screenshot: false,
395
+ highlight: false,
396
+ };
397
+ try {
398
+ await _preCommand(state, this);
399
+ await this.page.goForward({
400
+ waitUntil: "load",
401
+ });
402
+ await _screenshot(state, this);
403
+ }
404
+ catch (error) {
405
+ console.error("Error on goForward", error);
406
+ _commandError(state, error, this);
407
+ }
408
+ finally {
409
+ await _commandFinally(state, this);
410
+ }
411
+ }
312
412
  async _getLocator(locator, scope, _params) {
313
413
  locator = _fixLocatorUsingParams(locator, _params);
314
414
  // locator = await this._replaceWithLocalData(locator);
@@ -422,7 +522,7 @@ class StableBrowser {
422
522
  }
423
523
  return { elementCount: tagCount, randomToken };
424
524
  }
425
- async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null) {
525
+ async _collectLocatorInformation(selectorHierarchy, index = 0, scope, foundLocators, _params, info, visibleOnly = true, allowDisabled = false, element_name = null, logErrors = false) {
426
526
  if (!info) {
427
527
  info = {};
428
528
  }
@@ -434,14 +534,13 @@ class StableBrowser {
434
534
  info.locatorLog = new LocatorLog(selectorHierarchy);
435
535
  }
436
536
  let locatorSearch = selectorHierarchy[index];
437
- let originalLocatorSearch = "";
438
537
  try {
439
- originalLocatorSearch = _fixUsingParams(JSON.stringify(locatorSearch), _params);
440
- locatorSearch = JSON.parse(originalLocatorSearch);
538
+ locatorSearch = _fixLocatorUsingParams(locatorSearch, _params);
441
539
  }
442
540
  catch (e) {
443
541
  console.error(e);
444
542
  }
543
+ let originalLocatorSearch = JSON.stringify(locatorSearch);
445
544
  //info.log += "searching for locator " + JSON.stringify(locatorSearch) + "\n";
446
545
  let locator = null;
447
546
  if (locatorSearch.climb && locatorSearch.climb >= 0) {
@@ -489,7 +588,7 @@ class StableBrowser {
489
588
  }
490
589
  return;
491
590
  }
492
- if (info.locatorLog && count === 0) {
591
+ if (info.locatorLog && count === 0 && logErrors) {
493
592
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "NOT_FOUND");
494
593
  }
495
594
  for (let j = 0; j < count; j++) {
@@ -504,7 +603,7 @@ class StableBrowser {
504
603
  info.locatorLog.setLocatorSearchStatus(originalLocatorSearch, "FOUND");
505
604
  }
506
605
  }
507
- else {
606
+ else if (logErrors) {
508
607
  info.failCause.visible = visible;
509
608
  info.failCause.enabled = enabled;
510
609
  if (!info.printMessages) {
@@ -583,21 +682,135 @@ class StableBrowser {
583
682
  }
584
683
  return { rerun: false };
585
684
  }
685
+ getFilePath() {
686
+ const stackFrames = errorStackParser.parse(new Error());
687
+ const stackFrame = stackFrames.findLast((frame) => frame.fileName && frame.fileName.endsWith(".mjs"));
688
+ // return stackFrame?.fileName || null;
689
+ const filepath = stackFrame?.fileName;
690
+ if (filepath) {
691
+ let jsonFilePath = filepath.replace(".mjs", ".json");
692
+ if (existsSync(jsonFilePath)) {
693
+ return jsonFilePath;
694
+ }
695
+ const config = this.configuration ?? {};
696
+ if (!config?.locatorsMetadataDir) {
697
+ config.locatorsMetadataDir = "features/step_definitions/locators";
698
+ }
699
+ if (config && config.locatorsMetadataDir) {
700
+ jsonFilePath = path.join(config.locatorsMetadataDir, path.basename(jsonFilePath));
701
+ }
702
+ if (existsSync(jsonFilePath)) {
703
+ return jsonFilePath;
704
+ }
705
+ return null;
706
+ }
707
+ return null;
708
+ }
709
+ getFullElementLocators(selectors, filePath) {
710
+ if (!filePath || !existsSync(filePath)) {
711
+ return null;
712
+ }
713
+ const content = fs.readFileSync(filePath, "utf8");
714
+ try {
715
+ const allElements = JSON.parse(content);
716
+ const element_key = selectors?.element_key;
717
+ if (element_key && allElements[element_key]) {
718
+ return allElements[element_key];
719
+ }
720
+ for (const elementKey in allElements) {
721
+ const element = allElements[elementKey];
722
+ let foundStrategy = null;
723
+ for (const key in element) {
724
+ if (key === "strategy") {
725
+ continue;
726
+ }
727
+ const locators = element[key];
728
+ if (!locators || !locators.length) {
729
+ continue;
730
+ }
731
+ for (const locator of locators) {
732
+ delete locator.score;
733
+ }
734
+ if (JSON.stringify(locators) === JSON.stringify(selectors.locators)) {
735
+ foundStrategy = key;
736
+ break;
737
+ }
738
+ }
739
+ if (foundStrategy) {
740
+ return element;
741
+ }
742
+ }
743
+ }
744
+ catch (error) {
745
+ console.error("Error parsing locators from file: " + filePath, error);
746
+ }
747
+ return null;
748
+ }
586
749
  async _locate(selectors, info, _params, timeout, allowDisabled = false) {
587
750
  if (!timeout) {
588
751
  timeout = 30000;
589
752
  }
753
+ let element = null;
754
+ let allStrategyLocators = null;
755
+ let selectedStrategy = null;
756
+ if (this.tryAllStrategies) {
757
+ allStrategyLocators = this.getFullElementLocators(selectors, this.getFilePath());
758
+ selectedStrategy = allStrategyLocators?.strategy;
759
+ }
590
760
  for (let i = 0; i < 3; i++) {
591
761
  info.log += "attempt " + i + ": total locators " + selectors.locators.length + "\n";
592
762
  for (let j = 0; j < selectors.locators.length; j++) {
593
763
  let selector = selectors.locators[j];
594
764
  info.log += "searching for locator " + j + ":" + JSON.stringify(selector) + "\n";
595
765
  }
596
- let element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
766
+ if (this.tryAllStrategies && selectedStrategy) {
767
+ const strategyLocators = allStrategyLocators[selectedStrategy];
768
+ let err;
769
+ if (strategyLocators && strategyLocators.length) {
770
+ try {
771
+ selectors.locators = strategyLocators;
772
+ element = await this._locate_internal(selectors, info, _params, 10_000, allowDisabled);
773
+ info.selectedStrategy = selectedStrategy;
774
+ info.log += "element found using strategy " + selectedStrategy + "\n";
775
+ }
776
+ catch (error) {
777
+ err = error;
778
+ }
779
+ }
780
+ if (!element) {
781
+ for (const key in allStrategyLocators) {
782
+ if (key === "strategy" || key === selectedStrategy) {
783
+ continue;
784
+ }
785
+ const strategyLocators = allStrategyLocators[key];
786
+ if (strategyLocators && strategyLocators.length) {
787
+ try {
788
+ error = null;
789
+ info.log += "using strategy " + key + " with locators " + JSON.stringify(strategyLocators) + "\n";
790
+ selectors.locators = strategyLocators;
791
+ element = await this._locate_internal(selectors, info, _params, 10_000, allowDisabled);
792
+ info.selectedStrategy = key;
793
+ info.log += "element found using strategy " + key + "\n";
794
+ break;
795
+ }
796
+ catch (error) {
797
+ err = error;
798
+ }
799
+ }
800
+ }
801
+ }
802
+ if (err) {
803
+ throw err;
804
+ }
805
+ }
806
+ else {
807
+ element = await this._locate_internal(selectors, info, _params, timeout, allowDisabled);
808
+ }
597
809
  if (!element.rerun) {
598
810
  const randomToken = Math.random().toString(36).substring(7);
599
- element.evaluate((el, randomToken) => {
811
+ await element.evaluate((el, randomToken) => {
600
812
  el.setAttribute("data-blinq-id-" + randomToken, "");
813
+ console.log("set data-blinq-id-" + randomToken + " on element", el);
601
814
  }, randomToken);
602
815
  // if (element._frame) {
603
816
  // return element;
@@ -649,7 +862,7 @@ class StableBrowser {
649
862
  break;
650
863
  }
651
864
  catch (error) {
652
- console.error("frame not found " + frameLocator.css);
865
+ // console.error("frame not found " + frameLocator.css);
653
866
  }
654
867
  }
655
868
  }
@@ -727,7 +940,6 @@ class StableBrowser {
727
940
  let locatorsCount = 0;
728
941
  let lazy_scroll = false;
729
942
  //let arrayMode = Array.isArray(selectors);
730
- let scope = await this._findFrameScope(selectors, timeout, info);
731
943
  let selectorsLocators = null;
732
944
  selectorsLocators = selectors.locators;
733
945
  // group selectors by priority
@@ -755,6 +967,7 @@ class StableBrowser {
755
967
  let highPriorityOnly = true;
756
968
  let visibleOnly = true;
757
969
  while (true) {
970
+ let scope = await this._findFrameScope(selectors, timeout, info);
758
971
  locatorsCount = 0;
759
972
  let result = [];
760
973
  let popupResult = await this.closeUnexpectedPopups(info, _params);
@@ -845,7 +1058,7 @@ class StableBrowser {
845
1058
  }
846
1059
  throw new Error("failed to locate first element no elements found, " + info.log);
847
1060
  }
848
- async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name) {
1061
+ async _scanLocatorsGroup(locatorsGroup, scope, _params, info, visibleOnly, allowDisabled = false, element_name, logErrors = false) {
849
1062
  let foundElements = [];
850
1063
  const result = {
851
1064
  foundElements: foundElements,
@@ -864,7 +1077,9 @@ class StableBrowser {
864
1077
  await this._collectLocatorInformation(locatorsGroup, i, this.page, foundLocators, _params, info, visibleOnly, allowDisabled, element_name);
865
1078
  }
866
1079
  catch (e) {
867
- this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
1080
+ if (logErrors) {
1081
+ this.logger.info("unable to use locator (second try) " + JSON.stringify(locatorsGroup[i]));
1082
+ }
868
1083
  }
869
1084
  }
870
1085
  if (foundLocators.length === 1) {
@@ -905,7 +1120,7 @@ class StableBrowser {
905
1120
  });
906
1121
  result.locatorIndex = i;
907
1122
  }
908
- else {
1123
+ else if (logErrors) {
909
1124
  info.failCause.foundMultiple = true;
910
1125
  if (info.locatorLog) {
911
1126
  info.locatorLog.setLocatorSearchStatus(JSON.stringify(locatorsGroup[i]), "FOUND_NOT_UNIQUE");
@@ -1028,7 +1243,9 @@ class StableBrowser {
1028
1243
  try {
1029
1244
  await _preCommand(state, this);
1030
1245
  await performAction("click", state.element, options, this, state, _params);
1031
- await this.waitForPageLoad();
1246
+ if (!this.fastMode) {
1247
+ await this.waitForPageLoad();
1248
+ }
1032
1249
  return state.info;
1033
1250
  }
1034
1251
  catch (e) {
@@ -1091,7 +1308,7 @@ class StableBrowser {
1091
1308
  // if (world && world.screenshot && !world.screenshotPath) {
1092
1309
  // console.log(`Highlighting while running from recorder`);
1093
1310
  await this._highlightElements(state.element);
1094
- await state.element.setChecked(checked);
1311
+ await state.element.setChecked(checked, { timeout: 2000 });
1095
1312
  await new Promise((resolve) => setTimeout(resolve, 1000));
1096
1313
  // await this._unHighlightElements(element);
1097
1314
  // }
@@ -1103,11 +1320,28 @@ class StableBrowser {
1103
1320
  this.logger.info("element did not change its state, ignoring...");
1104
1321
  }
1105
1322
  else {
1323
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1106
1324
  //await this.closeUnexpectedPopups();
1107
1325
  state.info.log += "setCheck failed, will try again" + "\n";
1108
- state.element = await this._locate(selectors, state.info, _params);
1109
- await state.element.setChecked(checked, { timeout: 5000, force: true });
1110
- await new Promise((resolve) => setTimeout(resolve, 1000));
1326
+ state.element_found = false;
1327
+ try {
1328
+ state.element = await this._locate(selectors, state.info, _params, 100);
1329
+ state.element_found = true;
1330
+ // check the check state
1331
+ }
1332
+ catch (error) {
1333
+ // element dismissed
1334
+ }
1335
+ if (state.element_found) {
1336
+ const isChecked = await state.element.isChecked();
1337
+ if (isChecked !== checked) {
1338
+ // perform click
1339
+ await state.element.click({ timeout: 2000, force: true });
1340
+ }
1341
+ else {
1342
+ this.logger.info(`Element ${selectors.element_name} is already in the desired state (${checked})`);
1343
+ }
1344
+ }
1111
1345
  }
1112
1346
  }
1113
1347
  await this.waitForPageLoad();
@@ -1403,7 +1637,9 @@ class StableBrowser {
1403
1637
  await new Promise((resolve) => setTimeout(resolve, 500));
1404
1638
  }
1405
1639
  }
1640
+ //if (!this.fastMode) {
1406
1641
  await _screenshot(state, this);
1642
+ //}
1407
1643
  if (enter === true) {
1408
1644
  await new Promise((resolve) => setTimeout(resolve, 2000));
1409
1645
  await this.page.keyboard.press("Enter");
@@ -1712,14 +1948,17 @@ class StableBrowser {
1712
1948
  throw new Error("referanceSnapshot is null");
1713
1949
  }
1714
1950
  let text = null;
1715
- if (fs.existsSync(path.join(this.project_path, "snapshots", referanceSnapshot + ".yml"))) {
1716
- text = fs.readFileSync(path.join(this.project_path, "snapshots", referanceSnapshot + ".yml"), "utf8");
1951
+ if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"))) {
1952
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yml"), "utf8");
1953
+ }
1954
+ else if (fs.existsSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"))) {
1955
+ text = fs.readFileSync(path.join(this.project_path, "data", "snapshots", this.context.environment.name, referanceSnapshot + ".yaml"), "utf8");
1717
1956
  }
1718
1957
  else if (referanceSnapshot.startsWith("yaml:")) {
1719
1958
  text = referanceSnapshot.substring(5);
1720
1959
  }
1721
1960
  else {
1722
- throw new Error("referanceSnapshot file not found: " + referanceSnapshot);
1961
+ throw new Error("referenceSnapshot file not found: " + referanceSnapshot);
1723
1962
  }
1724
1963
  state.text = text;
1725
1964
  const newValue = await this._replaceWithLocalData(text, world);
@@ -1737,18 +1976,23 @@ class StableBrowser {
1737
1976
  scope = await this._findFrameScope(frameSelectors, timeout, state.info);
1738
1977
  }
1739
1978
  const snapshot = await scope.locator("body").ariaSnapshot({ timeout });
1740
- matchResult = snapshotValidation(snapshot, newValue);
1979
+ matchResult = snapshotValidation(snapshot, newValue, referanceSnapshot);
1741
1980
  if (matchResult.errorLine !== -1) {
1742
1981
  throw new Error("Snapshot validation failed at line " + matchResult.errorLineText);
1743
1982
  }
1744
1983
  // highlight and screenshot
1984
+ try {
1985
+ await await highlightSnapshot(newValue, scope);
1986
+ await _screenshot(state, this);
1987
+ }
1988
+ catch (e) { }
1745
1989
  return state.info;
1746
1990
  }
1747
1991
  catch (e) {
1748
1992
  // Log error but continue retrying until timeout is reached
1749
- this.logger.warn("Retrying containsText due to: " + e.message);
1993
+ //this.logger.warn("Retrying snapshot validation due to: " + e.message);
1750
1994
  }
1751
- await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1 second before retrying
1995
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 1 second before retrying
1752
1996
  }
1753
1997
  throw new Error("No snapshot match " + matchResult?.errorLineText);
1754
1998
  }
@@ -1900,12 +2144,7 @@ class StableBrowser {
1900
2144
  }
1901
2145
  }
1902
2146
  getTestData(world = null) {
1903
- const dataFile = _getDataFile(world, this.context, this);
1904
- let data = {};
1905
- if (fs.existsSync(dataFile)) {
1906
- data = JSON.parse(fs.readFileSync(dataFile, "utf8"));
1907
- }
1908
- return data;
2147
+ return _getTestData(world, this.context, this);
1909
2148
  }
1910
2149
  async _screenShot(options = {}, world = null, info = null) {
1911
2150
  // collect url/path/title
@@ -2125,6 +2364,77 @@ class StableBrowser {
2125
2364
  await _commandFinally(state, this);
2126
2365
  }
2127
2366
  }
2367
+ async extractProperty(selectors, property, variable, _params = null, options = {}, world = null) {
2368
+ const state = {
2369
+ selectors,
2370
+ _params,
2371
+ property,
2372
+ variable,
2373
+ options,
2374
+ world,
2375
+ type: Types.EXTRACT_PROPERTY,
2376
+ text: `Extract property from element`,
2377
+ _text: `Extract property ${property} from ${selectors.element_name}`,
2378
+ operation: "extractProperty",
2379
+ log: "***** extract property " + property + " from " + selectors.element_name + " *****\n",
2380
+ allowDisabled: true,
2381
+ };
2382
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2383
+ try {
2384
+ await _preCommand(state, this);
2385
+ switch (property) {
2386
+ case "inner_text":
2387
+ state.value = await state.element.innerText();
2388
+ break;
2389
+ case "href":
2390
+ state.value = await state.element.getAttribute("href");
2391
+ break;
2392
+ case "value":
2393
+ state.value = await state.element.inputValue();
2394
+ break;
2395
+ case "text":
2396
+ state.value = await state.element.textContent();
2397
+ break;
2398
+ default:
2399
+ if (property.startsWith("dataset.")) {
2400
+ const dataAttribute = property.substring(8);
2401
+ state.value = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2402
+ }
2403
+ else {
2404
+ state.value = String(await state.element.evaluate((element, prop) => element[prop], property));
2405
+ }
2406
+ }
2407
+ if (options !== null) {
2408
+ if (options.regex && options.regex !== "") {
2409
+ // Construct a regex pattern from the provided string
2410
+ const regex = options.regex.slice(1, -1);
2411
+ const regexPattern = new RegExp(regex, "g");
2412
+ const matches = state.value.match(regexPattern);
2413
+ if (matches) {
2414
+ let newValue = "";
2415
+ for (const match of matches) {
2416
+ newValue += match;
2417
+ }
2418
+ state.value = newValue;
2419
+ }
2420
+ }
2421
+ if (options.trimSpaces && options.trimSpaces === true) {
2422
+ state.value = state.value.trim();
2423
+ }
2424
+ }
2425
+ state.info.value = state.value;
2426
+ this.setTestData({ [variable]: state.value }, world);
2427
+ this.logger.info("set test data: " + variable + "=" + state.value);
2428
+ // await new Promise((resolve) => setTimeout(resolve, 500));
2429
+ return state.info;
2430
+ }
2431
+ catch (e) {
2432
+ await _commandError(state, e, this);
2433
+ }
2434
+ finally {
2435
+ await _commandFinally(state, this);
2436
+ }
2437
+ }
2128
2438
  async verifyAttribute(selectors, attribute, value, _params = null, options = {}, world = null) {
2129
2439
  const state = {
2130
2440
  selectors,
@@ -2177,14 +2487,167 @@ class StableBrowser {
2177
2487
  let regex;
2178
2488
  if (expectedValue.startsWith("/") && expectedValue.endsWith("/")) {
2179
2489
  const patternBody = expectedValue.slice(1, -1);
2180
- regex = new RegExp(patternBody, "g");
2490
+ const processedPattern = patternBody.replace(/\n/g, ".*");
2491
+ regex = new RegExp(processedPattern, "gs");
2492
+ state.info.regex = true;
2181
2493
  }
2182
2494
  else {
2183
2495
  const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2184
2496
  regex = new RegExp(escapedPattern, "g");
2185
2497
  }
2186
- if (!val.match(regex)) {
2187
- let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2498
+ if (attribute === "innerText") {
2499
+ if (state.info.regex) {
2500
+ if (!regex.test(val)) {
2501
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2502
+ state.info.failCause.assertionFailed = true;
2503
+ state.info.failCause.lastError = errorMessage;
2504
+ throw new Error(errorMessage);
2505
+ }
2506
+ }
2507
+ else {
2508
+ const valLines = val.split("\n");
2509
+ const expectedLines = expectedValue.split("\n");
2510
+ const isPart = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine === expectedLine));
2511
+ if (!isPart) {
2512
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2513
+ state.info.failCause.assertionFailed = true;
2514
+ state.info.failCause.lastError = errorMessage;
2515
+ throw new Error(errorMessage);
2516
+ }
2517
+ }
2518
+ }
2519
+ else {
2520
+ if (!val.match(regex)) {
2521
+ let errorMessage = `The ${attribute} attribute has a value of "${val}", but the expected value is "${expectedValue}"`;
2522
+ state.info.failCause.assertionFailed = true;
2523
+ state.info.failCause.lastError = errorMessage;
2524
+ throw new Error(errorMessage);
2525
+ }
2526
+ }
2527
+ return state.info;
2528
+ }
2529
+ catch (e) {
2530
+ await _commandError(state, e, this);
2531
+ }
2532
+ finally {
2533
+ await _commandFinally(state, this);
2534
+ }
2535
+ }
2536
+ async verifyProperty(selectors, property, value, _params = null, options = {}, world = null) {
2537
+ const state = {
2538
+ selectors,
2539
+ _params,
2540
+ property,
2541
+ value,
2542
+ options,
2543
+ world,
2544
+ type: Types.VERIFY_PROPERTY,
2545
+ highlight: true,
2546
+ screenshot: true,
2547
+ text: `Verify element property`,
2548
+ _text: `Verify property ${property} from ${selectors.element_name} is ${value}`,
2549
+ operation: "verifyProperty",
2550
+ log: "***** verify property " + property + " from " + selectors.element_name + " *****\n",
2551
+ allowDisabled: true,
2552
+ };
2553
+ await new Promise((resolve) => setTimeout(resolve, 2000));
2554
+ let val;
2555
+ let expectedValue;
2556
+ try {
2557
+ await _preCommand(state, this);
2558
+ expectedValue = await replaceWithLocalTestData(state.value, world);
2559
+ state.info.expectedValue = expectedValue;
2560
+ switch (property) {
2561
+ case "innerText":
2562
+ val = String(await state.element.innerText());
2563
+ break;
2564
+ case "text":
2565
+ val = String(await state.element.textContent());
2566
+ break;
2567
+ case "value":
2568
+ val = String(await state.element.inputValue());
2569
+ break;
2570
+ case "checked":
2571
+ val = String(await state.element.isChecked());
2572
+ break;
2573
+ case "disabled":
2574
+ val = String(await state.element.isDisabled());
2575
+ break;
2576
+ case "readOnly":
2577
+ const isEditable = await state.element.isEditable();
2578
+ val = String(!isEditable);
2579
+ break;
2580
+ case "innerHTML":
2581
+ val = String(await state.element.innerHTML());
2582
+ break;
2583
+ case "outerHTML":
2584
+ val = String(await state.element.evaluate((element) => element.outerHTML));
2585
+ break;
2586
+ default:
2587
+ if (property.startsWith("dataset.")) {
2588
+ const dataAttribute = property.substring(8);
2589
+ val = String(await state.element.getAttribute(`data-${dataAttribute}`)) || "";
2590
+ }
2591
+ else {
2592
+ val = String(await state.element.evaluate((element, prop) => element[prop], property));
2593
+ }
2594
+ }
2595
+ // Helper function to remove all style="" attributes
2596
+ const removeStyleAttributes = (htmlString) => {
2597
+ return htmlString.replace(/\s*style\s*=\s*"[^"]*"/gi, "");
2598
+ };
2599
+ // Remove style attributes for innerHTML and outerHTML properties
2600
+ if (property === "innerHTML" || property === "outerHTML") {
2601
+ val = removeStyleAttributes(val);
2602
+ expectedValue = removeStyleAttributes(expectedValue);
2603
+ }
2604
+ state.info.value = val;
2605
+ let regex;
2606
+ state.info.value = val;
2607
+ const isRegex = expectedValue.startsWith("regex:");
2608
+ const isContains = expectedValue.startsWith("contains:");
2609
+ const isExact = expectedValue.startsWith("exact:");
2610
+ let matchPassed = false;
2611
+ if (isRegex) {
2612
+ const rawPattern = expectedValue.slice(6); // remove "regex:"
2613
+ const lastSlashIndex = rawPattern.lastIndexOf("/");
2614
+ if (rawPattern.startsWith("/") && lastSlashIndex > 0) {
2615
+ const patternBody = rawPattern.slice(1, lastSlashIndex).replace(/\n/g, ".*");
2616
+ const flags = rawPattern.slice(lastSlashIndex + 1) || "gs";
2617
+ const regex = new RegExp(patternBody, flags);
2618
+ state.info.regex = true;
2619
+ matchPassed = regex.test(val);
2620
+ }
2621
+ else {
2622
+ // Fallback: treat as literal
2623
+ const escapedPattern = rawPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2624
+ const regex = new RegExp(escapedPattern, "g");
2625
+ matchPassed = regex.test(val);
2626
+ }
2627
+ }
2628
+ else if (isContains) {
2629
+ const containsValue = expectedValue.slice(9); // remove "contains:"
2630
+ matchPassed = val.includes(containsValue);
2631
+ }
2632
+ else if (isExact) {
2633
+ const exactValue = expectedValue.slice(6); // remove "exact:"
2634
+ matchPassed = val === exactValue;
2635
+ }
2636
+ else if (property === "innerText") {
2637
+ // Default innerText logic
2638
+ const normalizedExpectedValue = expectedValue.replace(/\\n/g, "\n");
2639
+ const valLines = val.split("\n");
2640
+ const expectedLines = normalizedExpectedValue.split("\n");
2641
+ matchPassed = expectedLines.every((expectedLine) => valLines.some((valLine) => valLine.trim() === expectedLine.trim()));
2642
+ }
2643
+ else {
2644
+ // Fallback exact or loose match
2645
+ const escapedPattern = expectedValue.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2646
+ const regex = new RegExp(escapedPattern, "g");
2647
+ matchPassed = regex.test(val);
2648
+ }
2649
+ if (!matchPassed) {
2650
+ let errorMessage = `The ${property} property has a value of "${val}", but the expected value is "${expectedValue}"`;
2188
2651
  state.info.failCause.assertionFailed = true;
2189
2652
  state.info.failCause.lastError = errorMessage;
2190
2653
  throw new Error(errorMessage);
@@ -2198,6 +2661,132 @@ class StableBrowser {
2198
2661
  await _commandFinally(state, this);
2199
2662
  }
2200
2663
  }
2664
+ async conditionalWait(selectors, condition, timeout = 1000, _params = null, options = {}, world = null) {
2665
+ // Convert timeout from seconds to milliseconds
2666
+ const timeoutMs = timeout * 1000;
2667
+ const state = {
2668
+ selectors,
2669
+ _params,
2670
+ condition,
2671
+ timeout: timeoutMs, // Store as milliseconds for internal use
2672
+ options,
2673
+ world,
2674
+ type: Types.CONDITIONAL_WAIT,
2675
+ highlight: true,
2676
+ screenshot: true,
2677
+ text: `Conditional wait for element`,
2678
+ _text: `Wait for ${selectors.element_name} to be ${condition} (timeout: ${timeout}s)`, // Display original seconds
2679
+ operation: "conditionalWait",
2680
+ log: `***** conditional wait for ${condition} on ${selectors.element_name} *****\n`,
2681
+ allowDisabled: true,
2682
+ info: {},
2683
+ };
2684
+ // Initialize startTime outside try block to ensure it's always accessible
2685
+ const startTime = Date.now();
2686
+ let conditionMet = false;
2687
+ let currentValue = null;
2688
+ let lastError = null;
2689
+ // Main retry loop - continues until timeout or condition is met
2690
+ while (Date.now() - startTime < timeoutMs) {
2691
+ const elapsedTime = Date.now() - startTime;
2692
+ const remainingTime = timeoutMs - elapsedTime;
2693
+ try {
2694
+ // Try to execute _preCommand (element location)
2695
+ await _preCommand(state, this);
2696
+ // If _preCommand succeeds, start condition checking
2697
+ const checkCondition = async () => {
2698
+ try {
2699
+ switch (condition.toLowerCase()) {
2700
+ case "checked":
2701
+ currentValue = await state.element.isChecked();
2702
+ return currentValue === true;
2703
+ case "unchecked":
2704
+ currentValue = await state.element.isChecked();
2705
+ return currentValue === false;
2706
+ case "visible":
2707
+ currentValue = await state.element.isVisible();
2708
+ return currentValue === true;
2709
+ case "hidden":
2710
+ currentValue = await state.element.isVisible();
2711
+ return currentValue === false;
2712
+ case "enabled":
2713
+ currentValue = await state.element.isDisabled();
2714
+ return currentValue === false;
2715
+ case "disabled":
2716
+ currentValue = await state.element.isDisabled();
2717
+ return currentValue === true;
2718
+ case "editable":
2719
+ // currentValue = await String(await state.element.evaluate((element, prop) => element[prop], "isContentEditable"));
2720
+ currentValue = await state.element.isContentEditable();
2721
+ return currentValue === true;
2722
+ default:
2723
+ state.info.message = `Unsupported condition: '${condition}'. Supported conditions are: checked, unchecked, visible, hidden, enabled, disabled, editable.`;
2724
+ state.info.success = false;
2725
+ return false;
2726
+ }
2727
+ }
2728
+ catch (error) {
2729
+ // Don't throw here, just return false to continue retrying
2730
+ return false;
2731
+ }
2732
+ };
2733
+ // Inner loop for condition checking (once element is located)
2734
+ while (Date.now() - startTime < timeoutMs) {
2735
+ const currentElapsedTime = Date.now() - startTime;
2736
+ conditionMet = await checkCondition();
2737
+ if (conditionMet) {
2738
+ break;
2739
+ }
2740
+ // Check if we still have time for another attempt
2741
+ if (Date.now() - startTime + 50 < timeoutMs) {
2742
+ await new Promise((res) => setTimeout(res, 50));
2743
+ }
2744
+ else {
2745
+ break;
2746
+ }
2747
+ }
2748
+ // If we got here and condition is met, break out of main loop
2749
+ if (conditionMet) {
2750
+ break;
2751
+ }
2752
+ // If condition not met but no exception, we've timed out
2753
+ break;
2754
+ }
2755
+ catch (e) {
2756
+ lastError = e;
2757
+ const currentElapsedTime = Date.now() - startTime;
2758
+ const timeLeft = timeoutMs - currentElapsedTime;
2759
+ // Check if we have enough time left to retry
2760
+ if (timeLeft > 100) {
2761
+ await new Promise((resolve) => setTimeout(resolve, 50));
2762
+ }
2763
+ else {
2764
+ break;
2765
+ }
2766
+ }
2767
+ }
2768
+ const actualWaitTime = Date.now() - startTime;
2769
+ state.info = {
2770
+ success: conditionMet,
2771
+ conditionMet,
2772
+ actualWaitTime,
2773
+ currentValue,
2774
+ lastError: lastError?.message || null,
2775
+ message: conditionMet
2776
+ ? `Condition '${condition}' met after ${(actualWaitTime / 1000).toFixed(2)}s`
2777
+ : `Condition '${condition}' not met within ${timeout}s timeout`,
2778
+ };
2779
+ if (lastError) {
2780
+ state.log += `Last error: ${lastError.message}\n`;
2781
+ }
2782
+ try {
2783
+ await _commandFinally(state, this);
2784
+ }
2785
+ catch (finallyError) {
2786
+ state.log += `Error in _commandFinally: ${finallyError.message}\n`;
2787
+ }
2788
+ return state.info;
2789
+ }
2201
2790
  async extractEmailData(emailAddress, options, world) {
2202
2791
  if (!emailAddress) {
2203
2792
  throw new Error("email address is null");
@@ -2355,56 +2944,49 @@ class StableBrowser {
2355
2944
  console.debug(error);
2356
2945
  }
2357
2946
  }
2358
- // async _unhighlightElements(scope, css) {
2359
- // try {
2360
- // if (!scope) {
2361
- // return;
2362
- // }
2363
- // if (!css) {
2364
- // scope
2365
- // .evaluate((node) => {
2366
- // if (node && node.style) {
2367
- // if (!node.__previousOutline) {
2368
- // node.style.outline = "";
2369
- // } else {
2370
- // node.style.outline = node.__previousOutline;
2371
- // }
2372
- // }
2373
- // })
2374
- // .then(() => {})
2375
- // .catch((e) => {
2376
- // // console.log(`Error while unhighlighting node ${JSON.stringify(scope)}: ${e}`);
2377
- // });
2378
- // } else {
2379
- // scope
2380
- // .evaluate(([css]) => {
2381
- // if (!css) {
2382
- // return;
2383
- // }
2384
- // let elements = Array.from(document.querySelectorAll(css));
2385
- // for (i = 0; i < elements.length; i++) {
2386
- // let element = elements[i];
2387
- // if (!element.style) {
2388
- // return;
2389
- // }
2390
- // if (!element.__previousOutline) {
2391
- // element.style.outline = "";
2392
- // } else {
2393
- // element.style.outline = element.__previousOutline;
2394
- // }
2395
- // }
2396
- // })
2397
- // .then(() => {})
2398
- // .catch((e) => {
2399
- // // console.error(`Error while unhighlighting element in css: ${e}`);
2400
- // });
2401
- // }
2402
- // } catch (error) {
2403
- // // console.debug(error);
2404
- // }
2405
- // }
2947
+ _matcher(text) {
2948
+ if (!text) {
2949
+ return { matcher: "contains", queryText: "" };
2950
+ }
2951
+ if (text.length < 2) {
2952
+ return { matcher: "contains", queryText: text };
2953
+ }
2954
+ const split = text.split(":");
2955
+ const matcher = split[0].toLowerCase();
2956
+ const queryText = split.slice(1).join(":").trim();
2957
+ return { matcher, queryText };
2958
+ }
2959
+ _getDomain(url) {
2960
+ if (url.length === 0 || (!url.startsWith("http://") && !url.startsWith("https://"))) {
2961
+ return "";
2962
+ }
2963
+ let hostnameFragments = url.split("/")[2].split(".");
2964
+ if (hostnameFragments.some((fragment) => fragment.includes(":"))) {
2965
+ return hostnameFragments.join("-").split(":").join("-");
2966
+ }
2967
+ let n = hostnameFragments.length;
2968
+ let fragments = [...hostnameFragments];
2969
+ while (n > 0 && hostnameFragments[n - 1].length <= 3) {
2970
+ hostnameFragments.pop();
2971
+ n = hostnameFragments.length;
2972
+ }
2973
+ if (n == 0) {
2974
+ if (fragments[0] === "www")
2975
+ fragments = fragments.slice(1);
2976
+ return fragments.length > 1 ? fragments.slice(0, fragments.length - 1).join("-") : fragments.join("-");
2977
+ }
2978
+ if (hostnameFragments[0] === "www")
2979
+ hostnameFragments = hostnameFragments.slice(1);
2980
+ return hostnameFragments.join(".");
2981
+ }
2982
+ /**
2983
+ * Verify the page path matches the given path.
2984
+ * @param {string} pathPart - The path to verify.
2985
+ * @param {object} options - Options for verification.
2986
+ * @param {object} world - The world context.
2987
+ * @returns {Promise<object>} - The state info after verification.
2988
+ */
2406
2989
  async verifyPagePath(pathPart, options = {}, world = null) {
2407
- const startTime = Date.now();
2408
2990
  let error = null;
2409
2991
  let screenshotId = null;
2410
2992
  let screenshotPath = null;
@@ -2418,113 +3000,212 @@ class StableBrowser {
2418
3000
  pathPart = newValue;
2419
3001
  }
2420
3002
  info.pathPart = pathPart;
3003
+ const { matcher, queryText } = this._matcher(pathPart);
3004
+ const state = {
3005
+ text_search: queryText,
3006
+ options,
3007
+ world,
3008
+ locate: false,
3009
+ scroll: false,
3010
+ highlight: false,
3011
+ type: Types.VERIFY_PAGE_PATH,
3012
+ text: `Verify the page url is ${queryText}`,
3013
+ _text: `Verify the page url is ${queryText}`,
3014
+ operation: "verifyPagePath",
3015
+ log: "***** verify page url is " + queryText + " *****\n",
3016
+ };
2421
3017
  try {
3018
+ await _preCommand(state, this);
3019
+ state.info.text = queryText;
2422
3020
  for (let i = 0; i < 30; i++) {
2423
3021
  const url = await this.page.url();
2424
- if (!url.includes(pathPart)) {
2425
- if (i === 29) {
2426
- throw new Error(`url ${url} doesn't contain ${pathPart}`);
2427
- }
2428
- await new Promise((resolve) => setTimeout(resolve, 1000));
2429
- continue;
3022
+ switch (matcher) {
3023
+ case "exact":
3024
+ if (url !== queryText) {
3025
+ if (i === 29) {
3026
+ throw new Error(`Page URL ${url} is not equal to ${queryText}`);
3027
+ }
3028
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3029
+ continue;
3030
+ }
3031
+ break;
3032
+ case "contains":
3033
+ if (!url.includes(queryText)) {
3034
+ if (i === 29) {
3035
+ throw new Error(`Page URL ${url} doesn't contain ${queryText}`);
3036
+ }
3037
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3038
+ continue;
3039
+ }
3040
+ break;
3041
+ case "starts-with":
3042
+ {
3043
+ const domain = this._getDomain(url);
3044
+ if (domain.length > 0 && domain !== queryText) {
3045
+ if (i === 29) {
3046
+ throw new Error(`Page URL ${url} doesn't start with ${queryText}`);
3047
+ }
3048
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3049
+ continue;
3050
+ }
3051
+ }
3052
+ break;
3053
+ case "ends-with":
3054
+ {
3055
+ const urlObj = new URL(url);
3056
+ let route = "/";
3057
+ if (urlObj.pathname !== "/") {
3058
+ route = urlObj.pathname.split("/").slice(-1)[0].trim();
3059
+ }
3060
+ else {
3061
+ route = "/";
3062
+ }
3063
+ if (route !== queryText) {
3064
+ if (i === 29) {
3065
+ throw new Error(`Page URL ${url} doesn't end with ${queryText}`);
3066
+ }
3067
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3068
+ continue;
3069
+ }
3070
+ }
3071
+ break;
3072
+ case "regex":
3073
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3074
+ if (!regex.test(url)) {
3075
+ if (i === 29) {
3076
+ throw new Error(`Page URL ${url} doesn't match regex ${queryText}`);
3077
+ }
3078
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3079
+ continue;
3080
+ }
3081
+ break;
3082
+ default:
3083
+ console.log("Unknown matching type, defaulting to contains matching");
3084
+ if (!url.includes(pathPart)) {
3085
+ if (i === 29) {
3086
+ throw new Error(`Page URL ${url} does not contain ${pathPart}`);
3087
+ }
3088
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3089
+ continue;
3090
+ }
2430
3091
  }
2431
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2432
- return info;
3092
+ await _screenshot(state, this);
3093
+ return state.info;
2433
3094
  }
2434
3095
  }
2435
3096
  catch (e) {
2436
- //await this.closeUnexpectedPopups();
2437
- this.logger.error("verify page path failed " + info.log);
2438
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2439
- info.screenshotPath = screenshotPath;
2440
- Object.assign(e, { info: info });
2441
- error = e;
2442
- // throw e;
2443
- await _commandError({ text: "verifyPagePath", operation: "verifyPagePath", pathPart, info }, e, this);
3097
+ state.info.failCause.lastError = e.message;
3098
+ state.info.failCause.assertionFailed = true;
3099
+ await _commandError(state, e, this);
2444
3100
  }
2445
3101
  finally {
2446
- const endTime = Date.now();
2447
- _reportToWorld(world, {
2448
- type: Types.VERIFY_PAGE_PATH,
2449
- text: "Verify page path",
2450
- _text: "Verify the page path contains " + pathPart,
2451
- screenshotId,
2452
- result: error
2453
- ? {
2454
- status: "FAILED",
2455
- startTime,
2456
- endTime,
2457
- message: error?.message,
2458
- }
2459
- : {
2460
- status: "PASSED",
2461
- startTime,
2462
- endTime,
2463
- },
2464
- info: info,
2465
- });
3102
+ await _commandFinally(state, this);
2466
3103
  }
2467
3104
  }
3105
+ /**
3106
+ * Verify the page title matches the given title.
3107
+ * @param {string} title - The title to verify.
3108
+ * @param {object} options - Options for verification.
3109
+ * @param {object} world - The world context.
3110
+ * @returns {Promise<object>} - The state info after verification.
3111
+ */
2468
3112
  async verifyPageTitle(title, options = {}, world = null) {
2469
- const startTime = Date.now();
2470
3113
  let error = null;
2471
3114
  let screenshotId = null;
2472
3115
  let screenshotPath = null;
2473
3116
  await new Promise((resolve) => setTimeout(resolve, 2000));
2474
- const info = {};
2475
- info.log = "***** verify page title " + title + " *****\n";
2476
- info.operation = "verifyPageTitle";
2477
3117
  const newValue = await this._replaceWithLocalData(title, world);
2478
3118
  if (newValue !== title) {
2479
3119
  this.logger.info(title + "=" + newValue);
2480
3120
  title = newValue;
2481
3121
  }
2482
- info.title = title;
3122
+ const { matcher, queryText } = this._matcher(title);
3123
+ const state = {
3124
+ text_search: queryText,
3125
+ options,
3126
+ world,
3127
+ locate: false,
3128
+ scroll: false,
3129
+ highlight: false,
3130
+ type: Types.VERIFY_PAGE_TITLE,
3131
+ text: `Verify the page title is ${queryText}`,
3132
+ _text: `Verify the page title is ${queryText}`,
3133
+ operation: "verifyPageTitle",
3134
+ log: "***** verify page title is " + queryText + " *****\n",
3135
+ };
2483
3136
  try {
3137
+ await _preCommand(state, this);
3138
+ state.info.text = queryText;
2484
3139
  for (let i = 0; i < 30; i++) {
2485
3140
  const foundTitle = await this.page.title();
2486
- if (!foundTitle.includes(title)) {
2487
- if (i === 29) {
2488
- throw new Error(`url ${foundTitle} doesn't contain ${title}`);
2489
- }
2490
- await new Promise((resolve) => setTimeout(resolve, 1000));
2491
- continue;
3141
+ switch (matcher) {
3142
+ case "exact":
3143
+ if (foundTitle !== queryText) {
3144
+ if (i === 29) {
3145
+ throw new Error(`Page Title ${foundTitle} is not equal to ${queryText}`);
3146
+ }
3147
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3148
+ continue;
3149
+ }
3150
+ break;
3151
+ case "contains":
3152
+ if (!foundTitle.includes(queryText)) {
3153
+ if (i === 29) {
3154
+ throw new Error(`Page Title ${foundTitle} doesn't contain ${queryText}`);
3155
+ }
3156
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3157
+ continue;
3158
+ }
3159
+ break;
3160
+ case "starts-with":
3161
+ if (!foundTitle.startsWith(queryText)) {
3162
+ if (i === 29) {
3163
+ throw new Error(`Page title ${foundTitle} doesn't start with ${queryText}`);
3164
+ }
3165
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3166
+ continue;
3167
+ }
3168
+ break;
3169
+ case "ends-with":
3170
+ if (!foundTitle.endsWith(queryText)) {
3171
+ if (i === 29) {
3172
+ throw new Error(`Page Title ${foundTitle} doesn't end with ${queryText}`);
3173
+ }
3174
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3175
+ continue;
3176
+ }
3177
+ break;
3178
+ case "regex":
3179
+ const regex = new RegExp(queryText.slice(1, -1), "g");
3180
+ if (!regex.test(foundTitle)) {
3181
+ if (i === 29) {
3182
+ throw new Error(`Page Title ${foundTitle} doesn't match regex ${queryText}`);
3183
+ }
3184
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3185
+ continue;
3186
+ }
3187
+ break;
3188
+ default:
3189
+ console.log("Unknown matching type, defaulting to contains matching");
3190
+ if (!foundTitle.includes(title)) {
3191
+ if (i === 29) {
3192
+ throw new Error(`Page Title ${foundTitle} does not contain ${title}`);
3193
+ }
3194
+ await new Promise((resolve) => setTimeout(resolve, 1000));
3195
+ continue;
3196
+ }
2492
3197
  }
2493
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2494
- return info;
3198
+ await _screenshot(state, this);
3199
+ return state.info;
2495
3200
  }
2496
3201
  }
2497
3202
  catch (e) {
2498
- //await this.closeUnexpectedPopups();
2499
- this.logger.error("verify page title failed " + info.log);
2500
- ({ screenshotId, screenshotPath } = await this._screenShot(options, world, info));
2501
- info.screenshotPath = screenshotPath;
2502
- Object.assign(e, { info: info });
2503
- error = e;
2504
- // throw e;
2505
- await _commandError({ text: "verifyPageTitle", operation: "verifyPageTitle", title, info, throwError: true }, e, this);
3203
+ state.info.failCause.lastError = e.message;
3204
+ state.info.failCause.assertionFailed = true;
3205
+ await _commandError(state, e, this);
2506
3206
  }
2507
3207
  finally {
2508
- const endTime = Date.now();
2509
- _reportToWorld(world, {
2510
- type: Types.VERIFY_PAGE_PATH,
2511
- text: "Verify page title",
2512
- _text: "Verify the page title contains " + title,
2513
- screenshotId,
2514
- result: error
2515
- ? {
2516
- status: "FAILED",
2517
- startTime,
2518
- endTime,
2519
- message: error?.message,
2520
- }
2521
- : {
2522
- status: "PASSED",
2523
- startTime,
2524
- endTime,
2525
- },
2526
- info: info,
2527
- });
3208
+ await _commandFinally(state, this);
2528
3209
  }
2529
3210
  }
2530
3211
  async findTextInAllFrames(dateAlternatives, numberAlternatives, text, state, partial = true, ignoreCase = false) {
@@ -2608,27 +3289,10 @@ class StableBrowser {
2608
3289
  const frame = resultWithElementsFound[0].frame;
2609
3290
  const dataAttribute = `[data-blinq-id-${resultWithElementsFound[0].randomToken}]`;
2610
3291
  await this._highlightElements(frame, dataAttribute);
2611
- // if (world && world.screenshot && !world.screenshotPath) {
2612
- // console.log(`Highlighting for verify text is found while running from recorder`);
2613
- // this._highlightElements(frame, dataAttribute).then(async () => {
2614
- // await new Promise((resolve) => setTimeout(resolve, 1000));
2615
- // this._unhighlightElements(frame, dataAttribute)
2616
- // .then(async () => {
2617
- // console.log(`Unhighlighted frame dataAttribute successfully`);
2618
- // })
2619
- // .catch(
2620
- // (e) => {}
2621
- // console.error(e)
2622
- // );
2623
- // });
2624
- // }
2625
3292
  const element = await frame.locator(dataAttribute).first();
2626
- // await new Promise((resolve) => setTimeout(resolve, 100));
2627
- // await this._unhighlightElements(frame, dataAttribute);
2628
3293
  if (element) {
2629
3294
  await this.scrollIfNeeded(element, state.info);
2630
3295
  await element.dispatchEvent("bvt_verify_page_contains_text");
2631
- // await _screenshot(state, this, element);
2632
3296
  }
2633
3297
  }
2634
3298
  await _screenshot(state, this);
@@ -2638,7 +3302,6 @@ class StableBrowser {
2638
3302
  console.error(error);
2639
3303
  }
2640
3304
  }
2641
- // await expect(element).toHaveCount(1, { timeout: 10000 });
2642
3305
  }
2643
3306
  catch (e) {
2644
3307
  await _commandError(state, e, this);
@@ -2720,6 +3383,8 @@ class StableBrowser {
2720
3383
  operation: "verify_text_with_relation",
2721
3384
  log: "***** search for " + textAnchor + " climb " + climb + " and verify " + textToVerify + " found *****\n",
2722
3385
  };
3386
+ const cmdStartTime = Date.now();
3387
+ let cmdEndTime = null;
2723
3388
  const timeout = this._getFindElementTimeout(options);
2724
3389
  await new Promise((resolve) => setTimeout(resolve, 2000));
2725
3390
  let newValue = await this._replaceWithLocalData(textAnchor, world);
@@ -2755,6 +3420,17 @@ class StableBrowser {
2755
3420
  await new Promise((resolve) => setTimeout(resolve, 1000));
2756
3421
  continue;
2757
3422
  }
3423
+ else {
3424
+ cmdEndTime = Date.now();
3425
+ if (cmdEndTime - cmdStartTime > 55000) {
3426
+ if (foundAncore) {
3427
+ throw new Error(`Text ${textToVerify} not found in page`);
3428
+ }
3429
+ else {
3430
+ throw new Error(`Text ${textAnchor} not found in page`);
3431
+ }
3432
+ }
3433
+ }
2758
3434
  try {
2759
3435
  for (let i = 0; i < resultWithElementsFound.length; i++) {
2760
3436
  foundAncore = true;
@@ -3154,6 +3830,43 @@ class StableBrowser {
3154
3830
  });
3155
3831
  }
3156
3832
  }
3833
+ /**
3834
+ * Explicit wait/sleep function that pauses execution for a specified duration
3835
+ * @param duration - Duration to sleep in milliseconds (default: 1000ms)
3836
+ * @param options - Optional configuration object
3837
+ * @param world - Optional world context
3838
+ * @returns Promise that resolves after the specified duration
3839
+ */
3840
+ async sleep(duration = 1000, options = {}, world = null) {
3841
+ const state = {
3842
+ duration,
3843
+ options,
3844
+ world,
3845
+ locate: false,
3846
+ scroll: false,
3847
+ screenshot: false,
3848
+ highlight: false,
3849
+ type: Types.SLEEP,
3850
+ text: `Sleep for ${duration} ms`,
3851
+ _text: `Sleep for ${duration} ms`,
3852
+ operation: "sleep",
3853
+ log: `***** Sleep for ${duration} ms *****\n`,
3854
+ };
3855
+ try {
3856
+ await _preCommand(state, this);
3857
+ if (duration < 0) {
3858
+ throw new Error("Sleep duration cannot be negative");
3859
+ }
3860
+ await new Promise((resolve) => setTimeout(resolve, duration));
3861
+ return state.info;
3862
+ }
3863
+ catch (e) {
3864
+ await _commandError(state, e, this);
3865
+ }
3866
+ finally {
3867
+ await _commandFinally(state, this);
3868
+ }
3869
+ }
3157
3870
  async _replaceWithLocalData(value, world, _decrypt = true, totpWait = true) {
3158
3871
  try {
3159
3872
  return await replaceWithLocalTestData(value, world, _decrypt, totpWait, this.context, this);
@@ -3184,6 +3897,7 @@ class StableBrowser {
3184
3897
  }
3185
3898
  async saveStoreState(path = null, world = null) {
3186
3899
  const storageState = await this.page.context().storageState();
3900
+ path = await this._replaceWithLocalData(path, this.world);
3187
3901
  //const testDataFile = _getDataFile(world, this.context, this);
3188
3902
  if (path) {
3189
3903
  // save { storageState: storageState } into the path
@@ -3194,6 +3908,7 @@ class StableBrowser {
3194
3908
  }
3195
3909
  }
3196
3910
  async restoreSaveState(path = null, world = null) {
3911
+ path = await this._replaceWithLocalData(path, this.world);
3197
3912
  await refreshBrowser(this, path, world);
3198
3913
  this.registerEventListeners(this.context);
3199
3914
  registerNetworkEvents(this.world, this, this.context, this.page);
@@ -3235,7 +3950,6 @@ class StableBrowser {
3235
3950
  else if (e.label === "domcontentloaded") {
3236
3951
  console.log("waited for the domcontent loaded timeout");
3237
3952
  }
3238
- console.log(".");
3239
3953
  }
3240
3954
  finally {
3241
3955
  await new Promise((resolve) => setTimeout(resolve, 2000));
@@ -3279,7 +3993,6 @@ class StableBrowser {
3279
3993
  await this.page.close();
3280
3994
  }
3281
3995
  catch (e) {
3282
- console.log(".");
3283
3996
  await _commandError(state, e, this);
3284
3997
  }
3285
3998
  finally {
@@ -3394,7 +4107,6 @@ class StableBrowser {
3394
4107
  await this.page.setViewportSize({ width: width, height: hight });
3395
4108
  }
3396
4109
  catch (e) {
3397
- console.log(".");
3398
4110
  await _commandError({ text: "setViewportSize", operation: "setViewportSize", width, hight, info }, e, this);
3399
4111
  }
3400
4112
  finally {
@@ -3432,7 +4144,6 @@ class StableBrowser {
3432
4144
  await this.page.reload();
3433
4145
  }
3434
4146
  catch (e) {
3435
- console.log(".");
3436
4147
  await _commandError({ text: "reloadPage", operation: "reloadPage", info }, e, this);
3437
4148
  }
3438
4149
  finally {
@@ -3476,6 +4187,10 @@ class StableBrowser {
3476
4187
  }
3477
4188
  }
3478
4189
  async beforeScenario(world, scenario) {
4190
+ if (world && world.attach) {
4191
+ world.attach(this.context.reportFolder, { mediaType: "text/plain" });
4192
+ }
4193
+ this.context.loadedRoutes = null;
3479
4194
  this.beforeScenarioCalled = true;
3480
4195
  if (scenario && scenario.pickle && scenario.pickle.name) {
3481
4196
  this.scenarioName = scenario.pickle.name;
@@ -3499,14 +4214,18 @@ class StableBrowser {
3499
4214
  envName = this.context.environment.name;
3500
4215
  }
3501
4216
  if (!process.env.TEMP_RUN) {
3502
- await getTestData(envName, world, undefined, this.featureName, this.scenarioName);
4217
+ await getTestData(envName, world, undefined, this.featureName, this.scenarioName, this.context);
3503
4218
  }
3504
4219
  await loadBrunoParams(this.context, this.context.environment.name);
3505
4220
  }
3506
4221
  async afterScenario(world, scenario) { }
3507
4222
  async beforeStep(world, step) {
4223
+ if (this.abortedExecution) {
4224
+ throw new Error("Aborted");
4225
+ }
3508
4226
  if (!this.beforeScenarioCalled) {
3509
4227
  this.beforeScenario(world, step);
4228
+ this.context.loadedRoutes = null;
3510
4229
  }
3511
4230
  if (this.stepIndex === undefined) {
3512
4231
  this.stepIndex = 0;
@@ -3531,13 +4250,16 @@ class StableBrowser {
3531
4250
  }
3532
4251
  if (this.initSnapshotTaken === false) {
3533
4252
  this.initSnapshotTaken = true;
3534
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4253
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3535
4254
  const snapshot = await this.getAriaSnapshot();
3536
4255
  if (snapshot) {
3537
4256
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-before");
3538
4257
  }
3539
4258
  }
3540
4259
  }
4260
+ this.context.routeResults = null;
4261
+ await registerBeforeStepRoutes(this.context, this.stepName);
4262
+ networkBeforeStep(this.stepName);
3541
4263
  }
3542
4264
  async getAriaSnapshot() {
3543
4265
  try {
@@ -3557,12 +4279,18 @@ class StableBrowser {
3557
4279
  try {
3558
4280
  // Ensure frame is attached and has body
3559
4281
  const body = frame.locator("body");
3560
- await body.waitFor({ timeout }); // wait explicitly
4282
+ //await body.waitFor({ timeout: 2000 }); // wait explicitly
3561
4283
  const snapshot = await body.ariaSnapshot({ timeout });
4284
+ if (!snapshot) {
4285
+ continue;
4286
+ }
3562
4287
  content.push(`- frame: ${i}`);
3563
4288
  content.push(snapshot);
3564
4289
  }
3565
- catch (innerErr) { }
4290
+ catch (innerErr) {
4291
+ console.warn(`Frame ${i} snapshot failed:`, innerErr);
4292
+ content.push(`- frame: ${i} - error: ${innerErr.message}`);
4293
+ }
3566
4294
  }
3567
4295
  return content.join("\n");
3568
4296
  }
@@ -3572,6 +4300,49 @@ class StableBrowser {
3572
4300
  }
3573
4301
  return null;
3574
4302
  }
4303
+ /**
4304
+ * Sends command with custom payload to report.
4305
+ * @param commandText - Title of the command to be shown in the report.
4306
+ * @param commandStatus - Status of the command (e.g. "PASSED", "FAILED").
4307
+ * @param content - Content of the command to be shown in the report.
4308
+ * @param options - Options for the command. Example: { type: "json", screenshot: true }
4309
+ * @param world - Optional world context.
4310
+ * @public
4311
+ */
4312
+ async addCommandToReport(commandText, commandStatus, content, options = {}, world = null) {
4313
+ const state = {
4314
+ options,
4315
+ world,
4316
+ locate: false,
4317
+ scroll: false,
4318
+ screenshot: options.screenshot ?? false,
4319
+ highlight: options.highlight ?? false,
4320
+ type: Types.REPORT_COMMAND,
4321
+ text: commandText,
4322
+ _text: commandText,
4323
+ operation: "report_command",
4324
+ log: "***** " + commandText + " *****\n",
4325
+ };
4326
+ try {
4327
+ await _preCommand(state, this);
4328
+ const payload = {
4329
+ type: options.type ?? "text",
4330
+ content: content,
4331
+ screenshotId: null,
4332
+ };
4333
+ state.payload = payload;
4334
+ if (commandStatus === "FAILED") {
4335
+ state.throwError = true;
4336
+ throw new Error("Command failed");
4337
+ }
4338
+ }
4339
+ catch (e) {
4340
+ await _commandError(state, e, this);
4341
+ }
4342
+ finally {
4343
+ await _commandFinally(state, this);
4344
+ }
4345
+ }
3575
4346
  async afterStep(world, step) {
3576
4347
  this.stepName = null;
3577
4348
  if (this.context && this.context.browserObject && this.context.browserObject.trace === true) {
@@ -3579,23 +4350,55 @@ class StableBrowser {
3579
4350
  await this.context.browserObject.context.tracing.stopChunk({
3580
4351
  path: path.join(this.context.browserObject.traceFolder, `trace-${this.stepIndex}.zip`),
3581
4352
  });
3582
- await world.attach(JSON.stringify({
3583
- type: "trace",
3584
- traceFilePath: `trace-${this.stepIndex}.zip`,
3585
- }), "application/json+trace");
4353
+ if (world && world.attach) {
4354
+ await world.attach(JSON.stringify({
4355
+ type: "trace",
4356
+ traceFilePath: `trace-${this.stepIndex}.zip`,
4357
+ }), "application/json+trace");
4358
+ }
3586
4359
  // console.log("trace file created", `trace-${this.stepIndex}.zip`);
3587
4360
  }
3588
4361
  }
3589
4362
  if (this.context) {
3590
4363
  this.context.examplesRow = null;
3591
4364
  }
3592
- if (world && world.attach && !process.env.DISABLE_SNAPSHOT) {
4365
+ if (world && world.attach && !process.env.DISABLE_SNAPSHOT && !this.fastMode) {
3593
4366
  const snapshot = await this.getAriaSnapshot();
3594
4367
  if (snapshot) {
3595
4368
  const obj = {};
3596
4369
  await world.attach(JSON.stringify(snapshot), "application/json+snapshot-after");
3597
4370
  }
3598
4371
  }
4372
+ this.context.routeResults = await registerAfterStepRoutes(this.context, world);
4373
+ if (this.context.routeResults) {
4374
+ if (world && world.attach) {
4375
+ await world.attach(JSON.stringify(this.context.routeResults), "application/json+intercept-results");
4376
+ }
4377
+ }
4378
+ if (!process.env.TEMP_RUN) {
4379
+ const state = {
4380
+ world,
4381
+ locate: false,
4382
+ scroll: false,
4383
+ screenshot: true,
4384
+ highlight: true,
4385
+ type: Types.STEP_COMPLETE,
4386
+ text: "end of scenario",
4387
+ _text: "end of scenario",
4388
+ operation: "step_complete",
4389
+ log: "***** " + "end of scenario" + " *****\n",
4390
+ };
4391
+ try {
4392
+ await _preCommand(state, this);
4393
+ }
4394
+ catch (e) {
4395
+ await _commandError(state, e, this);
4396
+ }
4397
+ finally {
4398
+ await _commandFinally(state, this);
4399
+ }
4400
+ }
4401
+ networkAfterStep(this.stepName);
3599
4402
  }
3600
4403
  }
3601
4404
  function createTimedPromise(promise, label) {