@webship-js/nextjs-steps 0.0.0-stage → 2.0.1

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.
@@ -0,0 +1,1036 @@
1
+ 'use strict';
2
+
3
+ // Shared helpers for the step files of this pack.
4
+ //
5
+ // Not a step file: it registers no step definitions and no hooks. It holds the
6
+ // plumbing the steps use and that a project can require for its own steps:
7
+ // the wait on the app's own signals, the requests the app sends and their
8
+ // kinds, the console of the page, the paths of the app, the users registry,
9
+ // the session cache and the login, the route announcer, the images, the
10
+ // development error overlay, and the friendly failures.
11
+ //
12
+ // Waiting: the page is ready when
13
+ // - the document is loaded;
14
+ // - the app has hydrated: the root of the page carries React's fiber, and no
15
+ // part the server rendered is still waiting to be hydrated (a Suspense
16
+ // boundary still "dehydrated");
17
+ // - no part of the page shows its loading state any more: no boundary the
18
+ // server streamed is waiting for its content (the <!--$?--> and <!--$~-->
19
+ // markers of the HTML) and no Suspense boundary shows its fallback;
20
+ // - the router of the Pages Router is ready and no route change is going on;
21
+ // - no request of the app is running (a navigation's RSC payload, a form
22
+ // action, a page's data, the app's own fetches), prefetches left aside;
23
+ // - and all of that has held for a moment (150 ms).
24
+ // No step sleeps.
25
+ //
26
+ // Every lookup starts with what a person reads (a label, a role, a text, the
27
+ // alternative text of an image) and falls back to the framework's stable
28
+ // hooks (`data-nimg` of the image component, `#__next-route-announcer__`,
29
+ // `.next-error-h1`, the `data-nextjs-*` attributes of the development overlay).
30
+
31
+ const { gotoUrl, friendly } = require('webship-js/tests/step-definitions/webship');
32
+
33
+ /**
34
+ * The per-assertion wait budget: `minWaitTime.page` from cucumber.js, at least
35
+ * 10 seconds. Kept below webship-js's 45 second step timeout.
36
+ */
37
+ function budget(world) {
38
+ return Math.max((world && world.minWaitTime && world.minWaitTime.page) || 0, 10000);
39
+ }
40
+
41
+ /** Escape a literal string for use in a RegExp. */
42
+ function escapeRegExp(text) {
43
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
44
+ }
45
+
46
+ /** White space collapsed and trimmed. */
47
+ function clean(text) {
48
+ return String(text === null || text === undefined ? '' : text).replace(/\s+/g, ' ').trim();
49
+ }
50
+
51
+ /** Letter case and white space ignored. */
52
+ function same(a, b) {
53
+ return clean(a).toLowerCase() === clean(b).toLowerCase();
54
+ }
55
+
56
+ /** A list for an error message: `"a", "b", "c"` or `(none)`. */
57
+ function listed(values) {
58
+ const items = [...new Set((values || []).map(clean).filter(Boolean))];
59
+ return items.length ? items.map((item) => `"${item}"`).join(', ') : '(none)';
60
+ }
61
+
62
+ /** The app's root without a trailing slash. */
63
+ function siteRoot(world) {
64
+ return String(world.launchUrl || (world.parameters && world.parameters.launchUrl) || '').replace(/\/+$/, '');
65
+ }
66
+
67
+ /** Join the app's root and a path with exactly one slash. Absolute URLs pass through. */
68
+ function siteUrl(world, url) {
69
+ if (!url) return siteRoot(world) + '/';
70
+ if (/^https?:\/\//i.test(url)) return url;
71
+ return siteRoot(world) + '/' + String(url).replace(/^\/+/, '');
72
+ }
73
+
74
+ /** The path of the page the browser shows, without the query and the fragment. */
75
+ function currentPath(world) {
76
+ try {
77
+ return new URL(world.page.url()).pathname.replace(/\/+$/, '') || '/';
78
+ } catch {
79
+ return '';
80
+ }
81
+ }
82
+
83
+ /** The path and the query of the page the browser shows. */
84
+ function currentAddress(world) {
85
+ try {
86
+ const url = new URL(world.page.url());
87
+ return (url.pathname.replace(/\/+$/, '') || '/') + url.search;
88
+ } catch {
89
+ return '';
90
+ }
91
+ }
92
+
93
+ /** The path of an address, without the query, the fragment and a trailing slash. */
94
+ function pathOf(url) {
95
+ try {
96
+ return new URL(url, 'https://x.invalid').pathname.replace(/\/+$/, '') || '/';
97
+ } catch {
98
+ return String(url || '');
99
+ }
100
+ }
101
+
102
+ // ---------------------------------------------------------------------------
103
+ // A request the browser cut
104
+ // ---------------------------------------------------------------------------
105
+
106
+ /**
107
+ * A sentence for a failure when the browser shows its own error page
108
+ * (`chrome-error://…`) instead of the app's answer, or when a request of the
109
+ * app failed with net::ERR_NETWORK_CHANGED: the request was cut before the app
110
+ * answered, as Chromium does to every request in flight when the network of
111
+ * the machine changes (a container starting or stopping on it). An empty
112
+ * string otherwise.
113
+ */
114
+ function cutRequest(world) {
115
+ const url = world && world.page ? world.page.url() : '';
116
+ if (/^chrome-error:/.test(url)) return `the browser shows its own error page (${url}): the request was cut before the app answered`;
117
+ const state = world && world.page ? TRACKED.get(world.page) : null;
118
+ const cut = state && state.failures.find((f) => /ERR_NETWORK_CHANGED|ERR_NETWORK_IO_SUSPENDED|ERR_INTERNET_DISCONNECTED/.test(f.error) && Date.now() - f.at < 60000);
119
+ if (cut) return `a request of the app (${shortUrl(cut.url)}) was cut by the browser (${cut.error})`;
120
+ return '';
121
+ }
122
+
123
+ /** The hint of a failure `cutRequest` explains. */
124
+ const CUT_REQUEST_HINT = 'Nothing is wrong with the scenario: Chromium cuts every request in flight when the network of the machine changes (a container starting or stopping on it). Run the scenario again, or run the suite inside the project\'s container.';
125
+
126
+ /** A failure, or the one that says a request was cut when the browser cut one. */
127
+ function failure(world, message, hint) {
128
+ const cut = cutRequest(world);
129
+ if (cut) return friendly({ message: `${message} But ${cut}.`, hint: CUT_REQUEST_HINT });
130
+ return friendly({ message, hint });
131
+ }
132
+
133
+ /** An address without the app's origin, shortened for a message. */
134
+ function shortUrl(url) {
135
+ return String(url || '').replace(/^https?:\/\/[^/]+/, '').slice(0, 90);
136
+ }
137
+
138
+ // ---------------------------------------------------------------------------
139
+ // The requests of the app, by kind
140
+ // ---------------------------------------------------------------------------
141
+
142
+ /**
143
+ * The kind of a request the page sends in the background (fetch or XHR):
144
+ * 'prefetch' the router fetching a page ahead of a click (a header
145
+ * next-router-prefetch, or purpose: prefetch);
146
+ * 'action' a form action (a header next-action);
147
+ * 'navigation' the App Router fetching the payload of a page (rsc: 1, or
148
+ * an _rsc= parameter);
149
+ * 'data' the Pages Router fetching a page's data (/_next/data/…);
150
+ * 'background' any other request of the app;
151
+ * or null for what is not a background request.
152
+ */
153
+ function kindOf(request) {
154
+ const type = request.resourceType();
155
+ if (type !== 'fetch' && type !== 'xhr') return null;
156
+ const h = request.headers();
157
+ const url = request.url();
158
+ if (h['next-router-prefetch'] || h['purpose'] === 'prefetch' || h['x-middleware-prefetch']) return 'prefetch';
159
+ if (h['next-action']) return 'action';
160
+ if (h['rsc'] === '1' || /[?&]_rsc=/.test(url)) return 'navigation';
161
+ if (h['x-nextjs-data'] || /\/_next\/data\//.test(url)) return 'data';
162
+ return 'background';
163
+ }
164
+
165
+ const TRACKED = new WeakMap();
166
+
167
+ /**
168
+ * The requests of a page, kept from the moment it opens: those still running
169
+ * (with their kind), how many of each kind started, the answers (newest
170
+ * last), the main documents and the failures. The tracker is attached once
171
+ * per page (onNewPage in nextjs-pages.steps.js attaches it to every page).
172
+ *
173
+ * @returns {{pending: Map, started: object, answers: Array, documents: Array, failures: Array}}
174
+ */
175
+ function requests(page) {
176
+ let state = TRACKED.get(page);
177
+ if (!state) {
178
+ state = {
179
+ pending: new Map(),
180
+ started: { prefetch: 0, action: 0, navigation: 0, data: 0, background: 0 },
181
+ answers: [],
182
+ documents: [],
183
+ failures: [],
184
+ prefetched: [],
185
+ };
186
+ TRACKED.set(page, state);
187
+ page.on('request', (request) => {
188
+ const kind = kindOf(request);
189
+ if (!kind) return;
190
+ state.pending.set(request, kind);
191
+ state.started[kind] += 1;
192
+ if (kind === 'prefetch') {
193
+ state.prefetched.push(request.url());
194
+ if (state.prefetched.length > 200) state.prefetched.shift();
195
+ }
196
+ });
197
+ page.on('response', (response) => {
198
+ const request = response.request();
199
+ if (request.resourceType() === 'document' && request.frame() === page.mainFrame()) {
200
+ state.documents.push({ url: response.url(), status: response.status(), at: Date.now() });
201
+ if (state.documents.length > 20) state.documents.shift();
202
+ return;
203
+ }
204
+ const kind = kindOf(request);
205
+ if (!kind || kind === 'prefetch') return;
206
+ const h = response.headers();
207
+ state.answers.push({ url: response.url(), kind, method: request.method(), status: response.status(), redirect: h['x-action-redirect'] || '', at: Date.now() });
208
+ if (state.answers.length > 100) state.answers.shift();
209
+ });
210
+ const done = (request) => { state.pending.delete(request); };
211
+ page.on('requestfinished', done);
212
+ page.on('requestfailed', (request) => {
213
+ state.pending.delete(request);
214
+ const error = (request.failure() && request.failure().errorText) || 'failed';
215
+ state.failures.push({ url: request.url(), error, at: Date.now() });
216
+ if (state.failures.length > 20) state.failures.shift();
217
+ });
218
+ // A new document drops the requests of the page it replaces.
219
+ page.on('framenavigated', (frame) => {
220
+ if (frame !== page.mainFrame()) return;
221
+ for (const [request, kind] of state.pending) {
222
+ if (kind !== 'action') state.pending.delete(request);
223
+ }
224
+ });
225
+ }
226
+ return state;
227
+ }
228
+
229
+ /** The requests still running that the page waits for (every kind but prefetches). */
230
+ function runningRequests(page) {
231
+ const state = requests(page);
232
+ return [...state.pending.entries()].filter(([, kind]) => kind !== 'prefetch').map(([request, kind]) => ({ url: request.url(), kind }));
233
+ }
234
+
235
+ /** The status of the last main document the page loaded, or 0. */
236
+ function lastDocumentStatus(page) {
237
+ const docs = requests(page).documents;
238
+ return docs.length ? docs[docs.length - 1].status : 0;
239
+ }
240
+
241
+ // ---------------------------------------------------------------------------
242
+ // The console of the page
243
+ // ---------------------------------------------------------------------------
244
+
245
+ const CONSOLES = new WeakMap();
246
+
247
+ /**
248
+ * The errors of the page's console and its uncaught errors, kept from the
249
+ * moment it opens (onNewPage attaches the recorder to every page), with the
250
+ * address of the page they belong to. Cleared when the main document changes.
251
+ */
252
+ function consoleOf(page) {
253
+ let list = CONSOLES.get(page);
254
+ if (!list) {
255
+ list = [];
256
+ CONSOLES.set(page, list);
257
+ const keep = (entry) => {
258
+ list.push(entry);
259
+ if (list.length > 300) list.shift();
260
+ };
261
+ page.on('console', (message) => {
262
+ const type = message.type();
263
+ if (type === 'error' || type === 'warning') keep({ type, text: message.text(), at: Date.now() });
264
+ });
265
+ page.on('pageerror', (error) => keep({ type: 'pageerror', text: String((error && error.message) || error), at: Date.now() }));
266
+ page.on('framenavigated', (frame) => {
267
+ if (frame === page.mainFrame()) list.splice(0, list.length);
268
+ });
269
+ }
270
+ return list;
271
+ }
272
+
273
+ /**
274
+ * The hydration errors of the console: React's own words in development
275
+ * ("Hydration failed", "hydration mismatch", "did not match", "error while
276
+ * hydrating") and its error codes in production (#418, #423, #425: the
277
+ * server's HTML and the first render in the browser differ).
278
+ */
279
+ function hydrationErrors(page) {
280
+ return consoleOf(page)
281
+ .filter((entry) => entry.type !== 'warning')
282
+ .map((entry) => entry.text)
283
+ .filter((text) => /hydrat|did not match|didn't match|Minified React error #(418|423|425)\b/i.test(text));
284
+ }
285
+
286
+ /**
287
+ * The errors the page reported for a render that failed on the server, in
288
+ * production: React's error #441 (the message is left out on purpose, and a
289
+ * digest stands for it), or an error with a `digest`.
290
+ */
291
+ function serverRenderErrors(page) {
292
+ return consoleOf(page)
293
+ .filter((entry) => entry.type !== 'warning')
294
+ .map((entry) => entry.text)
295
+ .filter((text) => /Minified React error #441\b|Server Components render|digest/i.test(text));
296
+ }
297
+
298
+ // ---------------------------------------------------------------------------
299
+ // The script every document of the run carries
300
+ // ---------------------------------------------------------------------------
301
+
302
+ /**
303
+ * Put into every document before the app's own scripts (addInitScript): an
304
+ * identity of the document (a full page load gives a new one, a client-side
305
+ * navigation keeps it), and the commits of the router to the address bar
306
+ * (pushState, replaceState, popstate).
307
+ */
308
+ function documentScript() {
309
+ if (window.__webshipNextjs) return;
310
+ const state = {
311
+ document: Math.random().toString(36).slice(2) + Date.now().toString(36),
312
+ commits: [],
313
+ routeChanges: 0,
314
+ routeEvents: false,
315
+ };
316
+ Object.defineProperty(window, '__webshipNextjs', { value: state, enumerable: false });
317
+ const remember = (how, url) => {
318
+ try {
319
+ state.commits.push({ how, url: new URL(url === undefined || url === null ? location.href : String(url), location.href).href, at: Date.now() });
320
+ if (state.commits.length > 50) state.commits.shift();
321
+ } catch (e) { /* an address the page cannot read is not a commit */ }
322
+ };
323
+ for (const name of ['pushState', 'replaceState']) {
324
+ const original = history[name];
325
+ history[name] = function (data, unused, url) {
326
+ const result = original.apply(this, arguments);
327
+ remember(name, url);
328
+ return result;
329
+ };
330
+ }
331
+ window.addEventListener('popstate', () => remember('popstate', location.href));
332
+ }
333
+
334
+ /** The identity of the document the page shows (see documentScript). */
335
+ async function documentId(world) {
336
+ return world.page.evaluate(() => (window.__webshipNextjs ? window.__webshipNextjs.document : '')).catch(() => '');
337
+ }
338
+
339
+ // ---------------------------------------------------------------------------
340
+ // Which router, and the app's own signals
341
+ // ---------------------------------------------------------------------------
342
+
343
+ /**
344
+ * What the page says about the app: `router` is 'app' (the App Router),
345
+ * 'pages' (the Pages Router) or '' (no app of the framework on this page),
346
+ * `version` the release the page runs, `development` whether it is served by
347
+ * the development server.
348
+ */
349
+ async function appInfo(world) {
350
+ return world.page.evaluate(() => {
351
+ const next = window.next;
352
+ const data = window.__NEXT_DATA__;
353
+ const router = next && next.appDir ? 'app' : (data || (next && next.router && next.router.events) ? 'pages' : '');
354
+ const development = !!document.querySelector('nextjs-portal')
355
+ || (data && data.buildId === 'development')
356
+ || typeof window.__nextHmrInitialVersion !== 'undefined'
357
+ || typeof window.TURBOPACK_CHUNK_UPDATE_LISTENERS !== 'undefined'
358
+ || typeof window.__NEXT_HMR_CB !== 'undefined';
359
+ return { router, version: (next && next.version) || '', development: !!development, buildId: data ? data.buildId : '' };
360
+ }).catch(() => ({ router: '', version: '', development: false, buildId: '' }));
361
+ }
362
+
363
+ /**
364
+ * What the page still has to do, as the page says it: '' when it is ready.
365
+ * See the head of this file.
366
+ */
367
+ async function pendingWork(world) {
368
+ let busy;
369
+ try {
370
+ busy = await world.page.evaluate(() => {
371
+ const out = [];
372
+ // While the document still loads, the parts it streamed so far are read too (below).
373
+ if (document.readyState !== 'complete') out.push('the document is still loading');
374
+ const next = window.next;
375
+ const data = window.__NEXT_DATA__;
376
+ const own = window.__webshipNextjs;
377
+ const reactKey = (node, prefix) => !!node && Object.keys(node).some((k) => k.startsWith(prefix));
378
+ const pagesRoot = document.getElementById('__next');
379
+
380
+ // Hydration: the root element carries React's fiber.
381
+ if (next && next.appDir) {
382
+ if (!reactKey(document.documentElement, '__reactFiber$')) out.push('the page is not hydrated yet');
383
+ } else if (data || (next && next.router && next.router.events)) {
384
+ const hydrated = performance.getEntriesByName('Next.js-hydration').length > 0
385
+ || reactKey(pagesRoot && pagesRoot.firstElementChild, '__reactFiber$');
386
+ if (!hydrated) out.push('the page is not hydrated yet');
387
+ const router = next && next.router;
388
+ if (router && router.isReady === false) out.push('the router is not ready');
389
+ if (own && router && router.events && !own.routeEvents) {
390
+ own.routeEvents = true;
391
+ const done = () => { own.routeChanges = Math.max(0, own.routeChanges - 1); };
392
+ router.events.on('routeChangeStart', () => { own.routeChanges += 1; });
393
+ router.events.on('routeChangeComplete', done);
394
+ router.events.on('routeChangeError', done);
395
+ }
396
+ if (own && own.routeChanges > 0) out.push('a route change is going on');
397
+ } else if (Array.isArray(self.__next_f) || pagesRoot) {
398
+ out.push('the app has not started yet');
399
+ }
400
+
401
+ // Parts the server streamed and that still wait for their content.
402
+ const walker = document.createNodeIterator(document.body || document.documentElement, NodeFilter.SHOW_COMMENT);
403
+ let node;
404
+ let waiting = 0;
405
+ while ((node = walker.nextNode())) {
406
+ if (node.data === '$?' || node.data === '$~') waiting += 1;
407
+ }
408
+ if (waiting) out.push(`${waiting} streamed part(s) of the page still waiting for their content`);
409
+
410
+ // Suspense boundaries, from the current tree of React: one showing its
411
+ // fallback (a loading state), one still waiting to be hydrated. A hidden
412
+ // part (a page the router keeps for going back) is left out.
413
+ const start = [document.documentElement, document.body, pagesRoot && pagesRoot.firstElementChild].find((el) => reactKey(el, '__reactFiber$'));
414
+ if (start) {
415
+ const key = Object.keys(start).find((k) => k.startsWith('__reactFiber$'));
416
+ let fiber = start[key];
417
+ while (fiber && fiber.return) fiber = fiber.return;
418
+ if (fiber && fiber.stateNode && fiber.stateNode.current) fiber = fiber.stateNode.current;
419
+ let fallbacks = 0;
420
+ let dehydrated = 0;
421
+ const stack = fiber ? [fiber] : [];
422
+ let visited = 0;
423
+ while (stack.length && visited < 50000) {
424
+ const f = stack.pop();
425
+ visited += 1;
426
+ if (f.tag === 22 && f.memoizedState !== null) {
427
+ if (f.sibling) stack.push(f.sibling);
428
+ continue;
429
+ }
430
+ if (f.tag === 13 && f.memoizedState !== null) {
431
+ if (f.memoizedState.dehydrated) dehydrated += 1;
432
+ else fallbacks += 1;
433
+ }
434
+ if (f.sibling) stack.push(f.sibling);
435
+ if (f.child) stack.push(f.child);
436
+ }
437
+ if (fallbacks) out.push(`${fallbacks} part(s) of the page showing their loading state`);
438
+ if (dehydrated) out.push(`${dehydrated} part(s) of the page not hydrated yet`);
439
+ }
440
+ return out;
441
+ });
442
+ } catch (err) {
443
+ // A navigation replaced the document while it was read: not ready yet.
444
+ return /Execution context was destroyed|navigation|Target closed|has been closed/i.test(String(err && err.message)) ? 'a new page is loading' : '';
445
+ }
446
+ const running = runningRequests(world.page);
447
+ if (running.length) {
448
+ busy.push(`${running.length} request(s) running: ${running.slice(0, 3).map((r) => `${r.kind} ${shortUrl(r.url)}`).join(', ')}`);
449
+ }
450
+ return busy.join('; ');
451
+ }
452
+
453
+ /**
454
+ * Why the page is not hydrated yet, or '' when it is: the document is still
455
+ * loading, the app has not started, its root has no fiber yet, or a part the
456
+ * server rendered still waits to be hydrated. The parts of pendingWork that
457
+ * are about hydration only.
458
+ */
459
+ async function hydrationProblem(world) {
460
+ const busy = await pendingWork(world);
461
+ return busy.split('; ').filter((part) => /document is still loading|not hydrated yet|has not started yet|router is not ready|new page is loading/.test(part)).join('; ');
462
+ }
463
+
464
+ /**
465
+ * Wait until the page is ready (see the head of this file) and stays so for a
466
+ * moment (150 ms). Returns '' when it is, else what it was still doing when
467
+ * the time ran out; `strict` makes that a failure.
468
+ */
469
+ async function pageReady(world, { timeout, strict = false } = {}) {
470
+ const limit = timeout || budget(world) * 2;
471
+ const deadline = Date.now() + limit;
472
+ requests(world.page);
473
+ let busy = '';
474
+ let quietSince = 0;
475
+ for (;;) {
476
+ busy = await pendingWork(world);
477
+ if (!busy) {
478
+ if (!quietSince) quietSince = Date.now();
479
+ if (Date.now() - quietSince >= 150) return '';
480
+ } else {
481
+ quietSince = 0;
482
+ }
483
+ if (Date.now() > deadline) break;
484
+ await world.page.waitForTimeout(40);
485
+ }
486
+ if (strict) {
487
+ throw failure(world, `The page did not get ready within ${limit} ms (${world.page.url()}): ${busy}.`, 'The page is ready when it is loaded and hydrated, no part of it shows a loading state, and no request of the app is running. A request that never ends, or a part that never stops loading, is a fault of the app: check its server and the browser console.');
488
+ }
489
+ return busy;
490
+ }
491
+
492
+ /**
493
+ * Run an action that may make the app work (a click, a key, a form), and wait
494
+ * for that work to finish: for a request, a commit of the router or a new
495
+ * document to start (a moment at most), then for the page to be ready.
496
+ */
497
+ async function afterAction(world, fn) {
498
+ const state = requests(world.page);
499
+ const before = Object.values(state.started).reduce((a, b) => a + b, 0) - state.started.prefetch;
500
+ const url = world.page.url();
501
+ const docs = state.documents.length;
502
+ const result = await fn();
503
+ const startBy = Date.now() + 1000;
504
+ while (Date.now() < startBy) {
505
+ const now = Object.values(state.started).reduce((a, b) => a + b, 0) - state.started.prefetch;
506
+ if (now !== before || world.page.url() !== url || state.documents.length !== docs) break;
507
+ await world.page.waitForTimeout(25);
508
+ }
509
+ await world.page.waitForLoadState('domcontentloaded', { timeout: budget(world) }).catch(() => {});
510
+ await pageReady(world);
511
+ return result;
512
+ }
513
+
514
+ /** Open an address of the app and wait for the page to be ready. */
515
+ async function open(world, url) {
516
+ requests(world.page);
517
+ await gotoUrl(world.page, siteUrl(world, url));
518
+ await world.page.waitForLoadState('load', { timeout: budget(world) }).catch(() => {});
519
+ await pageReady(world);
520
+ }
521
+
522
+ // ---------------------------------------------------------------------------
523
+ // Elements: hydrated, brought into view, clicked the way a person does
524
+ // ---------------------------------------------------------------------------
525
+
526
+ /**
527
+ * Is the element in the hands of the app yet: does it carry React's
528
+ * properties (its event handlers)? An element of a page that no React tree
529
+ * owns counts as ready.
530
+ */
531
+ async function elementHydrated(locator) {
532
+ return locator.evaluate((el) => {
533
+ const owned = (node) => !!node && Object.keys(node).some((k) => k.startsWith('__reactProps$') || k.startsWith('__reactFiber$'));
534
+ if (owned(el)) return true;
535
+ // An element no React tree owns at all (none of its ancestors carries a fiber) is plain HTML.
536
+ for (let node = el.parentElement; node; node = node.parentElement) {
537
+ if (owned(node)) return false;
538
+ }
539
+ return !document.querySelector('[id="__next"]') && !(window.next && window.next.appDir);
540
+ }).catch(() => false);
541
+ }
542
+
543
+ /**
544
+ * Wait until the element is attached, visible and hydrated (see
545
+ * elementHydrated); fail with a message that says which of them it is not.
546
+ */
547
+ async function waitHydrated(world, locator, label) {
548
+ const deadline = Date.now() + budget(world);
549
+ try {
550
+ await locator.waitFor({ state: 'visible', timeout: budget(world) });
551
+ } catch {
552
+ throw failure(world, `Expected to see ${label}, but it did not appear within ${budget(world)} ms (${world.page.url()}).`, 'Check its words on the page: a link, a button and a field are found by the name a person reads (their text, label or accessible name).');
553
+ }
554
+ while (!(await elementHydrated(locator))) {
555
+ if (Date.now() > deadline) {
556
+ throw failure(world, `${label[0].toUpperCase()}${label.slice(1)} is on the page but the app has not taken it over (it has no React properties) within ${budget(world)} ms: a click now would do what plain HTML does, not what the app does.`, 'The page has not finished hydrating: look for an error in the browser console, or a script that did not load.');
557
+ }
558
+ await world.page.waitForTimeout(40);
559
+ }
560
+ }
561
+
562
+ /**
563
+ * Click an element the way a person does: brought to the middle of the
564
+ * window (a sticky header never covers it), hydrated, then clicked.
565
+ */
566
+ async function personClick(world, locator, label) {
567
+ await waitHydrated(world, locator, label);
568
+ await locator.evaluate((el) => el.scrollIntoView({ block: 'center', inline: 'nearest' })).catch(() => {});
569
+ await locator.click({ timeout: budget(world) });
570
+ }
571
+
572
+ /**
573
+ * A link by its name (its text or accessible name, exactly, then containing
574
+ * the words), the visible one first.
575
+ */
576
+ function linkByName(world, name) {
577
+ const exact = world.page.getByRole('link', { name, exact: true });
578
+ const loose = world.page.getByRole('link', { name });
579
+ return { exact: exact.filter({ visible: true }), loose: loose.filter({ visible: true }) };
580
+ }
581
+
582
+ /** The first locator of a list that has a match, else the last one. */
583
+ async function firstPresent(locators) {
584
+ for (const locator of locators) {
585
+ if ((await locator.count().catch(() => 0)) > 0) return locator.first();
586
+ }
587
+ return locators[locators.length - 1].first();
588
+ }
589
+
590
+ /** The names of the visible links of the page, for a failure message. */
591
+ async function visibleLinkNames(world) {
592
+ return world.page.evaluate(() => [...document.querySelectorAll('a[href]')]
593
+ .filter((a) => a.offsetWidth || a.offsetHeight)
594
+ .map((a) => (a.getAttribute('aria-label') || a.textContent || '').replace(/\s+/g, ' ').trim())
595
+ .filter(Boolean)
596
+ .slice(0, 15)).catch(() => []);
597
+ }
598
+
599
+ // ---------------------------------------------------------------------------
600
+ // Answers held back, and a slow network
601
+ // ---------------------------------------------------------------------------
602
+
603
+ /**
604
+ * Hold back the app's answers: every request of the kinds the app waits for
605
+ * (a navigation's payload, a form action, a page's data) is held until
606
+ * releaseAnswers. Prefetches and other requests go through.
607
+ */
608
+ async function holdAnswers(world) {
609
+ if (world.__heldAnswers) return world.__heldAnswers;
610
+ const held = { urls: [], open: null, handler: null };
611
+ const gate = new Promise((resolve) => { held.open = resolve; });
612
+ held.handler = async (route) => {
613
+ const kind = kindOf(route.request());
614
+ if (kind !== 'navigation' && kind !== 'action' && kind !== 'data') return route.fallback();
615
+ held.urls.push(route.request().url());
616
+ await gate;
617
+ return route.continue().catch(() => {});
618
+ };
619
+ await world.page.route('**/*', held.handler);
620
+ world.__heldAnswers = held;
621
+ return held;
622
+ }
623
+
624
+ /** Let the answers held back go, and stop holding. */
625
+ async function releaseAnswers(world) {
626
+ const held = world.__heldAnswers;
627
+ if (!held) return null;
628
+ world.__heldAnswers = null;
629
+ held.open();
630
+ await world.page.unroute('**/*', held.handler).catch(() => {});
631
+ return held;
632
+ }
633
+
634
+ /**
635
+ * A slow network for the page (Chromium's own network emulation): every
636
+ * answer comes slowly, so the parts the app streams arrive one after the
637
+ * other, as on a slow mobile connection. `false` brings the speed back.
638
+ */
639
+ async function slowNetwork(world, on) {
640
+ const browser = world.page.context().browser();
641
+ const name = browser ? browser.browserType().name() : 'chromium';
642
+ if (name !== 'chromium') {
643
+ throw friendly({
644
+ message: `Only Chromium can slow the network of a page; this run uses ${name}.`,
645
+ hint: 'Run this scenario with BROWSER=chromium (the default of the pack).',
646
+ });
647
+ }
648
+ if (!world.__cdp || world.__cdpPage !== world.page) {
649
+ world.__cdp = await world.page.context().newCDPSession(world.page);
650
+ world.__cdpPage = world.page;
651
+ await world.__cdp.send('Network.enable');
652
+ }
653
+ await world.__cdp.send('Network.emulateNetworkConditions', on
654
+ ? { offline: false, latency: 200, downloadThroughput: 6 * 1024, uploadThroughput: 6 * 1024 }
655
+ : { offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 });
656
+ world.__slowNetwork = !!on;
657
+ }
658
+
659
+ // ---------------------------------------------------------------------------
660
+ // The route announcer
661
+ // ---------------------------------------------------------------------------
662
+
663
+ /**
664
+ * The route announcer of the page (the live region the router fills with the
665
+ * title of each new page): whether it is there, and what it says now.
666
+ */
667
+ async function announcer(world) {
668
+ return world.page.evaluate(() => {
669
+ const host = document.querySelector('next-route-announcer');
670
+ const inShadow = host && host.shadowRoot ? host.shadowRoot.getElementById('__next-route-announcer__') || host.shadowRoot.querySelector('[aria-live]') : null;
671
+ const region = inShadow || document.getElementById('__next-route-announcer__');
672
+ if (!region) return { present: false, text: '', live: '' };
673
+ return { present: true, text: (region.textContent || '').replace(/\s+/g, ' ').trim(), live: region.getAttribute('aria-live') || '' };
674
+ }).catch(() => ({ present: false, text: '', live: '' }));
675
+ }
676
+
677
+ // ---------------------------------------------------------------------------
678
+ // Accounts and the session
679
+ // ---------------------------------------------------------------------------
680
+
681
+ /**
682
+ * An account of the users registry in cucumber.js (`worldParameters.users`),
683
+ * by the handle a scenario names it with: the address (or user name) it logs
684
+ * in with, its password, and its name.
685
+ *
686
+ * @returns {{handle: string, login: string, password: string, email: (string|undefined), name: (string|undefined)}}
687
+ */
688
+ function resolveUser(world, handle) {
689
+ const users = (world.parameters && world.parameters.users) || {};
690
+ const entry = users[handle];
691
+ if (!entry) {
692
+ throw friendly({
693
+ message: `The user "${handle}" is not in the users registry. Known users: ${Object.keys(users).join(', ') || '(none)'}.`,
694
+ hint: `Add it to worldParameters.users in cucumber.js: users: { ${handle}: { email: '${handle}@example.com', password: process.env.${String(handle).toUpperCase()}_PASSWORD, name: 'Name' } }. The account itself is created once by the build of the app, never by a feature.`,
695
+ });
696
+ }
697
+ const login = entry.email || entry.username;
698
+ if (!login || !entry.password) {
699
+ throw friendly({
700
+ message: `The user "${handle}" has no ${login ? 'password' : 'email address'} in the users registry.`,
701
+ hint: `Set worldParameters.users.${handle}.email and .password in cucumber.js.`,
702
+ });
703
+ }
704
+ return { handle, login, password: entry.password, email: entry.email, name: entry.name };
705
+ }
706
+
707
+ /** The login page (`worldParameters.loginPath`, /login). */
708
+ function loginPath(world) {
709
+ return '/' + String((world.parameters && world.parameters.loginPath) || '/login').replace(/^\/+/, '');
710
+ }
711
+
712
+ /**
713
+ * The address that answers with the session of the browser
714
+ * (`worldParameters.sessionPath`, /api/auth/session, the one of the app's
715
+ * authentication library), or '' when the app has none.
716
+ */
717
+ function sessionPath(world) {
718
+ const configured = world.parameters ? world.parameters.sessionPath : undefined;
719
+ if (configured === '' || configured === false) return '';
720
+ return '/' + String(configured || '/api/auth/session').replace(/^\/+/, '');
721
+ }
722
+
723
+ /** The login form: the visible form with a password field. */
724
+ function loginForm(world) {
725
+ return world.page.locator('form:has(input[type="password"])').filter({ visible: true }).first();
726
+ }
727
+
728
+ /**
729
+ * Who the app says is signed in: the session address answers with the
730
+ * session of the browser's cookies (`{user: {name, email}}`, or null).
731
+ *
732
+ * @returns {Promise<{known: boolean, user: (object|null), status: number}>}
733
+ */
734
+ async function currentSession(world) {
735
+ const path = sessionPath(world);
736
+ if (!path) return { known: false, user: null, status: 0 };
737
+ try {
738
+ const response = await world.page.context().request.get(siteUrl(world, path), { headers: { accept: 'application/json' }, failOnStatusCode: false, maxRedirects: 0 });
739
+ const status = response.status();
740
+ if (status !== 200) return { known: false, user: null, status };
741
+ const body = await response.json().catch(() => undefined);
742
+ if (body === undefined) return { known: false, user: null, status };
743
+ return { known: true, user: body && body.user ? body.user : null, status };
744
+ } catch {
745
+ return { known: false, user: null, status: 0 };
746
+ }
747
+ }
748
+
749
+ const LOGIN_HINT = 'The login form is the visible form with a password field at worldParameters.loginPath (/login). Check launchUrl in cucumber.js, and that the build of the app created the account.';
750
+
751
+ // The sessions of the accounts that logged in during this run, by app and
752
+ // login: the cookies of the browser after a login through the form. A
753
+ // scenario that logs in as an account that already has a session takes it
754
+ // over instead of filling in the login form again.
755
+ // `worldParameters.reuseSessions: false` in cucumber.js turns it off.
756
+ const SESSIONS = new Map();
757
+
758
+ function sessionKey(world, login) {
759
+ return `${siteRoot(world)}|${String(login).toLowerCase()}`;
760
+ }
761
+
762
+ function reuseSessions(world) {
763
+ return !(world.parameters && world.parameters.reuseSessions === false);
764
+ }
765
+
766
+ /**
767
+ * The text of the messages of a form or of the page: live regions (the
768
+ * places an app announces what happened), alerts and status messages, the
769
+ * route announcer left out.
770
+ */
771
+ async function formMessages(world, scope) {
772
+ const root = scope || world.page.locator('body');
773
+ return root.evaluate((el) => {
774
+ const nodes = [...el.querySelectorAll('[aria-live], [role="alert"], [role="status"]')]
775
+ .filter((n) => !n.closest('next-route-announcer') && n.id !== '__next-route-announcer__');
776
+ return nodes.map((n) => (n.textContent || '').replace(/\s+/g, ' ').trim()).filter(Boolean);
777
+ }).catch(() => []);
778
+ }
779
+
780
+ /**
781
+ * Open the login page as a new visitor: the page the browser showed is left
782
+ * first, then the cookies of the browser are cleared.
783
+ */
784
+ async function openLoginForm(world) {
785
+ await world.page.goto('about:blank').catch(() => {});
786
+ await world.page.context().clearCookies();
787
+ world.__sessionKey = null;
788
+ await open(world, loginPath(world));
789
+ try {
790
+ await loginForm(world).waitFor({ state: 'visible', timeout: budget(world) });
791
+ } catch {
792
+ throw failure(world, `The login form did not appear at ${siteUrl(world, loginPath(world))} (${world.page.url()}).`, LOGIN_HINT);
793
+ }
794
+ }
795
+
796
+ /**
797
+ * Fill in and send the login form, and read its outcome: the page the app
798
+ * sends a signed-in account to, or the message of the login form.
799
+ *
800
+ * @returns {Promise<{error: string, cut: (boolean|undefined)}>}
801
+ */
802
+ async function submitLogin(world, login, password) {
803
+ await openLoginForm(world);
804
+ const form = loginForm(world);
805
+ const field = form.locator('input[type="email"], input[name="email"], input[name="username"], input[autocomplete="username"], input[type="text"]').first();
806
+ await waitHydrated(world, field, 'the address field of the login form');
807
+ await field.fill(login);
808
+ await form.locator('input[type="password"]').first().fill(password);
809
+ const submit = form.locator('button[type="submit"], input[type="submit"], button:not([type])').first();
810
+ await afterAction(world, () => personClick(world, submit, 'the button of the login form'));
811
+ if (cutRequest(world)) return { error: cutRequest(world), cut: true };
812
+ if (currentPath(world) !== pathOf(loginPath(world))) return { error: '' };
813
+ const messages = await formMessages(world, loginForm(world));
814
+ return { error: messages.join(' ') || `the login page came back with no message (${world.page.url()})` };
815
+ }
816
+
817
+ /** Take over the session an account opened earlier in this run. */
818
+ async function restoreSession(world, user) {
819
+ const key = sessionKey(world, user.login);
820
+ const saved = SESSIONS.get(key);
821
+ if (!saved || !reuseSessions(world)) return false;
822
+ const context = world.page.context();
823
+ await world.page.goto('about:blank').catch(() => {});
824
+ await context.clearCookies();
825
+ await context.addCookies(saved.cookies);
826
+ const session = await currentSession(world);
827
+ if (!session.known || (session.user && same(session.user.email || '', user.email || user.login))) {
828
+ world.__sessionKey = key;
829
+ world.__signedInAs = user.handle;
830
+ // The browser ends on a page of the app, as after a login through the form: its front page,
831
+ // which an app sends a signed-in account on from (the dashboard of the test app).
832
+ await open(world, '/');
833
+ return true;
834
+ }
835
+ // The session ended since (a logout, an expiry): log in again.
836
+ SESSIONS.delete(key);
837
+ await context.clearCookies();
838
+ return false;
839
+ }
840
+
841
+ /**
842
+ * Log in as an account of the users registry, by its handle: take over its
843
+ * session when it has one from earlier in the run, else log in through the
844
+ * form and keep the session for the next scenario.
845
+ */
846
+ async function logInAs(world, handle) {
847
+ const user = resolveUser(world, handle);
848
+ if (await restoreSession(world, user)) return user;
849
+ let outcome = await submitLogin(world, user.login, user.password);
850
+ if (outcome.error && outcome.cut) outcome = await submitLogin(world, user.login, user.password);
851
+ if (outcome.error) {
852
+ throw friendly({
853
+ message: `Could not log in as "${handle}" (${user.login}): ${outcome.error}`,
854
+ hint: outcome.cut ? CUT_REQUEST_HINT : 'Check the address and the password of the account in worldParameters.users, and that the build of the app created the account.',
855
+ });
856
+ }
857
+ if (reuseSessions(world)) {
858
+ const key = sessionKey(world, user.login);
859
+ SESSIONS.set(key, { cookies: await world.page.context().cookies() });
860
+ world.__sessionKey = key;
861
+ }
862
+ world.__signedInAs = handle;
863
+ return user;
864
+ }
865
+
866
+ /** Forget the session of the browser in the session cache: it ended (a logout). */
867
+ function forgetSession(world) {
868
+ if (world.__sessionKey) SESSIONS.delete(world.__sessionKey);
869
+ world.__sessionKey = null;
870
+ world.__signedInAs = null;
871
+ }
872
+
873
+ // ---------------------------------------------------------------------------
874
+ // Images
875
+ // ---------------------------------------------------------------------------
876
+
877
+ /**
878
+ * An image by its alternative text: the exact text first, then an image whose
879
+ * text has the words as whole words; the visible one first.
880
+ */
881
+ async function imageByAlt(world, alt) {
882
+ const exact = world.page.locator(`img[alt="${String(alt).replace(/"/g, '\\"')}"]`);
883
+ // The words of the text as whole words: "logo" finds "Company logo", not "logomark".
884
+ const loose = world.page.getByRole('img', { name: new RegExp(`(^|\\W)${escapeRegExp(alt)}($|\\W)`, 'i') });
885
+ const visibleExact = exact.filter({ visible: true });
886
+ return firstPresent([visibleExact, exact, loose.filter({ visible: true }), loose]);
887
+ }
888
+
889
+ /** The images of the page by their alternative text, for a failure message. */
890
+ async function imageNames(world) {
891
+ return world.page.evaluate(() => [...document.images].map((img) => img.alt).filter(Boolean).slice(0, 15)).catch(() => []);
892
+ }
893
+
894
+ /** What the page says of an image: how it loads, where from, and whether it has. */
895
+ async function imageInfo(locator) {
896
+ return locator.evaluate((img) => ({
897
+ alt: img.alt,
898
+ loading: img.getAttribute('loading') || '',
899
+ decoding: img.getAttribute('decoding') || '',
900
+ fetchPriority: img.getAttribute('fetchpriority') || '',
901
+ component: img.hasAttribute('data-nimg'),
902
+ src: img.getAttribute('src') || '',
903
+ srcset: img.getAttribute('srcset') || '',
904
+ currentSrc: img.currentSrc || '',
905
+ complete: img.complete,
906
+ naturalWidth: img.naturalWidth,
907
+ visible: !!(img.offsetWidth || img.offsetHeight),
908
+ preloaded: [...document.querySelectorAll('link[rel="preload"][as="image"]')].some((link) => {
909
+ const href = link.getAttribute('href') || '';
910
+ const set = link.getAttribute('imagesrcset') || '';
911
+ const src = img.getAttribute('src') || '';
912
+ return (href && (href === src || img.currentSrc.endsWith(href))) || (set && set === (img.getAttribute('srcset') || ''));
913
+ }),
914
+ }));
915
+ }
916
+
917
+ /** An image whose address goes through the image optimizer of the app. */
918
+ function optimizedAddress(url) {
919
+ return /\/_next\/image\?/.test(String(url || ''));
920
+ }
921
+
922
+ // ---------------------------------------------------------------------------
923
+ // The development error overlay
924
+ // ---------------------------------------------------------------------------
925
+
926
+ /**
927
+ * What the development tools of the page show: whether they are on the page
928
+ * at all (only the development server puts them there), the indicator, and
929
+ * the error overlay (its title, its message and how many errors it lists).
930
+ */
931
+ async function devOverlay(world) {
932
+ return world.page.evaluate(() => {
933
+ const host = document.querySelector('nextjs-portal');
934
+ const root = host && host.shadowRoot;
935
+ if (!root) return { present: false, indicator: false, open: false, label: '', message: '', count: 0, text: '' };
936
+ const dialog = root.querySelector('[data-nextjs-dialog], [role="dialog"][aria-labelledby="nextjs__container_errors_label"]');
937
+ const label = root.getElementById('nextjs__container_errors_label');
938
+ const desc = root.getElementById('nextjs__container_errors_desc');
939
+ const total = root.querySelector('[data-nextjs-dialog-header-total-count]');
940
+ const indicator = root.querySelector('[data-nextjs-dev-tools-button], #devtools-indicator, [data-nextjs-toast]');
941
+ const text = dialog ? (dialog.textContent || '').replace(/\s+/g, ' ').trim() : '';
942
+ return {
943
+ present: true,
944
+ indicator: !!indicator,
945
+ open: !!dialog,
946
+ label: label ? label.textContent.replace(/\s+/g, ' ').trim() : '',
947
+ message: desc ? desc.textContent.replace(/\s+/g, ' ').trim() : '',
948
+ count: total ? parseInt(total.textContent, 10) || (dialog ? 1 : 0) : (dialog ? 1 : 0),
949
+ text,
950
+ };
951
+ }).catch(() => ({ present: false, indicator: false, open: false, label: '', message: '', count: 0, text: '' }));
952
+ }
953
+
954
+ /**
955
+ * Poll a reading until it satisfies a check, or fail with the last reading.
956
+ *
957
+ * @param {object} world
958
+ * @param {Function} read - async () => value
959
+ * @param {Function} check - (value) => boolean
960
+ * @param {Function} explain - (value) => {message, hint}
961
+ */
962
+ async function eventually(world, read, check, explain, timeout) {
963
+ const deadline = Date.now() + (timeout || budget(world));
964
+ let value;
965
+ for (;;) {
966
+ value = await read();
967
+ if (check(value)) return value;
968
+ if (Date.now() > deadline) {
969
+ const why = explain(value);
970
+ throw failure(world, why.message, why.hint);
971
+ }
972
+ await world.page.waitForTimeout(100);
973
+ }
974
+ }
975
+
976
+ module.exports = {
977
+ budget,
978
+ escapeRegExp,
979
+ clean,
980
+ same,
981
+ listed,
982
+ siteRoot,
983
+ siteUrl,
984
+ currentPath,
985
+ currentAddress,
986
+ pathOf,
987
+ shortUrl,
988
+ cutRequest,
989
+ CUT_REQUEST_HINT,
990
+ failure,
991
+ kindOf,
992
+ requests,
993
+ runningRequests,
994
+ lastDocumentStatus,
995
+ consoleOf,
996
+ hydrationErrors,
997
+ serverRenderErrors,
998
+ documentScript,
999
+ documentId,
1000
+ appInfo,
1001
+ pendingWork,
1002
+ hydrationProblem,
1003
+ pageReady,
1004
+ afterAction,
1005
+ open,
1006
+ elementHydrated,
1007
+ waitHydrated,
1008
+ personClick,
1009
+ linkByName,
1010
+ firstPresent,
1011
+ visibleLinkNames,
1012
+ holdAnswers,
1013
+ releaseAnswers,
1014
+ slowNetwork,
1015
+ announcer,
1016
+ resolveUser,
1017
+ loginPath,
1018
+ sessionPath,
1019
+ loginForm,
1020
+ currentSession,
1021
+ LOGIN_HINT,
1022
+ SESSIONS,
1023
+ reuseSessions,
1024
+ formMessages,
1025
+ openLoginForm,
1026
+ submitLogin,
1027
+ restoreSession,
1028
+ logInAs,
1029
+ forgetSession,
1030
+ imageByAlt,
1031
+ imageNames,
1032
+ imageInfo,
1033
+ optimizedAddress,
1034
+ devOverlay,
1035
+ eventually,
1036
+ };