@webship-js/mediawiki-steps 0.0.0-stage → 2.0.0

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 (30) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +550 -2
  3. package/package.json +63 -4
  4. package/tests/features/README.md +26 -0
  5. package/tests/features/accessibility.feature +16 -0
  6. package/tests/features/account-creation.feature +28 -0
  7. package/tests/features/administration.feature +49 -0
  8. package/tests/features/categories.feature +28 -0
  9. package/tests/features/edit-conflict.feature +15 -0
  10. package/tests/features/history.feature +30 -0
  11. package/tests/features/preferences.feature +15 -0
  12. package/tests/features/reading.feature +84 -0
  13. package/tests/features/search.feature +34 -0
  14. package/tests/features/session.feature +43 -0
  15. package/tests/features/source-editor.feature +42 -0
  16. package/tests/features/talk-page.feature +19 -0
  17. package/tests/features/upload.feature +20 -0
  18. package/tests/features/visual-editor.feature +18 -0
  19. package/tests/features/watchlist.feature +24 -0
  20. package/tests/fixtures/blue-square.png +0 -0
  21. package/tests/step-definitions/README.md +41 -0
  22. package/tests/step-definitions/mediawiki-admin.steps.js +241 -0
  23. package/tests/step-definitions/mediawiki-editing.steps.js +413 -0
  24. package/tests/step-definitions/mediawiki-files.steps.js +93 -0
  25. package/tests/step-definitions/mediawiki-helpers.js +768 -0
  26. package/tests/step-definitions/mediawiki-history.steps.js +135 -0
  27. package/tests/step-definitions/mediawiki-pages.steps.js +710 -0
  28. package/tests/step-definitions/mediawiki-search.steps.js +234 -0
  29. package/tests/step-definitions/mediawiki-session.steps.js +287 -0
  30. package/tests/step-definitions/mediawiki-watchlist.steps.js +265 -0
@@ -0,0 +1,768 @@
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 addresses of the wiki, the waits on the wiki's own signals (its module
8
+ // loader, its hooks, its job queue), the users registry and the session cache,
9
+ // the messages of a page, the request the browser cut, and a client of the
10
+ // wiki's API that works as the administrator of the users registry for the
11
+ // test data (pages, files, protection, blocks) and its cleanup.
12
+ //
13
+ // Every lookup starts with what a person reads (a label, a role, a text) and
14
+ // falls back to the stable hooks of the wiki's pages (`mw.config`, the ids of
15
+ // its forms, the classes of its messages). Everything builds on webship-js's
16
+ // own helpers (`gotoUrl`, `friendly`) so the steps fail the way the core
17
+ // webship-js steps do.
18
+
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+ const { gotoUrl, friendly } = require('webship-js/tests/step-definitions/webship');
22
+
23
+ /** The per-assertion wait budget: `minWaitTime.page` from cucumber.js, at least 10 seconds. */
24
+ function budget(world) {
25
+ return Math.max((world && world.minWaitTime && world.minWaitTime.page) || 0, 10000);
26
+ }
27
+
28
+ /** The settle budget after an action (`minWaitTime.page`, 3 seconds by default). */
29
+ function settleBudget(world) {
30
+ return (world && world.minWaitTime && world.minWaitTime.page) || 3000;
31
+ }
32
+
33
+ /** Escape a literal string for use in a RegExp. */
34
+ function escapeRegExp(text) {
35
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
36
+ }
37
+
38
+ /** White space (and the bidirectional marks the wiki puts around names) collapsed and trimmed. */
39
+ function clean(text) {
40
+ return String(text === null || text === undefined ? '' : text).replace(/[‪-‮‎‏]/g, '').replace(/\s+/g, ' ').trim();
41
+ }
42
+
43
+ /** A list for an error message: `"a", "b", "c"` or `(none)`. */
44
+ function listed(values) {
45
+ const items = [...new Set((values || []).map(clean).filter(Boolean))];
46
+ return items.length ? items.map((item) => `"${item}"`).join(', ') : '(none)';
47
+ }
48
+
49
+ /** A page title as the wiki writes it in addresses: spaces as underscores, the first letter upper case. */
50
+ function titleKey(title) {
51
+ const key = clean(title).replace(/ /g, '_');
52
+ const colon = key.indexOf(':');
53
+ const upper = (s) => s.charAt(0).toUpperCase() + s.slice(1);
54
+ // "Talk:page" → "Talk:Page": the namespace and the name each start upper case.
55
+ if (colon > 0) return upper(key.slice(0, colon)) + ':' + upper(key.slice(colon + 1));
56
+ return upper(key);
57
+ }
58
+
59
+ /** A page title as the wiki shows it: underscores as spaces, the first letter upper case. */
60
+ function titleText(title) {
61
+ return titleKey(title).replace(/_/g, ' ');
62
+ }
63
+
64
+ /** An account name as the wiki stores it: the first letter upper case. */
65
+ function wikiUserName(name) {
66
+ const n = clean(name).replace(/_/g, ' ');
67
+ return n.charAt(0).toUpperCase() + n.slice(1);
68
+ }
69
+
70
+ /** The site root without a trailing slash. */
71
+ function siteRoot(world) {
72
+ return String(world.launchUrl || (world.parameters && world.parameters.launchUrl) || '').replace(/\/+$/, '');
73
+ }
74
+
75
+ /** The folder of index.php and api.php (`worldParameters.scriptPath`, '' at the root). */
76
+ function scriptPath(world) {
77
+ const value = String((world.parameters && world.parameters.scriptPath) || '').replace(/\/+$/, '');
78
+ return value && !value.startsWith('/') ? '/' + value : value;
79
+ }
80
+
81
+ /** The skin the steps ask for (`worldParameters.skin`), or '' for the wiki's default. */
82
+ function skinParam(world) {
83
+ return String((world.parameters && world.parameters.skin) || '').trim();
84
+ }
85
+
86
+ /** The address of index.php with a title and parameters (and the skin of `worldParameters.skin`). */
87
+ function indexUrl(world, title, params = {}) {
88
+ const query = new URLSearchParams();
89
+ if (title) query.set('title', titleKey(title));
90
+ for (const [key, value] of Object.entries(params)) {
91
+ if (value !== undefined && value !== null) query.set(key, String(value));
92
+ }
93
+ if (skinParam(world) && !query.has('useskin')) query.set('useskin', skinParam(world));
94
+ return `${siteRoot(world)}${scriptPath(world)}/index.php?${query.toString()}`;
95
+ }
96
+
97
+ /** The address of api.php. */
98
+ function apiUrl(world) {
99
+ return `${siteRoot(world)}${scriptPath(world)}/api.php`;
100
+ }
101
+
102
+ /** A value of the page's own configuration (`mw.config`), or null before the wiki's scripts ran. */
103
+ async function config(world, key) {
104
+ return world.page.evaluate((k) => (window.mw && mw.config ? mw.config.get(k) : null), key).catch(() => null);
105
+ }
106
+
107
+ // ---------------------------------------------------------------------------
108
+ // The request the browser cut, and opening a page
109
+ // ---------------------------------------------------------------------------
110
+
111
+ /**
112
+ * Whether the browser shows its own error page instead of the wiki's answer:
113
+ * Chromium aborts every request in flight when the network of the machine
114
+ * changes (a container starting or stopping on it) and shows
115
+ * chrome-error://chromewebdata/. Returns a sentence for an error message, or ''.
116
+ */
117
+ function cutRequest(world) {
118
+ const url = String(world.page.url() || '');
119
+ if (url.startsWith('chrome-error://')) {
120
+ return `the browser shows its own error page (${url}): the request was cut before the wiki answered`;
121
+ }
122
+ return '';
123
+ }
124
+
125
+ /** The hint of a failure where the browser cut the request. */
126
+ const CUT_HINT = 'The browser cut the request (a network change on the machine, such as a container starting); nothing is wrong with the scenario. Run it again. On a shared machine, run the suite in the project\'s container (cmd-tools-testing.sh <project> --run in the Webship Workspace), where the network of the host does not reach.';
127
+
128
+ /**
129
+ * Wait for the page to go quiet after an action: the document is loaded and
130
+ * the wiki's module loader has no module still loading.
131
+ */
132
+ async function settle(world, timeout) {
133
+ const deadline = Date.now() + (timeout || settleBudget(world));
134
+ await world.page.waitForLoadState('load', { timeout: Math.max(deadline - Date.now(), 1) }).catch(() => {});
135
+ await world.page.waitForFunction(() => {
136
+ // The loader is defined in stages while the page starts: read it only once it is whole.
137
+ if (!window.mw || !mw.loader || typeof mw.loader.getModuleNames !== 'function' || typeof mw.loader.getState !== 'function') return document.readyState === 'complete';
138
+ return !mw.loader.getModuleNames().some((name) => mw.loader.getState(name) === 'loading');
139
+ }, null, { timeout: Math.max(deadline - Date.now(), 1) }).catch(() => {});
140
+ }
141
+
142
+ /**
143
+ * Wait until the modules the page asked for (the wiki writes them in RLPAGEMODULES)
144
+ * are ready: `mw.loader.using()` resolved. Returns the modules that failed.
145
+ */
146
+ async function pageModulesReady(world, timeout) {
147
+ const t = timeout || budget(world);
148
+ await world.page.waitForFunction(() => !!(window.mw && mw.loader && typeof mw.loader.using === 'function' && typeof mw.loader.getState === 'function'), null, { timeout: t });
149
+ return world.page.evaluate((ms) => new Promise((resolve) => {
150
+ const modules = (window.RLPAGEMODULES || []).filter((name) => mw.loader.getState(name) !== null);
151
+ const timer = setTimeout(() => resolve(modules.filter((name) => mw.loader.getState(name) !== 'ready').map((name) => `${name} (${mw.loader.getState(name)})`)), ms);
152
+ mw.loader.using(modules).then(() => { clearTimeout(timer); resolve([]); }, () => {
153
+ clearTimeout(timer);
154
+ resolve(modules.filter((name) => mw.loader.getState(name) !== 'ready').map((name) => `${name} (${mw.loader.getState(name)})`));
155
+ });
156
+ }), t);
157
+ }
158
+
159
+ /**
160
+ * Wait until modules of the wiki's module loader are ready (`mw.loader.using()`
161
+ * resolved), loading them if the page has not yet. Fails with the states of the
162
+ * modules that did not get there.
163
+ */
164
+ async function waitForModules(world, modules, { what } = {}) {
165
+ const list = [].concat(modules).filter(Boolean);
166
+ const t = budget(world);
167
+ try {
168
+ await world.page.waitForFunction(() => !!(window.mw && mw.loader && typeof mw.loader.using === 'function' && typeof mw.loader.getState === 'function'), null, { timeout: t });
169
+ } catch {
170
+ throw friendly({ message: `The wiki's scripts did not start on ${world.page.url()} (no module loader). ${cutRequest(world)}`.trim(), hint: cutRequest(world) ? CUT_HINT : 'The page must be a page of the wiki, with JavaScript on.' });
171
+ }
172
+ const failed = await world.page.evaluate(({ names, ms }) => new Promise((resolve) => {
173
+ const known = names.filter((name) => mw.loader.getState(name) !== null);
174
+ const unknown = names.filter((name) => mw.loader.getState(name) === null);
175
+ const timer = setTimeout(() => resolve(names.map((name) => `${name}: ${mw.loader.getState(name)}`)), ms);
176
+ mw.loader.using(known).then(() => { clearTimeout(timer); resolve(unknown.map((name) => `${name}: not registered`)); },
177
+ () => { clearTimeout(timer); resolve(known.map((name) => `${name}: ${mw.loader.getState(name)}`).filter((s) => !/: ready$/.test(s))); });
178
+ }), { names: list, ms: t });
179
+ if (failed.length) {
180
+ throw friendly({
181
+ message: `${what || 'The wiki\'s modules'} did not load: ${failed.join(', ')}.`,
182
+ hint: 'A module that is "not registered" belongs to an extension or a skin the wiki does not have; "error" means its script failed (see the browser console).',
183
+ });
184
+ }
185
+ }
186
+
187
+ /**
188
+ * Opening another page leaves the page on screen: an editor with changes asks
189
+ * "Leave site?" (a beforeunload prompt), and a person who opens another page
190
+ * means to leave. The prompt is accepted; every other dialog is left to
191
+ * webship-js's dialog steps when a scenario set them up, and dismissed otherwise
192
+ * (Playwright's own default).
193
+ */
194
+ function leaveEditorsWithoutAsking(world) {
195
+ const page = world.page;
196
+ if (page.__webshipLeaveHandler) return;
197
+ page.__webshipLeaveHandler = (dialog) => {
198
+ if (world._dialogHandler) return;
199
+ (dialog.type() === 'beforeunload' ? dialog.accept() : dialog.dismiss()).catch(() => {});
200
+ };
201
+ page.on('dialog', page.__webshipLeaveHandler);
202
+ }
203
+
204
+ /**
205
+ * Open a URL and wait for the page to settle. A network change on the machine
206
+ * aborts a navigation once now and then (ERR_NETWORK_CHANGED, or the browser's
207
+ * own error page): the step goes again, once.
208
+ */
209
+ async function open(world, url) {
210
+ leaveEditorsWithoutAsking(world);
211
+ try {
212
+ await gotoUrl(world.page, url);
213
+ } catch (err) {
214
+ if (!/ERR_NETWORK_CHANGED|chrome-error:\/\/chromewebdata|ERR_ABORTED/.test(String(err && err.message))) throw err;
215
+ await world.page.waitForTimeout(500);
216
+ await gotoUrl(world.page, url);
217
+ }
218
+ if (cutRequest(world)) {
219
+ await world.page.waitForTimeout(500);
220
+ await gotoUrl(world.page, url);
221
+ }
222
+ await world.page.waitForSelector('body', { state: 'attached', timeout: budget(world) });
223
+ await settle(world);
224
+ }
225
+
226
+ /** Open a page of the wiki by its title (with parameters such as action=edit). */
227
+ async function openPage(world, title, params) {
228
+ await open(world, indexUrl(world, title, params));
229
+ }
230
+
231
+ /**
232
+ * Run an action that sends a form or follows a link, and wait for the new page:
233
+ * the browser leaves the page it was on and the new one is loaded.
234
+ */
235
+ async function afterNavigation(world, fn) {
236
+ await Promise.all([
237
+ world.page.waitForNavigation({ timeout: budget(world), waitUntil: 'load' }).catch(() => {}),
238
+ fn(),
239
+ ]);
240
+ await world.page.waitForLoadState('load', { timeout: budget(world) }).catch(() => {});
241
+ await settle(world);
242
+ }
243
+
244
+ /**
245
+ * Wait until a locator has (or, with `notCase`, no longer has) a visible match
246
+ * and fail with a friendly error otherwise.
247
+ */
248
+ async function assertPresence(locator, notCase, { label, hint, timeout, found }) {
249
+ try {
250
+ await locator.first().waitFor({ state: notCase ? 'hidden' : 'visible', timeout });
251
+ } catch {
252
+ const seen = found ? await found().catch(() => '') : '';
253
+ throw friendly({
254
+ message: (notCase ? `Expected not to see ${label}, but it is on the page.` : `Expected to see ${label}, but it did not appear within ${timeout} ms.`) + (seen ? ` ${seen}` : ''),
255
+ hint,
256
+ });
257
+ }
258
+ }
259
+
260
+ /** Poll a reading until it satisfies a check, or fail with the last reading. */
261
+ async function eventually(world, read, check, explain, timeout) {
262
+ const deadline = Date.now() + (timeout || budget(world));
263
+ let value;
264
+ for (;;) {
265
+ value = await read();
266
+ if (check(value)) return value;
267
+ if (Date.now() > deadline) throw friendly(explain(value));
268
+ await world.page.waitForTimeout(200);
269
+ }
270
+ }
271
+
272
+ /** The title the page shows (#firstHeading), as a person reads it. */
273
+ async function shownTitle(world) {
274
+ return clean(await world.page.locator('#firstHeading, h1').first().innerText({ timeout: 2000 }).catch(() => ''));
275
+ }
276
+
277
+ /** What the page on screen says about itself, for an error message. */
278
+ async function pageSummary(world) {
279
+ const cut = cutRequest(world);
280
+ if (cut) return cut;
281
+ const heading = await shownTitle(world);
282
+ const action = await config(world, 'wgAction');
283
+ return `the page shows "${heading || '(no heading)'}"${action ? ` (action ${action})` : ''} at ${world.page.url()}`;
284
+ }
285
+
286
+ // ---------------------------------------------------------------------------
287
+ // Messages
288
+ // ---------------------------------------------------------------------------
289
+
290
+ const MESSAGE_SELECTORS = {
291
+ error: '.cdx-message--error, .mw-message-box-error, .errorbox, .permissions-errors, .mw-htmlform-field-error, .oo-ui-fieldLayout-messages .oo-ui-flaggedElement-error',
292
+ warning: '.cdx-message--warning, .mw-message-box-warning, .warningbox, .mw-warning-with-logexcerpt',
293
+ success: '.cdx-message--success, .mw-message-box-success, .successbox, .mw-preferences-messagebox',
294
+ notice: '.postedit, .mw-notification',
295
+ };
296
+
297
+ /** The visible messages of a kind (error, warning, success, notice), each split into its lines. */
298
+ async function messages(world, kind) {
299
+ return world.page.evaluate((selector) => {
300
+ const out = [];
301
+ const boxes = [...document.querySelectorAll(selector)];
302
+ for (const box of boxes) {
303
+ if (boxes.some((other) => other !== box && other.contains(box))) continue;
304
+ const style = getComputedStyle(box);
305
+ const rect = box.getBoundingClientRect();
306
+ if (style.display === 'none' || style.visibility === 'hidden' || (!rect.width && !rect.height)) continue;
307
+ for (const line of (box.innerText || '').split('\n')) {
308
+ const text = line.replace(/[‪-‮‎‏]/g, '').replace(/\s+/g, ' ').trim();
309
+ if (text) out.push(text);
310
+ }
311
+ }
312
+ return out;
313
+ }, MESSAGE_SELECTORS[kind]).catch(() => []);
314
+ }
315
+
316
+ /** Whether a message (or a part of it) is among the lines: the bidi marks and white space are ignored. */
317
+ function hasMessage(lines, expected) {
318
+ const want = clean(expected).toLowerCase();
319
+ const joined = clean(lines.join(' ')).toLowerCase();
320
+ return lines.some((line) => clean(line).toLowerCase().includes(want)) || joined.includes(want);
321
+ }
322
+
323
+ // ---------------------------------------------------------------------------
324
+ // Accounts and sessions
325
+ // ---------------------------------------------------------------------------
326
+
327
+ /**
328
+ * An account of the users registry in cucumber.js (`worldParameters.users`),
329
+ * by the handle a scenario names it with.
330
+ *
331
+ * @returns {{handle: string, username: string, password: string, email: (string|undefined), wikiName: string}}
332
+ */
333
+ function resolveUser(world, handle) {
334
+ const users = (world.parameters && world.parameters.users) || {};
335
+ const entry = users[handle];
336
+ if (!entry) {
337
+ throw friendly({
338
+ message: `The user "${handle}" is not in the users registry. Known users: ${Object.keys(users).join(', ') || '(none)'}.`,
339
+ hint: `Add it to worldParameters.users in cucumber.js: users: { ${handle}: { username: '${handle}', password: process.env.${String(handle).toUpperCase()}_PASSWORD } }. The account itself is created once by the build of the wiki, never by a feature.`,
340
+ });
341
+ }
342
+ if (!entry.username || !entry.password) {
343
+ throw friendly({
344
+ message: `The user "${handle}" has no ${entry.username ? 'password' : 'user name'} in the users registry.`,
345
+ hint: `Set worldParameters.users.${handle}.username and .password in cucumber.js, from environment variables.`,
346
+ });
347
+ }
348
+ return { handle, username: entry.username, password: entry.password, email: entry.email, wikiName: wikiUserName(entry.username) };
349
+ }
350
+
351
+ /** A handle of the users registry stands for its account name; anything else is an account name. */
352
+ function accountName(world, who) {
353
+ const users = (world.parameters && world.parameters.users) || {};
354
+ return users[who] ? resolveUser(world, who).wikiName : wikiUserName(who);
355
+ }
356
+
357
+ // The sessions of the accounts that logged in during this run, by site and
358
+ // account: the cookies of the browser after a login through the form.
359
+ const SESSIONS = new Map();
360
+
361
+ function sessionKey(world, username) {
362
+ return `${siteRoot(world)}|${wikiUserName(username).toLowerCase()}`;
363
+ }
364
+
365
+ function reuseSessions(world) {
366
+ return !(world.parameters && world.parameters.reuseSessions === false);
367
+ }
368
+
369
+ /** The account the page says is signed in (`wgUserName`), or null for a visitor. */
370
+ async function signedInName(world) {
371
+ return config(world, 'wgUserName');
372
+ }
373
+
374
+ const LOGIN_HINT = 'The login page is Special:UserLogin: the fields "Username" and "Password", the box "Keep me logged in" and the button "Log in". Check launchUrl and scriptPath in cucumber.js.';
375
+ const THROTTLE = /too many recent login attempts/i;
376
+
377
+ /**
378
+ * Fill in and send the login form, then read its outcome: the account the next
379
+ * page says is signed in, or the error messages of the login page.
380
+ *
381
+ * @returns {Promise<{name: (string|null), errors: string[]}>}
382
+ */
383
+ async function submitLogin(world, username, password, { remember = false } = {}) {
384
+ await world.page.context().clearCookies();
385
+ world.__sessionKey = null;
386
+ await openPage(world, 'Special:UserLogin');
387
+ const page = world.page;
388
+ try {
389
+ await page.locator('#wpName1').waitFor({ state: 'visible', timeout: budget(world) });
390
+ } catch (err) {
391
+ throw friendly({ message: `The login form did not appear: ${await pageSummary(world)}.`, cause: err, hint: cutRequest(world) ? CUT_HINT : LOGIN_HINT });
392
+ }
393
+ await page.locator('#wpName1').fill(username);
394
+ await page.locator('#wpPassword1').fill(password);
395
+ if (remember) await page.locator('#wpRemember').check();
396
+ await afterNavigation(world, () => page.locator('#wpLoginAttempt').click());
397
+ const cut = cutRequest(world);
398
+ if (cut) return { name: null, errors: [cut], cut: true };
399
+ const name = await signedInName(world);
400
+ const errors = name ? [] : await messages(world, 'error');
401
+ return { name, errors };
402
+ }
403
+
404
+ /** Take over the session an account opened earlier in this run. */
405
+ async function restoreSession(world, user) {
406
+ const key = sessionKey(world, user.username);
407
+ const cookies = SESSIONS.get(key);
408
+ if (!cookies || !reuseSessions(world)) return false;
409
+ const context = world.page.context();
410
+ await context.clearCookies();
411
+ await context.addCookies(cookies);
412
+ await openPage(world, 'Special:BlankPage');
413
+ if ((await signedInName(world)) === user.wikiName) {
414
+ world.__sessionKey = key;
415
+ return true;
416
+ }
417
+ SESSIONS.delete(key);
418
+ await context.clearCookies();
419
+ return false;
420
+ }
421
+
422
+ /**
423
+ * Log in as an account of the users registry, by its handle: take over its
424
+ * session when it has one from earlier in the run, else log in through the
425
+ * form and keep the session for the next scenario.
426
+ */
427
+ async function logInAs(world, handle) {
428
+ const user = resolveUser(world, handle);
429
+ if (await restoreSession(world, user)) return user;
430
+ const outcome = await submitLogin(world, user.username, user.password);
431
+ if (outcome.name !== user.wikiName) {
432
+ const throttled = outcome.errors.some((e) => THROTTLE.test(e));
433
+ throw friendly({
434
+ message: `Could not log in as "${handle}" (${user.username}): ${outcome.name ? `the wiki says "${outcome.name}" is signed in` : listed(outcome.errors)}.`,
435
+ hint: outcome.cut ? CUT_HINT : (throttled
436
+ ? 'The wiki allows 5 failed logins of an account from one address in 5 minutes; a successful login clears the count. Wait 5 minutes, and keep the scenarios that try wrong passwords to accounts the other scenarios do not use.'
437
+ : 'Check the user name and the password of the account in worldParameters.users, and that the build of the wiki created the account (createAndPromote).'),
438
+ });
439
+ }
440
+ if (reuseSessions(world)) {
441
+ const key = sessionKey(world, user.username);
442
+ SESSIONS.set(key, await world.page.context().cookies());
443
+ world.__sessionKey = key;
444
+ }
445
+ return user;
446
+ }
447
+
448
+ /** Forget the session of the browser in the session cache: it ended (a logout). */
449
+ function forgetSession(world) {
450
+ if (world.__sessionKey) SESSIONS.delete(world.__sessionKey);
451
+ world.__sessionKey = null;
452
+ }
453
+
454
+ // ---------------------------------------------------------------------------
455
+ // The editors
456
+ // ---------------------------------------------------------------------------
457
+
458
+ /**
459
+ * Close the visual editor's welcome dialog when it shows ("Welcome to <wiki>"):
460
+ * it opens over the first editor an account opens, and the page behind it is
461
+ * inert until it is closed. "Start editing" keeps the editor that was opened.
462
+ * Waits for the editor's own init module first, which decides whether to show it.
463
+ */
464
+ async function closeWelcomeDialog(world) {
465
+ const page = world.page;
466
+ const hasEditorInit = await page.evaluate(() => !!(window.mw && mw.loader && mw.loader.getState('ext.visualEditor.desktopArticleTarget.init'))).catch(() => false);
467
+ if (!hasEditorInit) return;
468
+ await page.evaluate(() => mw.loader.using('ext.visualEditor.desktopArticleTarget.init')).catch(() => {});
469
+ // The dialog is shown by the module ext.visualEditor.welcome, which the init module loads only
470
+ // when the account has not seen it (its option visualeditor-hidebetawelcome).
471
+ const shown = await page.evaluate(() => {
472
+ const hidden = mw.user && mw.user.options && String(mw.user.options.get('visualeditor-hidebetawelcome')) === '1';
473
+ const state = mw.loader.getState('ext.visualEditor.welcome');
474
+ return !!document.querySelector('.ve-init-mw-welcomeDialog') || (!hidden && state !== 'registered') || ['loading', 'loaded', 'executing'].includes(state);
475
+ }).catch(() => false);
476
+ if (!shown) return;
477
+ const dialog = page.locator('.ve-init-mw-welcomeDialog.oo-ui-window-active');
478
+ await dialog.waitFor({ state: 'visible', timeout: 5000 }).catch(() => {});
479
+ if (await dialog.count()) {
480
+ await dialog.getByRole('button', { name: 'Start editing' }).click();
481
+ await page.waitForFunction(() => !document.querySelector('.ve-init-mw-welcomeDialog.oo-ui-window-active') && !document.querySelector('.mw-page-container[inert]'), null, { timeout: budget(world) }).catch(() => {});
482
+ }
483
+ }
484
+
485
+ /** Whether the visual editor is open on the page. */
486
+ async function visualEditorActive(world) {
487
+ return world.page.evaluate(() => document.documentElement.classList.contains('ve-active') && !!(window.ve && ve.init && ve.init.target && ve.init.target.active)).catch(() => false);
488
+ }
489
+
490
+ /**
491
+ * Count the times a hook of the wiki (mw.hook) fires from now on. The wiki's hooks
492
+ * remember their last firing and replay it to a late listener, so the count starts
493
+ * at what the listener saw at once, and a wait is for a count above it.
494
+ */
495
+ async function countHook(world, name) {
496
+ return world.page.evaluate((hook) => {
497
+ window.__webshipHooks = window.__webshipHooks || {};
498
+ if (!(hook in window.__webshipHooks)) {
499
+ window.__webshipHooks[hook] = 0;
500
+ mw.hook(hook).add(() => { window.__webshipHooks[hook] += 1; });
501
+ }
502
+ return window.__webshipHooks[hook];
503
+ }, name);
504
+ }
505
+
506
+ /** Wait until a hook counted by countHook() fired more than `seen` times. */
507
+ async function waitForHook(world, name, seen, timeout) {
508
+ await world.page.waitForFunction(({ hook, n }) => window.__webshipHooks && window.__webshipHooks[hook] > n, { hook: name, n: seen }, { timeout: timeout || budget(world) * 2 });
509
+ }
510
+
511
+ // ---------------------------------------------------------------------------
512
+ // Files of the pack and of the project
513
+ // ---------------------------------------------------------------------------
514
+
515
+ /**
516
+ * A file a step reads: a path from the project (where cucumber-js runs), else
517
+ * from this pack's own folder, so a feature copied from the pack finds the
518
+ * fixtures that ship with it (tests/fixtures/).
519
+ */
520
+ function fixturePath(file) {
521
+ const candidates = [path.resolve(process.cwd(), file), path.resolve(__dirname, '..', '..', file)];
522
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
523
+ if (!found) {
524
+ throw friendly({ message: `The file "${file}" is not there (looked in ${candidates.join(' and ')}).`, hint: 'Give the path from the project root, for example tests/fixtures/blue-square.png (the pack ships it).' });
525
+ }
526
+ return found;
527
+ }
528
+
529
+ // ---------------------------------------------------------------------------
530
+ // The wiki's API, as the administrator of the users registry
531
+ // ---------------------------------------------------------------------------
532
+
533
+ const API_CLIENTS = new Map();
534
+ const MARKER = '(test page of a scenario)';
535
+
536
+ /** The handle of the account the test-data steps work as (`worldParameters.wikiAdmin`). */
537
+ function adminHandle(world) {
538
+ return (world.parameters && world.parameters.wikiAdmin) || 'administrator';
539
+ }
540
+
541
+ /**
542
+ * A client of the wiki's API, logged in as the administrator of the users
543
+ * registry (action=clientlogin), with its own cookies: the browser's session is
544
+ * never touched. One client per site and account, for the whole run.
545
+ */
546
+ async function adminApi(world) {
547
+ const admin = resolveUser(world, adminHandle(world));
548
+ const key = `${apiUrl(world)}|${admin.wikiName}`;
549
+ if (API_CLIENTS.has(key)) return API_CLIENTS.get(key);
550
+ const { request } = require('playwright');
551
+ const context = await request.newContext({ ignoreHTTPSErrors: true });
552
+ const endpoint = apiUrl(world);
553
+ const call = async (params, { post = false, multipart = null } = {}) => {
554
+ const form = { format: 'json', formatversion: '2', ...params };
555
+ let response;
556
+ for (let attempt = 0; ; attempt += 1) {
557
+ try {
558
+ response = post || multipart
559
+ ? await context.post(endpoint, multipart ? { multipart: { ...form, ...multipart } } : { form })
560
+ : await context.get(endpoint, { params: form });
561
+ break;
562
+ } catch (err) {
563
+ // A network change on the machine cuts a request now and then: go again, twice.
564
+ if (attempt >= 2 || !/ERR_NETWORK_CHANGED|ECONNRESET|socket hang up|ETIMEDOUT/i.test(String(err && err.message))) throw err;
565
+ await new Promise((r) => setTimeout(r, 500));
566
+ }
567
+ }
568
+ const text = await response.text();
569
+ let body;
570
+ try { body = JSON.parse(text); } catch { body = null; }
571
+ if (!body) {
572
+ throw friendly({ message: `The wiki's API at ${endpoint} did not answer with JSON (HTTP ${response.status()}): ${clean(text).slice(0, 160)}`, hint: 'Check launchUrl and scriptPath in cucumber.js: api.php must answer at <launchUrl><scriptPath>/api.php.' });
573
+ }
574
+ return body;
575
+ };
576
+ const tokens = await call({ action: 'query', meta: 'tokens', type: 'login' });
577
+ const login = await call({ action: 'clientlogin', username: admin.username, password: admin.password, logintoken: tokens.query.tokens.logintoken, loginreturnurl: siteRoot(world) + '/' }, { post: true });
578
+ if (!login.clientlogin || login.clientlogin.status !== 'PASS') {
579
+ throw friendly({
580
+ message: `The test-data steps could not log in to the wiki's API as "${adminHandle(world)}" (${admin.username}): ${clean(JSON.stringify(login.clientlogin || login.error || login))}.`,
581
+ hint: 'worldParameters.wikiAdmin names the account the test pages are made and deleted with: an administrator of the users registry, with its password.',
582
+ });
583
+ }
584
+ const csrf = (await call({ action: 'query', meta: 'tokens' })).query.tokens.csrftoken;
585
+ const client = { call, csrf, admin, context };
586
+ API_CLIENTS.set(key, client);
587
+ return client;
588
+ }
589
+
590
+ /** Fail with the API's own error, when it gave one. */
591
+ function apiError(body, what) {
592
+ if (body && body.error) {
593
+ throw friendly({ message: `${what}: the wiki's API refused it (${body.error.code}: ${clean(body.error.info)}).`, hint: 'The test-data steps work as worldParameters.wikiAdmin: it needs the rights of an administrator (sysop).' });
594
+ }
595
+ return body;
596
+ }
597
+
598
+ /** What the API says about a page: whether it is there, its latest revision, its protection. */
599
+ async function pageInfo(world, title) {
600
+ const api = await adminApi(world);
601
+ const body = apiError(await api.call({ action: 'query', titles: titleText(title), prop: 'info|revisions', inprop: 'protection', rvprop: 'ids|user|comment|content', rvslots: 'main' }), `Reading the page "${title}"`);
602
+ const page = body.query.pages[0];
603
+ const rev = page.revisions && page.revisions[0];
604
+ return {
605
+ exists: !page.missing && !page.invalid,
606
+ title: page.title,
607
+ protection: page.protection || [],
608
+ revision: rev ? { id: rev.revid, user: rev.user, comment: rev.comment || '', text: rev.slots && rev.slots.main ? rev.slots.main.content : '' } : null,
609
+ };
610
+ }
611
+
612
+ /** Make or change a page as the administrator. */
613
+ async function apiEdit(world, title, text, summary) {
614
+ const api = await adminApi(world);
615
+ return apiError(await api.call({ action: 'edit', title: titleText(title), text, summary, token: api.csrf, bot: '0' }, { post: true }), `Saving the page "${title}"`);
616
+ }
617
+
618
+ /** Delete a page as the administrator; a page that is not there is skipped. */
619
+ async function apiDelete(world, title, reason) {
620
+ const api = await adminApi(world);
621
+ const body = await api.call({ action: 'delete', title: titleText(title), reason: reason || 'Cleanup after a test scenario', token: api.csrf }, { post: true });
622
+ if (body.error && body.error.code === 'missingtitle') return false;
623
+ apiError(body, `Deleting the page "${title}"`);
624
+ return true;
625
+ }
626
+
627
+ /** Protect a page as the administrator: level '' (all users), 'autoconfirmed' or 'sysop'. */
628
+ async function apiProtect(world, title, level) {
629
+ const api = await adminApi(world);
630
+ return apiError(await api.call({ action: 'protect', title: titleText(title), protections: `edit=${level || 'all'}|move=${level || 'all'}`, expiry: 'infinite|infinite', reason: `Test page of a scenario ${MARKER}`, token: api.csrf }, { post: true }), `Protecting the page "${title}"`);
631
+ }
632
+
633
+ /** Upload a file as the administrator, whatever the warnings. */
634
+ async function apiUpload(world, fileName, localFile, comment) {
635
+ const api = await adminApi(world);
636
+ return apiError(await api.call({ action: 'upload', filename: fileName, comment: comment || `Test file of a scenario ${MARKER}`, ignorewarnings: '1', token: api.csrf }, { multipart: { file: { name: path.basename(localFile), mimeType: 'application/octet-stream', buffer: fs.readFileSync(localFile) } } }), `Uploading the file "${fileName}"`);
637
+ }
638
+
639
+ /** The blocks of an account (API list=blocks). */
640
+ async function apiBlocks(world, name) {
641
+ const api = await adminApi(world);
642
+ const body = apiError(await api.call({ action: 'query', list: 'blocks', bkusers: wikiUserName(name), bkprop: 'id|user|expiry|reason|flags' }), `Reading the blocks of "${name}"`);
643
+ return body.query.blocks || [];
644
+ }
645
+
646
+ /** Lift the block of an account as the administrator; an account without one is skipped. */
647
+ async function apiUnblock(world, name, reason) {
648
+ if (!(await apiBlocks(world, name)).length) return false;
649
+ const api = await adminApi(world);
650
+ apiError(await api.call({ action: 'unblock', user: wikiUserName(name), reason: reason || 'Cleanup after a test scenario', token: api.csrf }, { post: true }), `Unblocking "${name}"`);
651
+ return true;
652
+ }
653
+
654
+ /**
655
+ * Wait until the wiki's job queue is empty (API siteinfo statistics.jobs): the
656
+ * category counts and the links tables are written by jobs, and the category
657
+ * tree reads them. Returns the jobs left when the budget ran out.
658
+ */
659
+ async function waitForJobs(world, timeout) {
660
+ const api = await adminApi(world);
661
+ const deadline = Date.now() + (timeout || budget(world));
662
+ let jobs = 0;
663
+ for (;;) {
664
+ const body = await api.call({ action: 'query', meta: 'siteinfo', siprop: 'statistics' });
665
+ jobs = body.query && body.query.statistics ? body.query.statistics.jobs : 0;
666
+ if (!jobs || Date.now() > deadline) return jobs;
667
+ await new Promise((r) => setTimeout(r, 300));
668
+ }
669
+ }
670
+
671
+ /**
672
+ * Wait until the counts of categories (API prop=categoryinfo: its size and its
673
+ * subcategories) match their members (list=categorymembers). A page saved in a
674
+ * category is listed at once, but the counts are written by a job of the wiki,
675
+ * and the category tree offers a toggle only from them. (The job queue's size in
676
+ * siteinfo is no signal for this: it is cached, and one waiting job reads 0.)
677
+ * Returns the categories whose counts still differ when the budget ran out.
678
+ */
679
+ async function waitForCategoryCounts(world, categories, timeout) {
680
+ const names = [...new Set((categories || []).map((c) => titleText(String(c).replace(/^Category:/i, ''))).filter(Boolean))];
681
+ if (!names.length) return [];
682
+ const api = await adminApi(world);
683
+ const deadline = Date.now() + (timeout || budget(world) * 2);
684
+ let behind = names;
685
+ for (;;) {
686
+ const still = [];
687
+ for (const name of behind) {
688
+ const info = await api.call({ action: 'query', titles: `Category:${name}`, prop: 'categoryinfo' });
689
+ const page = info.query && info.query.pages && info.query.pages[0];
690
+ const counts = (page && page.categoryinfo) || { size: 0, subcats: 0 };
691
+ const members = await api.call({ action: 'query', list: 'categorymembers', cmtitle: `Category:${name}`, cmprop: 'type', cmlimit: 'max' });
692
+ const list = (members.query && members.query.categorymembers) || [];
693
+ const subcats = list.filter((m) => m.type === 'subcat').length;
694
+ if (counts.size !== list.length || counts.subcats !== subcats) still.push(name);
695
+ }
696
+ behind = still;
697
+ if (!behind.length || Date.now() > deadline) return behind;
698
+ await new Promise((r) => setTimeout(r, 300));
699
+ }
700
+ }
701
+
702
+ /** The categories wikitext puts a page in ([[Category:Name]] links). */
703
+ function categoriesOf(wikitext) {
704
+ return [...String(wikitext || '').matchAll(/\[\[\s*Category\s*:\s*([^\]|#]+)/gi)].map((m) => m[1].trim());
705
+ }
706
+
707
+ module.exports = {
708
+ budget,
709
+ settleBudget,
710
+ escapeRegExp,
711
+ clean,
712
+ listed,
713
+ titleKey,
714
+ titleText,
715
+ wikiUserName,
716
+ siteRoot,
717
+ scriptPath,
718
+ skinParam,
719
+ indexUrl,
720
+ apiUrl,
721
+ config,
722
+ cutRequest,
723
+ CUT_HINT,
724
+ settle,
725
+ pageModulesReady,
726
+ waitForModules,
727
+ open,
728
+ openPage,
729
+ afterNavigation,
730
+ assertPresence,
731
+ eventually,
732
+ shownTitle,
733
+ pageSummary,
734
+ MESSAGE_SELECTORS,
735
+ messages,
736
+ hasMessage,
737
+ resolveUser,
738
+ accountName,
739
+ SESSIONS,
740
+ sessionKey,
741
+ reuseSessions,
742
+ signedInName,
743
+ LOGIN_HINT,
744
+ THROTTLE,
745
+ submitLogin,
746
+ restoreSession,
747
+ logInAs,
748
+ forgetSession,
749
+ closeWelcomeDialog,
750
+ visualEditorActive,
751
+ countHook,
752
+ waitForHook,
753
+ fixturePath,
754
+ MARKER,
755
+ adminHandle,
756
+ adminApi,
757
+ apiError,
758
+ pageInfo,
759
+ apiEdit,
760
+ apiDelete,
761
+ apiProtect,
762
+ apiUpload,
763
+ apiBlocks,
764
+ apiUnblock,
765
+ waitForJobs,
766
+ waitForCategoryCounts,
767
+ categoriesOf,
768
+ };