webship-js 2.0.10 → 2.0.11

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 (110) hide show
  1. package/.github/ISSUE_TEMPLATE/issue.md +37 -0
  2. package/.github/PULL_REQUEST_TEMPLATE.md +24 -0
  3. package/.github/workflows/github-actions.yml +56 -4
  4. package/CLAUDE.md +5 -2
  5. package/README.md +13 -1
  6. package/bin/generate-reports.js +51 -7
  7. package/bin/init-webship.js +85 -17
  8. package/cucumber.js +29 -1
  9. package/docs/00-quick-start.md +30 -7
  10. package/docs/02-bbr-smart-waits.md +6 -0
  11. package/docs/04-step-reference.md +2 -2
  12. package/docs/11-debugging.md +21 -0
  13. package/docs/12-ai-agent-guide.md +3 -1
  14. package/docs/13-faq.md +3 -0
  15. package/docs/15-tag-conventions.md +4 -1
  16. package/docs/16-ci-cd.md +29 -13
  17. package/docs/global-settings.md +2 -2
  18. package/docs/install-webship-js/ddev-webship-js.md +3 -0
  19. package/docs/install-webship-js.md +14 -2
  20. package/examples/a11y-legacy-widget.html +34 -0
  21. package/examples/auth-state.html +42 -0
  22. package/examples/clock.html +33 -0
  23. package/examples/downloads/webship-archive.zip +0 -0
  24. package/examples/downloads/webship-notes.txt +4 -0
  25. package/examples/downloads/webship-report.csv +4 -0
  26. package/examples/downloads.html +16 -0
  27. package/examples/element-viewport.html +42 -0
  28. package/examples/field-types.html +98 -0
  29. package/examples/iframe-newsletter.html +29 -0
  30. package/examples/iframe-order.html +26 -0
  31. package/examples/iframe.html +21 -0
  32. package/examples/javascript-errors.html +35 -0
  33. package/examples/links.html +1 -0
  34. package/examples/metatags.html +18 -0
  35. package/examples/mouse-and-pointer.html +83 -0
  36. package/examples/native-dialogs.html +8 -0
  37. package/examples/network.html +83 -0
  38. package/examples/scroll-horizontal.html +50 -0
  39. package/examples/selectors-position.html +29 -0
  40. package/examples/storage.html +57 -0
  41. package/examples/viewport-size.html +24 -0
  42. package/examples/wait-conditions.html +69 -0
  43. package/examples/web-first.html +99 -0
  44. package/package.json +9 -2
  45. package/tests/assets/catalog.xml +19 -0
  46. package/tests/assets/feed-namespaced.xml +13 -0
  47. package/tests/assets/sitemap.xml +14 -0
  48. package/tests/assets/webship-site-expected.yaml +21 -0
  49. package/tests/assets/webship-site.schema.json +46 -0
  50. package/tests/assets/webship-site.yaml +21 -0
  51. package/tests/check-examples.js +235 -0
  52. package/tests/check-must-fail.js +84 -0
  53. package/tests/check-paths.js +82 -0
  54. package/tests/check-report.js +119 -0
  55. package/tests/check-scaffold.js +211 -0
  56. package/tests/features/a11y.feature +18 -0
  57. package/tests/features/auth-state.feature +32 -0
  58. package/tests/features/clock.feature +27 -0
  59. package/tests/features/cookie.feature +9 -0
  60. package/tests/features/dialog.feature +27 -0
  61. package/tests/features/element.feature +47 -0
  62. package/tests/features/field.feature +104 -0
  63. package/tests/features/file-download.feature +64 -0
  64. package/tests/features/iframe.feature +83 -0
  65. package/tests/features/javascript.feature +47 -0
  66. package/tests/features/link.feature +11 -0
  67. package/tests/features/metatag.feature +38 -0
  68. package/tests/features/mouse-and-pointer.feature +86 -0
  69. package/tests/features/network-mocking.feature +80 -0
  70. package/tests/features/responsive.feature +27 -0
  71. package/tests/features/scroll-horizontal.feature +55 -0
  72. package/tests/features/selectors-position.feature +41 -0
  73. package/tests/features/storage.feature +98 -0
  74. package/tests/features/test--then--i-see-locator.feature +13 -0
  75. package/tests/features/test--then--i-should--see-text-in-element.feature +9 -1
  76. package/tests/features/test--then--the-field-should-contain-value.feature +8 -0
  77. package/tests/features/video.feature +1 -0
  78. package/tests/features/wait.feature +89 -0
  79. package/tests/features/web-first.feature +100 -0
  80. package/tests/features/xml.feature +96 -0
  81. package/tests/features/yaml.feature +75 -0
  82. package/tests/must-fail/assertions.feature +96 -0
  83. package/tests/must-fail/waits.feature +51 -0
  84. package/tests/reports/README.md +2 -2
  85. package/tests/step-definitions/a11y.steps.js +12 -8
  86. package/tests/step-definitions/assertion.steps.js +235 -61
  87. package/tests/step-definitions/dialog.steps.js +2 -2
  88. package/tests/step-definitions/element.steps.js +3 -1
  89. package/tests/step-definitions/field.steps.js +152 -22
  90. package/tests/step-definitions/file-download.steps.js +74 -10
  91. package/tests/step-definitions/screenshot.steps.js +1 -1
  92. package/tests/step-definitions/selectors.steps.js +9 -3
  93. package/tests/step-definitions/storage.steps.js +3 -3
  94. package/tests/step-definitions/wait.steps.js +129 -39
  95. package/tests/step-definitions/webship.js +144 -3
  96. package/tests/step-definitions/xml.steps.js +76 -14
  97. package/tests/step-definitions/yaml.steps.js +46 -27
  98. package/.scratch/commit.txt +0 -14
  99. package/.scratch/docs.py +0 -42
  100. package/.scratch/echo-server.js +0 -8
  101. package/.scratch/echo.js +0 -35
  102. package/.scratch/echo.pid +0 -1
  103. package/.scratch/features/cookies.feature +0 -22
  104. package/.scratch/http.pid +0 -1
  105. package/.scratch/https.pid +0 -1
  106. package/.scratch/issue.md +0 -49
  107. package/.scratch/one.js +0 -2
  108. package/.scratch/one.json +0 -280
  109. package/.scratch/patch.py +0 -163
  110. package/.scratch/pr.md +0 -30
@@ -11,7 +11,7 @@
11
11
  // so this file never duplicates BBR plumbing.
12
12
 
13
13
  const { When } = require('@cucumber/cucumber');
14
- const { smartSettle, waitForModalState } = require('./webship');
14
+ const { smartSettle, pollPage, waitForModalState, friendly, failure, excerpt, isTimeout } = require('./webship');
15
15
 
16
16
  /**
17
17
  * Wait UP TO N seconds for the page to settle. Returns early on idle.
@@ -53,7 +53,8 @@ When(/^(I |we )*wait for (\d+) seconds? for AJAX to finish$/, async function (pr
53
53
  });
54
54
 
55
55
  /**
56
- * Wait UP TO a number of seconds for the page to settle.
56
+ * Wait UP TO a number of seconds for the page to settle. A number with no
57
+ * unit is read as seconds.
57
58
  *
58
59
  * Example #1: When I wait 1 second
59
60
  * Example #2: When I wait 5 seconds
@@ -63,6 +64,7 @@ When(/^(I |we )*wait for (\d+) seconds? for AJAX to finish$/, async function (pr
63
64
  * Example #6: When we wait 1 second
64
65
  * Example #7: When we wait 5 seconds
65
66
  * Example #8: When we wait 4s
67
+ * Example #9: When I wait 2
66
68
  *
67
69
  */
68
70
  When(/^(I |we )*wait (\d+)( second| seconds|s)?$/, async function (pronounCase, number, withSecondWord) {
@@ -70,7 +72,8 @@ When(/^(I |we )*wait (\d+)( second| seconds|s)?$/, async function (pronounCase,
70
72
  });
71
73
 
72
74
  /**
73
- * Wait UP TO a maximum number of seconds for the page to settle.
75
+ * Wait UP TO a maximum number of seconds for the page to settle. A number with
76
+ * no unit is read as seconds.
74
77
  *
75
78
  * Example #1: When I wait max of 1 second
76
79
  * Example #2: When I wait max of 5 seconds
@@ -80,6 +83,7 @@ When(/^(I |we )*wait (\d+)( second| seconds|s)?$/, async function (pronounCase,
80
83
  * Example #6: When we wait max of 1 second
81
84
  * Example #7: When we wait max of 5 seconds
82
85
  * Example #8: When we wait max of 4s
86
+ * Example #9: When I wait max of 2
83
87
  *
84
88
  */
85
89
  When(/^(I |we )*wait max of (\d+)( second| seconds|s)?$/, async function (pronounCase, number, withSecondWord) {
@@ -87,7 +91,8 @@ When(/^(I |we )*wait max of (\d+)( second| seconds|s)?$/, async function (pronou
87
91
  });
88
92
 
89
93
  /**
90
- * Wait UP TO a number of minutes for the page to settle.
94
+ * Wait UP TO a number of minutes for the page to settle. The unit is required:
95
+ * a number with no unit is read as seconds.
91
96
  *
92
97
  * Example #1: When I wait 1 minute
93
98
  * Example #2: When I wait 10 minutes
@@ -96,12 +101,13 @@ When(/^(I |we )*wait max of (\d+)( second| seconds|s)?$/, async function (pronou
96
101
  * Example #5: And wait 2 minutes
97
102
  *
98
103
  */
99
- When(/^(I |we )*wait (\d+)( minute| minutes|m)?$/, async function (pronounCase, number, withMinuteWord) {
104
+ When(/^(I |we )*wait (\d+)( minute| minutes|m)$/, async function (pronounCase, number, withMinuteWord) {
100
105
  await smartSettle(this.page, parseInt(number, 10) * 1000 * 60);
101
106
  });
102
107
 
103
108
  /**
104
- * Wait UP TO a maximum number of minutes for the page to settle.
109
+ * Wait UP TO a maximum number of minutes for the page to settle. The unit is
110
+ * required: a number with no unit is read as seconds.
105
111
  *
106
112
  * Example #1: When I wait max of 1 minute
107
113
  * Example #2: When I wait max of 10 minutes
@@ -110,7 +116,7 @@ When(/^(I |we )*wait (\d+)( minute| minutes|m)?$/, async function (pronounCase,
110
116
  * Example #5: And wait max of 2 minutes
111
117
  *
112
118
  */
113
- When(/^(I |we )*wait max of (\d+)( minute| minutes|m)?$/, async function (pronounCase, number, withMinuteWord) {
119
+ When(/^(I |we )*wait max of (\d+)( minute| minutes|m)$/, async function (pronounCase, number, withMinuteWord) {
114
120
  await smartSettle(this.page, parseInt(number, 10) * 1000 * 60);
115
121
  });
116
122
 
@@ -167,7 +173,17 @@ When(/^(I |we )*wait for( the)* modal( dialog)* to (appear|disappear)$/, async f
167
173
  *
168
174
  */
169
175
  When(/^(I |we )*wait for "([^"]*)" to appear$/, async function (pronounCase, selector) {
170
- await this.page.waitForSelector(selector, { state: 'visible', timeout: 10000 });
176
+ try {
177
+ await this.page.waitForSelector(selector, { state: 'visible', timeout: 10000 });
178
+ } catch (e) {
179
+ if (!isTimeout(e)) throw e;
180
+ const present = await this.page.locator(selector).count().catch(() => 0);
181
+ throw failure(this.page, present
182
+ ? `The element "${selector}" is on the page but did not become visible within 10 seconds.`
183
+ : `The element "${selector}" did not appear within 10 seconds.`, {
184
+ hint: `"${selector}" is a CSS selector. For a text, use: I wait for the text "..." to appear`,
185
+ });
186
+ }
171
187
  });
172
188
 
173
189
  /**
@@ -184,7 +200,14 @@ When(/^(I |we )*wait for "([^"]*)" to appear$/, async function (pronounCase, sel
184
200
  *
185
201
  */
186
202
  When(/^(I |we )*wait for "([^"]*)" to disappear$/, async function (pronounCase, selector) {
187
- await this.page.waitForSelector(selector, { state: 'hidden', timeout: 10000 });
203
+ try {
204
+ await this.page.waitForSelector(selector, { state: 'hidden', timeout: 10000 });
205
+ } catch (e) {
206
+ if (!isTimeout(e)) throw e;
207
+ throw failure(this.page, `The element "${selector}" is still visible after 10 seconds.`, {
208
+ hint: `"${selector}" is a CSS selector; the step passes when the first element it matches is hidden or gone.`,
209
+ });
210
+ }
188
211
  });
189
212
 
190
213
  /**
@@ -202,10 +225,17 @@ When(/^(I |we )*wait for "([^"]*)" to disappear$/, async function (pronounCase,
202
225
  *
203
226
  */
204
227
  When(/^(I |we )*wait for( the)* text "([^"]*)" to appear$/, async function (pronounCase, theCase, text) {
205
- await this.page.waitForFunction(
206
- (t) => document.body && document.body.innerText.includes(t),
207
- text, { timeout: 10000, polling: 100 }
208
- );
228
+ try {
229
+ await this.page.waitForFunction(
230
+ (t) => document.body && document.body.innerText.includes(t),
231
+ text, { timeout: 10000, polling: 100 }
232
+ );
233
+ } catch (e) {
234
+ if (!isTimeout(e)) throw e;
235
+ throw failure(this.page, `The text "${text}" did not appear within 10 seconds.`, {
236
+ hint: 'check the spelling and the letter case; the step reads the visible text of the page.',
237
+ });
238
+ }
209
239
  });
210
240
 
211
241
  /**
@@ -221,10 +251,17 @@ When(/^(I |we )*wait for( the)* text "([^"]*)" to appear$/, async function (pron
221
251
  *
222
252
  */
223
253
  When(/^(I |we )*wait for( the)* text "([^"]*)" to disappear$/, async function (pronounCase, theCase, text) {
224
- await this.page.waitForFunction(
225
- (t) => !document.body || !document.body.innerText.includes(t),
226
- text, { timeout: 10000, polling: 100 }
227
- );
254
+ try {
255
+ await this.page.waitForFunction(
256
+ (t) => !document.body || !document.body.innerText.includes(t),
257
+ text, { timeout: 10000, polling: 100 }
258
+ );
259
+ } catch (e) {
260
+ if (!isTimeout(e)) throw e;
261
+ throw failure(this.page, `The text "${text}" is still on the page after 10 seconds.`, {
262
+ hint: 'the step reads the visible text of the page.',
263
+ });
264
+ }
228
265
  });
229
266
 
230
267
  /**
@@ -241,10 +278,17 @@ When(/^(I |we )*wait for( the)* text "([^"]*)" to disappear$/, async function (p
241
278
  *
242
279
  */
243
280
  When(/^(I |we )*wait until( the)* URL contains "([^"]*)"$/, async function (pronounCase, theCase, fragment) {
244
- await this.page.waitForFunction(
245
- (frag) => window.location.href.includes(frag),
246
- fragment, { timeout: 10000, polling: 100 }
247
- );
281
+ try {
282
+ await this.page.waitForFunction(
283
+ (frag) => window.location.href.includes(frag),
284
+ fragment, { timeout: 10000, polling: 100 }
285
+ );
286
+ } catch (e) {
287
+ if (!isTimeout(e)) throw e;
288
+ throw failure(this.page, `The URL does not contain "${fragment}" after 10 seconds.`, {
289
+ hint: 'the step looks for the text in the whole address, with the domain, the query and the hash.',
290
+ });
291
+ }
248
292
  });
249
293
 
250
294
  /**
@@ -259,10 +303,21 @@ When(/^(I |we )*wait until( the)* URL contains "([^"]*)"$/, async function (pron
259
303
  *
260
304
  */
261
305
  When(/^(I |we )*wait until( the)* page title (is|contains) "([^"]*)"$/, async function (pronounCase, theCase, op, value) {
262
- await this.page.waitForFunction(
263
- ({ op, value }) => op === 'is' ? document.title === value : document.title.includes(value),
264
- { op, value }, { timeout: 10000, polling: 100 }
265
- );
306
+ try {
307
+ await this.page.waitForFunction(
308
+ ({ op, value }) => op === 'is' ? document.title === value : document.title.includes(value),
309
+ { op, value }, { timeout: 10000, polling: 100 }
310
+ );
311
+ } catch (e) {
312
+ if (!isTimeout(e)) throw e;
313
+ const title = await this.page.title().catch(() => '');
314
+ throw failure(this.page, op === 'is'
315
+ ? `The page title is not "${value}" after 10 seconds.`
316
+ : `The page title does not contain "${value}" after 10 seconds.`, {
317
+ found: `"${excerpt(title)}"`,
318
+ hint: 'the page title is the text of the browser tab, not the main heading of the page.',
319
+ });
320
+ }
266
321
  });
267
322
 
268
323
  /**
@@ -281,10 +336,19 @@ When(/^(I |we )*wait until( the)* page title (is|contains) "([^"]*)"$/, async fu
281
336
  */
282
337
  When(/^(I |we )*wait until (\d+) elements? match(?:es)? "([^"]*)"$/, async function (pronounCase, count, selector) {
283
338
  const expected = parseInt(count, 10);
284
- await this.page.waitForFunction(
285
- ({ sel, n }) => document.querySelectorAll(sel).length === n,
286
- { sel: selector, n: expected }, { timeout: 10000, polling: 100 }
287
- );
339
+ try {
340
+ await this.page.waitForFunction(
341
+ ({ sel, n }) => document.querySelectorAll(sel).length === n,
342
+ { sel: selector, n: expected }, { timeout: 10000, polling: 100 }
343
+ );
344
+ } catch (e) {
345
+ if (!isTimeout(e)) throw e;
346
+ const actual = await this.page.locator(selector).count().catch(() => 0);
347
+ throw failure(this.page, `Expected ${expected} element(s) matching "${selector}" within 10 seconds.`, {
348
+ found: `${actual} element(s)`,
349
+ hint: `"${selector}" is a CSS selector; hidden elements count too. For a minimum, use: I wait until at least ${expected} elements match "${selector}"`,
350
+ });
351
+ }
288
352
  });
289
353
 
290
354
  /**
@@ -303,10 +367,19 @@ When(/^(I |we )*wait until (\d+) elements? match(?:es)? "([^"]*)"$/, async funct
303
367
  */
304
368
  When(/^(I |we )*wait until at least (\d+) elements? match(?:es)? "([^"]*)"$/, async function (pronounCase, count, selector) {
305
369
  const expected = parseInt(count, 10);
306
- await this.page.waitForFunction(
307
- ({ sel, n }) => document.querySelectorAll(sel).length >= n,
308
- { sel: selector, n: expected }, { timeout: 10000, polling: 100 }
309
- );
370
+ try {
371
+ await this.page.waitForFunction(
372
+ ({ sel, n }) => document.querySelectorAll(sel).length >= n,
373
+ { sel: selector, n: expected }, { timeout: 10000, polling: 100 }
374
+ );
375
+ } catch (e) {
376
+ if (!isTimeout(e)) throw e;
377
+ const actual = await this.page.locator(selector).count().catch(() => 0);
378
+ throw failure(this.page, `Expected at least ${expected} element(s) matching "${selector}" within 10 seconds.`, {
379
+ found: `${actual} element(s)`,
380
+ hint: `"${selector}" is a CSS selector; hidden elements count too.`,
381
+ });
382
+ }
310
383
  });
311
384
 
312
385
  /**
@@ -369,13 +442,23 @@ When(/^(I |we )*wait until( the)* page is interactive$/, async function (pronoun
369
442
  *
370
443
  */
371
444
  When(/^(I |we )*wait until pending timers settle$/, async function (pronounCase) {
372
- await this.page.waitForFunction(
445
+ // Polled from Node: a poll on the page's own setTimeout would be counted as
446
+ // one more pending timer, and the wait could never see the count reach zero.
447
+ const settled = await pollPage(
448
+ this.page,
373
449
  () => {
374
450
  const t = window.__webshipPendingTimers;
375
451
  return typeof t !== 'number' || t <= 0;
376
452
  },
377
- null, { timeout: 10000, polling: 100 }
453
+ null, 10000, 100
378
454
  );
455
+ if (!settled) {
456
+ throw friendly({
457
+ action: 'wait until pending timers settle',
458
+ cause: 'the page still had a pending timer after 10 seconds',
459
+ hint: 'a page that reschedules a timer forever never settles; wait for the element or the text you expect instead.',
460
+ });
461
+ }
379
462
  });
380
463
 
381
464
  /**
@@ -393,8 +476,15 @@ When(/^(I |we )*wait until pending timers settle$/, async function (pronounCase)
393
476
  */
394
477
  When(/^eventually (I |we )*should see "([^"]*)"(?: within (\d+) seconds?)?$/, async function (pronoun, text, seconds) {
395
478
  const total = (seconds ? parseInt(seconds, 10) : 10) * 1000;
396
- await this.page.waitForFunction(
397
- (t) => document.body && document.body.innerText.includes(t),
398
- text, { timeout: total, polling: 100 }
399
- );
479
+ try {
480
+ await this.page.waitForFunction(
481
+ (t) => document.body && document.body.innerText.includes(t),
482
+ text, { timeout: total, polling: 100 }
483
+ );
484
+ } catch (e) {
485
+ if (!isTimeout(e)) throw e;
486
+ throw failure(this.page, `The text "${text}" did not appear within ${total / 1000} seconds.`, {
487
+ hint: 'check the spelling and the letter case; the step reads the visible text of the page. For a longer wait, add "within N seconds" to the step.',
488
+ });
489
+ }
400
490
  });
@@ -65,8 +65,11 @@ if (process.env.WEBSHIP_FILTER_HOOK_LINES !== 'off') {
65
65
  // 5. window.__webshipPendingTimers === 0 (custom setTimeout counter)
66
66
  // 6. Date.now() - window.__webshipLastMutation >= quietMs (DOM-quiet)
67
67
  //
68
- // Steps 4/5/6 are evaluated atomically via a single waitForFunction, so a
68
+ // Steps 4/5/6 are evaluated atomically in one page-side probe, so a
69
69
  // late-firing setTimeout that mutates the DOM re-arms the wait correctly.
70
+ // The probe is polled from Node (see pollPage), never from a timer inside the
71
+ // page: a poll that runs on the page's own setTimeout is counted by step 5 as
72
+ // a pending timer, so the probe would see itself and never pass.
70
73
  // ---------------------------------------------------------------------------
71
74
 
72
75
  /**
@@ -78,6 +81,38 @@ if (process.env.WEBSHIP_FILTER_HOOK_LINES !== 'off') {
78
81
  */
79
82
  const SETTLE_MIN_MS = 25;
80
83
 
84
+ /**
85
+ * Poll a page-side probe from Node until it returns a truthy value or the
86
+ * budget is spent.
87
+ *
88
+ * Use this instead of `page.waitForFunction(..., { polling: <ms> })` for any
89
+ * probe that reads `window.__webshipPendingTimers`. Interval polling inside
90
+ * the page runs on the page's `setTimeout`, which the init script wraps to
91
+ * count pending timers, so such a probe counts its own next poll: it can only
92
+ * pass on its very first look, and waits out its whole timeout otherwise.
93
+ *
94
+ * A probe that throws (the page is navigating, the context was replaced) is
95
+ * read as "not yet" and looked at again.
96
+ *
97
+ * @param {import('playwright').Page} page - Page being probed.
98
+ * @param {Function} probe - Runs in the page; truthy means done.
99
+ * @param {*} arg - Single argument handed to the probe.
100
+ * @param {number} timeout - Budget in ms.
101
+ * @param {number} [interval=50] - Pause between two looks, in ms.
102
+ * @returns {Promise<boolean>} true when the probe passed inside the budget.
103
+ */
104
+ async function pollPage(page, probe, arg, timeout, interval) {
105
+ const pause = typeof interval === 'number' && interval > 0 ? interval : 50;
106
+ const deadline = Date.now() + (typeof timeout === 'number' && timeout > 0 ? timeout : 0);
107
+ for (;;) {
108
+ let done = false;
109
+ try { done = await page.evaluate(probe, arg); } catch { /* not ready yet */ }
110
+ if (done) return true;
111
+ if (Date.now() + pause >= deadline) return false;
112
+ await new Promise((resolve) => setTimeout(resolve, pause));
113
+ }
114
+ }
115
+
81
116
  /**
82
117
  * Wait for the page to reach an "edge" of activity — DOM ready, network
83
118
  * idle, no pending AJAX or timers, and no DOM mutations for ≥250 ms.
@@ -116,7 +151,8 @@ async function smartSettle(page, timeout) {
116
151
  if (!await stage(0.25, (t) => page.waitForSelector('body', { state: 'attached', timeout: t }))) return;
117
152
  if (!await stage(0.25, (t) => page.waitForLoadState('domcontentloaded', { timeout: t }))) return;
118
153
  if (!await stage(0.5, (t) => page.waitForLoadState('networkidle', { timeout: t }))) return;
119
- await stage(0.5, (t) => page.waitForFunction(
154
+ await stage(0.5, (t) => pollPage(
155
+ page,
120
156
  (quietMs) => {
121
157
  const ajax = window.__webshipAjaxCount;
122
158
  const timers = window.__webshipPendingTimers;
@@ -127,7 +163,7 @@ async function smartSettle(page, timeout) {
127
163
  return true;
128
164
  },
129
165
  250,
130
- { timeout: t, polling: 50 }
166
+ t
131
167
  ));
132
168
  }
133
169
 
@@ -460,6 +496,33 @@ async function getLocatorText(locator) {
460
496
  }
461
497
  }
462
498
 
499
+ /**
500
+ * Find the element a step names either by the text of its label or by a CSS
501
+ * selector: the field of the label with that exact text and a `for`
502
+ * attribute when the page has one, else the first element the selector
503
+ * matches. Both are looked for together, so a selector does not wait for a
504
+ * label that will never come.
505
+ *
506
+ * @param {import('playwright').Page} page - Page being probed.
507
+ * @param {string} name - Label text or CSS selector.
508
+ * @param {number} [timeout=5000] - How long to look, in ms.
509
+ * @returns {Promise<import('playwright').Locator|null>} The element, or null when neither was found in time.
510
+ */
511
+ async function locateByLabelOrSelector(page, name, timeout) {
512
+ const deadline = Date.now() + (typeof timeout === 'number' && timeout > 0 ? timeout : 5000);
513
+ const labels = page.getByText(name, { exact: true });
514
+ for (;;) {
515
+ const forIds = await labels.evaluateAll((nodes) => nodes.map((node) => node.getAttribute('for'))).catch(() => []);
516
+ const forId = forIds.find((id) => id);
517
+ if (forId) return page.locator(`[id="${forId.replace(/["\\]/g, '\\$&')}"]`).first();
518
+ // A label text is rarely a valid selector: an invalid one matches nothing.
519
+ const bySelector = await page.locator(name).count().catch(() => 0);
520
+ if (bySelector > 0) return page.locator(name).first();
521
+ if (Date.now() >= deadline) return null;
522
+ await page.waitForTimeout(100);
523
+ }
524
+ }
525
+
463
526
  /**
464
527
  * Left-pad a number with zeros to the requested width.
465
528
  *
@@ -684,8 +747,56 @@ function friendly(input, cause) {
684
747
  return e;
685
748
  }
686
749
 
750
+ /**
751
+ * Shorten a text for a failure message: white space collapsed, cut at
752
+ * `max` characters.
753
+ *
754
+ * @param {string} text
755
+ * @param {number} [max=200]
756
+ * @returns {string}
757
+ */
758
+ function excerpt(text, max) {
759
+ const limit = typeof max === 'number' && max > 0 ? max : 200;
760
+ const clean = String(text === null || text === undefined ? '' : text).replace(/\s+/g, ' ').trim();
761
+ return clean.length > limit ? clean.slice(0, limit) + '…' : clean;
762
+ }
763
+
764
+ /**
765
+ * True when an error is Playwright giving up after its timeout, which in an
766
+ * assertion means "what was looked for is not there".
767
+ *
768
+ * @param {Error} error
769
+ * @returns {boolean}
770
+ */
771
+ function isTimeout(error) {
772
+ return !!error && (error.name === 'TimeoutError' || /Timeout \d+ms exceeded/.test(String(error.message || '')));
773
+ }
774
+
775
+ /**
776
+ * Build the failure of an assertion for a tester: what was looked for, what
777
+ * was found, the address of the page and a hint. No call log, no stack.
778
+ *
779
+ * @param {import('playwright').Page} page - Page the assertion ran on.
780
+ * @param {string} message - What was expected and did not hold.
781
+ * @param {Object} [details]
782
+ * @param {string} [details.found] - What was there instead.
783
+ * @param {string} [details.hint] - What to check or try next.
784
+ * @returns {Error}
785
+ */
786
+ function failure(page, message, details) {
787
+ const lines = [message];
788
+ const info = details || {};
789
+ if (info.found !== undefined && info.found !== null) lines.push(` Found: ${info.found}`);
790
+ let url = '';
791
+ try { url = page.url(); } catch { /* the page is gone */ }
792
+ if (url) lines.push(` Page: ${url}`);
793
+ if (info.hint) lines.push(` Hint: ${info.hint}`);
794
+ return friendly(lines.join('\n'));
795
+ }
796
+
687
797
  module.exports = {
688
798
  smartSettle,
799
+ pollPage,
689
800
  waitForPageLoad,
690
801
  getModalSelector,
691
802
  getModalLocator,
@@ -698,12 +809,16 @@ module.exports = {
698
809
  sendRequest,
699
810
  fillField,
700
811
  getLocatorText,
812
+ locateByLabelOrSelector,
701
813
  pad,
702
814
  resolveRelativeDate,
703
815
  parseRelativeOffset,
704
816
  formatRelativeDate,
705
817
  friendly,
706
818
  humanize,
819
+ failure,
820
+ excerpt,
821
+ isTimeout,
707
822
  };
708
823
 
709
824
  // ---------------------------------------------------------------------------
@@ -902,12 +1017,38 @@ function buildVideoFilename(template, scope, status) {
902
1017
  .replace('{ext}', 'webm');
903
1018
  }
904
1019
 
1020
+ // ---------------------------------------------------------------------------
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.
1026
+ // ---------------------------------------------------------------------------
1027
+
1028
+ const TAG_VIEWPORTS = [
1029
+ ['@mobile', 'mobile', { width: 375, height: 667 }],
1030
+ ['@desktop', 'desktop', { width: 1200, height: 900 }],
1031
+ ];
1032
+
1033
+ function tagViewport(world, scope) {
1034
+ 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);
1042
+ }
1043
+
905
1044
  Before({ order: 5 }, async function (scope) {
906
1045
  this._videoSettings = videoSettings(this, scope);
907
1046
  this._videoRequested = shouldRecordAtStart(this._videoSettings, scope);
908
1047
  this._videoForcedByTag = videoHasTag(scope, '@video');
909
1048
 
910
1049
  const extra = {};
1050
+ const viewport = tagViewport(this, scope);
1051
+ if (viewport) extra.viewport = viewport;
911
1052
  if (this._videoRequested) {
912
1053
  require('fs').mkdirSync(this._videoSettings.dir, { recursive: true });
913
1054
  extra.recordVideo = {
@@ -3,6 +3,11 @@
3
3
  const { friendly } = require('./webship');
4
4
 
5
5
  // Parse and assert against an XML response loaded from a file or doc string.
6
+ //
7
+ // The XPath of a step reads like the XML does: a prefixed name such as
8
+ // //dc:creator resolves against the xmlns:dc="..." declarations of the
9
+ // document, and a name without a prefix such as /urlset/url also matches an
10
+ // element of the default namespace (xmlns="..."), as in a sitemap or a feed.
6
11
 
7
12
  const { Given, Then, When } = require('@cucumber/cucumber');
8
13
  const assert = require('assert');
@@ -16,18 +21,80 @@ catch (e) {
16
21
  catch (e2) { /* will throw on use */ }
17
22
  }
18
23
 
19
- function ensureXml(world) {
24
+ function requireParser() {
20
25
  if (!DOMParser) throw friendly('XML steps require an XML DOM parser. Install @xmldom/xmldom.');
26
+ }
27
+
28
+ function ensureXml(world) {
29
+ requireParser();
30
+ if (world._xmlParseError) throw friendly(`The response is not valid XML: ${world._xmlParseError}`);
21
31
  if (!world._xml) throw friendly('No XML response has been set.');
22
32
  return world._xml;
23
33
  }
24
34
 
35
+ // Parse without throwing and without printing: returns the document, or the
36
+ // reason the content is not well-formed XML.
37
+ function parseXml(content) {
38
+ requireParser();
39
+ const problems = [];
40
+ let doc = null;
41
+ try {
42
+ doc = new DOMParser({
43
+ onError: (level, message) => { if (level !== 'warning') problems.push(String(message).trim()); },
44
+ }).parseFromString(String(content), 'text/xml');
45
+ } catch (e) {
46
+ if (problems.length === 0) problems.push(e.message);
47
+ }
48
+ if (problems.length === 0 && (!doc || !doc.documentElement)) problems.push('missing root element');
49
+ return problems.length ? { doc: null, error: problems[0] } : { doc, error: null };
50
+ }
51
+
52
+ // Keep the raw content even when it is not XML, so that the two format steps
53
+ // ("should be" / "should not be in XML format") can judge it.
54
+ function setXmlResponse(world, content) {
55
+ const { doc, error } = parseXml(content);
56
+ world._rawResponse = content;
57
+ world._xml = doc;
58
+ world._xmlParseError = error;
59
+ }
60
+
61
+ // Every prefix the document declares (xmlns:dc="..."), wherever it is declared.
62
+ function declaredNamespaces(doc) {
63
+ const map = {};
64
+ const walk = (el) => {
65
+ for (const a of Array.from(el.attributes || [])) {
66
+ if (a.name.indexOf('xmlns:') === 0 && !(a.name.slice(6) in map)) map[a.name.slice(6)] = a.value;
67
+ }
68
+ for (const c of Array.from(el.childNodes || [])) if (c.nodeType === 1) walk(c);
69
+ };
70
+ if (doc && doc.documentElement) walk(doc.documentElement);
71
+ return map;
72
+ }
73
+
25
74
  function evalXPath(doc, xpath) {
26
75
  // Minimal XPath: support /a/b and /a/b[@attr] and /a/b/text()
27
76
  // For richer XPath, users can install xpath module.
28
77
  let xpathLib;
29
78
  try { xpathLib = require('xpath'); } catch (e) { xpathLib = null; }
30
- if (xpathLib) return xpathLib.select(xpath, doc);
79
+ if (xpathLib) {
80
+ // The XPath reads like the XML does: a prefixed name (//dc:creator)
81
+ // resolves against the prefixes the document itself declares, and a name
82
+ // without a prefix (/urlset/url) also matches an element of the default
83
+ // namespace (xmlns="..."), which every sitemap and Atom feed declares.
84
+ try {
85
+ return xpathLib.parse(xpath).select({
86
+ node: doc,
87
+ namespaces: declaredNamespaces(doc),
88
+ allowAnyNamespaceForNoPrefix: true,
89
+ });
90
+ } catch (e) {
91
+ throw friendly({
92
+ action: `evaluate the XPath "${xpath}"`,
93
+ cause: e,
94
+ hint: 'check the XPath syntax; a prefix (dc:creator) must be declared in the XML with xmlns:dc="...".',
95
+ });
96
+ }
97
+ }
31
98
  // Fallback simple traversal
32
99
  const parts = xpath.split('/').filter(Boolean);
33
100
  let nodes = [doc.documentElement].filter((n) => n && n.nodeName === parts[0]);
@@ -54,9 +121,7 @@ function evalXPath(doc, xpath) {
54
121
  */
55
122
  Given('the response content from the file {string}', async function (filename) {
56
123
  const p = path.isAbsolute(filename) ? filename : path.join(this.assetsFolder || './tests/assets', filename);
57
- const content = fs.readFileSync(p, 'utf-8');
58
- this._rawResponse = content;
59
- this._xml = new DOMParser().parseFromString(content, 'text/xml');
124
+ setXmlResponse(this, fs.readFileSync(p, 'utf-8'));
60
125
  });
61
126
 
62
127
  /**
@@ -85,8 +150,7 @@ Given('the response content from the file {string}', async function (filename) {
85
150
  *
86
151
  */
87
152
  Given('the response content is the following:', async function (docString) {
88
- this._rawResponse = docString;
89
- this._xml = new DOMParser().parseFromString(docString, 'text/xml');
153
+ setXmlResponse(this, docString);
90
154
  });
91
155
 
92
156
  /**
@@ -107,8 +171,8 @@ Given('the response content is the following:', async function (docString) {
107
171
  */
108
172
  Then('the response should be in XML format', async function () {
109
173
  assert.ok(this._rawResponse, 'No response content set.');
110
- const doc = new DOMParser().parseFromString(this._rawResponse, 'text/xml');
111
- assert.ok(doc && doc.documentElement, 'Response is not valid XML.');
174
+ const { error } = parseXml(this._rawResponse);
175
+ assert.ok(!error, `Response is not valid XML: ${error}`);
112
176
  });
113
177
 
114
178
  /**
@@ -131,11 +195,9 @@ Then('the response should be in XML format', async function () {
131
195
  *
132
196
  */
133
197
  Then('the response should not be in XML format', async function () {
134
- if (!this._rawResponse) return;
135
- try {
136
- const doc = new DOMParser().parseFromString(this._rawResponse, 'text/xml');
137
- assert.ok(!doc || !doc.documentElement || doc.getElementsByTagName('parsererror').length > 0, 'Response is XML.');
138
- } catch (e) { /* good */ }
198
+ assert.ok(this._rawResponse, 'No response content set.');
199
+ const { error } = parseXml(this._rawResponse);
200
+ assert.ok(error, 'Response is valid XML.');
139
201
  });
140
202
 
141
203
  /**