@webship-js/django-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.
@@ -0,0 +1,1198 @@
1
+ 'use strict';
2
+
3
+ // Shared plumbing of the admin steps: addresses, the request the browser cut,
4
+ // opening a page and waiting for the admin's own scripts, messages, the users
5
+ // registry and the session cache, the form fields found by their labels, the
6
+ // change list, the inline rows, and the test-data client that makes and
7
+ // deletes the test objects as the data administrator of the users registry.
8
+ //
9
+ // This file registers no step. The admin draws its pages on the server: an
10
+ // action is a page load, and the few widgets that work in the browser (the
11
+ // autocomplete field, the two-list selector, the date shortcuts, the inline
12
+ // rows, the collapsible sections) are set up by the admin's scripts once the
13
+ // page has loaded. The steps wait for that load and for the answer of the
14
+ // request a widget sends, never for a fixed time.
15
+
16
+ const { gotoUrl, friendly } = require('webship-js/tests/step-definitions/webship');
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Budgets and text
20
+ // ---------------------------------------------------------------------------
21
+
22
+ /** The per-assertion wait budget: `minWaitTime.page` from cucumber.js, at least 10 seconds. */
23
+ function budget(world) {
24
+ return Math.max((world && world.minWaitTime && world.minWaitTime.page) || 0, 10000);
25
+ }
26
+
27
+ /** White space collapsed and trimmed; the invisible marks some texts carry removed. */
28
+ function clean(text) {
29
+ return String(text === null || text === undefined ? '' : text).replace(/[­​-‏‪-‮⁠]/g, '').replace(/\s+/g, ' ').trim();
30
+ }
31
+
32
+ /**
33
+ * A text as a comparison sees it: cleaned, in lower case, the typographic
34
+ * quotes and apostrophes (“ ” ‘ ’, which the admin writes in its messages)
35
+ * the same as the straight ones, and a label's closing colon dropped.
36
+ */
37
+ function normal(text) {
38
+ return clean(text).replace(/[“”„"]/g, '"').replace(/[‘’‚']/g, "'").replace(/["']/g, "'").replace(/\s*:$/, '').toLowerCase();
39
+ }
40
+
41
+ /** Whether a text contains another, as `normal` reads them. */
42
+ function mentions(text, part) {
43
+ return normal(text).includes(normal(part));
44
+ }
45
+
46
+ /** A list for an error message: `"a", "b", "c"` or `(none)`. */
47
+ function listed(values) {
48
+ const items = [...new Set((values || []).map(clean).filter(Boolean))];
49
+ return items.length ? items.map((item) => `"${item}"`).join(', ') : '(none)';
50
+ }
51
+
52
+ /** Escape a literal string for use in a RegExp. */
53
+ function escapeRegExp(text) {
54
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
55
+ }
56
+
57
+ /** The entities the server writes in a page, decoded. */
58
+ function decodeEntities(text) {
59
+ return String(text)
60
+ .replace(/&#x([0-9a-f]+);/gi, (m, hex) => String.fromCodePoint(parseInt(hex, 16)))
61
+ .replace(/&#(\d+);/g, (m, dec) => String.fromCodePoint(parseInt(dec, 10)))
62
+ .replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&nbsp;/g, ' ')
63
+ .replace(/&amp;/g, '&');
64
+ }
65
+
66
+ /** The text of an HTML fragment: tags dropped, entities decoded. */
67
+ function htmlText(html) {
68
+ return clean(decodeEntities(String(html).replace(/<[^>]*>/g, ' ')));
69
+ }
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // Addresses
73
+ // ---------------------------------------------------------------------------
74
+
75
+ /** The site root without a trailing slash. */
76
+ function siteRoot(world) {
77
+ return String(world.launchUrl || (world.parameters && world.parameters.launchUrl) || '').replace(/\/+$/, '');
78
+ }
79
+
80
+ /** The path of the admin (`worldParameters.adminPath`, /admin/ by default), with its slashes. */
81
+ function adminPath(world) {
82
+ const value = String((world.parameters && world.parameters.adminPath) || '/admin/').trim();
83
+ return '/' + value.replace(/^\/+|\/+$/g, '') + '/';
84
+ }
85
+
86
+ /** An address under the admin: `adminUrl(world, 'login/')`. */
87
+ function adminUrl(world, rel = '') {
88
+ return siteRoot(world) + adminPath(world) + String(rel).replace(/^\/+/, '');
89
+ }
90
+
91
+ /** An address of the site from a path the page or a step gave (absolute URLs stay as they are). */
92
+ function absolute(world, href) {
93
+ if (/^https?:\/\//.test(href)) return href;
94
+ return siteRoot(world) + (String(href).startsWith('/') ? '' : '/') + href;
95
+ }
96
+
97
+ /** A path or an address without its query string. */
98
+ function withoutQuery(href) {
99
+ return String(href).split('?')[0].split('#')[0];
100
+ }
101
+
102
+ // ---------------------------------------------------------------------------
103
+ // The request the browser cut, opening a page, waiting
104
+ // ---------------------------------------------------------------------------
105
+
106
+ /**
107
+ * Whether the browser shows its own error page instead of the site's answer:
108
+ * Chromium aborts every request in flight when the network of the machine
109
+ * changes (a container starting or stopping on it) and shows
110
+ * chrome-error://chromewebdata/. Returns a sentence for an error message, or ''.
111
+ */
112
+ function cutRequest(world) {
113
+ const url = String((world.page && world.page.url()) || '');
114
+ if (url.startsWith('chrome-error://')) {
115
+ return `the browser shows its own error page (${url}): the request was cut before the site answered`;
116
+ }
117
+ return '';
118
+ }
119
+
120
+ /** The hint of a failure where the browser cut the request. */
121
+ const CUT_HINT = 'The request was cut, or the site\'s name did not resolve, because the network of the machine changed (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.';
122
+
123
+ /** The hint for a failure: the cut request's when the browser cut it, else the one given. */
124
+ function hintFor(world, hint) {
125
+ return cutRequest(world) ? CUT_HINT : hint;
126
+ }
127
+
128
+ /**
129
+ * Wait until the admin page is ready to use: the document has loaded (the
130
+ * admin's scripts set the widgets up on the load event: the date shortcuts,
131
+ * the two-list selectors, the inline rows' links) and the autocomplete fields
132
+ * are drawn.
133
+ */
134
+ async function adminReady(page, timeout) {
135
+ await page.waitForLoadState('load', { timeout }).catch(() => {});
136
+ await page.waitForFunction(() => {
137
+ if (document.readyState !== 'complete') return false;
138
+ // An autocomplete field (select2) is ready once its box is drawn next to it.
139
+ for (const select of document.querySelectorAll('select.admin-autocomplete')) {
140
+ if (select.closest('.empty-form')) continue;
141
+ if (!select.classList.contains('select2-hidden-accessible')) return false;
142
+ }
143
+ // A two-list selector is ready once its "available" list is drawn.
144
+ for (const select of document.querySelectorAll('select.selectfilter, select.selectfilterstacked')) {
145
+ if (select.closest('.empty-form')) continue;
146
+ if (!document.getElementById(select.id + '_from')) return false;
147
+ }
148
+ return true;
149
+ }, null, { timeout }).catch(() => {});
150
+ }
151
+
152
+ /**
153
+ * Open a URL and wait for the admin page to be ready. A network change on the
154
+ * machine aborts a navigation once now and then (ERR_NETWORK_CHANGED, or the
155
+ * browser's own error page): the step goes again, once.
156
+ *
157
+ * @returns {Promise<import('playwright').Response|null>} the answer of the server, when the browser gives it.
158
+ */
159
+ async function open(world, url) {
160
+ const page = world.page;
161
+ const go = () => page.goto(url, { waitUntil: 'domcontentloaded' });
162
+ let response = null;
163
+ try {
164
+ response = await go();
165
+ } catch (err) {
166
+ if (/ERR_NETWORK_CHANGED|chrome-error:\/\/chromewebdata|ERR_ABORTED/.test(String(err && err.message))) {
167
+ await page.waitForTimeout(500);
168
+ response = await go();
169
+ } else {
170
+ // webship-js's own words for a refused connection or an unknown host.
171
+ await gotoUrl(page, url);
172
+ }
173
+ }
174
+ if (cutRequest(world)) {
175
+ await page.waitForTimeout(500);
176
+ response = await go().catch(() => null);
177
+ }
178
+ await adminReady(page, budget(world));
179
+ return response;
180
+ }
181
+
182
+ /**
183
+ * Run an action that sends a form or follows a link, and wait for the new
184
+ * page: the browser leaves the page it was on and the new one is ready. When
185
+ * a network change on the machine cut the request (the browser shows its own
186
+ * error page), the step fails and says so, unless `cut: 'return'` asks the
187
+ * caller to decide (a login is sent again).
188
+ */
189
+ async function afterNavigation(world, fn, { cut = 'fail' } = {}) {
190
+ const page = world.page;
191
+ await Promise.all([
192
+ page.waitForNavigation({ timeout: budget(world), waitUntil: 'load' }).catch(() => {}),
193
+ fn(),
194
+ ]);
195
+ await adminReady(page, budget(world));
196
+ if (cut === 'fail' && cutRequest(world)) {
197
+ throw friendly({ message: `The page did not load: ${cutRequest(world)}.`, hint: CUT_HINT });
198
+ }
199
+ }
200
+
201
+ /** The main heading of the page, as a person reads it. */
202
+ async function heading(page) {
203
+ return clean(await page.locator('#content h1, h1').first().innerText({ timeout: 2000 }).catch(() => ''));
204
+ }
205
+
206
+ /** What the page on screen says about itself, for an error message. */
207
+ async function pageSummary(world) {
208
+ const cut = cutRequest(world);
209
+ if (cut) return cut;
210
+ const page = world.page;
211
+ const title = clean(await page.title().catch(() => ''));
212
+ const h1 = await heading(page);
213
+ return `the page shows "${h1 || '(no heading)'}" (title "${title}") at ${page.url()}`;
214
+ }
215
+
216
+ /** Poll a reading until it satisfies a check, or fail with the last reading. */
217
+ async function eventually(world, read, check, explain, timeout) {
218
+ const deadline = Date.now() + (timeout || budget(world));
219
+ let value;
220
+ for (;;) {
221
+ value = await read();
222
+ if (check(value)) return value;
223
+ if (Date.now() > deadline) throw friendly(await explain(value));
224
+ await world.page.waitForTimeout(150);
225
+ }
226
+ }
227
+
228
+ // ---------------------------------------------------------------------------
229
+ // Messages
230
+ // ---------------------------------------------------------------------------
231
+
232
+ /** The messages the admin shows (`ul.messagelist`), of one kind or all: success, warning, error, info. */
233
+ async function messages(page, kind) {
234
+ const selector = kind && kind !== 'any' ? `ul.messagelist li.${kind}` : 'ul.messagelist li';
235
+ return (await page.locator(selector).allTextContents().catch(() => [])).map(clean).filter(Boolean);
236
+ }
237
+
238
+ /** The error note above a form ("Please correct the errors below.") and the errors of the whole form. */
239
+ async function formErrors(page) {
240
+ const note = (await page.locator('#content .errornote').allTextContents().catch(() => [])).map(clean);
241
+ const general = (await page.locator('#content form ul.errorlist.nonfield li, #content form > div > ul.errorlist li').allTextContents().catch(() => [])).map(clean);
242
+ return [...note, ...general].filter(Boolean);
243
+ }
244
+
245
+ // ---------------------------------------------------------------------------
246
+ // Accounts and sessions
247
+ // ---------------------------------------------------------------------------
248
+
249
+ /**
250
+ * An account of the users registry in cucumber.js (`worldParameters.users`),
251
+ * by the handle a scenario names it with.
252
+ *
253
+ * @returns {{handle: string, username: string, password: string, email: (string|undefined)}}
254
+ */
255
+ function resolveUser(world, handle) {
256
+ const users = (world.parameters && world.parameters.users) || {};
257
+ const entry = users[handle];
258
+ if (!entry) {
259
+ throw friendly({
260
+ message: `The user "${handle}" is not in the users registry. Known users: ${Object.keys(users).join(', ') || '(none)'}.`,
261
+ hint: `Add it to worldParameters.users in cucumber.js: users: { ${handle}: { username: '${handle}', password: process.env.${String(handle).toUpperCase()}_PASSWORD } }. The account itself is made once by the build of the site, never by a feature.`,
262
+ });
263
+ }
264
+ if (!entry.username || !entry.password) {
265
+ throw friendly({
266
+ message: `The user "${handle}" has no ${entry.username ? 'password' : 'user name'} in the users registry.`,
267
+ hint: `Set worldParameters.users.${handle}.username and .password in cucumber.js, from environment variables.`,
268
+ });
269
+ }
270
+ return { handle, username: entry.username, password: entry.password, email: entry.email };
271
+ }
272
+
273
+ /** A handle of the users registry stands for its user name; anything else is a user name. */
274
+ function userName(world, who) {
275
+ const users = (world.parameters && world.parameters.users) || {};
276
+ return users[who] ? resolveUser(world, who).username : who;
277
+ }
278
+
279
+ // The sessions of the accounts that logged in during this run, by site and
280
+ // account: the cookies of the browser after a login through the form.
281
+ const SESSIONS = new Map();
282
+
283
+ function sessionKey(world, username) {
284
+ return `${siteRoot(world)}|${String(username).toLowerCase()}`;
285
+ }
286
+
287
+ function reuseSessions(world) {
288
+ return !(world.parameters && world.parameters.reuseSessions === false);
289
+ }
290
+
291
+ /** The name the admin greets the signed-in account with ("Welcome, editor."), or null. */
292
+ async function signedInName(page) {
293
+ if (!(await page.locator('#logout-form, #user-tools').count().catch(() => 0))) return null;
294
+ const name = await page.locator('#user-tools strong').first().textContent({ timeout: 2000 }).catch(() => ''); // textContent: the admin's CSS writes the name in capitals
295
+ return clean(name) || null;
296
+ }
297
+
298
+ const LOGIN_HINT = 'The admin login page has the fields "Username" and "Password" and the button "Log in". Check launchUrl and adminPath in cucumber.js, and that the account is staff (only staff accounts may log in to the admin).';
299
+
300
+ /**
301
+ * Fill in and send the admin login form, then read its outcome: the name the
302
+ * next page greets, or the error the login page shows.
303
+ *
304
+ * @returns {Promise<{name: (string|null), errors: string[], cut: boolean}>}
305
+ */
306
+ async function submitLogin(world, username, password, again = true) {
307
+ const page = world.page;
308
+ await page.context().clearCookies();
309
+ world.__djangoSession = null;
310
+ await open(world, adminUrl(world, 'login/?next=' + encodeURIComponent(adminPath(world))));
311
+ try {
312
+ await page.locator('#login-form input[name="username"]').waitFor({ state: 'visible', timeout: budget(world) });
313
+ } catch (err) {
314
+ throw friendly({ message: `The admin login form did not appear: ${await pageSummary(world)}.`, cause: err, hint: hintFor(world, LOGIN_HINT) });
315
+ }
316
+ await page.locator('#login-form input[name="username"]').fill(username);
317
+ await page.locator('#login-form input[name="password"]').fill(password);
318
+ await afterNavigation(world, () => page.locator('#login-form [type="submit"]').first().click(), { cut: 'return' });
319
+ if (cutRequest(world)) {
320
+ // A network change on the machine cut the request: a login can be sent again, once.
321
+ if (again) return submitLogin(world, username, password, false);
322
+ return { name: null, errors: [cutRequest(world)], cut: true };
323
+ }
324
+ const name = await signedInName(page);
325
+ const errors = name ? [] : await formErrors(page);
326
+ return { name, errors, cut: false };
327
+ }
328
+
329
+ /** Take over the session an account opened earlier in this run. */
330
+ async function restoreSession(world, user) {
331
+ const key = sessionKey(world, user.username);
332
+ const cookies = SESSIONS.get(key);
333
+ if (!cookies || !reuseSessions(world)) return false;
334
+ const context = world.page.context();
335
+ await context.clearCookies();
336
+ await context.addCookies(cookies);
337
+ await open(world, adminUrl(world));
338
+ const name = await signedInName(world.page);
339
+ if (name && name.toLowerCase() === user.username.toLowerCase()) {
340
+ world.__djangoSession = key;
341
+ world.__djangoUser = user;
342
+ return true;
343
+ }
344
+ SESSIONS.delete(key);
345
+ await context.clearCookies();
346
+ return false;
347
+ }
348
+
349
+ /**
350
+ * Log in as an account of the users registry, by its handle: take over its
351
+ * session when it has one from earlier in the run, else log in through the
352
+ * form and keep the session for the next scenario.
353
+ */
354
+ async function logInAs(world, handle) {
355
+ const user = resolveUser(world, handle);
356
+ if (await restoreSession(world, user)) return user;
357
+ const outcome = await submitLogin(world, user.username, user.password);
358
+ if (!outcome.name) {
359
+ throw friendly({
360
+ message: `Could not log in to the admin as "${handle}" (${user.username}): ${listed(outcome.errors)}.`,
361
+ hint: outcome.cut ? CUT_HINT : 'Check the user name and the password of the account in worldParameters.users, and that the build of the site made it a staff account.',
362
+ });
363
+ }
364
+ world.__djangoUser = user;
365
+ if (reuseSessions(world)) {
366
+ const key = sessionKey(world, user.username);
367
+ SESSIONS.set(key, await world.page.context().cookies());
368
+ world.__djangoSession = key;
369
+ }
370
+ return user;
371
+ }
372
+
373
+ /** Forget the session of the browser in the session cache (it ended), or every session of an account. */
374
+ function forgetSession(world, username) {
375
+ if (username) SESSIONS.delete(sessionKey(world, username));
376
+ if (world.__djangoSession) SESSIONS.delete(world.__djangoSession);
377
+ world.__djangoSession = null;
378
+ }
379
+
380
+ /** The account of the registry this scenario logged in as, or a failure that says to log in first. */
381
+ function currentUser(world) {
382
+ if (world.__djangoUser) return world.__djangoUser;
383
+ throw friendly({
384
+ message: 'No account of the users registry is logged in in this scenario.',
385
+ hint: 'Log in first: Given I am a logged in user with the "editor" user',
386
+ });
387
+ }
388
+
389
+ // ---------------------------------------------------------------------------
390
+ // The models of the admin
391
+ // ---------------------------------------------------------------------------
392
+
393
+ // The address of each model's list, by site, app and plural name, as the
394
+ // admin index lists them: read once per run.
395
+ const MODEL_URLS = new Map();
396
+
397
+ /**
398
+ * The models of an admin index page: app name, model name and the address of
399
+ * its list (the admin draws the same index for every release line).
400
+ *
401
+ * @param {string} html
402
+ * @returns {Array<{app: string, model: string, href: string, add: (string|null)}>}
403
+ */
404
+ function modelsOfIndex(html) {
405
+ const found = [];
406
+ const blocks = String(html).split(/<div class="app-/).slice(1);
407
+ for (const block of blocks) {
408
+ const caption = block.match(/<caption>\s*<a [^>]*>([\s\S]*?)<\/a>/);
409
+ const app = caption ? htmlText(caption[1]) : '';
410
+ const rows = block.match(/<tr class="model-[^"]*">[\s\S]*?<\/tr>/g) || [];
411
+ for (const row of rows) {
412
+ const link = row.match(/<th scope="row"[^>]*>\s*<a href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/);
413
+ if (!link) continue;
414
+ const add = row.match(/<a href="([^"]+)"[^>]*class="addlink"/);
415
+ found.push({ app, model: htmlText(link[2]), href: decodeEntities(link[1]), add: add ? decodeEntities(add[1]) : null });
416
+ }
417
+ }
418
+ return found;
419
+ }
420
+
421
+ /**
422
+ * The address of a model's list, by the model's name as the index shows it
423
+ * ("Questions"), with the app's name when two apps have a model of that name.
424
+ * Read from the index the data administrator sees, which lists every model.
425
+ */
426
+ async function modelListUrl(world, model, app) {
427
+ const key = `${siteRoot(world)}|${normal(app || '')}|${normal(model)}`;
428
+ if (MODEL_URLS.has(key)) return MODEL_URLS.get(key);
429
+ const client = await dataClient(world);
430
+ const index = await client.get(adminUrl(world));
431
+ const models = modelsOfIndex(index.html);
432
+ const matches = models.filter((m) => normal(m.model) === normal(model) && (!app || normal(m.app) === normal(app)));
433
+ if (matches.length !== 1) {
434
+ throw friendly({
435
+ message: matches.length
436
+ ? `More than one app has a model "${model}": ${listed(matches.map((m) => `${m.model} of ${m.app}`))}.`
437
+ : `The admin index lists no model "${model}"${app ? ` in the app "${app}"` : ''}. It lists: ${listed(models.map((m) => `${m.model} (${m.app})`))}.`,
438
+ hint: matches.length ? `Name the app too: the "${model}" list of "${matches[0].app}".` : 'Write the model the way the admin index shows it: its plural name, such as "Questions" or "Users".',
439
+ });
440
+ }
441
+ const url = absolute(world, matches[0].href);
442
+ MODEL_URLS.set(key, url);
443
+ return url;
444
+ }
445
+
446
+ // ---------------------------------------------------------------------------
447
+ // The test-data client: the admin's own pages, as the data administrator
448
+ // ---------------------------------------------------------------------------
449
+
450
+ const CLIENTS = new Map();
451
+
452
+ /** The handle of the account the test-data steps work as (`worldParameters.dataAdmin`, a superuser). */
453
+ function dataAdminHandle(world) {
454
+ return (world.parameters && world.parameters.dataAdmin) || 'administrator';
455
+ }
456
+
457
+ /** The token a form of the admin carries against cross-site requests. */
458
+ function csrfOf(html) {
459
+ const m = String(html).match(/name="csrfmiddlewaretoken" value="([^"]+)"/);
460
+ return m ? m[1] : null;
461
+ }
462
+
463
+ /**
464
+ * A client of the admin's own pages, logged in as the data administrator of
465
+ * the users registry, with cookies of its own: the browser's session is never
466
+ * touched. It reads pages and sends their forms the way the browser does
467
+ * (the token of the form, the page it was sent from). One client per site
468
+ * and account, for the whole run.
469
+ */
470
+ async function dataClient(world) {
471
+ const admin = resolveUser(world, dataAdminHandle(world));
472
+ const key = `${siteRoot(world)}|${admin.username}`;
473
+ if (CLIENTS.has(key)) return CLIENTS.get(key);
474
+ const { request } = require('playwright');
475
+ const context = await request.newContext({ ignoreHTTPSErrors: true });
476
+ const retrying = async (fn) => {
477
+ for (let attempt = 0; ; attempt += 1) {
478
+ try {
479
+ return await fn();
480
+ } catch (err) {
481
+ // A network change on the machine cuts a request now and then, or the site's name does not
482
+ // resolve for a moment (a container network starting): go again, four times, waiting longer
483
+ // each time; then say what happened.
484
+ const passing = /ERR_NETWORK_CHANGED|ECONNRESET|socket hang up|ETIMEDOUT|EPIPE|EAI_AGAIN/i.test(String(err && err.message));
485
+ if (passing && attempt < 4) {
486
+ await new Promise((r) => setTimeout(r, 500 * 2 ** attempt));
487
+ continue;
488
+ }
489
+ if (passing) {
490
+ throw friendly({ message: `The test-data steps could not reach the site: ${String(err.message).split('\n')[0]}.`, cause: err, hint: CUT_HINT });
491
+ }
492
+ throw err;
493
+ }
494
+ }
495
+ };
496
+ const get = async (url) => {
497
+ const response = await retrying(() => context.get(url, { failOnStatusCode: false }));
498
+ return { status: response.status(), url: response.url(), html: await response.text() };
499
+ };
500
+ const post = async (url, form) => {
501
+ const page = await get(url);
502
+ const token = csrfOf(page.html);
503
+ if (!token) {
504
+ throw friendly({ message: `The test-data client found no form on ${url} (HTTP ${page.status}, now at ${page.url}).`, hint: `The test-data steps work as worldParameters.dataAdmin ("${dataAdminHandle(world)}"): a superuser of the users registry, with its password.` });
505
+ }
506
+ const response = await retrying(() => context.post(url, {
507
+ form: { csrfmiddlewaretoken: token, ...form },
508
+ headers: { Referer: url },
509
+ failOnStatusCode: false,
510
+ }));
511
+ return { status: response.status(), url: response.url(), html: await response.text(), before: page };
512
+ };
513
+ const login = adminUrl(world, 'login/?next=' + encodeURIComponent(adminPath(world)));
514
+ const answer = await post(login, { username: admin.username, password: admin.password, next: adminPath(world) });
515
+ if (!/id="logout-form"|id="user-tools"/.test(answer.html)) {
516
+ const note = answer.html.match(/<p class="errornote">([\s\S]*?)<\/p>/);
517
+ throw friendly({
518
+ message: `The test-data steps could not log in to the admin as "${dataAdminHandle(world)}" (${admin.username}): ${note ? htmlText(note[1]) : `HTTP ${answer.status} at ${answer.url}`}.`,
519
+ hint: 'worldParameters.dataAdmin names the account the test objects are made and deleted with: a superuser of the users registry, with its password.',
520
+ });
521
+ }
522
+ const client = { get, post, context, admin };
523
+ CLIENTS.set(key, client);
524
+ return client;
525
+ }
526
+
527
+ /** Close the test-data clients at the end of the run. */
528
+ async function closeClients() {
529
+ for (const client of CLIENTS.values()) await client.context.dispose().catch(() => {});
530
+ CLIENTS.clear();
531
+ }
532
+
533
+ /** The objects a change list page shows: their text and the address of each one's page. */
534
+ function objectsOfList(html) {
535
+ const found = [];
536
+ const table = String(html).match(/<table id="result_list">([\s\S]*?)<\/table>/);
537
+ if (!table) return found;
538
+ const rows = table[1].match(/<tr[^>]*>[\s\S]*?<\/tr>/g) || [];
539
+ for (const row of rows) {
540
+ const link = row.match(/<(?:th|td) class="field-[^"]*"[^>]*>\s*<a href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/);
541
+ if (link) found.push({ text: htmlText(link[2]), href: withoutQuery(decodeEntities(link[1])) });
542
+ }
543
+ return found;
544
+ }
545
+
546
+ /**
547
+ * The objects of a model's list whose text is exactly the one given, found
548
+ * with the list's own search when it has one (and on every page otherwise),
549
+ * as the data administrator.
550
+ */
551
+ async function findObjects(world, model, text, app) {
552
+ const client = await dataClient(world);
553
+ const list = await modelListUrl(world, model, app);
554
+ const hits = [];
555
+ for (let page = 1; page <= 50; page += 1) {
556
+ const url = `${list}?q=${encodeURIComponent(text)}${page > 1 ? `&p=${page}` : ''}`;
557
+ const answer = await client.get(url);
558
+ const objects = objectsOfList(answer.html);
559
+ for (const o of objects) if (normal(o.text) === normal(text)) hits.push(absolute(world, o.href));
560
+ const pages = answer.html.match(/[?&]p=(\d+)/g) || [];
561
+ const last = Math.max(1, ...pages.map((p) => parseInt(p.replace(/\D/g, ''), 10)));
562
+ if (page >= last || !objects.length) break;
563
+ }
564
+ return [...new Set(hits)];
565
+ }
566
+
567
+ /**
568
+ * Delete the object at its change page's address, through its delete page, as
569
+ * the data administrator. An object that is no longer there is left alone.
570
+ *
571
+ * @returns {Promise<{deleted: boolean, refused: (string|null)}>}
572
+ */
573
+ async function deleteObject(world, changeUrl) {
574
+ const client = await dataClient(world);
575
+ const url = withoutQuery(changeUrl).replace(/\/(change\/)?$/, '/') + 'delete/';
576
+ const page = await client.get(url);
577
+ if (page.status === 404 || !/name="post" value="yes"/.test(page.html)) {
578
+ const protectedList = page.html.match(/<ul id="deleted-objects">([\s\S]*?)<\/ul>/);
579
+ if (protectedList && !/name="post"/.test(page.html)) return { deleted: false, refused: htmlText(protectedList[1]) };
580
+ return { deleted: false, refused: null };
581
+ }
582
+ const answer = await client.post(url, { post: 'yes' });
583
+ return { deleted: answer.status < 400, refused: null };
584
+ }
585
+
586
+ /** Delete every object of a model's list with that text, as the data administrator. */
587
+ async function deleteObjectsNamed(world, model, text, app) {
588
+ const urls = await findObjects(world, model, text, app);
589
+ const refused = [];
590
+ for (const url of urls) {
591
+ const outcome = await deleteObject(world, url);
592
+ if (outcome.refused) refused.push(outcome.refused);
593
+ }
594
+ if (refused.length) {
595
+ throw friendly({
596
+ message: `"${text}" of the "${model}" list could not be deleted: the admin keeps it for ${listed(refused)}.`,
597
+ hint: 'A protected relation keeps it: delete the objects that point to it first.',
598
+ });
599
+ }
600
+ return urls.length;
601
+ }
602
+
603
+ /** Give an account its password back, as the data administrator: the admin's own form for a user's password. */
604
+ async function setPasswordOf(world, username, password) {
605
+ const urls = await findObjects(world, 'Users', username);
606
+ if (!urls.length) {
607
+ throw friendly({ message: `The "Users" list has no "${username}": its password could not be set back.`, hint: 'The build of the site makes the accounts of the users registry; build it again, or run its --add-users.' });
608
+ }
609
+ const client = await dataClient(world);
610
+ const form = withoutQuery(urls[0]).replace(/change\/$/, '') + 'password/';
611
+ const answer = await client.post(form, { usable_password: 'true', password1: password, password2: password, 'set-password': 'Change password' });
612
+ if (/class="errornote"/.test(answer.html)) {
613
+ const errors = (answer.html.match(/<ul class="errorlist[^"]*"[^>]*>([\s\S]*?)<\/ul>/g) || []).map(htmlText);
614
+ throw friendly({ message: `The password of "${username}" could not be set back: ${listed(errors)}.`, hint: 'The admin\'s password rules refused the password of the users registry.' });
615
+ }
616
+ }
617
+
618
+ // ---------------------------------------------------------------------------
619
+ // Cleaning up after a scenario
620
+ // ---------------------------------------------------------------------------
621
+
622
+ /** Whether the steps clean up after each scenario (`worldParameters.adminCleanUp`, on by default). */
623
+ function cleansUp(world) {
624
+ return !(world.parameters && world.parameters.adminCleanUp === false);
625
+ }
626
+
627
+ /** Do something after the scenario, whatever happens in it (in the reverse order of the calls). */
628
+ function afterScenario(world, label, fn) {
629
+ if (!world.__djangoCleanUp) world.__djangoCleanUp = [];
630
+ if (world.__djangoCleanUp.some((item) => item.label === label)) return;
631
+ world.__djangoCleanUp.push({ label, fn });
632
+ }
633
+
634
+ // ---------------------------------------------------------------------------
635
+ // Form fields, found by their labels
636
+ // ---------------------------------------------------------------------------
637
+
638
+ let MARK = 0;
639
+
640
+ /**
641
+ * Find the field a person names by its label ("Question text", the closing
642
+ * colon optional; a section's field by the label in its row; a tabular inline
643
+ * row's field by its column), inside `scope` (a locator: the form, an inline
644
+ * row), and say what kind it is. The admin draws a field's label as a
645
+ * `label` (5.2 and 6.1), as the `legend` of the field's own fieldset (6.1:
646
+ * dates and times, many-to-many fields), or next to a checkbox.
647
+ *
648
+ * @returns {Promise<{box: import('playwright').Locator, kind: string, label: string}|null>}
649
+ */
650
+ async function findField(page, scope, label) {
651
+ const mark = `f${(MARK += 1)}`;
652
+ const found = await scope.first().evaluate((root, args) => {
653
+ const [wanted, mark] = args;
654
+ const norm = (t) => String(t || '').replace(/[­​-‏]/g, '').replace(/\s+/g, ' ').trim().replace(/\s*:$/, '').toLowerCase();
655
+ const want = norm(wanted);
656
+ const inInline = (el) => !!el.closest('.inline-group') && !root.closest('.inline-related') && !root.matches('.inline-related, tr');
657
+ const kindOf = (box) => {
658
+ if (box.querySelector('.readonly') && !box.querySelector('input:not([type=hidden]), select, textarea')) return 'readonly';
659
+ if (box.querySelector('select.admin-autocomplete')) return 'autocomplete';
660
+ if (box.querySelector('.selector, select.selectfilter, select.selectfilterstacked')) return 'selector';
661
+ if (box.querySelector('input.vDateField') && box.querySelector('input.vTimeField')) return 'datetime';
662
+ if (box.querySelector('input.vDateField')) return 'date';
663
+ if (box.querySelector('input.vTimeField')) return 'time';
664
+ if (box.querySelector('input[type=radio]')) return 'radio';
665
+ if (box.querySelector('input[type=checkbox]') && !box.querySelector('input:not([type=checkbox]):not([type=hidden]), select, textarea')) return 'checkbox';
666
+ if (box.querySelector('input[type=file]')) return 'file';
667
+ if (box.querySelector('select[multiple]')) return 'multiselect';
668
+ if (box.querySelector('select')) return 'select';
669
+ if (box.querySelector('textarea')) return 'textarea';
670
+ if (box.querySelector('input:not([type=hidden])')) return 'text';
671
+ return 'unknown';
672
+ };
673
+ // The sub-labels of a widget are no field's label: "Date:" and "Time:", the lists of a selector.
674
+ const isSubLabel = (el) => !!el.closest('p.datetime, .selector, .select2-container, .datetimeshortcuts, .help');
675
+ const candidates = [...root.querySelectorAll('label, legend')].filter((el) => !isSubLabel(el) && !inInline(el));
676
+ const labels = [];
677
+ for (const el of candidates) {
678
+ const text = norm(el.textContent);
679
+ if (!text) continue;
680
+ labels.push(el.textContent.replace(/\s+/g, ' ').trim());
681
+ if (text !== want) continue;
682
+ let box = null;
683
+ if (el.tagName === 'LEGEND') box = el.parentElement;
684
+ else if (el.classList.contains('vCheckboxLabel')) box = el.closest('.checkbox-row, .fieldBox, .form-row') || el.parentElement;
685
+ else box = el.closest('.fieldBox') || el.closest('.form-row') || el.parentElement;
686
+ if (!box) continue;
687
+ box.setAttribute('data-wsj-field', mark);
688
+ return { kind: kindOf(box), label: el.textContent.replace(/\s+/g, ' ').trim() };
689
+ }
690
+ // A tabular inline row: the field is in the column whose heading is the label.
691
+ const row = root.matches('tr') ? root : null;
692
+ if (row) {
693
+ const table = row.closest('table');
694
+ const heads = table ? [...table.querySelectorAll('thead th')] : [];
695
+ for (const th of heads) {
696
+ if (norm(th.textContent) !== want) continue;
697
+ const column = [...th.classList].find((c) => c.startsWith('column-'));
698
+ const cell = column ? row.querySelector('td.field-' + column.slice('column-'.length)) : row.children[heads.indexOf(th)];
699
+ if (!cell) continue;
700
+ cell.setAttribute('data-wsj-field', mark);
701
+ return { kind: kindOf(cell), label: th.textContent.replace(/\s+/g, ' ').trim() };
702
+ }
703
+ for (const th of heads) if (norm(th.textContent)) labels.push(th.textContent.replace(/\s+/g, ' ').trim());
704
+ }
705
+ return { kind: null, labels };
706
+ }, [label, mark]).catch(() => null);
707
+ if (!found || !found.kind) return found ? { missing: true, labels: found.labels || [] } : null;
708
+ return { box: page.locator(`[data-wsj-field="${mark}"]`), kind: found.kind, label: found.label };
709
+ }
710
+
711
+ /** The form of the page a field step works in: the change form, or the main form of the content. */
712
+ function mainForm(page) {
713
+ return page.locator('#content-main form, #content form').first();
714
+ }
715
+
716
+ /** Find a field or fail with the labels the form has. */
717
+ async function fieldOrFail(world, scope, label, where) {
718
+ const field = await findField(world.page, scope, label);
719
+ if (field && !field.missing) return field;
720
+ throw friendly({
721
+ message: `${where || 'The form'} has no field "${label}". Its fields: ${listed((field && field.labels) || [])}.`,
722
+ hint: hintFor(world, 'Name a field by its label as the form shows it, without the colon ("Question text"); a field of an inline row by its column ("Choice text").'),
723
+ });
724
+ }
725
+
726
+ const YES = /^(yes|true|on|checked|ticked|1)$/i;
727
+ const NO = /^(no|false|off|unchecked|unticked|0)$/i;
728
+
729
+ /** The values of a list field from a step ("Fun, Serious"), each trimmed. */
730
+ function valuesOf(value) {
731
+ return String(value).split(',').map(clean).filter(Boolean);
732
+ }
733
+
734
+ /**
735
+ * Choose an object in an autocomplete field (the admin's select2 box): open
736
+ * it, type the text, wait for the answer of the admin's autocomplete request
737
+ * to that text, and choose the result whose text is exactly the one given.
738
+ */
739
+ async function chooseAutocomplete(world, page, box, value, label) {
740
+ const select = box.locator('select.admin-autocomplete').first();
741
+ const id = await select.getAttribute('id');
742
+ if (!clean(value)) {
743
+ const clear = box.locator('.select2-selection__clear');
744
+ if (await clear.count()) await clear.first().click();
745
+ return;
746
+ }
747
+ await box.locator('.select2-selection').first().click();
748
+ const search = page.locator('.select2-container--open .select2-search__field');
749
+ await search.waitFor({ state: 'visible', timeout: budget(world) });
750
+ const answered = page.waitForResponse((r) => {
751
+ try {
752
+ const u = new URL(r.url());
753
+ return /\/autocomplete\/?$/.test(u.pathname) && u.searchParams.get('term') === value;
754
+ } catch { return false; }
755
+ }, { timeout: budget(world) }).catch(() => null);
756
+ await search.fill(value);
757
+ await answered;
758
+ const results = page.locator(`#select2-${id}-results`);
759
+ await page.waitForFunction((rid) => {
760
+ const list = document.getElementById(rid);
761
+ return !!list && !list.querySelector('.loading-results');
762
+ }, `select2-${id}-results`, { timeout: budget(world) }).catch(() => {});
763
+ const options = results.locator('li.select2-results__option').filter({ hasText: new RegExp('^\\s*' + escapeRegExp(clean(value)) + '\\s*$') });
764
+ if (!(await options.count())) {
765
+ const offered = await results.locator('li.select2-results__option').allTextContents().catch(() => []);
766
+ await page.keyboard.press('Escape').catch(() => {});
767
+ throw friendly({
768
+ message: `The autocomplete field "${label}" offers no "${value}" for that text. It offers: ${listed(offered)}.`,
769
+ hint: hintFor(world, 'The field searches the objects the admin of its model searches (search_fields); write the object as the field lists it.'),
770
+ });
771
+ }
772
+ await options.first().click();
773
+ await eventually(world,
774
+ () => box.locator('.select2-selection__rendered').first().getAttribute('title').catch(() => null),
775
+ (title) => normal(title) === normal(value),
776
+ (title) => ({ message: `The autocomplete field "${label}" shows "${title || '(nothing)'}" after choosing "${value}".`, hint: 'The choice did not reach the field.' }));
777
+ }
778
+
779
+ /** The lists and buttons of a two-list selector: what is available, what is chosen. */
780
+ function selectorParts(box) {
781
+ return {
782
+ from: box.locator('select[id$="_from"]').first(),
783
+ to: box.locator('select[id$="_to"]').first(),
784
+ add: box.locator('button.selector-add, a.selector-add').first(),
785
+ remove: box.locator('button.selector-remove, a.selector-remove').first(),
786
+ addAll: box.locator('button.selector-chooseall, a.selector-chooseall').first(),
787
+ removeAll: box.locator('button.selector-clearall, a.selector-clearall').first(),
788
+ filter: box.locator('input[id$="_input"]').first(),
789
+ };
790
+ }
791
+
792
+ /** The options of a list, as their texts. */
793
+ async function optionTexts(select) {
794
+ return (await select.locator('option').allTextContents().catch(() => [])).map(clean);
795
+ }
796
+
797
+ /** Move options from one list of a selector to the other, by their texts, with the list's own button. */
798
+ async function moveInSelector(world, box, values, direction, label) {
799
+ const parts = selectorParts(box);
800
+ const source = direction === 'choose' ? parts.from : parts.to;
801
+ const button = direction === 'choose' ? parts.add : parts.remove;
802
+ const have = await optionTexts(source);
803
+ const missing = values.filter((v) => !have.some((h) => normal(h) === normal(v)));
804
+ if (missing.length) {
805
+ const other = await optionTexts(direction === 'choose' ? parts.to : parts.from);
806
+ throw friendly({
807
+ message: `The ${direction === 'choose' ? 'available' : 'chosen'} "${label}" have no ${listed(missing)}. ${direction === 'choose' ? 'Available' : 'Chosen'}: ${listed(have)}; ${direction === 'choose' ? 'chosen' : 'available'}: ${listed(other)}.`,
808
+ hint: 'Write the option as the list shows it. An option in the other list is already where the step would move it.',
809
+ });
810
+ }
811
+ const exact = values.map((v) => have.find((h) => normal(h) === normal(v)));
812
+ await source.selectOption(exact.map((label) => ({ label })));
813
+ await button.click();
814
+ // The options leave the list they were in. (The other list may hide them: its filter box shows only the
815
+ // options with its text.)
816
+ await eventually(world, () => optionTexts(source),
817
+ (now) => exact.every((v) => !now.includes(v)),
818
+ (now) => ({ message: `After pressing "${direction === 'choose' ? 'Choose' : 'Remove'}", the ${direction === 'choose' ? 'available' : 'chosen'} "${label}" still list ${listed(exact.filter((v) => now.includes(v)))}.`, hint: 'The selector did not move the options.' }));
819
+ }
820
+
821
+ /** Open the folded section (a closed details element) a field is in, with its heading, so that the field shows. */
822
+ async function openFoldedSection(box) {
823
+ const closed = await box.evaluate((el) => { const d = el.closest('details'); return !!d && !d.open; }).catch(() => false);
824
+ if (!closed) return false;
825
+ await box.locator('xpath=ancestor::details[1]/summary').first().click();
826
+ await box.page().waitForFunction((el) => { const d = el.closest('details'); return !d || d.open; }, await box.elementHandle(), { timeout: 5000 }).catch(() => {});
827
+ return true;
828
+ }
829
+
830
+ /**
831
+ * Set a field to a value, whatever its kind: a text, a list (by the option's
832
+ * text), a box to tick ("yes" / "no"), a date ("2026-01-15", "today"), a time
833
+ * ("10:30:00", "now"), a date and time ("2026-01-15 10:30", "now"), an
834
+ * autocomplete field (by the object's text), a two-list selector ("Fun,
835
+ * Serious": exactly those chosen), a file (a path).
836
+ */
837
+ async function setField(world, scope, label, value, where) {
838
+ const page = world.page;
839
+ const field = await fieldOrFail(world, scope, label, where);
840
+ const { box, kind } = field;
841
+ const text = value === null || value === undefined ? '' : String(value);
842
+ const T = { timeout: budget(world) };
843
+ // A field in a folded section is hidden: open the section first, as a person does.
844
+ await openFoldedSection(box);
845
+ switch (kind) {
846
+ case 'readonly':
847
+ throw friendly({ message: `The field "${label}" is read-only: it shows "${clean(await box.locator('.readonly').first().innerText())}" and takes no value.`, hint: 'Check it with: Then "' + label + '" should be read-only' });
848
+ case 'autocomplete':
849
+ await chooseAutocomplete(world, page, box, text, label);
850
+ return;
851
+ case 'selector': {
852
+ const parts = selectorParts(box);
853
+ const wanted = valuesOf(text);
854
+ const chosen = await optionTexts(parts.to);
855
+ const drop = chosen.filter((c) => !wanted.some((w) => normal(w) === normal(c)));
856
+ if (drop.length) await moveInSelector(world, box, drop, 'remove', label);
857
+ const now = await optionTexts(parts.to);
858
+ const add = wanted.filter((w) => !now.some((c) => normal(c) === normal(w)));
859
+ if (add.length) await moveInSelector(world, box, add, 'choose', label);
860
+ return;
861
+ }
862
+ case 'datetime': {
863
+ if (/^(now|today)$/i.test(text)) {
864
+ // The shortcuts beside the two inputs: "Today" for the date, "Now" for the time.
865
+ await box.locator('.datetimeshortcuts').nth(0).locator('a').first().click(T);
866
+ await box.locator('.datetimeshortcuts').nth(1).locator('a').first().click(T);
867
+ return;
868
+ }
869
+ const m = text.match(/^(\S+)(?:\s+(\S+))?$/);
870
+ await box.locator('input.vDateField').first().fill(m ? m[1] : '', T);
871
+ await box.locator('input.vTimeField').first().fill(m && m[2] ? m[2] : '', T);
872
+ return;
873
+ }
874
+ case 'date':
875
+ if (/^today$/i.test(text)) { await box.locator('.datetimeshortcuts a').first().click(T); return; }
876
+ await box.locator('input.vDateField').first().fill(text, T);
877
+ return;
878
+ case 'time':
879
+ if (/^now$/i.test(text)) { await box.locator('.datetimeshortcuts a').first().click(T); return; }
880
+ await box.locator('input.vTimeField').first().fill(text, T);
881
+ return;
882
+ case 'checkbox': {
883
+ const box1 = box.locator('input[type=checkbox]').first();
884
+ if (YES.test(text)) await box1.check(T);
885
+ else if (NO.test(text)) await box1.uncheck(T);
886
+ else throw friendly({ message: `"${text}" is no state for the box "${label}".`, hint: 'Write "yes" to tick it and "no" to clear it.' });
887
+ return;
888
+ }
889
+ case 'radio': {
890
+ const radios = box.locator('input[type=radio]');
891
+ const count = await radios.count();
892
+ const offered = [];
893
+ for (let i = 0; i < count; i += 1) {
894
+ const radio = radios.nth(i);
895
+ const id = await radio.getAttribute('id');
896
+ const own = clean(await box.locator(`label[for="${id}"]`).first().innerText().catch(() => '')) || clean(await radio.evaluate((el) => (el.closest('label') ? el.closest('label').textContent : el.value)));
897
+ offered.push(own);
898
+ if (normal(own) === normal(text)) { await radio.check(T); return; }
899
+ }
900
+ throw friendly({ message: `The field "${label}" has no choice "${text}". Its choices: ${listed(offered)}.`, hint: 'Write the choice as the form shows it.' });
901
+ }
902
+ case 'multiselect': {
903
+ const select = box.locator('select[multiple]').first();
904
+ const have = await optionTexts(select);
905
+ const wanted = valuesOf(text).map((w) => have.find((h) => normal(h) === normal(w)) || w);
906
+ await select.selectOption(wanted.map((label) => ({ label })), T);
907
+ return;
908
+ }
909
+ case 'select': {
910
+ const select = box.locator('select').first();
911
+ const have = await optionTexts(select);
912
+ const exact = have.find((h) => normal(h) === normal(text));
913
+ if (exact === undefined) {
914
+ throw friendly({ message: `The list "${label}" has no option "${text}". Its options: ${listed(have)}.`, hint: 'Write the option as the list shows it.' });
915
+ }
916
+ await select.selectOption({ label: exact }, T);
917
+ return;
918
+ }
919
+ case 'file':
920
+ await box.locator('input[type=file]').first().setInputFiles(text, T);
921
+ return;
922
+ case 'textarea':
923
+ await box.locator('textarea').first().fill(text, T);
924
+ return;
925
+ case 'text':
926
+ await box.locator('input:not([type=hidden]):not([type=checkbox]):not([type=radio])').first().fill(text, T);
927
+ return;
928
+ default:
929
+ throw friendly({ message: `The field "${label}" is of a kind the steps do not know how to set.`, hint: 'Set it with webship-js\'s own steps, by its name: I fill in "<name>" with "<value>" by attr' });
930
+ }
931
+ }
932
+
933
+ /** What a field shows now, as a text, whatever its kind (see setField). */
934
+ async function readField(world, scope, label, where) {
935
+ const field = await fieldOrFail(world, scope, label, where);
936
+ const { box, kind } = field;
937
+ switch (kind) {
938
+ case 'readonly':
939
+ return clean(await box.locator('.readonly').first().innerText());
940
+ case 'autocomplete': {
941
+ const title = await box.locator('.select2-selection__rendered').first().getAttribute('title').catch(() => null);
942
+ if (title) return clean(title);
943
+ return clean(await box.locator('select.admin-autocomplete option:checked').first().textContent().catch(() => ''));
944
+ }
945
+ case 'selector':
946
+ return (await optionTexts(selectorParts(box).to)).join(', ');
947
+ case 'datetime':
948
+ return clean(`${await box.locator('input.vDateField').first().inputValue()} ${await box.locator('input.vTimeField').first().inputValue()}`);
949
+ case 'date':
950
+ return box.locator('input.vDateField').first().inputValue();
951
+ case 'time':
952
+ return box.locator('input.vTimeField').first().inputValue();
953
+ case 'checkbox':
954
+ return (await box.locator('input[type=checkbox]').first().isChecked()) ? 'yes' : 'no';
955
+ case 'radio': {
956
+ const checked = box.locator('input[type=radio]:checked');
957
+ if (!(await checked.count())) return '';
958
+ return clean(await checked.first().evaluate((el) => {
959
+ const own = el.id && document.querySelector(`label[for="${el.id}"]`);
960
+ return own ? own.textContent : (el.closest('label') ? el.closest('label').textContent : el.value);
961
+ }));
962
+ }
963
+ case 'multiselect':
964
+ return (await box.locator('select[multiple] option:checked').allTextContents()).map(clean).join(', ');
965
+ case 'select':
966
+ return clean(await box.locator('select option:checked').first().textContent().catch(() => ''));
967
+ case 'textarea':
968
+ return box.locator('textarea').first().inputValue();
969
+ case 'text':
970
+ return box.locator('input:not([type=hidden]):not([type=checkbox]):not([type=radio])').first().inputValue();
971
+ default:
972
+ return clean(await box.innerText());
973
+ }
974
+ }
975
+
976
+ // ---------------------------------------------------------------------------
977
+ // The change list
978
+ // ---------------------------------------------------------------------------
979
+
980
+ /** Whether the page is a change list (the admin marks its body with the class change-list). */
981
+ async function onChangeList(page) {
982
+ return page.locator('body.change-list').count().then((n) => n > 0).catch(() => false);
983
+ }
984
+
985
+ /** Fail unless the page is a change list. */
986
+ async function changeListOrFail(world) {
987
+ if (await onChangeList(world.page)) return;
988
+ throw friendly({
989
+ message: `The page is not a list of the admin: ${await pageSummary(world)}.`,
990
+ hint: hintFor(world, 'Open the list first: When I open the "Questions" list'),
991
+ });
992
+ }
993
+
994
+ /** The rows of the change list on screen: the object's text (the row's link) and the text of each cell. */
995
+ async function listRows(page) {
996
+ return page.evaluate(() => {
997
+ const table = document.getElementById('result_list');
998
+ if (!table) return [];
999
+ return [...table.querySelectorAll('tbody tr')].map((tr) => {
1000
+ const head = tr.querySelector('th') || tr.querySelector('td:not(.action-checkbox)');
1001
+ return {
1002
+ object: (head ? head.textContent : '').replace(/\s+/g, ' ').trim(),
1003
+ selected: tr.classList.contains('selected') || !!(tr.querySelector('input.action-select') || {}).checked,
1004
+ };
1005
+ });
1006
+ }).catch(() => []);
1007
+ }
1008
+
1009
+ /** The headings of the change list's columns, without the checkbox column. */
1010
+ async function listColumns(page) {
1011
+ return page.evaluate(() => {
1012
+ const table = document.getElementById('result_list');
1013
+ if (!table) return [];
1014
+ return [...table.querySelectorAll('thead th')].filter((th) => !th.classList.contains('action-checkbox-column')).map((th) => th.textContent.replace(/\s+/g, ' ').trim());
1015
+ }).catch(() => []);
1016
+ }
1017
+
1018
+ /**
1019
+ * The text of one cell of the change list: the row of an object, the column
1020
+ * of a heading. A yes/no column shows an icon: its text is the icon's
1021
+ * description ("True", "False", "None").
1022
+ */
1023
+ async function listCell(page, object, column) {
1024
+ return page.evaluate(([object, column]) => {
1025
+ const norm = (t) => String(t || '').replace(/[“”"‘’']/g, "'").replace(/\s+/g, ' ').trim().toLowerCase();
1026
+ const table = document.getElementById('result_list');
1027
+ if (!table) return { error: 'no list' };
1028
+ const heads = [...table.querySelectorAll('thead th')];
1029
+ const index = heads.findIndex((th) => norm(th.textContent) === norm(column));
1030
+ if (index < 0) return { error: 'column', columns: heads.map((th) => th.textContent.replace(/\s+/g, ' ').trim()).filter(Boolean) };
1031
+ const rows = [...table.querySelectorAll('tbody tr')];
1032
+ const row = rows.find((tr) => { const head = tr.querySelector('th') || tr.querySelector('td:not(.action-checkbox)'); return head && norm(head.textContent) === norm(object); });
1033
+ if (!row) return { error: 'row', rows: rows.map((tr) => (tr.querySelector('th') || tr).textContent.replace(/\s+/g, ' ').trim()) };
1034
+ const cell = row.children[index];
1035
+ if (!cell) return { error: 'cell' };
1036
+ const icon = cell.querySelector('img[alt]');
1037
+ const text = cell.textContent.replace(/\s+/g, ' ').trim();
1038
+ return { text: text || (icon ? icon.getAttribute('alt') : '') };
1039
+ }, [object, column]);
1040
+ }
1041
+
1042
+ /** The count the change list gives: "24 questions" (the paginator), and after a search "2 results (24 total)". */
1043
+ async function listCounts(page) {
1044
+ return page.evaluate(() => {
1045
+ const pag = document.querySelector('.paginator');
1046
+ const search = document.querySelector('#changelist-search .small.quiet, #toolbar .small.quiet');
1047
+ const found = search ? search.textContent.replace(/\s+/g, ' ').match(/(\d+)\s+results?\s*\((\d+)/) : null;
1048
+ // The count is the text of the paginator itself, outside its page links: "24 questions".
1049
+ const own = pag ? [...pag.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent.replace(/\s+/g, ' ').trim()).filter(Boolean).join(' ') : '';
1050
+ const m = own.match(/(\d+)\s+\S/);
1051
+ return {
1052
+ paginator: own,
1053
+ count: m ? parseInt(m[1], 10) : null,
1054
+ results: found ? parseInt(found[1], 10) : null,
1055
+ total: found ? parseInt(found[2], 10) : null,
1056
+ searchText: search ? search.textContent.replace(/\s+/g, ' ').trim() : '',
1057
+ };
1058
+ }).catch(() => ({ paginator: '', count: null, results: null, total: null, searchText: '' }));
1059
+ }
1060
+
1061
+ /** The pages of the change list: the current one, and how many. */
1062
+ async function listPages(page) {
1063
+ return page.evaluate(() => {
1064
+ const pag = document.querySelector('.paginator');
1065
+ if (!pag) return { current: 1, last: 1 };
1066
+ const current = pag.querySelector('[aria-current="page"], .this-page');
1067
+ const numbers = [...pag.querySelectorAll('a, span.this-page')].map((e) => parseInt(e.textContent.trim(), 10)).filter((n) => !Number.isNaN(n));
1068
+ return { current: current ? parseInt(current.textContent.trim(), 10) : 1, last: numbers.length ? Math.max(...numbers) : 1 };
1069
+ }).catch(() => ({ current: 1, last: 1 }));
1070
+ }
1071
+
1072
+ /** The filter of the sidebar with that title ("By category", or "category"). */
1073
+ function filterBlock(page, title) {
1074
+ const want = normal(title).replace(/^by /, '');
1075
+ return page.locator('#changelist-filter details').filter({
1076
+ has: page.locator('summary', { hasText: new RegExp('^\\s*(?:By\\s+)?' + escapeRegExp(clean(title).replace(/^By\s+/i, '')) + '\\s*$', 'i') }),
1077
+ }).or(page.locator(`#changelist-filter details[data-filter-title="${want.replace(/"/g, '\\"')}"]`));
1078
+ }
1079
+
1080
+ /** The titles of the sidebar's filters. */
1081
+ async function filterTitles(page) {
1082
+ return (await page.locator('#changelist-filter details summary, #changelist-filter h3').allTextContents().catch(() => [])).map(clean).filter((t) => t && !/^(show counts|hide counts|✖ clear all filters)$/i.test(t));
1083
+ }
1084
+
1085
+ // ---------------------------------------------------------------------------
1086
+ // Inline rows
1087
+ // ---------------------------------------------------------------------------
1088
+
1089
+ /** The inline group with that heading ("Choices"): its rows, whether tabular or stacked. */
1090
+ async function inlineGroup(world, name) {
1091
+ const page = world.page;
1092
+ const groups = page.locator('.inline-group');
1093
+ const count = await groups.count();
1094
+ const names = [];
1095
+ for (let i = 0; i < count; i += 1) {
1096
+ const group = groups.nth(i);
1097
+ const title = clean(await group.locator('h2').first().innerText().catch(() => ''));
1098
+ names.push(title);
1099
+ if (normal(title) === normal(name)) {
1100
+ const prefix = await group.evaluate((g) => {
1101
+ try { return JSON.parse(g.dataset.inlineFormset).options.prefix; } catch { return (g.id || '').replace(/-group$/, ''); }
1102
+ });
1103
+ const tabular = (await group.getAttribute('data-inline-type')) === 'tabular';
1104
+ return { group, prefix, tabular };
1105
+ }
1106
+ }
1107
+ throw friendly({
1108
+ message: `The form has no inline "${name}". Its inlines: ${listed(names)}.`,
1109
+ hint: hintFor(world, 'Name an inline by its heading on the form, such as "Choices".'),
1110
+ });
1111
+ }
1112
+
1113
+ /** The rows of an inline group: its saved and new rows, without the hidden template, in page order. */
1114
+ function inlineRows(inline) {
1115
+ const ids = `[id^="${inline.prefix}-"]:not([id$="-empty"]):not(.empty-form)`;
1116
+ return inline.tabular
1117
+ ? inline.group.locator(`tbody tr.form-row${ids}`)
1118
+ : inline.group.locator(`.inline-related${ids}`);
1119
+ }
1120
+
1121
+ /** Row n (from 1) of an inline group, or a failure that says how many rows it has. */
1122
+ async function inlineRow(world, inline, n, name) {
1123
+ const rows = inlineRows(inline);
1124
+ const count = await rows.count();
1125
+ if (n < 1 || n > count) {
1126
+ throw friendly({ message: `The inline "${name}" has no row ${n}: it has ${count} row${count === 1 ? '' : 's'}.`, hint: `Add a row first: When I add a row to the "${name}" inline` });
1127
+ }
1128
+ return rows.nth(n - 1);
1129
+ }
1130
+
1131
+ module.exports = {
1132
+ budget,
1133
+ clean,
1134
+ normal,
1135
+ mentions,
1136
+ listed,
1137
+ escapeRegExp,
1138
+ decodeEntities,
1139
+ htmlText,
1140
+ siteRoot,
1141
+ adminPath,
1142
+ adminUrl,
1143
+ absolute,
1144
+ withoutQuery,
1145
+ cutRequest,
1146
+ CUT_HINT,
1147
+ hintFor,
1148
+ adminReady,
1149
+ open,
1150
+ afterNavigation,
1151
+ heading,
1152
+ pageSummary,
1153
+ eventually,
1154
+ messages,
1155
+ formErrors,
1156
+ resolveUser,
1157
+ userName,
1158
+ signedInName,
1159
+ submitLogin,
1160
+ logInAs,
1161
+ forgetSession,
1162
+ currentUser,
1163
+ LOGIN_HINT,
1164
+ modelsOfIndex,
1165
+ modelListUrl,
1166
+ dataAdminHandle,
1167
+ dataClient,
1168
+ closeClients,
1169
+ objectsOfList,
1170
+ findObjects,
1171
+ deleteObject,
1172
+ deleteObjectsNamed,
1173
+ setPasswordOf,
1174
+ cleansUp,
1175
+ afterScenario,
1176
+ findField,
1177
+ fieldOrFail,
1178
+ openFoldedSection,
1179
+ mainForm,
1180
+ setField,
1181
+ readField,
1182
+ selectorParts,
1183
+ optionTexts,
1184
+ moveInSelector,
1185
+ chooseAutocomplete,
1186
+ onChangeList,
1187
+ changeListOrFail,
1188
+ listRows,
1189
+ listColumns,
1190
+ listCell,
1191
+ listCounts,
1192
+ listPages,
1193
+ filterBlock,
1194
+ filterTitles,
1195
+ inlineGroup,
1196
+ inlineRows,
1197
+ inlineRow,
1198
+ };