@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
@@ -1,49 +1,49 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import {
3
- cpSync,
4
- existsSync,
5
- mkdirSync,
6
- readdirSync,
7
- readFileSync,
8
- rmSync,
9
- symlinkSync,
10
- } from "node:fs";
2
+ import { existsSync, rmSync } from "node:fs";
11
3
  import { createRequire } from "node:module";
12
4
  import { homedir } from "node:os";
13
- import { basename, dirname, join, relative, resolve, sep } from "node:path";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { layOutFrontendBuild } from "./build-cache.mjs";
7
+ import { existingBuildRoots } from "./build-inputs.mjs";
14
8
  import { describeFailure } from "./failure.mjs";
15
9
  import { checkoutOf } from "./git.mjs";
16
- import { stringField } from "./json.mjs";
17
- import { dropDatabase, dropRunDatabases, startMongod } from "./mongo.mjs";
10
+ import { apiTargetFile, writeTarget } from "./forwarder.mjs";
11
+ import { currentNamespaces, isSameProcess } from "./identity.mjs";
12
+ import { dropRunDatabases, startMongod } from "./mongo.mjs";
18
13
  import {
19
14
  freePort,
20
- isAlive,
21
15
  runToEnd,
22
16
  startDetached,
23
- stopAll,
17
+ stopRecorded,
24
18
  waitForOk,
25
19
  waitForOwnPort,
26
20
  } from "./processes.mjs";
27
21
  import {
22
+ backendsFolder,
28
23
  createRunFolders,
29
24
  databaseName,
25
+ forgetBackend,
30
26
  newRunId,
27
+ recordBackend,
28
+ recordedBackends,
31
29
  runsRoot,
32
30
  saveRun,
33
31
  } from "./run-state.mjs";
34
32
  import { RENDERER_CLI, resolveRenderer } from "./renderer.mjs";
33
+ import { layOutCopy } from "./run-copy.mjs";
35
34
  import { newPassword } from "./session.mjs";
35
+ import { appendTiming, recordTiming, stopwatch, timed } from "./timing.mjs";
36
36
 
37
37
  /**
38
38
  * @typedef {import("./run-state.mjs").RunState} RunState
39
- * @typedef {{ playground: string, renderer?: string, runs?: string, mongoUrl?: string, env?: string[], base?: string, skill?: string }} UpOptions Where the playground and the runs are
39
+ * @typedef {{ playground: string, renderer?: string, runs?: string, mongoUrl?: string, env?: string[], base?: string, skill?: string, prepared?: import("./timing.mjs").TimingEntry[], noStandby?: boolean, buildCache?: boolean }} UpOptions Where the playground and the runs are, the `prepare` entries to record once the run exists, whether fresh databases start their backend on the spot, and whether the frontend build may come from the build cache (it may unless `buildCache` is false)
40
40
  */
41
41
 
42
42
  const READY_TIMEOUT_MS = 180_000;
43
43
  const SECRET_BYTES = 32;
44
+ const PREPARED_WORKSPACE = new URL("prepared-workspace.mjs", import.meta.url)
45
+ .href;
44
46
  const MAIL_PORT_ATTEMPTS = 3;
45
- const COPY_SKIPPED = new Set(["node_modules", ".antelope", ".dms-frontend"]);
46
- const SHADOW_SKIPPED = new Set([".antelope", ".dms-frontend", ".git"]);
47
47
  const SECRET_NAMES = [
48
48
  "DMS_JWT_SECRET",
49
49
  "AUTH_JWT_SECRET",
@@ -85,78 +85,26 @@ export function resolutionFolders(state) {
85
85
  export function cliPaths(playground, renderer) {
86
86
  const require = createRequire(join(playground, "package.json"));
87
87
  const core = dirname(require.resolve("@antelopejs/core/package.json"));
88
- const frontend =
89
- renderer ??
90
- dirname(require.resolve("@antelopejs/dms-frontend/package.json"));
91
88
  return {
92
89
  ajs: join(core, "dist", "core", "cli", "index.js"),
93
- dms: join(frontend, RENDERER_CLI),
90
+ dms: join(frontendPackage(playground, renderer), RENDERER_CLI),
94
91
  };
95
92
  }
96
93
 
97
94
  /**
98
- * @param {string} real
99
- * @param {string} shadow
100
- * @param {string} keep
101
- */
102
- function shadowLevel(real, shadow, keep) {
103
- mkdirSync(shadow, { recursive: true });
104
- for (const entry of readdirSync(real)) {
105
- if (entry === keep || SHADOW_SKIPPED.has(entry)) continue;
106
- symlinkSync(join(real, entry), join(shadow, entry));
107
- }
108
- }
109
-
110
- /**
111
- * A `node_modules` that is `modules` with `@antelopejs/dms-frontend` replaced
112
- * by the renderer checkout, every other entry linked to the original.
113
- *
114
- * @param {string} modules The playground's installed modules
115
- * @param {string} shadow The run's `node_modules`
116
- * @param {string} renderer The renderer checkout
117
- */
118
- export function linkRenderer(modules, shadow, renderer) {
119
- const scope = "@antelopejs";
120
- shadowLevel(modules, shadow, scope);
121
- const scoped = join(modules, scope);
122
- const shadowScope = join(shadow, scope);
123
- if (existsSync(scoped)) shadowLevel(scoped, shadowScope, "dms-frontend");
124
- else mkdirSync(shadowScope);
125
- symlinkSync(renderer, join(shadowScope, "dms-frontend"));
126
- }
127
-
128
- /**
129
- * Lays out the run's copy of the checkout: from the checkout root down to
130
- * the playground, every sibling is linked, so relative paths such as a
131
- * tsconfig `extends` resolve as in the checkout. The playground itself is
132
- * copied without its installed modules and build, so `.antelope/` and the
133
- * frontend build belong to the run. Its `node_modules` is the playground's,
134
- * except that `@antelopejs/dms-frontend` is the `renderer` checkout when
135
- * there is one.
95
+ * The `@antelopejs/dms-frontend` that builds and serves the run's dashboard:
96
+ * the renderer checkout, else the one the playground installs.
136
97
  *
137
98
  * @param {string} playground The playground folder
138
- * @param {string} checkout The checkout root, or the module folder outside one
139
- * @param {string} root The run's copy of the checkout
140
99
  * @param {string} [renderer] The renderer checkout the run serves
141
- * @returns {string} The run's playground folder
100
+ * @returns {string} Its folder
142
101
  */
143
- export function layOutCopy(playground, checkout, root, renderer) {
144
- const segments = relative(checkout, playground).split(sep);
145
- let real = checkout;
146
- let shadow = root;
147
- for (const segment of segments) {
148
- shadowLevel(real, shadow, segment);
149
- real = join(real, segment);
150
- shadow = join(shadow, segment);
151
- }
152
- cpSync(playground, shadow, {
153
- recursive: true,
154
- filter: (source) => !COPY_SKIPPED.has(basename(source)),
155
- });
156
- const modules = join(playground, "node_modules");
157
- if (renderer) linkRenderer(modules, join(shadow, "node_modules"), renderer);
158
- else symlinkSync(modules, join(shadow, "node_modules"));
159
- return shadow;
102
+ export function frontendPackage(playground, renderer) {
103
+ const require = createRequire(join(playground, "package.json"));
104
+ return (
105
+ renderer ??
106
+ dirname(require.resolve("@antelopejs/dms-frontend/package.json"))
107
+ );
160
108
  }
161
109
 
162
110
  function inheritedEnv() {
@@ -262,11 +210,13 @@ async function initialState(options) {
262
210
  adminPassword: newPassword(),
263
211
  extraEnv: parseExtraEnv(options.env ?? []),
264
212
  processes: [],
213
+ namespaces: currentNamespaces(),
265
214
  accounts: {},
266
215
  tokens: {},
267
216
  ready: false,
268
217
  };
269
218
  if (renderer) state.renderer = renderer;
219
+ if (options.noStandby) state.noStandby = true;
270
220
  return state;
271
221
  }
272
222
 
@@ -293,10 +243,12 @@ export function spec(state, name, script, args, cwd = state.runPlayground) {
293
243
  }
294
244
 
295
245
  /**
296
- * @param {RunState} state
297
- * @param {import("./run-state.mjs").ProcessRecord} processRecord
246
+ * Records a process of the run, in place of the one of the same name.
247
+ *
248
+ * @param {RunState} state The run
249
+ * @param {import("./run-state.mjs").ProcessRecord} processRecord The process
298
250
  */
299
- function record(state, processRecord) {
251
+ export function record(state, processRecord) {
300
252
  state.processes = [
301
253
  ...state.processes.filter((entry) => entry.name !== processRecord.name),
302
254
  processRecord,
@@ -305,25 +257,47 @@ function record(state, processRecord) {
305
257
  }
306
258
 
307
259
  /**
308
- * Starts the run's mail sink unless it already runs, and waits until it is
309
- * the process listening on the run's mail port.
310
- *
311
- * @param {import("./run-state.mjs").RunState} state The run
312
- * @returns {Promise<void>} Resolves once it listens
260
+ * @param {RunState} state
261
+ * @param {"mail" | "api"} name
262
+ * @param {number} port
263
+ * @returns {Promise<void>}
313
264
  */
314
- export async function ensureMail(state) {
315
- const running = state.processes.find((entry) => entry.name === "mail");
316
- if (running && isAlive(running.pid)) return;
317
- const mail = startDetached({
318
- name: "mail",
265
+ async function ensureService(state, name, port) {
266
+ const running = state.processes.find((entry) => entry.name === name);
267
+ if (running && isSameProcess(running)) return;
268
+ const service = startDetached({
269
+ name,
319
270
  program: process.execPath,
320
- args: [CONTROL_BIN, "serve-mail", state.dir],
271
+ args: [CONTROL_BIN, `serve-${name}`, state.dir],
321
272
  cwd: state.dir,
322
273
  env: process.env,
323
274
  logs: state.logs,
324
275
  });
325
- record(state, { ...mail, port: state.smtpPort });
326
- await waitForOwnPort(state.smtpPort, mail, READY_TIMEOUT_MS);
276
+ record(state, { ...service, port });
277
+ await waitForOwnPort(port, service, READY_TIMEOUT_MS);
278
+ }
279
+
280
+ /**
281
+ * Starts the run's mail sink unless it already runs, and waits until it is
282
+ * the process listening on the run's mail port.
283
+ *
284
+ * @param {import("./run-state.mjs").RunState} state The run
285
+ * @returns {Promise<void>} Resolves once it listens
286
+ */
287
+ export function ensureMail(state) {
288
+ return ensureService(state, "mail", state.smtpPort);
289
+ }
290
+
291
+ /**
292
+ * Starts the run's API forwarder unless it already runs, and waits until it
293
+ * is the process listening on the run's API port. The dashboard, the
294
+ * journeys and `DMS_API_BASE_URL` reach the backend through it.
295
+ *
296
+ * @param {import("./run-state.mjs").RunState} state The run
297
+ * @returns {Promise<void>} Resolves once it listens
298
+ */
299
+ export function ensureApi(state) {
300
+ return ensureService(state, "api", state.apiPort);
327
301
  }
328
302
 
329
303
  /**
@@ -343,155 +317,244 @@ async function startFirstMail(state) {
343
317
  }
344
318
 
345
319
  /**
346
- * @param {RunState} state
347
- * @param {{ playground?: string, cwd?: string }} [build]
348
- * @returns {Promise<void>}
320
+ * Starts a backend of the run on `database` and a free loopback port of its
321
+ * own, from the run's build or `build`, without waiting for it, and records
322
+ * it in a file of its own. Its log is named after its database,
323
+ * `backend_<suffix>.log`, so two backends that run at once write apart; the
324
+ * first database's is `backend.log`.
325
+ *
326
+ * @param {RunState} state The run
327
+ * @param {string} database The database it serves
328
+ * @param {{ playground?: string, cwd?: string }} [build] Another build to start
329
+ * @returns {Promise<import("./run-state.mjs").BackendRecord>} Its record
349
330
  */
350
- async function startBackend(state, build) {
331
+ export async function launchBackend(state, database, build) {
351
332
  const { ajs } = cliPaths(build?.playground ?? state.playground);
352
- const backend = startDetached(
353
- spec(
354
- state,
355
- "backend",
356
- ajs,
357
- ["project", "start", "-e", ENVIRONMENT, "--refresh-config"],
358
- build?.cwd,
359
- ),
333
+ const port = await freePort();
334
+ const launch = spec(
335
+ state,
336
+ `backend${database.slice(state.databasePrefix.length)}`,
337
+ ajs,
338
+ ["project", "start", "-e", ENVIRONMENT, "--refresh-config"],
339
+ build?.cwd,
360
340
  );
361
- record(state, { ...backend, port: state.apiPort });
362
- await waitForOk(
363
- `${state.apiUrl}/api/onboarding/informations`,
341
+ launch.env = { ...launch.env, PORT: String(port), MONGO_DATABASE: database };
342
+ const backend = { ...startDetached(launch), name: "backend", port, database };
343
+ recordBackend(state.dir, backend);
344
+ return backend;
345
+ }
346
+
347
+ /**
348
+ * The backends the run started that still run. A record whose pid no longer
349
+ * runs the process the run started is forgotten: the backend exited, and
350
+ * the pid may be another process's now.
351
+ *
352
+ * @param {RunState} state The run
353
+ * @returns {import("./run-state.mjs").BackendRecord[]} The backends
354
+ */
355
+ export function liveBackends(state) {
356
+ return recordedBackends(state.dir).filter((backend) => {
357
+ if (isSameProcess(backend)) return true;
358
+ forgetBackend(state.dir, backend.pid);
359
+ return false;
360
+ });
361
+ }
362
+
363
+ /**
364
+ * Waits until a backend answers `/api/onboarding/informations` on its own port.
365
+ *
366
+ * @param {import("./run-state.mjs").ServerRecord} backend The backend
367
+ * @returns {Promise<void>} Resolves once it answers 200
368
+ * @throws When it exits first or the timeout passes, naming its log
369
+ */
370
+ export function waitForBackend(backend) {
371
+ return waitForOk(
372
+ `http://127.0.0.1:${backend.port}/api/onboarding/informations`,
364
373
  backend,
365
374
  READY_TIMEOUT_MS,
366
375
  );
367
376
  }
368
377
 
378
+ /**
379
+ * Starts the run's backend on `state.database`, from the run's build or
380
+ * `build`, and points the API at it once it answers.
381
+ *
382
+ * @param {RunState} state The run
383
+ * @param {{ playground?: string, cwd?: string }} [build] Another build to start
384
+ * @returns {Promise<void>} Resolves once the API reaches it
385
+ */
386
+ export async function startBackend(state, build) {
387
+ await ensureApi(state);
388
+ const backend = await launchBackend(state, state.database, build);
389
+ record(state, backend);
390
+ await waitForBackend(backend);
391
+ writeTarget(apiTargetFile(state.dir), backend.port);
392
+ }
393
+
394
+ /**
395
+ * How the run sets up a frontend workspace from the project in `project`
396
+ * as `ajs dms build` does before it builds (see `setUpFrontendWorkspace`),
397
+ * in a process with the run's environment and its own log.
398
+ *
399
+ * @param {RunState} state The run, after its project build
400
+ * @param {string} name The log name
401
+ * @param {string} project The project folder
402
+ * @param {boolean} install Whether to install the workspace's dependencies
403
+ * @returns {(workspace: string) => Promise<void>} Sets up the workspace folder it is given
404
+ */
405
+ export function workspaceSetup(state, name, project, install) {
406
+ return (workspace) =>
407
+ runToEnd(
408
+ spec(
409
+ state,
410
+ name,
411
+ CONTROL_BIN,
412
+ [
413
+ "prepare-frontend",
414
+ frontendPackage(state.playground, state.renderer),
415
+ workspace,
416
+ ENVIRONMENT,
417
+ install ? "install" : "sources",
418
+ ],
419
+ project,
420
+ ),
421
+ );
422
+ }
423
+
369
424
  /**
370
425
  * @param {RunState} state
426
+ * @param {boolean} useCache
371
427
  * @returns {Promise<void>}
372
428
  */
373
- async function buildAndStart(state) {
429
+ async function buildAndStart(state, useCache) {
374
430
  const clis = cliPaths(state.playground, state.renderer);
375
- state.runPlayground = layOutCopy(
376
- state.playground,
377
- state.repo ?? state.moduleRoot,
378
- state.root,
379
- state.renderer,
431
+ state.runPlayground = await timed(state, "layout", () =>
432
+ layOutCopy(
433
+ state.playground,
434
+ state.repo ?? state.moduleRoot,
435
+ state.root,
436
+ state.renderer,
437
+ ),
380
438
  );
381
439
  if (state.ownsMongo) {
382
- const mongo = await startMongod(state, resolutionFolders(state));
440
+ const mongo = await timed(state, "mongod", () =>
441
+ startMongod(state, resolutionFolders(state)),
442
+ );
383
443
  state.mongoUrl = mongo.url;
384
444
  record(state, mongo.record);
385
445
  }
386
- await startFirstMail(state);
387
- await runToEnd(
388
- spec(state, "project-build", clis.ajs, [
389
- "project",
390
- "build",
391
- "-e",
392
- ENVIRONMENT,
393
- ]),
394
- );
395
- await runToEnd(
396
- spec(state, "frontend-build", clis.dms, ["build", "-e", ENVIRONMENT]),
446
+ await timed(state, "mail", () => startFirstMail(state));
447
+ await timed(state, "project-build", () =>
448
+ runToEnd(
449
+ spec(state, "project-build", clis.ajs, [
450
+ "project",
451
+ "build",
452
+ "-e",
453
+ ENVIRONMENT,
454
+ ]),
455
+ ),
397
456
  );
398
- await startBackend(state);
399
- const frontend = startDetached(
400
- spec(state, "frontend", clis.dms, [
401
- "start",
402
- "-e",
403
- ENVIRONMENT,
404
- "-b",
405
- state.apiUrl,
406
- "-p",
407
- String(state.webPort),
408
- ]),
457
+ await timed(state, "frontend-build", () =>
458
+ layOutFrontendBuild(
459
+ state,
460
+ frontendPackage(state.playground, state.renderer),
461
+ {
462
+ prepare: (workspace) =>
463
+ timed(state, "frontend-prepare", () =>
464
+ workspaceSetup(
465
+ state,
466
+ "frontend-prepare",
467
+ state.runPlayground ?? "",
468
+ true,
469
+ )(workspace),
470
+ ),
471
+ build: (prepared) => {
472
+ const build = spec(state, "frontend-build", clis.dms, [
473
+ "build",
474
+ "-e",
475
+ ENVIRONMENT,
476
+ ]);
477
+ if (prepared) build.args.unshift("--import", PREPARED_WORKSPACE);
478
+ return runToEnd(build);
479
+ },
480
+ },
481
+ useCache,
482
+ ),
409
483
  );
410
- record(state, { ...frontend, port: state.webPort });
411
- await waitForOk(`${state.webUrl}/dms-preview`, frontend, READY_TIMEOUT_MS);
484
+ state.buildRoots = existingBuildRoots(state);
485
+ saveRun(state);
486
+ await timed(state, "backend-start", () => startBackend(state));
487
+ await timed(state, "frontend-start", async () => {
488
+ const frontend = startDetached(
489
+ spec(state, "frontend", clis.dms, [
490
+ "start",
491
+ "-e",
492
+ ENVIRONMENT,
493
+ "-b",
494
+ state.apiUrl,
495
+ "-p",
496
+ String(state.webPort),
497
+ ]),
498
+ );
499
+ record(state, { ...frontend, port: state.webPort });
500
+ await waitForOk(`${state.webUrl}/dms-preview`, frontend, READY_TIMEOUT_MS);
501
+ });
412
502
  }
413
503
 
414
504
  /**
415
505
  * Starts an isolated DMS from a playground: a copy of it in a run folder,
416
506
  * free ports, the `docs` environment, a `verify_<run>` database on a mongod
417
- * the run owns (or `--mongo-url`), fresh secrets and a mail sink. With
507
+ * the run owns (or `--mongo-url`), fresh secrets, a mail sink, and a
508
+ * forwarder on the API port to a backend on a port of its own. With
418
509
  * `renderer`, the dashboard is that built dms-frontend checkout. Ready once
419
- * `/api/onboarding/informations` and `/dms-preview` answer 200. On failure
510
+ * `/api/onboarding/informations` and `/dms-preview` answer 200. The frontend
511
+ * build comes from the build cache when an earlier run built the same inputs
512
+ * (see `buildInputs`), unless `buildCache` is false. On failure
420
513
  * it stops what it started and keeps the logs.
421
514
  *
422
515
  * @param {UpOptions} options Where the playground and the runs are
423
516
  * @returns {Promise<import("./run-state.mjs").RunState>} The ready run
424
517
  */
425
518
  export async function up(options) {
519
+ const stop = stopwatch();
426
520
  const state = await initialState(options);
427
521
  saveRun(state);
522
+ for (const entry of options.prepared ?? []) appendTiming(state, entry);
428
523
  try {
429
- await buildAndStart(state);
524
+ await buildAndStart(state, options.buildCache !== false);
430
525
  } catch (error) {
431
526
  state.error = String(error?.message ?? error);
432
527
  saveRun(state);
433
- await stopAll(state.processes.map((entry) => entry.pid));
528
+ await stopRecorded(state.processes);
529
+ recordTiming(state, "up", stop(), false);
434
530
  throw error;
435
531
  }
436
532
  state.ready = true;
437
533
  saveRun(state);
534
+ recordTiming(state, "up", stop(), true);
438
535
  return state;
439
536
  }
440
537
 
441
538
  /**
442
- * Stops the backend and starts it again on `state.database`, as a deploy or
443
- * a crash would, from the run's build or another one (`build`, the base
444
- * version's). The frontend keeps serving and proxies to the same port.
445
- *
446
- * @param {import("./run-state.mjs").RunState} state The run
447
- * @param {{ playground: string, cwd: string }} [build] Another build to start
448
- * @returns {Promise<void>} Resolves once the backend answers again
449
- */
450
- export async function restartBackend(state, build) {
451
- const backend = state.processes.find((entry) => entry.name === "backend");
452
- if (backend) await stopAll([backend.pid]);
453
- await startBackend(state, build);
454
- }
455
-
456
- /**
457
- * Restarts the backend on another database of the run, so a journey starts
458
- * from an empty one: not onboarded, no user, no session. The previous
459
- * journey database is dropped, so a long run does not exhaust mongod's
460
- * file handles; its evidence stays.
461
- *
462
- * @param {import("./run-state.mjs").RunState} state The run
463
- * @param {string} suffix What tells the database apart, such as `j03`
464
- * @returns {Promise<string>} The database now in use
465
- */
466
- export async function freshDatabase(state, suffix) {
467
- const previous = state.database;
468
- state.database = `${state.databasePrefix}_${suffix}`;
469
- state.tokens = {};
470
- state.accounts = {};
471
- saveRun(state);
472
- await restartBackend(state);
473
- if (previous !== state.databasePrefix && previous !== state.database) {
474
- await dropDatabase(state.mongoUrl, previous, resolutionFolders(state));
475
- }
476
- return state.database;
477
- }
478
-
479
- /**
480
- * Stops every process the run recorded and their descendants, drops the
481
- * run's databases, and removes everything but `evidence/`, `logs/` and
482
- * `run.json`, from which the secrets and passwords are removed.
539
+ * Stops every process the run recorded, every backend it started and their
540
+ * descendants, each only while its pid still runs the process the run
541
+ * started, drops the run's databases, and removes everything but
542
+ * `evidence/`, `logs/` and `run.json`, from which the secrets and passwords
543
+ * are removed.
483
544
  *
484
545
  * @param {import("./run-state.mjs").RunState} state The run
485
546
  * @returns {Promise<string[]>} One line per action
486
547
  */
487
548
  export async function down(state) {
488
- const browser = state.browser ? [state.browser.pid] : [];
489
- const app = state.processes
490
- .filter((entry) => entry.name !== "mongod")
491
- .map((entry) => entry.pid);
492
- const lines = await stopAll([...app, ...browser]);
549
+ const browser = state.browser ? [state.browser] : [];
550
+ const app = state.processes.filter((entry) => entry.name !== "mongod");
551
+ const lines = await stopRecorded([
552
+ ...app,
553
+ ...browser,
554
+ ...liveBackends(state),
555
+ ]);
493
556
  const mongod = state.processes.find((entry) => entry.name === "mongod");
494
- if (mongod && !isAlive(mongod.pid)) {
557
+ if (mongod && !isSameProcess(mongod)) {
495
558
  lines.push(`mongod already stopped; its data goes with ${state.mongo}`);
496
559
  } else if (state.mongoUrl) {
497
560
  const dropped = await dropRunDatabases(
@@ -503,13 +566,15 @@ export async function down(state) {
503
566
  ]);
504
567
  lines.push(...dropped);
505
568
  }
506
- lines.push(...(await stopAll(state.processes.map((entry) => entry.pid))));
569
+ lines.push(...(await stopRecorded(state.processes)));
507
570
  for (const folder of [
508
571
  state.root,
509
572
  state.home,
510
573
  state.mongo,
511
574
  state.baseRoot,
512
575
  state.cache,
576
+ apiTargetFile(state.dir),
577
+ backendsFolder(state.dir),
513
578
  ]) {
514
579
  if (folder && existsSync(folder)) {
515
580
  rmSync(folder, { recursive: true, force: true });
@@ -532,21 +597,5 @@ export async function down(state) {
532
597
  stoppedAt: new Date().toISOString(),
533
598
  });
534
599
  saveRun(state);
535
- return lines;
536
- }
537
-
538
- /**
539
- * The version a package.json declares, or `missing`.
540
- *
541
- * @param {string} file The package.json
542
- * @returns {string} The version
543
- */
544
- export function packageVersion(file) {
545
- try {
546
- /** @type {unknown} */
547
- const manifest = JSON.parse(readFileSync(file, "utf8"));
548
- return stringField(manifest, "version") ?? "missing";
549
- } catch {
550
- return "missing";
551
- }
600
+ return [...new Set(lines)];
552
601
  }