webship-js 2.0.11 → 2.0.12

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 (168) hide show
  1. package/.circleci/config.yml +10 -1
  2. package/.drone.yml +7 -7
  3. package/.github/workflows/github-actions.yml +45 -0
  4. package/.gitlab-ci.yml +9 -4
  5. package/.harness/webship-js-pipeline.yml +5 -6
  6. package/.semaphore/semaphore.yml +6 -9
  7. package/.teamcity/settings.kts +7 -6
  8. package/.travis.yml +6 -1
  9. package/AGENTS.md +1 -1
  10. package/CLAUDE.md +65 -23
  11. package/Jenkinsfile +5 -3
  12. package/azure-pipelines.yml +17 -8
  13. package/bamboo-specs/bamboo.yml +9 -15
  14. package/bin/init-webship.js +44 -8
  15. package/bitbucket-pipelines.yml +5 -1
  16. package/buildspec.yml +6 -7
  17. package/cloudbuild.yaml +28 -12
  18. package/codefresh.yml +6 -6
  19. package/cucumber.js +17 -10
  20. package/docs/00-quick-start.md +8 -0
  21. package/docs/02-bbr-smart-waits.md +15 -10
  22. package/docs/03-selector-registry.md +24 -0
  23. package/docs/04-step-reference.md +51 -25
  24. package/docs/05-web-first-assertions.md +6 -0
  25. package/docs/07-auth-state.md +1 -1
  26. package/docs/08-clock-mocking.md +21 -2
  27. package/docs/09-api-testing.md +40 -2
  28. package/docs/10-accessibility.md +2 -0
  29. package/docs/11-debugging.md +3 -1
  30. package/docs/12-ai-agent-guide.md +5 -0
  31. package/docs/13-faq.md +72 -1
  32. package/docs/14-recipes-cookbook.md +2 -0
  33. package/docs/15-tag-conventions.md +2 -1
  34. package/docs/16-ci-cd.md +140 -119
  35. package/docs/README.md +5 -5
  36. package/docs/advanced-screenshots.md +3 -1
  37. package/docs/api-step-definitions.md +16 -2
  38. package/docs/global-settings.md +69 -17
  39. package/docs/install-webship-js.md +2 -0
  40. package/docs/step-definitions/then-i-should-see.md +14 -1
  41. package/docs/step-definitions/then-item-checkbox.md +2 -0
  42. package/docs/step-definitions/when-i-fill.md +4 -0
  43. package/docs/step-definitions/when-i-select-option-select-list.md +2 -0
  44. package/examples/choice-controls.html +29 -0
  45. package/examples/datetime-fields.html +52 -0
  46. package/examples/element-selector-hint.html +16 -0
  47. package/examples/field-states.html +27 -0
  48. package/examples/fill-in-empty.html +26 -0
  49. package/examples/fill-unreachable.html +27 -0
  50. package/examples/iframe-inner.html +20 -0
  51. package/examples/iframe-nested.html +16 -0
  52. package/examples/iframe-outer.html +15 -0
  53. package/examples/multi-value-fields.html +54 -0
  54. package/examples/registered-names.html +15 -0
  55. package/examples/select-by-label.html +33 -0
  56. package/examples/settle-budget.html +21 -0
  57. package/examples/sorted-tables.html +38 -0
  58. package/examples/text-matching.html +48 -0
  59. package/examples/text-order.html +25 -0
  60. package/examples/touch.html +22 -0
  61. package/examples/viewport-top.html +36 -0
  62. package/package.json +16 -1
  63. package/playwright.config.ts +3 -1
  64. package/tests/check-api-launch-url.js +106 -0
  65. package/tests/check-assets.js +103 -0
  66. package/tests/check-attachments.js +105 -0
  67. package/tests/check-breakpoints.js +117 -0
  68. package/tests/check-clock.js +143 -0
  69. package/tests/check-config.js +90 -0
  70. package/tests/check-context.js +215 -0
  71. package/tests/check-dry-run.js +104 -0
  72. package/tests/check-examples.js +10 -4
  73. package/tests/check-exit-report.js +141 -0
  74. package/tests/check-javascript-errors.js +105 -0
  75. package/tests/check-must-fail.js +5 -4
  76. package/tests/check-scaffold.js +36 -1
  77. package/tests/check-screenshots.js +117 -0
  78. package/tests/check-settle-verbs.js +137 -0
  79. package/tests/check-time-limit.js +104 -0
  80. package/tests/check-video.js +156 -0
  81. package/tests/check-world.js +167 -0
  82. package/tests/features/api-base-url.feature +25 -0
  83. package/tests/features/api-form-data.feature +18 -0
  84. package/tests/features/api-json-paths.feature +24 -0
  85. package/tests/features/api-response-contains.feature +21 -0
  86. package/tests/features/api-response-header-presence.feature +17 -0
  87. package/tests/features/api-response-header.feature +17 -0
  88. package/tests/features/api-saved-placeholders.feature +37 -0
  89. package/tests/features/api-step-definitions-individual.feature +1 -1
  90. package/tests/features/api-tables.feature +40 -0
  91. package/tests/features/breakpoints.feature +25 -0
  92. package/tests/features/choice-controls.feature +35 -0
  93. package/tests/features/complete-api-testing-examples.feature +1 -1
  94. package/tests/features/datetime-field-lookup.feature +29 -0
  95. package/tests/features/element-selector-hint.feature +14 -0
  96. package/tests/features/field-state.feature +21 -0
  97. package/tests/features/fill-in-empty-value.feature +41 -0
  98. package/tests/features/fill-reachable.feature +13 -0
  99. package/tests/features/iframe-nested.feature +43 -0
  100. package/tests/features/javascript-tolerated-errors.feature +20 -0
  101. package/tests/features/modal-open.feature +13 -0
  102. package/tests/features/multi-value-field-lookup.feature +30 -0
  103. package/tests/features/registered-names.feature +14 -0
  104. package/tests/features/select-by-label.feature +31 -0
  105. package/tests/features/selector-files.feature +14 -0
  106. package/tests/features/selectors-table-header.feature +35 -0
  107. package/tests/features/settle-budget.feature +11 -0
  108. package/tests/features/sorted-tables.feature +19 -0
  109. package/tests/features/storage-quoted-values.feature +26 -0
  110. package/tests/features/text-matching.feature +38 -0
  111. package/tests/features/text-order.feature +14 -0
  112. package/tests/features/touch.feature +21 -0
  113. package/tests/features/viewport-top.feature +13 -0
  114. package/tests/features/xml-namespaces.feature +34 -0
  115. package/tests/must-fail/api-json-paths.feature +21 -0
  116. package/tests/must-fail/api-response-contains.feature +23 -0
  117. package/tests/must-fail/api-response-header-presence.feature +17 -0
  118. package/tests/must-fail/api-response-header.feature +21 -0
  119. package/tests/must-fail/api-without-base-url.feature +11 -0
  120. package/tests/must-fail/breakpoints.feature +15 -0
  121. package/tests/must-fail/choice-controls.feature +25 -0
  122. package/tests/must-fail/clock.feature +11 -0
  123. package/tests/must-fail/datetime-field.feature +10 -0
  124. package/tests/must-fail/element-selector-hint.feature +17 -0
  125. package/tests/must-fail/field-state.feature +20 -0
  126. package/tests/must-fail/fill-field.feature +30 -0
  127. package/tests/must-fail/iframe-text.feature +17 -0
  128. package/tests/must-fail/modal-open.feature +26 -0
  129. package/tests/must-fail/multi-value-field.feature +18 -0
  130. package/tests/must-fail/registered-names.feature +25 -0
  131. package/tests/must-fail/select-list.feature +15 -0
  132. package/tests/must-fail/selector-files.feature +10 -0
  133. package/tests/must-fail/sorted-tables.feature +20 -0
  134. package/tests/must-fail/storage-before-a-page.feature +13 -0
  135. package/tests/must-fail/text-matching.feature +16 -0
  136. package/tests/must-fail/text-order.feature +15 -0
  137. package/tests/must-fail/viewport-top.feature +20 -0
  138. package/tests/must-fail/yaml-numbers.feature +48 -0
  139. package/tests/step-definitions/a11y.steps.js +24 -15
  140. package/tests/step-definitions/action.steps.js +22 -8
  141. package/tests/step-definitions/api.steps.js +349 -67
  142. package/tests/step-definitions/assertion.steps.js +100 -10
  143. package/tests/step-definitions/auth.steps.js +15 -18
  144. package/tests/step-definitions/clock.steps.js +22 -0
  145. package/tests/step-definitions/debug.steps.js +8 -0
  146. package/tests/step-definitions/dialog.steps.js +7 -0
  147. package/tests/step-definitions/element.steps.js +132 -17
  148. package/tests/step-definitions/field.steps.js +409 -96
  149. package/tests/step-definitions/form.steps.js +76 -29
  150. package/tests/step-definitions/iframe.steps.js +89 -29
  151. package/tests/step-definitions/input.steps.js +26 -7
  152. package/tests/step-definitions/javascript.steps.js +64 -22
  153. package/tests/step-definitions/modal.steps.js +79 -13
  154. package/tests/step-definitions/navigation.steps.js +14 -0
  155. package/tests/step-definitions/network.steps.js +15 -5
  156. package/tests/step-definitions/response.steps.js +6 -4
  157. package/tests/step-definitions/responsive.steps.js +26 -33
  158. package/tests/step-definitions/screenshot.steps.js +25 -8
  159. package/tests/step-definitions/scroll.steps.js +20 -0
  160. package/tests/step-definitions/selectors.steps.js +95 -48
  161. package/tests/step-definitions/storage.steps.js +38 -13
  162. package/tests/step-definitions/table.steps.js +81 -6
  163. package/tests/step-definitions/video.steps.js +52 -55
  164. package/tests/step-definitions/wait.steps.js +88 -23
  165. package/tests/step-definitions/web-first.steps.js +69 -35
  166. package/tests/step-definitions/webship.js +681 -143
  167. package/tests/step-definitions/xml.steps.js +49 -15
  168. package/tests/step-definitions/yaml.steps.js +45 -20
@@ -4,22 +4,42 @@ const { setWorldConstructor, World, Before, After, BeforeStep, AfterStep, setDef
4
4
  const playwright = require('playwright');
5
5
  const playwrightConfig = require(require('path').join(process.cwd(), 'playwright.config'));
6
6
  const path = require('path');
7
+ const fs = require('fs');
7
8
 
8
9
  // ---------------------------------------------------------------------------
9
10
  // Output filter — strip noisy `✔ Before # ...` / `✔ After # ...` hook lines
10
11
  // from cucumber-js's failure dump so tester-facing output stays focused on
11
- // the failing step + hint. Disable with WEBSHIP_FILTER_HOOK_LINES=off.
12
+ // the failing step + hint. In a dry run (--dry-run or -d), also strip the
13
+ // pretty formatter's "- skipped" lines: every hook and every step of a dry
14
+ // run is skipped, and a line for each buries the "? undefined" and
15
+ // "✖ ambiguous" lines the dry run is for. Disable with
16
+ // WEBSHIP_FILTER_HOOK_LINES=off.
12
17
  // ---------------------------------------------------------------------------
13
18
  if (process.env.WEBSHIP_FILTER_HOOK_LINES !== 'off') {
14
19
  const HOOK_LINE = /^\s*[✔✖✗⚠?-]\s+(?:Before|After|BeforeStep|AfterStep)\b.*$/;
20
+ const DRY_RUN = process.argv.slice(2).some((arg) => arg === '--dry-run' || arg === '-d');
21
+ const SKIPPED_LINE = /^\s*-\s+skipped\s*$/;
22
+ const plain = (line) => line.replace(/\x1b\[[0-9;]*m/g, '');
23
+ const dropped = (line) => HOOK_LINE.test(plain(line)) || (DRY_RUN && SKIPPED_LINE.test(plain(line)));
15
24
  const wrap = (stream) => {
16
25
  const orig = stream.write.bind(stream);
26
+ // The pretty formatter writes a line and its line break in two writes:
27
+ // when a line is dropped, so is the line break that follows it.
28
+ let dropLineBreak = false;
17
29
  stream.write = (chunk, encoding, cb) => {
18
30
  if (typeof chunk === 'string' || Buffer.isBuffer(chunk)) {
19
31
  const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
32
+ const skipBreak = dropLineBreak && /^\r?\n$/.test(text);
33
+ dropLineBreak = false;
34
+ if (skipBreak || (!text.includes('\n') && text.trim() && dropped(text))) {
35
+ dropLineBreak = !skipBreak;
36
+ const done = typeof encoding === 'function' ? encoding : cb;
37
+ if (typeof done === 'function') process.nextTick(done);
38
+ return true;
39
+ }
20
40
  const filtered = text
21
41
  .split('\n')
22
- .filter((line) => !HOOK_LINE.test(line.replace(/\x1b\[[0-9;]*m/g, '')))
42
+ .filter((line) => !dropped(line))
23
43
  .join('\n');
24
44
  return orig(filtered, encoding, cb);
25
45
  }
@@ -117,11 +137,14 @@ async function pollPage(page, probe, arg, timeout, interval) {
117
137
  * Wait for the page to reach an "edge" of activity — DOM ready, network
118
138
  * idle, no pending AJAX or timers, and no DOM mutations for ≥250 ms.
119
139
  *
120
- * Each stage gets a share of the budget rather than "whatever is left", so a
121
- * stage that can never resolve cannot starve the ones after it. On a page with
122
- * analytics, a chat widget or a self-rescheduling timer, `networkidle` never
123
- * arrives; capping it at half the budget keeps the AJAX / pending-timer /
124
- * DOM-quiet probe — the useful one — running.
140
+ * Each stage but the last gets a share of the budget rather than "whatever
141
+ * is left", so a stage that can never resolve cannot starve the ones after
142
+ * it. On a page with analytics, a chat widget or a self-rescheduling timer,
143
+ * `networkidle` never arrives; capping it at half the budget keeps the AJAX /
144
+ * pending-timer / DOM-quiet probe — the useful one — running. That probe is
145
+ * the last stage, with nothing after it to starve: it gets everything the
146
+ * earlier stages left, so a request or a timer of more than half the budget
147
+ * is still waited for.
125
148
  *
126
149
  * Returns within `timeout` ms even when nothing on the page ever settles.
127
150
  *
@@ -151,15 +174,19 @@ async function smartSettle(page, timeout) {
151
174
  if (!await stage(0.25, (t) => page.waitForSelector('body', { state: 'attached', timeout: t }))) return;
152
175
  if (!await stage(0.25, (t) => page.waitForLoadState('domcontentloaded', { timeout: t }))) return;
153
176
  if (!await stage(0.5, (t) => page.waitForLoadState('networkidle', { timeout: t }))) return;
154
- await stage(0.5, (t) => pollPage(
177
+ await stage(1, (t) => pollPage(
155
178
  page,
156
179
  (quietMs) => {
157
180
  const ajax = window.__webshipAjaxCount;
158
181
  const timers = window.__webshipPendingTimers;
159
182
  const last = window.__webshipLastMutation;
183
+ const now = typeof window.__webshipNow === 'function' ? window.__webshipNow() : Date.now();
184
+ // Under a fake clock the page's timers are the clock's and run only
185
+ // when it moves; the ones the probes count are the clock's own.
186
+ const fakeClock = !!(window.Date && window.Date.isFake);
160
187
  if (typeof ajax === 'number' && ajax > 0) return false;
161
- if (typeof timers === 'number' && timers > 0) return false;
162
- if (typeof last === 'number' && Date.now() - last < quietMs) return false;
188
+ if (!fakeClock && typeof timers === 'number' && timers > 0) return false;
189
+ if (typeof last === 'number' && now - last < quietMs) return false;
163
190
  return true;
164
191
  },
165
192
  250,
@@ -454,31 +481,75 @@ async function gotoUrl(page, url) {
454
481
  *
455
482
  * @param {import('playwright').Page} page
456
483
  * @param {string} field - Label / placeholder / name.
457
- * @param {string} value - Value to type.
484
+ * @param {string} value - Value to type; null or undefined fills an empty value.
485
+ * @param {WebshipWorld} [world] - The World of the step, to tell a name of the selector registry.
458
486
  * @returns {Promise<void>}
459
487
  */
460
- async function fillField(page, field, value) {
488
+ async function fillField(page, field, value, world) {
489
+ // An empty value in a step ("") reaches the definition as null: it means "".
490
+ value = value === undefined || value === null ? '' : String(value);
461
491
  const byLabel = page.getByLabel(field, { exact: true });
462
492
  if (await byLabel.count() > 0) {
463
- await byLabel.fill(value);
493
+ await fillLocator(page, byLabel, value, field);
464
494
  return;
465
495
  }
466
496
  const byPlaceholder = page.getByPlaceholder(field, { exact: true });
467
497
  if (await byPlaceholder.count() > 0) {
468
- await byPlaceholder.fill(value);
498
+ await fillLocator(page, byPlaceholder, value, field);
469
499
  return;
470
500
  }
471
501
  const byName = page.locator(`[name="${field}"]`).first();
472
502
  if (await byName.count() > 0) {
473
- await byName.fill(value);
503
+ await fillLocator(page, byName, value, field);
474
504
  return;
475
505
  }
476
- throw friendly(
477
- `Could not find a field for "${field}".\n` +
478
- ` Tried: getByLabel(exact), getByPlaceholder(exact), [name="${field}"].\n` +
479
- ` Hints: check the label/placeholder text matches exactly (case-sensitive),\n` +
480
- ` or use the attribute variant: 'I fill in "${field}" with "${value}" by attr'.`
481
- );
506
+ throw failure(page, `Could not find a field for "${field}".`, {
507
+ hint: registeredNameHint(world, field, { withSelector: (selector) => `I fill in the field "${selector}" with "${value}"` }) ||
508
+ `the step looks for a field whose label, placeholder or name is exactly "${field}", letter case included. For an id, a class or another attribute, use: I fill in "${field}" with "${value}" by attr`,
509
+ });
510
+ }
511
+
512
+ /**
513
+ * Fill the field a step found. A field that is hidden, disabled or read-only,
514
+ * or that is not on the page, fails the step within 5 seconds with what is
515
+ * wrong with it, the page and a hint, instead of Playwright's raw timeout.
516
+ *
517
+ * @param {import('playwright').Page} page
518
+ * @param {import('playwright').Locator} loc - The field.
519
+ * @param {string} value - Value to type; null or undefined fills an empty value.
520
+ * @param {string} name - How the step named the field, for the message.
521
+ * @returns {Promise<void>}
522
+ */
523
+ async function fillLocator(page, loc, value, name) {
524
+ const text = value === undefined || value === null ? '' : String(value);
525
+ try {
526
+ await loc.fill(text, { timeout: 5000 });
527
+ return;
528
+ } catch (e) {
529
+ let state = '';
530
+ try {
531
+ if (await loc.count() === 0) state = 'missing';
532
+ else if (!(await loc.first().isVisible())) state = 'hidden';
533
+ else if (await loc.first().isDisabled({ timeout: 1000 })) state = 'disabled';
534
+ else if (!(await loc.first().isEditable({ timeout: 1000 }))) state = 'read-only';
535
+ } catch { /* the page changed while it was looked at */ }
536
+ if (state === 'missing') {
537
+ throw failure(page, `No field with "${name}" was found after 5 seconds.`, {
538
+ hint: 'by attribute the step reads the text as the attribute it names, else as an id, a class, a name, a test id, an aria-label, a value, a placeholder or a title; a text that starts with #, . or [ is a CSS selector.',
539
+ });
540
+ }
541
+ if (state === 'hidden') {
542
+ throw failure(page, `The field "${name}" is on the page but hidden, so it cannot be filled.`, {
543
+ hint: 'a field that shows after an action can be filled once it is visible: wait for it first. A field hidden behind a rich-text editor is filled with: I fill in the WYSIWYG field "<name>" with the "<text>"',
544
+ });
545
+ }
546
+ if (state === 'disabled' || state === 'read-only') {
547
+ throw failure(page, `The field "${name}" is ${state}, so it cannot be filled.`, {
548
+ hint: `a ${state} field keeps its value; to check it, use: the field "${name}" should have "${state}" state`,
549
+ });
550
+ }
551
+ throw failure(page, `Could not fill the field "${name}".`, { hint: `${humanize(e)}.` });
552
+ }
482
553
  }
483
554
 
484
555
  /**
@@ -523,6 +594,40 @@ async function locateByLabelOrSelector(page, name, timeout) {
523
594
  }
524
595
  }
525
596
 
597
+ // The package's own tests/assets/: read last, so that a file only the package
598
+ // ships keeps working.
599
+ const PACKAGE_ASSETS = path.join(__dirname, '..', 'assets');
600
+
601
+ /**
602
+ * Find a file a step names by its name: an absolute path as written; a
603
+ * relative one in the World's `assetsFolder` (the project's tests/assets/),
604
+ * then as written from the project root, then in the package's own
605
+ * tests/assets/. Fails plainly, with the paths tried, when none holds it.
606
+ *
607
+ * @param {WebshipWorld} world
608
+ * @param {string} name - The file as the step gives it.
609
+ * @returns {string} The absolute path of the file.
610
+ */
611
+ function resolveAssetFile(world, name) {
612
+ const fs = require('fs');
613
+ const file = String(name === undefined || name === null ? '' : name).trim();
614
+ const tried = path.isAbsolute(file)
615
+ ? [file]
616
+ : [...new Set([
617
+ path.resolve((world && world.assetsFolder) || path.join(process.cwd(), 'tests', 'assets'), file),
618
+ path.resolve(process.cwd(), file),
619
+ path.resolve(PACKAGE_ASSETS, file),
620
+ ])];
621
+ const found = tried.find((candidate) => {
622
+ try { return fs.statSync(candidate).isFile(); } catch { return false; }
623
+ });
624
+ if (found) return found;
625
+ throw failure(world && world.page, `The file "${file}" was not found.`, {
626
+ found: `nothing at ${tried.map((candidate) => path.relative(process.cwd(), candidate) || candidate).join(', ')}`,
627
+ hint: 'put the file in the tests/assets/ folder of the project, or name it by its path from the project root.',
628
+ });
629
+ }
630
+
526
631
  /**
527
632
  * Left-pad a number with zeros to the requested width.
528
633
  *
@@ -761,6 +866,55 @@ function excerpt(text, max) {
761
866
  return clean.length > limit ? clean.slice(0, limit) + '…' : clean;
762
867
  }
763
868
 
869
+ /**
870
+ * Locator for the page when its text contains `text`, read the way the page
871
+ * text steps (`I should see`, `I should not see`, `eventually I should see`)
872
+ * read it: Playwright's text matching on `<body>`, letter case ignored, white
873
+ * space collapsed, the text of hidden elements included, the text of
874
+ * `<script>`, `<noscript>` and `<style>` left out. It matches nothing while
875
+ * the text is not on the page, so `waitFor({ state: 'attached' })` waits for
876
+ * the text to come and `waitFor({ state: 'detached' })` for it to go.
877
+ *
878
+ * @param {import('playwright').Page} page
879
+ * @param {string} text
880
+ * @returns {import('playwright').Locator}
881
+ */
882
+ function pageTextLocator(page, text) {
883
+ return page.locator('body').filter({ hasText: text === undefined || text === null ? '' : String(text) });
884
+ }
885
+
886
+ /**
887
+ * The hint for a step that was given a name of the named-selector registry
888
+ * where it reads a text, a label or a CSS selector: it does not read the
889
+ * registry, so the name matched nothing. Names the bare-name step that reads
890
+ * it, when there is one and the name fits it, and the same step with the
891
+ * selector the name stands for. An empty string when `name` is not a
892
+ * registered name, so a failure that has nothing to do with the registry
893
+ * reads as before.
894
+ *
895
+ * @param {WebshipWorld} world
896
+ * @param {string} name - The argument the step was given.
897
+ * @param {Object} [forms]
898
+ * @param {string} [forms.bare] - The bare-name step, "{name}" for the name.
899
+ * @param {function(string): string} [forms.withSelector] - The step to use with the selector.
900
+ * @returns {string}
901
+ */
902
+ function registeredNameHint(world, name, forms) {
903
+ const key = String(name === undefined || name === null ? '' : name).trim();
904
+ if (!key || !world) return '';
905
+ const css = world.__selectorsCss || {};
906
+ const xpath = world.__selectorsXpath || {};
907
+ let selector = null;
908
+ if (Object.prototype.hasOwnProperty.call(css, key)) selector = css[key];
909
+ else if (Object.prototype.hasOwnProperty.call(xpath, key)) selector = xpath[key].startsWith('xpath=') ? xpath[key] : `xpath=${xpath[key]}`;
910
+ if (!selector) return '';
911
+ const uses = [];
912
+ if (forms && forms.bare && /^[a-zA-Z0-9 ,-]+$/.test(key)) uses.push(forms.bare.replace('{name}', key));
913
+ if (forms && typeof forms.withSelector === 'function') uses.push(forms.withSelector(selector));
914
+ return `"${key}" is a name of the selector registry (${selector}), but this step does not read the registry.` +
915
+ (uses.length ? ` Use: ${uses.join(', or: ')}` : '');
916
+ }
917
+
764
918
  /**
765
919
  * True when an error is Playwright giving up after its timeout, which in an
766
920
  * assertion means "what was looked for is not there".
@@ -808,8 +962,10 @@ module.exports = {
808
962
  resolveUrl,
809
963
  sendRequest,
810
964
  fillField,
965
+ fillLocator,
811
966
  getLocatorText,
812
967
  locateByLabelOrSelector,
968
+ resolveAssetFile,
813
969
  pad,
814
970
  resolveRelativeDate,
815
971
  parseRelativeOffset,
@@ -819,21 +975,132 @@ module.exports = {
819
975
  failure,
820
976
  excerpt,
821
977
  isTimeout,
978
+ registeredNameHint,
979
+ pageTextLocator,
980
+ breakpoints,
981
+ breakpoint,
982
+ onNewPage,
983
+ videoFileName,
822
984
  };
823
985
 
824
986
  // ---------------------------------------------------------------------------
825
987
  // Auto HTML report on cucumber-js process exit.
826
988
  // Disable: WEBSHIP_REPORT_DISABLE=1. Extra flags: WEBSHIP_REPORT_ARGS="--theme hierarchy --layout 2".
827
- // Registered once per process.
989
+ // Registered once per process, and run only in the process that runs
990
+ // cucumber-js: the workers of a --parallel run load these files too, but exit
991
+ // before the JSON report is complete.
828
992
  // ---------------------------------------------------------------------------
993
+
994
+ /**
995
+ * The values given to an option on a command line, in order: `--name value`,
996
+ * `--name=value` and the short form `-n value`.
997
+ *
998
+ * @param {string[]} args
999
+ * @param {string} name - Long name, with its dashes (`--format`).
1000
+ * @param {string} [short] - Short name, with its dash (`-f`).
1001
+ * @returns {string[]}
1002
+ */
1003
+ function optionValues(args, name, short) {
1004
+ const values = [];
1005
+ for (let i = 0; i < args.length; i += 1) {
1006
+ if (args[i] === name || (short && args[i] === short)) {
1007
+ if (i + 1 < args.length) values.push(args[i + 1]);
1008
+ i += 1;
1009
+ } else if (args[i].startsWith(name + '=')) {
1010
+ values.push(args[i].slice(name.length + 1));
1011
+ }
1012
+ }
1013
+ return values;
1014
+ }
1015
+
1016
+ /**
1017
+ * The file of the last `json` formatter in a list of cucumber-js formats
1018
+ * (`json:path`, `"json":"path"` or `['json', 'path']`), or '' when there is
1019
+ * none that writes to a file.
1020
+ *
1021
+ * @param {Array<string|string[]>} formats
1022
+ * @returns {string}
1023
+ */
1024
+ function jsonFormatterFile(formats) {
1025
+ let file = '';
1026
+ for (const format of formats || []) {
1027
+ if (Array.isArray(format)) {
1028
+ if (format[0] === 'json' && format[1]) file = String(format[1]);
1029
+ continue;
1030
+ }
1031
+ const match = /^"?json"?:(.+)$/.exec(String(format));
1032
+ if (match) file = match[1].replace(/^"(.*)"$/, '$1');
1033
+ }
1034
+ return file;
1035
+ }
1036
+
1037
+ /**
1038
+ * The formats of the cucumber-js config file of this run, for the profiles
1039
+ * the command line names, else the default one. A config file that cannot be
1040
+ * read here (an ES module, a YAML file) gives none.
1041
+ *
1042
+ * @param {string[]} args - The command line of cucumber-js.
1043
+ * @returns {Array<string|string[]>}
1044
+ */
1045
+ function configFormats(args) {
1046
+ const named = optionValues(args, '--config', '-c');
1047
+ const candidates = named.length
1048
+ ? [named[named.length - 1]]
1049
+ : ['cucumber.js', 'cucumber.cjs', 'cucumber.json'];
1050
+ for (const candidate of candidates) {
1051
+ const file = path.resolve(process.cwd(), candidate);
1052
+ if (!/\.(c?js|json)$/.test(file) || !require('fs').existsSync(file)) continue;
1053
+ try {
1054
+ const loaded = require(file);
1055
+ const profiles = optionValues(args, '--profile', '-p');
1056
+ const formats = [];
1057
+ for (const profile of profiles.length ? profiles : ['default']) {
1058
+ const config = (loaded && loaded[profile]) || (profile === 'default' && loaded && !loaded.default ? loaded : null);
1059
+ if (config && Array.isArray(config.format)) formats.push(...config.format);
1060
+ }
1061
+ return formats;
1062
+ } catch {
1063
+ return [];
1064
+ }
1065
+ }
1066
+ return [];
1067
+ }
1068
+
1069
+ /**
1070
+ * Where this run wrote its JSON report: WEBSHIP_REPORT_JSON, else the file of
1071
+ * the `json` formatter of the command line, else the one of the config file,
1072
+ * else the scaffold's `tests/reports/cucumber_report.json`.
1073
+ *
1074
+ * @returns {string}
1075
+ */
1076
+ function reportJsonFile() {
1077
+ if (process.env.WEBSHIP_REPORT_JSON) return process.env.WEBSHIP_REPORT_JSON;
1078
+ const args = process.argv.slice(2);
1079
+ return jsonFormatterFile(optionValues(args, '--format', '-f'))
1080
+ || jsonFormatterFile(configFormats(args))
1081
+ || 'tests/reports/cucumber_report.json';
1082
+ }
1083
+
829
1084
  if (!global.__WEBSHIP_AUTO_REPORT__) {
830
1085
  global.__WEBSHIP_AUTO_REPORT__ = true;
831
1086
  process.on('exit', () => {
832
1087
  if (process.env.WEBSHIP_REPORT_DISABLE) return;
1088
+ // A worker of a --parallel run: the process that runs cucumber-js builds
1089
+ // the report once the whole JSON report is written.
1090
+ if (process.env.CUCUMBER_WORKER_ID) return;
833
1091
  try {
1092
+ const json = reportJsonFile();
1093
+ let size = 0;
1094
+ try { size = require('fs').statSync(path.resolve(process.cwd(), json)).size; } catch { /* not written */ }
1095
+ if (!size) {
1096
+ console.error(`[webship-js] No HTML report: this run wrote no JSON report at "${json}". Set WEBSHIP_REPORT_JSON to the file of your json formatter, or WEBSHIP_REPORT_DISABLE=1 to build no report.`);
1097
+ return;
1098
+ }
834
1099
  const { run } = require(path.join(__dirname, '..', '..', 'bin', 'generate-reports'));
835
1100
  const extra = (process.env.WEBSHIP_REPORT_ARGS || '').split(/\s+/).filter(Boolean);
836
- run(extra);
1101
+ Promise.resolve(run(['--json', json].concat(extra))).catch((err) => {
1102
+ console.error('[webship-js] Report generation failed:', err.message);
1103
+ });
837
1104
  } catch (err) {
838
1105
  console.error('[webship-js] Report generation failed:', err.message);
839
1106
  }
@@ -857,101 +1124,205 @@ const STEP_TIMEOUT = (() => {
857
1124
  })();
858
1125
  setDefaultTimeout(STEP_TIMEOUT);
859
1126
 
1127
+ // The pacing of worldParameters.minWaitTime, in ms. A project may leave the
1128
+ // block out or set only some of its keys: the others keep these values.
1129
+ const MIN_WAIT_TIME = Object.freeze({
1130
+ page: 3000,
1131
+ before_scenario: 0,
1132
+ after_scenario: 0,
1133
+ before_step: 0,
1134
+ after_step: 0,
1135
+ });
1136
+
1137
+ // BBR: the init script installed on every browser context the World opens.
1138
+ // It runs before any document script and counts in-flight fetch / XHR
1139
+ // requests and pending timers and stamps the last DOM mutation, so
1140
+ // smartSettle() detects the edge of background activity rather than guessing
1141
+ // a fixed delay.
1142
+ function smartWaitProbes() {
1143
+ if (window.__webshipAjaxInstalled) return;
1144
+ window.__webshipAjaxInstalled = true;
1145
+ // The time of the probes is real time: a fake clock (Playwright's
1146
+ // page.clock) replaces Date later, and its Date.now() may stand still or
1147
+ // lie in the past.
1148
+ const realNow = Date.now.bind(Date);
1149
+ window.__webshipNow = realNow;
1150
+ window.__webshipAjaxCount = 0;
1151
+ window.__webshipPendingTimers = 0;
1152
+ window.__webshipLastMutation = realNow();
1153
+
1154
+ // Track in-flight fetch requests.
1155
+ const origFetch = window.fetch;
1156
+ if (typeof origFetch === 'function') {
1157
+ window.fetch = function (...args) {
1158
+ window.__webshipAjaxCount++;
1159
+ const p = origFetch.apply(this, args);
1160
+ const settle = () => { window.__webshipAjaxCount--; };
1161
+ p.then(settle, settle);
1162
+ return p;
1163
+ };
1164
+ }
1165
+
1166
+ // Track in-flight XMLHttpRequests.
1167
+ const XHR = window.XMLHttpRequest;
1168
+ if (XHR && XHR.prototype) {
1169
+ const origSend = XHR.prototype.send;
1170
+ XHR.prototype.send = function (...args) {
1171
+ window.__webshipAjaxCount++;
1172
+ const settle = () => { window.__webshipAjaxCount--; };
1173
+ this.addEventListener('loadend', settle, { once: true });
1174
+ return origSend.apply(this, args);
1175
+ };
1176
+ }
1177
+
1178
+ // Track pending setTimeout callbacks. Many client-side frameworks use
1179
+ // setTimeout to schedule UI updates (animation frames, throttled
1180
+ // re-renders, fade-out → display:none). BBR demands we wait for those
1181
+ // timers to drain rather than guess a fixed delay.
1182
+ const origSetTimeout = window.setTimeout;
1183
+ const origClearTimeout = window.clearTimeout;
1184
+ const liveTimers = new Set();
1185
+ if (typeof origSetTimeout === 'function') {
1186
+ window.setTimeout = function (cb, delay, ...args) {
1187
+ window.__webshipPendingTimers++;
1188
+ let id;
1189
+ const wrapped = function () {
1190
+ try {
1191
+ if (typeof cb === 'function') return cb.apply(this, args);
1192
+ } finally {
1193
+ if (liveTimers.delete(id)) window.__webshipPendingTimers--;
1194
+ }
1195
+ };
1196
+ id = origSetTimeout(wrapped, delay);
1197
+ liveTimers.add(id);
1198
+ return id;
1199
+ };
1200
+ if (typeof origClearTimeout === 'function') {
1201
+ window.clearTimeout = function (id) {
1202
+ if (liveTimers.delete(id)) window.__webshipPendingTimers--;
1203
+ return origClearTimeout(id);
1204
+ };
1205
+ }
1206
+ }
1207
+
1208
+ // Track last DOM mutation so smartSettle can wait for the *edge* of
1209
+ // client-side rendering (animations, async hydration, transitions).
1210
+ const startObserver = () => {
1211
+ if (!document || !document.documentElement) return false;
1212
+ try {
1213
+ new MutationObserver(() => { window.__webshipLastMutation = realNow(); })
1214
+ .observe(document.documentElement, { childList: true, subtree: true, attributes: true, characterData: true });
1215
+ return true;
1216
+ } catch (e) { return false; }
1217
+ };
1218
+ if (!startObserver()) {
1219
+ document.addEventListener('DOMContentLoaded', startObserver, { once: true });
1220
+ }
1221
+ }
1222
+
1223
+ // Functions that set up every page the World opens: the first page of a
1224
+ // scenario and each page a step opens in a new browser context (restoring an
1225
+ // auth state, starting or stopping a video recording). Step files add theirs
1226
+ // with onNewPage().
1227
+ const NEW_PAGE_SETUPS = [];
1228
+
1229
+ /**
1230
+ * Run `setup(world, page)` on every page the World opens from now on, before
1231
+ * any step uses it: the first page of each scenario and every page of a
1232
+ * browser context that a step replaces.
1233
+ *
1234
+ * @param {function(WebshipWorld, import('playwright').Page): (void|Promise<void>)} setup
1235
+ * @returns {void}
1236
+ */
1237
+ function onNewPage(setup) {
1238
+ if (typeof setup === 'function') NEW_PAGE_SETUPS.push(setup);
1239
+ }
1240
+
860
1241
  class PlaywrightWorld extends World {
861
1242
  constructor(options) {
862
1243
  super(options);
863
1244
  this.launchUrl = this.parameters.launchUrl;
864
- this.minWaitTime = this.parameters.minWaitTime;
1245
+ this.minWaitTime = Object.assign({}, MIN_WAIT_TIME, this.parameters.minWaitTime || {});
865
1246
  this.playwrightBrowser = null;
866
1247
  this.context = null;
867
1248
  this.page = null;
868
- this.assetsFolder = path.join(__dirname, '../assets/');
1249
+ this.assetsFolder = path.join(process.cwd(), 'tests', 'assets');
869
1250
  }
870
1251
 
871
1252
  async openBrowser(extraContextOptions) {
872
- const { browser: browserName, launchOptions, contextOptions } = playwrightConfig;
1253
+ const { browser: browserName, launchOptions } = playwrightConfig;
873
1254
  this.playwrightBrowser = await playwright[browserName].launch(launchOptions);
874
- const merged = Object.assign({}, contextOptions, extraContextOptions || {});
875
- this.context = await this.playwrightBrowser.newContext(merged);
876
- // BBR: install in-flight fetch/XHR counter on every page (init script runs
877
- // before any document script). The counter lets smartSettle() detect the
878
- // edge of background activity rather than guessing a fixed delay.
879
- await this.context.addInitScript(() => {
880
- if (window.__webshipAjaxInstalled) return;
881
- window.__webshipAjaxInstalled = true;
882
- window.__webshipAjaxCount = 0;
883
- window.__webshipPendingTimers = 0;
884
- window.__webshipLastMutation = Date.now();
885
-
886
- // Track in-flight fetch requests.
887
- const origFetch = window.fetch;
888
- if (typeof origFetch === 'function') {
889
- window.fetch = function (...args) {
890
- window.__webshipAjaxCount++;
891
- const p = origFetch.apply(this, args);
892
- const settle = () => { window.__webshipAjaxCount--; };
893
- p.then(settle, settle);
894
- return p;
895
- };
896
- }
1255
+ await this.openContext(extraContextOptions);
1256
+ }
897
1257
 
898
- // Track in-flight XMLHttpRequests.
899
- const XHR = window.XMLHttpRequest;
900
- if (XHR && XHR.prototype) {
901
- const origSend = XHR.prototype.send;
902
- XHR.prototype.send = function (...args) {
903
- window.__webshipAjaxCount++;
904
- const settle = () => { window.__webshipAjaxCount--; };
905
- this.addEventListener('loadend', settle, { once: true });
906
- return origSend.apply(this, args);
907
- };
908
- }
1258
+ /**
1259
+ * Open a browser context and its page with everything a scenario relies
1260
+ * on: the context options of playwright.config.ts, the scenario's own (the
1261
+ * viewport of an @mobile / @desktop tag, video recording while it is on),
1262
+ * then `extraContextOptions`; the smart-wait init script; and the page
1263
+ * setups registered with onNewPage() (JavaScript-error capture, the
1264
+ * response tracker, the request log, a pending dialog handler).
1265
+ *
1266
+ * @param {import('playwright').BrowserContextOptions} [extraContextOptions]
1267
+ * @returns {Promise<void>}
1268
+ */
1269
+ async openContext(extraContextOptions) {
1270
+ const options = Object.assign({}, playwrightConfig.contextOptions, this._scenarioContextOptions || {});
1271
+ if (this._videoRequested && this._videoSettings) {
1272
+ fs.mkdirSync(this._videoSettings.dir, { recursive: true });
1273
+ options.recordVideo = { dir: this._videoSettings.dir, size: this._videoSettings.size };
1274
+ }
1275
+ Object.assign(options, extraContextOptions || {});
1276
+ this.context = await this.playwrightBrowser.newContext(options);
1277
+ await this.context.addInitScript(smartWaitProbes);
1278
+ this.page = await this.context.newPage();
1279
+ this.frame = null;
1280
+ for (const setup of NEW_PAGE_SETUPS) await setup(this, this.page);
1281
+ }
909
1282
 
910
- // Track pending setTimeout callbacks. Many client-side frameworks use
911
- // setTimeout to schedule UI updates (animation frames, throttled
912
- // re-renders, fade-out → display:none). BBR demands we wait for those
913
- // timers to drain rather than guess a fixed delay.
914
- const origSetTimeout = window.setTimeout;
915
- const origClearTimeout = window.clearTimeout;
916
- const liveTimers = new Set();
917
- if (typeof origSetTimeout === 'function') {
918
- window.setTimeout = function (cb, delay, ...args) {
919
- window.__webshipPendingTimers++;
920
- let id;
921
- const wrapped = function () {
922
- try {
923
- if (typeof cb === 'function') return cb.apply(this, args);
924
- } finally {
925
- if (liveTimers.delete(id)) window.__webshipPendingTimers--;
926
- }
927
- };
928
- id = origSetTimeout(wrapped, delay);
929
- liveTimers.add(id);
930
- return id;
931
- };
932
- if (typeof origClearTimeout === 'function') {
933
- window.clearTimeout = function (id) {
934
- if (liveTimers.delete(id)) window.__webshipPendingTimers--;
935
- return origClearTimeout(id);
936
- };
937
- }
938
- }
1283
+ /**
1284
+ * Replace the browser context in the middle of a scenario (restoring an
1285
+ * auth state, starting a video recording) with one opened by
1286
+ * openContext(), so the new page keeps the smart waits, the viewport of the
1287
+ * scenario, video recording and every page setup. The cookies and the
1288
+ * local storage of the context go over to the new one, unless
1289
+ * `extraContextOptions.storageState` gives others. The new page is blank,
1290
+ * and a video of the context being replaced is not kept.
1291
+ *
1292
+ * @param {import('playwright').BrowserContextOptions} [extraContextOptions]
1293
+ * @returns {Promise<void>}
1294
+ */
1295
+ async replaceContext(extraContextOptions) {
1296
+ const extra = Object.assign({}, extraContextOptions || {});
1297
+ const outgoing = this.context;
1298
+ const video = this.page && typeof this.page.video === 'function' ? this.page.video() : null;
1299
+ if (outgoing && !('storageState' in extra)) {
1300
+ try { extra.storageState = await outgoing.storageState(); } catch { /* a closed context has nothing to carry */ }
1301
+ }
1302
+ if (outgoing) {
1303
+ try { await outgoing.close(); } catch { /* already closed */ }
1304
+ }
1305
+ if (video) await video.delete().catch(() => {});
1306
+ await this.openContext(extra);
1307
+ }
939
1308
 
940
- // Track last DOM mutation so smartSettle can wait for the *edge* of
941
- // client-side rendering (animations, async hydration, transitions).
942
- const startObserver = () => {
943
- if (!document || !document.documentElement) return false;
944
- try {
945
- new MutationObserver(() => { window.__webshipLastMutation = Date.now(); })
946
- .observe(document.documentElement, { childList: true, subtree: true, attributes: true, characterData: true });
947
- return true;
948
- } catch (e) { return false; }
949
- };
950
- if (!startObserver()) {
951
- document.addEventListener('DOMContentLoaded', startObserver, { once: true });
952
- }
953
- });
954
- this.page = await this.context.newPage();
1309
+ /**
1310
+ * Wait for the page to settle the way the built-in action steps do: no
1311
+ * request in flight, no pending timer and a DOM quiet for 250 ms, bounded
1312
+ * by `budget` ms (by default 1500, the budget after a step). For a
1313
+ * project's own step that changes the page:
1314
+ *
1315
+ * When('I add {string} to the cart', async function (item) {
1316
+ * await this.page.click(`[data-add="${item}"]`);
1317
+ * await this.smartSettle();
1318
+ * });
1319
+ *
1320
+ * @param {number} [budget=1500]
1321
+ * @returns {Promise<void>}
1322
+ */
1323
+ async smartSettle(budget) {
1324
+ if (!this.page) return;
1325
+ await smartSettle(this.page, typeof budget === 'number' && budget > 0 ? budget : 1500);
955
1326
  }
956
1327
 
957
1328
  async closeBrowser() {
@@ -966,6 +1337,35 @@ class PlaywrightWorld extends World {
966
1337
 
967
1338
  setWorldConstructor(PlaywrightWorld);
968
1339
 
1340
+ // A project extends the World instead of replacing it, so the smart waits,
1341
+ // the viewport tags, video recording and the page setups stay:
1342
+ // const { PlaywrightWorld } = require('webship-js/tests/step-definitions/webship');
1343
+ // setWorldConstructor(class extends PlaywrightWorld { … });
1344
+ module.exports.PlaywrightWorld = PlaywrightWorld;
1345
+
1346
+ let foreignWorldReported = false;
1347
+
1348
+ // A World set with setWorldConstructor that does not extend PlaywrightWorld
1349
+ // has none of what webship-js puts on a page: say so once, plainly.
1350
+ function checkWorld(world) {
1351
+ if (world instanceof PlaywrightWorld) return;
1352
+ // The hooks below read the pacing of the World: give a World of its own
1353
+ // the defaults, so it can still run.
1354
+ if (!world.minWaitTime) world.minWaitTime = Object.assign({}, MIN_WAIT_TIME);
1355
+ if (typeof world.openBrowser !== 'function') {
1356
+ throw friendly(
1357
+ 'The World of this run is not a PlaywrightWorld of webship-js, and it has no openBrowser().\n' +
1358
+ " Hint: extend it instead of replacing it: const { PlaywrightWorld } = require('webship-js/tests/step-definitions/webship'); setWorldConstructor(class extends PlaywrightWorld { … });"
1359
+ );
1360
+ }
1361
+ if (foreignWorldReported) return;
1362
+ foreignWorldReported = true;
1363
+ process.stderr.write(
1364
+ '\n[webship-js] The World of this run does not extend PlaywrightWorld: the smart waits, the @mobile / @desktop viewport, video recording and the page setups depend on it. ' +
1365
+ "Extend it instead: const { PlaywrightWorld } = require('webship-js/tests/step-definitions/webship').\n"
1366
+ );
1367
+ }
1368
+
969
1369
  // ---------------------------------------------------------------------------
970
1370
  // Video recording — Playwright records at browser-context creation. The
971
1371
  // helpers below resolve config + tags into either an empty {} (no
@@ -975,6 +1375,14 @@ setWorldConstructor(PlaywrightWorld);
975
1375
 
976
1376
  const VIDEO_MODES = new Set(['off', 'on', 'on-failure', 'tag']);
977
1377
 
1378
+ // WEBSHIP_VIDEO_SIZE: "<width>x<height>", such as "1280x720".
1379
+ function videoSizeFromEnv() {
1380
+ const m = String(process.env.WEBSHIP_VIDEO_SIZE || '').trim().match(/^(\d+)\s*[x×]\s*(\d+)$/i);
1381
+ return m && parseInt(m[1], 10) > 0 && parseInt(m[2], 10) > 0
1382
+ ? { width: parseInt(m[1], 10), height: parseInt(m[2], 10) }
1383
+ : null;
1384
+ }
1385
+
978
1386
  function videoSettings(world, scope) {
979
1387
  const cfg = (world.parameters && world.parameters.video) || {};
980
1388
  let mode = process.env.WEBSHIP_VIDEO || cfg.mode || 'off';
@@ -982,7 +1390,7 @@ function videoSettings(world, scope) {
982
1390
  return {
983
1391
  mode,
984
1392
  dir: process.env.WEBSHIP_VIDEO_DIR || cfg.dir || './videos',
985
- size: cfg.size || { width: 1280, height: 720 },
1393
+ size: videoSizeFromEnv() || cfg.size || { width: 1280, height: 720 },
986
1394
  filenamePattern: cfg.filenamePattern || '{datetime}.{feature_file}.{scenario}.{status}.{ext}',
987
1395
  };
988
1396
  }
@@ -1002,68 +1410,185 @@ function sanitisePart(s) {
1002
1410
  return String(s || '').replace(/[^a-zA-Z0-9._-]+/g, '_').slice(0, 80);
1003
1411
  }
1004
1412
 
1005
- function buildVideoFilename(template, scope, status) {
1413
+ // The file name of a scenario's video: {datetime} is when the recording
1414
+ // started, {status} the scenario's result in lower case (passed, failed, …),
1415
+ // or the word given for a recording a step stopped. A null status leaves
1416
+ // "<status>" in the name, for a name printed before the scenario ends.
1417
+ function buildVideoFilename(template, scope, status, startedAt) {
1006
1418
  const featurePath = (scope && scope.gherkinDocument && scope.gherkinDocument.uri) || 'unknown';
1007
1419
  const feature = (scope && scope.gherkinDocument && scope.gherkinDocument.feature && scope.gherkinDocument.feature.name) || 'feature';
1008
1420
  const scenario = (scope && scope.pickle && scope.pickle.name) || 'scenario';
1009
1421
  const featureFile = featurePath.split('/').pop().replace(/\.feature$/, '');
1010
- const dt = new Date().toISOString().replace(/[:.]/g, '-');
1422
+ const dt = (startedAt instanceof Date ? startedAt : new Date()).toISOString().replace(/[:.]/g, '-');
1011
1423
  return template
1012
1424
  .replace('{datetime}', dt)
1013
1425
  .replace('{feature_file}', sanitisePart(featureFile))
1014
1426
  .replace('{feature}', sanitisePart(feature))
1015
1427
  .replace('{scenario}', sanitisePart(scenario))
1016
- .replace('{status}', sanitisePart(status))
1428
+ .replace('{status}', status === null ? '<status>' : sanitisePart(String(status).toLowerCase()))
1017
1429
  .replace('{ext}', 'webm');
1018
1430
  }
1019
1431
 
1432
+ /**
1433
+ * The file name the current video of the scenario is saved under: the name a
1434
+ * step reserved ("I save the current video as"), else the filenamePattern of
1435
+ * worldParameters.video with the given status (null: "<status>").
1436
+ *
1437
+ * @param {WebshipWorld} world
1438
+ * @param {?string} status
1439
+ * @returns {string}
1440
+ */
1441
+ function videoFileName(world, status) {
1442
+ if (world._videoSaveAsName) return world._videoSaveAsName;
1443
+ const settings = world._videoSettings || videoSettings(world);
1444
+ return buildVideoFilename(settings.filenamePattern, world._scenarioScope, status, world._videoStartedAt);
1445
+ }
1446
+
1020
1447
  // ---------------------------------------------------------------------------
1021
- // Viewport tags: a scenario tagged @mobile or @desktop opens at the size of
1022
- // the `mobile` or `desktop` breakpoint of worldParameters.selectors.breakpoints,
1023
- // else at the built-in size (the xs and the default xl sizes). Without either
1024
- // tag the viewport stays fluid (contextOptions.viewport). A step can still
1025
- // change the viewport inside the scenario.
1448
+ // Breakpoints: one registry of named viewport sizes for every step and tag
1449
+ // that names a size — the @mobile and @desktop tags, "I set the viewport to
1450
+ // the "…" breakpoint" and "I am viewing the site on a … screen".
1451
+ //
1452
+ // The built-in names come first, then worldParameters.selectors.breakpoints,
1453
+ // then the JSON object of WEBSHIP_SELECTORS_BREAKPOINTS, then the names a
1454
+ // scenario adds with "the following responsive breakpoints:"; each replaces
1455
+ // the sizes of the names it gives and keeps the others. `desktop` stands for
1456
+ // the breakpoint marked `default: true` when the project gives no `desktop`
1457
+ // of its own.
1026
1458
  // ---------------------------------------------------------------------------
1027
1459
 
1028
- const TAG_VIEWPORTS = [
1029
- ['@mobile', 'mobile', { width: 375, height: 667 }],
1030
- ['@desktop', 'desktop', { width: 1200, height: 900 }],
1031
- ];
1460
+ const BUILT_IN_BREAKPOINTS = Object.freeze({
1461
+ xs: { width: 375, height: 667 },
1462
+ sm: { width: 576, height: 800 },
1463
+ md: { width: 768, height: 1024 },
1464
+ lg: { width: 992, height: 768 },
1465
+ xl: { width: 1200, height: 900 },
1466
+ xxl: { width: 1400, height: 900 },
1467
+ xxxl: { width: 1920, height: 1080 },
1468
+ mobile: { width: 375, height: 667 },
1469
+ tablet: { width: 768, height: 1024 },
1470
+ desktop: { width: 1200, height: 900 },
1471
+ });
1472
+
1473
+ let badBreakpointsReported = false;
1474
+
1475
+ /**
1476
+ * The named sizes of WEBSHIP_SELECTORS_BREAKPOINTS, or an empty object when
1477
+ * it is not set. A value that is not a JSON object of sizes is reported once
1478
+ * and ignored.
1479
+ *
1480
+ * @returns {Object<string, {width: number, height: number}>}
1481
+ */
1482
+ function breakpointsFromEnv() {
1483
+ const raw = process.env.WEBSHIP_SELECTORS_BREAKPOINTS;
1484
+ if (!raw) return {};
1485
+ try {
1486
+ const parsed = JSON.parse(raw);
1487
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
1488
+ } catch { /* reported below */ }
1489
+ if (!badBreakpointsReported) {
1490
+ badBreakpointsReported = true;
1491
+ process.stderr.write('\n[webship-js] WEBSHIP_SELECTORS_BREAKPOINTS is not a JSON object of named sizes, such as {"tablet":{"width":800,"height":1280}}; it is ignored.\n');
1492
+ }
1493
+ return {};
1494
+ }
1495
+
1496
+ /**
1497
+ * A `{ width, height }` of whole positive pixels, or null.
1498
+ *
1499
+ * @param {*} size
1500
+ * @returns {{width: number, height: number}|null}
1501
+ */
1502
+ function breakpointSize(size) {
1503
+ const width = parseInt(size && size.width, 10);
1504
+ const height = parseInt(size && size.height, 10);
1505
+ return width > 0 && height > 0 ? { width, height } : null;
1506
+ }
1507
+
1508
+ /**
1509
+ * Every named viewport size the scenario can use, in the order of precedence
1510
+ * described above.
1511
+ *
1512
+ * @param {WebshipWorld} world
1513
+ * @returns {Object<string, {width: number, height: number}>}
1514
+ */
1515
+ function breakpoints(world) {
1516
+ const configured = (world && world.parameters && world.parameters.selectors && world.parameters.selectors.breakpoints) || {};
1517
+ const fromEnv = breakpointsFromEnv();
1518
+ const named = Object.assign({}, BUILT_IN_BREAKPOINTS);
1519
+ for (const source of [configured, fromEnv]) {
1520
+ for (const [name, value] of Object.entries(source)) {
1521
+ const size = breakpointSize(value);
1522
+ if (size) named[name] = size;
1523
+ }
1524
+ }
1525
+ if (!('desktop' in configured) && !('desktop' in fromEnv)) {
1526
+ const marked = Object.values(Object.assign({}, configured, fromEnv)).find((value) => value && value.default === true);
1527
+ const size = breakpointSize(marked);
1528
+ if (size) named.desktop = size;
1529
+ }
1530
+ return Object.assign(named, (world && world.__scenarioBreakpoints) || {});
1531
+ }
1532
+
1533
+ /**
1534
+ * The size of a named breakpoint. Throws a tester-facing error that lists the
1535
+ * known names when there is no such breakpoint.
1536
+ *
1537
+ * @param {WebshipWorld} world
1538
+ * @param {string} name
1539
+ * @returns {{width: number, height: number}}
1540
+ */
1541
+ function breakpoint(world, name) {
1542
+ const named = breakpoints(world);
1543
+ const key = String(name === undefined || name === null ? '' : name).trim();
1544
+ if (Object.prototype.hasOwnProperty.call(named, key)) return Object.assign({}, named[key]);
1545
+ throw failure(world && world.page, `There is no breakpoint named "${key}".`, {
1546
+ found: `the breakpoints ${Object.keys(named).join(', ')}`,
1547
+ hint: 'name a size in worldParameters.selectors.breakpoints of cucumber.js, in WEBSHIP_SELECTORS_BREAKPOINTS (a JSON object), or for one scenario with "Given the following responsive breakpoints:".',
1548
+ });
1549
+ }
1550
+
1551
+ // A scenario tagged @mobile or @desktop opens at the size of the `mobile` or
1552
+ // the `desktop` breakpoint. Without either tag the viewport stays fluid
1553
+ // (contextOptions.viewport). A step can still change the viewport inside the
1554
+ // scenario.
1555
+ const TAG_BREAKPOINTS = [['@mobile', 'mobile'], ['@desktop', 'desktop']];
1032
1556
 
1033
1557
  function tagViewport(world, scope) {
1034
1558
  const tags = new Set(((scope && scope.pickle && scope.pickle.tags) || []).map((t) => t.name));
1035
- const entry = TAG_VIEWPORTS.find(([tag]) => tags.has(tag));
1036
- if (!entry) return null;
1037
- const [, name, size] = entry;
1038
- const named = ((world.parameters && world.parameters.selectors && world.parameters.selectors.breakpoints) || {})[name];
1039
- const width = parseInt(named && named.width, 10);
1040
- const height = parseInt(named && named.height, 10);
1041
- return width > 0 && height > 0 ? { width, height } : Object.assign({}, size);
1559
+ const entry = TAG_BREAKPOINTS.find(([tag]) => tags.has(tag));
1560
+ return entry ? breakpoint(world, entry[1]) : null;
1042
1561
  }
1043
1562
 
1044
- Before({ order: 5 }, async function (scope) {
1563
+ // The order of the hooks is the order they are registered in: cucumber-js
1564
+ // runs the Before hooks in that order and the After hooks in the reverse one
1565
+ // (it has no `order` option). This file is loaded before any other hook is
1566
+ // registered — the first step file of the glob and every step file with
1567
+ // hooks of its own require it at their top — so the Before hook below opens
1568
+ // the browser before any other Before hook runs, and the After hook below
1569
+ // closes it after every other After hook ran.
1570
+ Before(async function (scope) {
1571
+ checkWorld(this);
1572
+ this._scenarioScope = scope;
1045
1573
  this._videoSettings = videoSettings(this, scope);
1046
1574
  this._videoRequested = shouldRecordAtStart(this._videoSettings, scope);
1047
1575
  this._videoForcedByTag = videoHasTag(scope, '@video');
1576
+ this._videoStartedAt = this._videoRequested ? new Date() : null;
1048
1577
 
1049
- const extra = {};
1578
+ // Kept for the whole scenario: a step that replaces the browser context
1579
+ // opens the new one with the same viewport and touch (see openContext).
1580
+ // @touch opens the context with touch on, so "I tap on" fires touch events.
1050
1581
  const viewport = tagViewport(this, scope);
1051
- if (viewport) extra.viewport = viewport;
1052
- if (this._videoRequested) {
1053
- require('fs').mkdirSync(this._videoSettings.dir, { recursive: true });
1054
- extra.recordVideo = {
1055
- dir: this._videoSettings.dir,
1056
- size: this._videoSettings.size,
1057
- };
1058
- }
1582
+ this._scenarioContextOptions = viewport ? { viewport } : {};
1583
+ if (videoHasTag(scope, '@touch')) this._scenarioContextOptions.hasTouch = true;
1059
1584
 
1060
- await this.openBrowser(extra);
1585
+ await this.openBrowser();
1061
1586
  if (this.minWaitTime.before_scenario > 0) {
1062
1587
  await this.page.waitForTimeout(this.minWaitTime.before_scenario);
1063
1588
  }
1064
1589
  });
1065
1590
 
1066
- After({ order: 5 }, async function (scope) {
1591
+ After(async function (scope) {
1067
1592
  if (this.minWaitTime.after_scenario > 0) {
1068
1593
  try { await this.page.waitForTimeout(this.minWaitTime.after_scenario); } catch { /* page already closed */ }
1069
1594
  }
@@ -1085,11 +1610,13 @@ After({ order: 5 }, async function (scope) {
1085
1610
 
1086
1611
  if (videoRef) {
1087
1612
  const settings = this._videoSettings;
1088
- const filename = this._videoSaveAsName || buildVideoFilename(settings.filenamePattern, scope, status);
1613
+ const filename = videoFileName(this, status);
1089
1614
  const dest = require('path').join(settings.dir, filename);
1090
1615
  try {
1091
1616
  const passed = status === 'PASSED' || status === 'passed';
1092
- if (settings.mode === 'on-failure' && passed && !this._videoForcedByTag) {
1617
+ // on-failure keeps a passing scenario's video only when the @video tag
1618
+ // or "I save the current video as" asked for it.
1619
+ if (settings.mode === 'on-failure' && passed && !this._videoForcedByTag && !this._videoSaveAsName) {
1093
1620
  await videoRef.delete().catch(() => {});
1094
1621
  } else {
1095
1622
  await videoRef.saveAs(dest);
@@ -1120,10 +1647,21 @@ BeforeStep(async function () {
1120
1647
  }
1121
1648
  });
1122
1649
 
1123
- // BBR: regex matches steps that mutate page state (click/press/fill/check/etc.).
1124
- // After such a step, run a short smartSettle so assertions in the next step
1125
- // observe the post-action edge instead of mid-transition state.
1126
- const STATE_MUTATING_STEP = /\b(click|press|fill|submit|select|check|uncheck|choose|attach|reload|move (?:back|forward)|go to|navigate|on (?:the )?(?:home|front)page)\b/i;
1650
+ // BBR: the verbs of a step that changes the page — the built-in ones (click,
1651
+ // press, fill, …) and the ones a project's own steps use (add, open, delete,
1652
+ // save, log in, …). After such a step, run a short smartSettle so the next
1653
+ // step observes the post-action edge instead of a mid-transition state. The
1654
+ // verbs are read in the step's own words, not in its quoted arguments: "Then
1655
+ // I should see "Delete"" is no action. "scroll" is left out on purpose: a
1656
+ // scroll often starts a loader that the next step checks while it shows. A
1657
+ // project step whose words carry none of them can settle itself with
1658
+ // `await this.smartSettle()`.
1659
+ const STATE_MUTATING_STEP = /\b(click|press|fill|submit|select|check|uncheck|choose|attach|upload|reload|move (?:back|forward)|go to|navigate|on (?:the )?(?:home|front)page|open|close|add|remove|insert|delete|save|publish|edit|update|create|enter|type|clear|reset|drag|drop|hover|tap|toggle|expand|collapse|search|send|request|flush|confirm|cancel|accept|dismiss|log ?in|log ?out|sign ?in|sign ?out)\b/i;
1660
+
1661
+ // The words of a step without its quoted arguments.
1662
+ function stepWords(text) {
1663
+ return String(text).replace(/"(?:[^"\\]|\\.)*"/g, '""');
1664
+ }
1127
1665
 
1128
1666
  AfterStep(async function (scope) {
1129
1667
  if (!this.page) return;
@@ -1134,7 +1672,7 @@ AfterStep(async function (scope) {
1134
1672
  if (process.env.WEBSHIP_AUTO_SETTLE === 'off') return;
1135
1673
  const text = scope && scope.pickleStep && scope.pickleStep.text;
1136
1674
  if (typeof text !== 'string') return;
1137
- if (!STATE_MUTATING_STEP.test(text)) return;
1675
+ if (!STATE_MUTATING_STEP.test(stepWords(text))) return;
1138
1676
  try { await smartSettle(this.page, 1500); } catch { /* best effort */ }
1139
1677
  });
1140
1678