@antelopejs/dms 0.18.0 → 0.18.2

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 (61) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +3 -3
  3. package/bin/control/backend-records.test.mjs +276 -0
  4. package/bin/control/backend.mjs +212 -0
  5. package/bin/control/backend.test.mjs +325 -0
  6. package/bin/control/base.mjs +3 -7
  7. package/bin/control/browser-client.mjs +6 -4
  8. package/bin/control/browser.mjs +173 -36
  9. package/bin/control/build-cache.mjs +394 -0
  10. package/bin/control/build-cache.test.mjs +270 -0
  11. package/bin/control/build-inputs.mjs +172 -0
  12. package/bin/control/build-key-refusals.test.mjs +138 -0
  13. package/bin/control/build-key.mjs +479 -0
  14. package/bin/control/build-key.test.mjs +392 -0
  15. package/bin/control/build-layout.test.mjs +314 -0
  16. package/bin/control/commands-stack.mjs +46 -6
  17. package/bin/control/commands-verify.mjs +14 -25
  18. package/bin/control/doctor.mjs +87 -16
  19. package/bin/control/forwarder.mjs +86 -0
  20. package/bin/control/forwarder.test.mjs +141 -0
  21. package/bin/control/frontend-check.mjs +54 -0
  22. package/bin/control/frontend-workspace.mjs +150 -0
  23. package/bin/control/frontend-workspace.test.mjs +133 -0
  24. package/bin/control/helpers/env.mjs +21 -0
  25. package/bin/control/helpers/evidence.mjs +13 -0
  26. package/bin/control/helpers/fake-run.mjs +290 -0
  27. package/bin/control/helpers/key-fixture.mjs +82 -0
  28. package/bin/control/helpers/pids.mjs +27 -0
  29. package/bin/control/helpers/repo.mjs +13 -0
  30. package/bin/control/helpers/tree.mjs +40 -0
  31. package/bin/control/identity.mjs +238 -0
  32. package/bin/control/identity.test.mjs +166 -0
  33. package/bin/control/journey.mjs +64 -16
  34. package/bin/control/journey.test.mjs +60 -2
  35. package/bin/control/namespaces.test.mjs +211 -0
  36. package/bin/control/options.mjs +2 -0
  37. package/bin/control/pid-guard.test.mjs +202 -0
  38. package/bin/control/prepared-workspace.mjs +20 -0
  39. package/bin/control/processes.mjs +122 -33
  40. package/bin/control/processes.test.mjs +255 -0
  41. package/bin/control/renderer.test.mjs +2 -1
  42. package/bin/control/run-copy.mjs +77 -0
  43. package/bin/control/run-state.mjs +142 -16
  44. package/bin/control/stack.mjs +259 -210
  45. package/bin/control/tab.mjs +13 -6
  46. package/bin/control/tab.test.mjs +444 -0
  47. package/bin/control/timing.mjs +244 -0
  48. package/bin/control/timing.test.mjs +197 -0
  49. package/bin/control/verify/decode.mjs +34 -36
  50. package/bin/control/verify/decode.test.mjs +40 -14
  51. package/bin/control/verify/doors.test.mjs +2 -0
  52. package/bin/control/verify/map.mjs +57 -7
  53. package/bin/control/verify/map.test.mjs +264 -0
  54. package/bin/control/verify/skill.mjs +12 -3
  55. package/bin/control/verify/types.mjs +2 -2
  56. package/bin/control/verify/verdict.mjs +34 -37
  57. package/bin/dms-control.mjs +13 -6
  58. package/frontend-vue/layers/dms-layout/app/components/layout/DashboardSearch.vue +24 -1
  59. package/package.json +1 -1
  60. package/skills/dms-project/SKILL.md +6 -3
  61. package/bin/control/verify/publish.mjs +0 -186
@@ -0,0 +1,325 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ chmodSync,
4
+ copyFileSync,
5
+ cpSync,
6
+ mkdirSync,
7
+ renameSync,
8
+ rmSync,
9
+ statSync,
10
+ symlinkSync,
11
+ utimesSync,
12
+ writeFileSync,
13
+ } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import test from "node:test";
16
+ import { freshDatabase, restartBackend } from "./backend.mjs";
17
+ import { doctor } from "./doctor.mjs";
18
+ import {
19
+ buildFiles,
20
+ bystander,
21
+ dropped,
22
+ newRun,
23
+ rebuild,
24
+ running,
25
+ served,
26
+ startedOn,
27
+ } from "./helpers/fake-run.mjs";
28
+ import { isRunning } from "./identity.mjs";
29
+ import { loadRun, saveRun } from "./run-state.mjs";
30
+ import { down, liveBackends } from "./stack.mjs";
31
+
32
+ await test("each fresh database is served by a backend that served nothing before, and the one it replaces is gone", async (t) => {
33
+ const state = await newRun(t);
34
+ /** @type {number[]} */
35
+ const servers = [];
36
+ for (const suffix of ["j001", "j002", "j003"]) {
37
+ state.accounts = { admin: { email: "admin@example.com" } };
38
+ state.tokens = { admin: "a session of the previous database" };
39
+ const database = await freshDatabase(state, suffix);
40
+ const answer = await served(state);
41
+ const saved = loadRun(state.dir);
42
+ assert.equal(database, `${state.databasePrefix}_${suffix}`);
43
+ assert.deepEqual([saved.accounts, saved.tokens], [{}, {}]);
44
+ assert.deepEqual(answer, { pid: answer.pid, database });
45
+ assert.equal(servers.includes(answer.pid), false);
46
+ assert.deepEqual(servers.filter(isRunning), []);
47
+ servers.push(answer.pid);
48
+ }
49
+ });
50
+
51
+ await test("the next journey's backend already runs when a fresh database is ready, and takes over the next call", async (t) => {
52
+ const state = await newRun(t);
53
+ await freshDatabase(state, "j001");
54
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
55
+ assert.equal(isRunning(standby.pid), true);
56
+ await freshDatabase(state, "j002");
57
+ assert.deepEqual(await served(state), {
58
+ pid: standby.pid,
59
+ database: `${state.databasePrefix}_j002`,
60
+ });
61
+ });
62
+
63
+ await test("a standby started for another database is killed and its database dropped", async (t) => {
64
+ const state = await newRun(t);
65
+ await freshDatabase(state, "j001");
66
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
67
+ await freshDatabase(state, "r1");
68
+ const answer = await served(state);
69
+ assert.equal(answer.database, `${state.databasePrefix}_r1`);
70
+ assert.notEqual(answer.pid, standby.pid);
71
+ assert.equal(isRunning(standby.pid), false);
72
+ assert.deepEqual(dropped().toSorted(), [
73
+ `${state.databasePrefix}_j001`,
74
+ `${state.databasePrefix}_j002`,
75
+ ]);
76
+ });
77
+
78
+ await test("a standby that died is replaced by a backend started on the spot", async (t) => {
79
+ const state = await newRun(t);
80
+ await freshDatabase(state, "j001");
81
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
82
+ process.kill(standby.pid, "SIGKILL");
83
+ await freshDatabase(state, "j002");
84
+ const answer = await served(state);
85
+ assert.equal(answer.database, `${state.databasePrefix}_j002`);
86
+ assert.notEqual(answer.pid, standby.pid);
87
+ });
88
+
89
+ await test("a restart inside a journey keeps its database, and the next journey still gets its standby", async (t) => {
90
+ const state = await newRun(t);
91
+ await freshDatabase(state, "j001");
92
+ const first = await served(state);
93
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
94
+ await restartBackend(state);
95
+ const restarted = await served(state);
96
+ assert.equal(restarted.database, `${state.databasePrefix}_j001`);
97
+ assert.notEqual(restarted.pid, first.pid);
98
+ assert.equal(isRunning(first.pid), false);
99
+ await freshDatabase(state, "j002");
100
+ assert.deepEqual(await served(state), {
101
+ pid: standby.pid,
102
+ database: `${state.databasePrefix}_j002`,
103
+ });
104
+ });
105
+
106
+ await test("down stops the standby with the rest of the run", async (t) => {
107
+ const state = await newRun(t);
108
+ await freshDatabase(state, "j001");
109
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
110
+ await down(state);
111
+ assert.equal(isRunning(standby.pid), false);
112
+ });
113
+
114
+ await test("a standby started before a build is not used, whichever build input changed, and one started after it takes over", async (t) => {
115
+ const state = await newRun(t);
116
+ await freshDatabase(state, "j001");
117
+ const files = buildFiles(dirname(state.playground));
118
+ for (const [index, file] of files.entries()) {
119
+ const database = `${state.databasePrefix}_j00${index + 2}`;
120
+ const standby = await startedOn(database);
121
+ rebuild(file);
122
+ await freshDatabase(state, `j00${index + 2}`);
123
+ const answer = await served(state);
124
+ assert.equal(answer.database, database);
125
+ assert.notEqual(
126
+ answer.pid,
127
+ standby.pid,
128
+ `${file} changed after it started`,
129
+ );
130
+ assert.equal(isRunning(standby.pid), false);
131
+ }
132
+ const fresh = await startedOn(
133
+ `${state.databasePrefix}_j00${files.length + 2}`,
134
+ );
135
+ await freshDatabase(state, `j00${files.length + 2}`);
136
+ assert.equal((await served(state)).pid, fresh.pid);
137
+ });
138
+
139
+ await test("doctor fails while the backend behind the API started before the last build", async (t) => {
140
+ const state = await newRun(t);
141
+ await freshDatabase(state, "j001");
142
+ const check = async () =>
143
+ (await doctor(state)).find(
144
+ (line) => line.check === "backend started after the last build",
145
+ )?.ok;
146
+ assert.equal(await check(), true);
147
+ rebuild(join(state.moduleRoot, "dist/index.js"));
148
+ assert.equal(await check(), false);
149
+ await freshDatabase(state, "j002");
150
+ assert.equal(await check(), true);
151
+ });
152
+
153
+ await test("while a build folder is missing, a fresh database refuses before it stops anything, and doctor fails", async (t) => {
154
+ const state = await newRun(t);
155
+ await freshDatabase(state, "j001");
156
+ const serving = await served(state);
157
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
158
+ const dist = join(state.moduleRoot, "dist");
159
+ renameSync(dist, `${dist}.away`);
160
+ await assert.rejects(freshDatabase(state, "j002"), (error) => {
161
+ assert.ok(error instanceof Error && error.message.includes(dist));
162
+ return true;
163
+ });
164
+ assert.deepEqual(await served(state), serving);
165
+ assert.equal(isRunning(standby.pid), true);
166
+ const build = (await doctor(state)).find(
167
+ (line) => line.check === "backend started after the last build",
168
+ );
169
+ assert.equal(build?.ok, false);
170
+ });
171
+
172
+ await test(
173
+ "a build folder that cannot be read keeps a standby from being used; a version that counts what it cannot read as unchanged uses it",
174
+ {
175
+ skip: process.getuid?.() === 0 && "root reads a folder whatever its mode",
176
+ },
177
+ async (t) => {
178
+ const state = await newRun(t);
179
+ const locked = join(state.moduleRoot, "dist/locked");
180
+ mkdirSync(locked);
181
+ chmodSync(locked, 0);
182
+ try {
183
+ await freshDatabase(state, "j001");
184
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
185
+ await freshDatabase(state, "j002");
186
+ assert.notEqual((await served(state)).pid, standby.pid);
187
+ } finally {
188
+ chmodSync(locked, 0o700);
189
+ }
190
+ },
191
+ );
192
+
193
+ await test("a link to nothing in a build folder, there before the standby started, does not keep the standby from being used; a version that counts it as missing starts a backend for every journey", async (t) => {
194
+ const state = await newRun(t);
195
+ symlinkSync(
196
+ join(state.moduleRoot, "removed.js"),
197
+ join(state.moduleRoot, "dist/dangling.js"),
198
+ );
199
+ await freshDatabase(state, "j001");
200
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
201
+ await freshDatabase(state, "j002");
202
+ assert.equal((await served(state)).pid, standby.pid);
203
+ const build = (await doctor(state)).find(
204
+ (line) => line.check === "backend started after the last build",
205
+ );
206
+ assert.equal(build?.ok, true, build?.detail);
207
+ });
208
+
209
+ await test("a standby started before a build is not used when an older build is moved into place, a file copied with its old times, or the build rewritten behind a link", async (t) => {
210
+ const state = await newRun(t);
211
+ const parent = state.moduleRoot;
212
+ const build = join(state.playground, ".antelope/build");
213
+ cpSync(build, `${build}.old`, { recursive: true, preserveTimestamps: true });
214
+ const older = join(parent, "older.js");
215
+ writeFileSync(older, "an older build\n");
216
+ const { mtime } = statSync(older);
217
+ renameSync(join(parent, "dist"), join(parent, "dist-real"));
218
+ symlinkSync(join(parent, "dist-real"), join(parent, "dist"));
219
+ const interfaceFile = join(parent, "interface/dist/index.js");
220
+ const changes = {
221
+ "an older build moved into place": () => {
222
+ rmSync(build, { recursive: true });
223
+ renameSync(`${build}.old`, build);
224
+ },
225
+ "a file copied with its old times": () => {
226
+ copyFileSync(older, interfaceFile);
227
+ utimesSync(interfaceFile, mtime, mtime);
228
+ },
229
+ "a file rewritten behind a linked dist": () =>
230
+ writeFileSync(join(parent, "dist-real/index.js"), "rewritten\n"),
231
+ };
232
+ await freshDatabase(state, "j001");
233
+ for (const [index, [change, apply]] of Object.entries(changes).entries()) {
234
+ const suffix = `j00${index + 2}`;
235
+ const standby = await startedOn(`${state.databasePrefix}_${suffix}`);
236
+ apply();
237
+ await freshDatabase(state, suffix);
238
+ assert.notEqual((await served(state)).pid, standby.pid, change);
239
+ }
240
+ });
241
+
242
+ await test("a build folder linked to a folder a build removed counts as missing, and doctor fails; a version that counts that link by its own times passes it", async (t) => {
243
+ const state = await newRun(t);
244
+ const dist = join(state.moduleRoot, "dist");
245
+ renameSync(dist, `${dist}-real`);
246
+ symlinkSync(`${dist}-real`, dist);
247
+ await freshDatabase(state, "j001");
248
+ rmSync(`${dist}-real`, { recursive: true });
249
+ const build = (await doctor(state)).find(
250
+ (line) => line.check === "backend started after the last build",
251
+ );
252
+ assert.equal(build?.ok, false);
253
+ assert.ok(build?.detail.startsWith(`${dist} is missing`), build?.detail);
254
+ });
255
+
256
+ await test("a build folder that a later build creates keeps a standby started before it from being used", async (t) => {
257
+ const state = await newRun(t);
258
+ const created = join(state.playground, "dist");
259
+ rmSync(created, { recursive: true });
260
+ state.buildRoots = state.buildRoots?.filter((folder) => folder !== created);
261
+ await freshDatabase(state, "j001");
262
+ const standby = await startedOn(`${state.databasePrefix}_j002`);
263
+ rebuild(join(created, "index.js"));
264
+ await freshDatabase(state, "j002");
265
+ assert.notEqual((await served(state)).pid, standby.pid);
266
+ });
267
+
268
+ await test("a command that saves a run.json it loaded before a fresh database loses no backend", async (t) => {
269
+ const state = await newRun(t);
270
+ await freshDatabase(state, "j001");
271
+ const stale = loadRun(state.dir);
272
+ await freshDatabase(state, "j002");
273
+ saveRun(stale);
274
+ const standby = await startedOn(`${state.databasePrefix}_j003`);
275
+ await freshDatabase(loadRun(state.dir), "j003");
276
+ assert.equal((await served(state)).pid, standby.pid);
277
+ const next = await startedOn(`${state.databasePrefix}_j004`);
278
+ assert.deepEqual(
279
+ running(),
280
+ [standby.pid, next.pid].toSorted((a, b) => a - b),
281
+ );
282
+ saveRun(stale);
283
+ await down(loadRun(state.dir));
284
+ assert.deepEqual(running(), []);
285
+ });
286
+
287
+ await test("with no standby, no backend runs ahead and each fresh database starts its own", async (t) => {
288
+ const state = await newRun(t);
289
+ state.noStandby = true;
290
+ await freshDatabase(state, "j001");
291
+ const first = await served(state);
292
+ assert.deepEqual(
293
+ liveBackends(state).map((backend) => backend.pid),
294
+ [first.pid],
295
+ );
296
+ await freshDatabase(state, "j002");
297
+ const second = await served(state);
298
+ assert.notEqual(second.pid, first.pid);
299
+ assert.deepEqual(
300
+ liveBackends(state).map((backend) => backend.pid),
301
+ [second.pid],
302
+ );
303
+ });
304
+
305
+ await test("a run whose backend holds the API port itself is refused before any backend starts", async (t) => {
306
+ const state = await newRun(t);
307
+ const old = bystander(t);
308
+ state.processes = [
309
+ {
310
+ name: "backend",
311
+ pid: old,
312
+ command: "an earlier dms-control's backend",
313
+ cwd: state.dir,
314
+ log: join(state.logs, "backend.log"),
315
+ startedAt: new Date().toISOString(),
316
+ port: state.apiPort,
317
+ },
318
+ ];
319
+ await assert.rejects(freshDatabase(state, "r1"), {
320
+ message: "this run was started by an older dms-control; run `up` again",
321
+ });
322
+ assert.deepEqual(liveBackends(state), []);
323
+ assert.equal(isRunning(old), true);
324
+ state.processes = [];
325
+ });
@@ -5,13 +5,9 @@ import { git } from "./git.mjs";
5
5
  import { runToEnd } from "./processes.mjs";
6
6
  import { saveRun } from "./run-state.mjs";
7
7
  import { runPrepare } from "./verify/skill.mjs";
8
- import {
9
- cliPaths,
10
- ENVIRONMENT,
11
- layOutCopy,
12
- restartBackend,
13
- spec,
14
- } from "./stack.mjs";
8
+ import { layOutCopy } from "./run-copy.mjs";
9
+ import { cliPaths, ENVIRONMENT, spec } from "./stack.mjs";
10
+ import { restartBackend } from "./backend.mjs";
15
11
 
16
12
  const READY_MARK = ".dms-control-ready";
17
13
 
@@ -1,7 +1,8 @@
1
1
  import { isOutcome } from "./browser-wire.mjs";
2
2
  import { decode } from "./json.mjs";
3
3
  import { CONTROL_BIN } from "./stack.mjs";
4
- import { freePort, isAlive, startDetached, waitForOk } from "./processes.mjs";
4
+ import { isSameProcess } from "./identity.mjs";
5
+ import { freePort, startDetached, waitForOk } from "./processes.mjs";
5
6
  import { saveRun } from "./run-state.mjs";
6
7
  import { nextFolder } from "./session.mjs";
7
8
 
@@ -12,7 +13,7 @@ const READY_TIMEOUT_MS = 60_000;
12
13
  * @returns {Promise<import("./run-state.mjs").ServerRecord>} Its running browser server, started if it was not
13
14
  */
14
15
  async function browserServer(state) {
15
- if (state.browser && isAlive(state.browser.pid)) return state.browser;
16
+ if (state.browser && isSameProcess(state.browser)) return state.browser;
16
17
  const port = await freePort();
17
18
  const started = startDetached({
18
19
  name: "browser",
@@ -31,8 +32,9 @@ async function browserServer(state) {
31
32
  /**
32
33
  * Runs one browser action in the run's long-lived browser, starting it on
33
34
  * first use. Each account has its own context and each tab name its own
34
- * page, both kept between commands. The action, the URL, the ARIA snapshot
35
- * and a screenshot go to `<run>/evidence/browser/NN-<label>/`.
35
+ * page, both kept between commands. The action, the URL and the ARIA
36
+ * snapshot go to `<run>/evidence/browser/NN-<label>/`, with a screenshot when
37
+ * the action failed or is `screenshot`.
36
38
  *
37
39
  * @param {import("./run-state.mjs").RunState} state The run
38
40
  * @param {Omit<import("./browser.mjs").BrowserRequest, "folder">} request The action: `do`, `account`, `tab`, and the action's target, value, key or path
@@ -1,11 +1,12 @@
1
1
  import { writeFileSync } from "node:fs";
2
2
  import { createServer } from "node:http";
3
- import { join } from "node:path";
3
+ import { join, relative } from "node:path";
4
4
  import { isBrowserRequest } from "./browser-wire.mjs";
5
5
  import { describeFailure } from "./failure.mjs";
6
6
  import { decode } from "./json.mjs";
7
7
  import { importFrom } from "./mongo.mjs";
8
8
  import { loadRun } from "./run-state.mjs";
9
+ import { timed } from "./timing.mjs";
9
10
 
10
11
  /**
11
12
  * @typedef {import("playwright-core").Browser} Browser
@@ -20,8 +21,30 @@ import { loadRun } from "./run-state.mjs";
20
21
  const ACTION_TIMEOUT_MS = 15_000;
21
22
  const NAVIGATION_TIMEOUT_MS = 60_000;
22
23
  const SETTLE_MS = 400;
24
+ const POLL_MS = 50;
25
+ const NETWORK_CHANGED = "net::ERR_NETWORK_CHANGED";
23
26
  const VIEWPORT = { width: 1280, height: 900 };
24
27
 
28
+ /**
29
+ * Holds in a page once its document is parsed and every root the server
30
+ * rendered for a Vue app has mounted. Inertia marks such a root
31
+ * `data-server-rendered`, and Vue sets `__vue_app__` on it when `app.mount()`
32
+ * returns, hydration included. Before that the markup shows but takes no
33
+ * input: a click does nothing, a submit posts the form natively and
34
+ * hydration resets a typed value. A parsed page with no such root, such as a
35
+ * JSON answer or a page rendered in the browser only, holds at once.
36
+ */
37
+ const HYDRATED = `document.readyState !== "loading" && [...document.querySelectorAll("[data-server-rendered]")].every((root) => "__vue_app__" in root)`;
38
+
39
+ /**
40
+ * Holds in a hydrated page that has left `/auth` and rendered the content of
41
+ * the page it landed on. Signing in ends with a client-side visit: the URL
42
+ * changes first, and the layout and the page render once their chunks have
43
+ * loaded. Every layout of the dashboard, the error page's included, marks
44
+ * the region that holds the page `data-dms-page-content`.
45
+ */
46
+ const LANDED = `${HYDRATED} && !location.pathname.startsWith("/auth") && document.querySelector("[data-dms-page-content]")?.childElementCount > 0`;
47
+
25
48
  /**
26
49
  * Launches the headless Chromium that playwright-core pins.
27
50
  *
@@ -135,44 +158,138 @@ const ACTIONS = {
135
158
  /** The action names `perform` accepts. */
136
159
  export const ACTION_NAMES = Object.keys(ACTIONS);
137
160
 
161
+ /** The actions that only load a page, so running one again repeats no input. */
162
+ const LOADS = new Set(["goto", "reload"]);
163
+
138
164
  /**
139
- * Writes what the page shows into `folder`: `url.txt`, `aria.yml` (the ARIA
140
- * snapshot of the body) and `screenshot.png`.
165
+ * Writes a full-page `screenshot.png` of the page into `folder`, timed as a
166
+ * `screenshot` phase. A page that cannot be captured, such as a closed one,
167
+ * leaves no file.
141
168
  *
142
169
  * @param {Page} page The Playwright page
143
170
  * @param {string} folder The evidence folder
171
+ * @param {{ evidence: string }} state The run, whose timings record the screenshot
172
+ * @returns {Promise<void>} Resolves once the screenshot is written or given up
173
+ */
174
+ export async function screenshot(page, folder, state) {
175
+ await timed(
176
+ state,
177
+ "screenshot",
178
+ () =>
179
+ page
180
+ .screenshot({
181
+ path: join(folder, "screenshot.png"),
182
+ fullPage: true,
183
+ timeout: ACTION_TIMEOUT_MS,
184
+ })
185
+ .catch(() => undefined),
186
+ { step: relative(state.evidence, folder) },
187
+ );
188
+ }
189
+
190
+ /**
191
+ * Waits until a condition holds in the page, at most `ACTION_TIMEOUT_MS`. A
192
+ * page where it never holds leaves what follows to succeed or fail on its
193
+ * own.
194
+ *
195
+ * @param {Page} page The Playwright page
196
+ * @param {string} condition An expression evaluated in the page, such as `HYDRATED`
197
+ * @returns {Promise<boolean>} Whether it held before the timeout
198
+ */
199
+ function reached(page, condition) {
200
+ return page
201
+ .waitForFunction(condition, undefined, {
202
+ polling: POLL_MS,
203
+ timeout: ACTION_TIMEOUT_MS,
204
+ })
205
+ .then(
206
+ () => true,
207
+ () => false,
208
+ );
209
+ }
210
+
211
+ /**
212
+ * Runs an action, then waits until the page it leads to has loaded, and
213
+ * then both until it has hydrated and `SETTLE_MS`: a client-side visit, such
214
+ * as the one signing in starts, renders its page within the document that
215
+ * already hydrated.
216
+ *
217
+ * @param {Page} page The Playwright page
218
+ * @param {() => Promise<unknown> | undefined} act The action
219
+ * @returns {Promise<string[]>} When the page did not hydrate in time, the URLs of its requests that failed with `net::ERR_NETWORK_CHANGED`; none otherwise
220
+ */
221
+ async function settle(page, act) {
222
+ /** @type {string[]} */
223
+ const networkChanged = [];
224
+ /** @param {import("playwright-core").Request} request The request that failed */
225
+ const onFailed = (request) => {
226
+ if (request.failure()?.errorText === NETWORK_CHANGED)
227
+ networkChanged.push(request.url());
228
+ };
229
+ page.on("requestfailed", onFailed);
230
+ try {
231
+ await act();
232
+ await page
233
+ .waitForLoadState("load", { timeout: NAVIGATION_TIMEOUT_MS })
234
+ .catch(() => undefined);
235
+ const [hydratedInTime] = await Promise.all([
236
+ reached(page, HYDRATED),
237
+ page.waitForTimeout(SETTLE_MS),
238
+ ]);
239
+ return hydratedInTime ? [] : networkChanged;
240
+ } finally {
241
+ page.off("requestfailed", onFailed);
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Writes what the page shows into `folder`: `url.txt` and `aria.yml` (the
247
+ * ARIA snapshot of the body).
248
+ *
249
+ * @param {Page} page The Playwright page
250
+ * @param {string} folder The evidence folder
251
+ * @param {{ evidence: string }} state The run, whose timings record the capture
144
252
  * @returns {Promise<string>} The ARIA snapshot
145
253
  */
146
- export async function capture(page, folder) {
254
+ export async function capture(page, folder, state) {
255
+ const step = relative(state.evidence, folder);
147
256
  writeFileSync(join(folder, "url.txt"), `${page.url()}\n`);
148
- const aria = await page
149
- .locator("body")
150
- .ariaSnapshot({ timeout: ACTION_TIMEOUT_MS })
151
- .catch(
152
- (/** @type {unknown} */ error) =>
153
- `snapshot failed: ${describeFailure(error)}`,
154
- );
257
+ const aria = await timed(
258
+ state,
259
+ "aria",
260
+ () =>
261
+ page
262
+ .locator("body")
263
+ .ariaSnapshot({ timeout: ACTION_TIMEOUT_MS })
264
+ .catch(
265
+ (/** @type {unknown} */ error) =>
266
+ `snapshot failed: ${describeFailure(error)}`,
267
+ ),
268
+ { step },
269
+ );
155
270
  writeFileSync(join(folder, "aria.yml"), `${aria}\n`);
156
- await page
157
- .screenshot({
158
- path: join(folder, "screenshot.png"),
159
- fullPage: true,
160
- timeout: ACTION_TIMEOUT_MS,
161
- })
162
- .catch(() => undefined);
163
271
  return aria;
164
272
  }
165
273
 
166
274
  /**
167
- * Runs one action on a page, then captures the page into `folder`. A target
168
- * that is missing, hidden or disabled past the timeout fails the action.
275
+ * Runs one action on a page, then captures the page into `folder`: the
276
+ * action, the URL and the ARIA snapshot always, a screenshot only when the
277
+ * action failed, is the `screenshot` action or is asked for. The action
278
+ * ends once the page it leads to has hydrated, and starts once the current
279
+ * page has, except a `goto` or `reload`, which replaces it. A `goto` or
280
+ * `reload` whose page did not hydrate after a request failed with
281
+ * `net::ERR_NETWORK_CHANGED` runs once more, and leaves
282
+ * `network-changed.txt`. A target that is missing, hidden or disabled past
283
+ * the timeout fails the action.
169
284
  *
170
285
  * @param {Page} page The Playwright page
171
286
  * @param {Action} action What to do
172
287
  * @param {string} folder The evidence folder
288
+ * @param {{ evidence: string }} state The run, whose timings record the capture and the screenshot
289
+ * @param {{ screenshot?: boolean }} [options] Whether to write a screenshot whatever the outcome
173
290
  * @returns {Promise<Outcome>} The outcome
174
291
  */
175
- export async function perform(page, action, folder) {
292
+ export async function perform(page, action, folder, state, options = {}) {
176
293
  const run = ACTIONS[action.do];
177
294
  if (!run)
178
295
  throw new Error(
@@ -182,26 +299,36 @@ export async function perform(page, action, folder) {
182
299
  join(folder, "action.json"),
183
300
  `${JSON.stringify({ ...action, target: action.target && describeTarget(action.target) }, null, 2)}\n`,
184
301
  );
302
+ const loads = LOADS.has(action.do);
185
303
  let error = null;
186
304
  try {
187
- await run(page, action);
188
- await page
189
- .waitForLoadState("load", { timeout: NAVIGATION_TIMEOUT_MS })
190
- .catch(() => undefined);
191
- await page.waitForTimeout(SETTLE_MS);
305
+ if (!loads) await reached(page, HYDRATED);
306
+ const failed = await settle(page, () => run(page, action));
307
+ if (loads && failed.length > 0) {
308
+ writeFileSync(
309
+ join(folder, "network-changed.txt"),
310
+ `The page had not hydrated ${ACTION_TIMEOUT_MS / 1000} s after it loaded. It was loaded again. These requests failed with ${NETWORK_CHANGED} meanwhile:\n${failed.map((url) => `${url}\n`).join("")}`,
311
+ );
312
+ await settle(page, () => run(page, action));
313
+ }
192
314
  } catch (failure) {
193
315
  error = describeFailure(failure).split("\n")[0];
194
316
  }
195
- const aria = await capture(page, folder);
317
+ const aria = await capture(page, folder, state);
318
+ if (error !== null || action.do === "screenshot" || options.screenshot)
319
+ await screenshot(page, folder, state);
196
320
  return { ok: error === null, url: page.url(), error, aria };
197
321
  }
198
322
 
199
323
  /**
200
- * Signs an account in through the sign-in form, the way a user does.
324
+ * Signs an account in through the sign-in form, the way a user does, and
325
+ * returns once the page it lands on has rendered its content (`LANDED`), or
326
+ * the timeout passed. When the page stays on `/auth`, a screenshot of it
327
+ * goes into the last step's folder.
201
328
  *
202
329
  * @param {Page} page The Playwright page
203
330
  * @param {{ email: string, password: string }} credentials The account
204
- * @param {{ baseUrl: string, folder: (label: string) => string }} options Where the frontend is and where evidence goes
331
+ * @param {{ baseUrl: string, folder: (label: string) => string, state: { evidence: string } }} options Where the frontend is, where evidence goes and the run whose timings record the captures
205
332
  * @returns {Promise<Outcome>} The outcome of the last step
206
333
  */
207
334
  export async function signInThroughForm(page, credentials, options) {
@@ -220,11 +347,16 @@ export async function signInThroughForm(page, credentials, options) {
220
347
  { do: "click", target: { role: "button", name: "Login", exact: true } },
221
348
  ];
222
349
  let outcome = { ok: true, url: page.url(), error: null, aria: "" };
350
+ let folder = "";
223
351
  for (const step of steps) {
352
+ folder = options.folder(
353
+ `sign in ${step.do} ${step.target?.name ?? step.path}`,
354
+ );
224
355
  outcome = await perform(
225
356
  page,
226
357
  { ...step, baseUrl: options.baseUrl },
227
- options.folder(`sign in ${step.do} ${step.target?.name ?? step.path}`),
358
+ folder,
359
+ options.state,
228
360
  );
229
361
  if (!outcome.ok) return outcome;
230
362
  }
@@ -233,11 +365,10 @@ export async function signInThroughForm(page, credentials, options) {
233
365
  timeout: NAVIGATION_TIMEOUT_MS,
234
366
  })
235
367
  .catch(() => undefined);
236
- return {
237
- ...outcome,
238
- url: page.url(),
239
- ok: !new URL(page.url()).pathname.startsWith("/auth"),
240
- };
368
+ const ok = !new URL(page.url()).pathname.startsWith("/auth");
369
+ if (ok) await reached(page, LANDED);
370
+ else await screenshot(page, folder, options.state);
371
+ return { ...outcome, url: page.url(), ok };
241
372
  }
242
373
 
243
374
  /**
@@ -320,9 +451,15 @@ export async function serveBrowser(dir, from, port) {
320
451
  return signInThroughForm(page, credentials, {
321
452
  baseUrl: state.webUrl,
322
453
  folder: () => request.folder,
454
+ state,
323
455
  });
324
456
  }
325
- return perform(page, { ...request, baseUrl: state.webUrl }, request.folder);
457
+ return perform(
458
+ page,
459
+ { ...request, baseUrl: state.webUrl },
460
+ request.folder,
461
+ state,
462
+ );
326
463
  };
327
464
  const server = createServer((incoming, outgoing) => {
328
465
  if (incoming.method !== "POST") {