@tsplc/build 0.2.20 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +1052 -836
  3. package/dist/cli.js.map +27 -24
  4. package/dist/images.js +165 -0
  5. package/dist/images.js.map +12 -0
  6. package/dist/index.js +888 -668
  7. package/dist/index.js.map +23 -20
  8. package/dist/libraries.js +4 -3
  9. package/dist/libraries.js.map +3 -3
  10. package/docker/Dockerfile.dockerignore +0 -4
  11. package/docker/Dockerfile.source +5 -0
  12. package/docker/build-image +30 -26
  13. package/docker/config.ts +1 -1
  14. package/docker/install/wine-signal/README.md +1 -1
  15. package/docker/runner.ts +9 -7
  16. package/package.json +24 -8
  17. package/python/build.py +231 -20
  18. package/python/codesys_online.py +121 -10
  19. package/python/worker.py +2 -0
  20. package/src/artifacts.ts +9 -7
  21. package/src/build.ts +9 -4
  22. package/src/cli.ts +11 -20
  23. package/src/controller-online.ts +145 -61
  24. package/src/controller-protocol.ts +48 -5
  25. package/src/controller-session.ts +386 -147
  26. package/src/device-tree.ts +1 -1
  27. package/src/docker-build.ts +80 -98
  28. package/src/docker-context.ts +56 -3
  29. package/src/docker-run.ts +56 -3
  30. package/src/engineering-settings.ts +3 -3
  31. package/src/host/codesys-host.ts +3 -3
  32. package/src/host/codesys-worker.ts +77 -3
  33. package/src/images.ts +105 -0
  34. package/src/import-request.ts +1 -0
  35. package/src/index.ts +30 -16
  36. package/src/io.ts +1 -1
  37. package/src/libraries.ts +3 -2
  38. package/src/project-operations.ts +48 -0
  39. package/src/run.ts +9 -6
  40. package/src/sources.ts +2 -2
  41. package/docker/install/wine-signal/check.sh +0 -34
  42. package/docker/install/wine-signal/tests/avx-registers.c +0 -53
  43. package/docker/install/wine-signal/tests/frame-and-handler.c +0 -192
  44. package/docker/install/wine-signal/tests/loader-i386.c +0 -8
  45. package/docker/install/wine-signal/tests/signal-return.c +0 -47
  46. package/python/test_build.py +0 -579
  47. package/python/test_codesys_login.py +0 -139
  48. package/python/test_codesys_online.py +0 -259
  49. package/python/test_installer_packages.py +0 -217
  50. package/python/test_installer_verification.py +0 -307
  51. package/python/test_worker.py +0 -154
package/src/cli.ts CHANGED
@@ -1,16 +1,17 @@
1
1
  #!/usr/bin/env bun
2
2
  import { parseArgs } from "node:util";
3
- import { loadHardware, resolveIo } from "@tsplc/typegen/hardware";
4
- import { controllerFor, loadTsplcConfig, rawBuildConfig } from "@tsplc/config";
3
+ import { loadTsplcConfig } from "@tsplc/config";
5
4
  import { z } from "zod";
6
5
  import { buildProject } from "./build.ts";
7
- import { resolveConfig } from "@tsplc/config/build";
8
- import { inspectController, updateController } from "./controller-online.ts";
6
+ import { updateController } from "./controller-online.ts";
9
7
  import { configureDocker, configureRuntime } from "./docker-build.ts";
10
8
  import { rawEngineeringSettings } from "./engineering-settings.ts";
11
9
  import { installLibraries } from "./libraries.ts";
10
+ import {
11
+ checkRawSources,
12
+ inspectProjectController,
13
+ } from "./project-operations.ts";
12
14
  import { runProject } from "./run.ts";
13
- import { loadSources } from "./sources.ts";
14
15
 
15
16
  const commandSchema = z.enum([
16
17
  "configure",
@@ -58,7 +59,7 @@ async function main() {
58
59
  return;
59
60
  }
60
61
  const loaded = await loadTsplcConfig(values.config);
61
- const { config, configFile, root } = loaded;
62
+ const { config, root } = loaded;
62
63
  if (command === "install") {
63
64
  const libraries = await installLibraries(config.dependencies, root, {
64
65
  frozen: values["frozen-lockfile"],
@@ -70,17 +71,11 @@ async function main() {
70
71
  throw new Error("Configure build options in tsplc.config.ts.");
71
72
  }
72
73
  if (command === "inspect") {
73
- // Inspection only needs connection/baseline settings; it remains usable
74
- // without sources, EDS descriptors or installed library payloads.
75
74
  console.log(
76
75
  JSON.stringify(
77
- await inspectController(
78
- resolveConfig(
79
- { ...config.build, controller: controllerFor(config, command) },
80
- configFile,
81
- ),
82
- values.read,
83
- ),
76
+ await inspectProjectController(loaded, values.read, {
77
+ progress: "stderr",
78
+ }),
84
79
  null,
85
80
  2,
86
81
  ),
@@ -93,11 +88,7 @@ async function main() {
93
88
  );
94
89
  }
95
90
  if (command === "check") {
96
- const build = rawBuildConfig(config);
97
- const hardware = await loadHardware(config, root);
98
- const sources = await loadSources(
99
- resolveConfig({ ...build, io: resolveIo(config, hardware) }, configFile),
100
- );
91
+ const sources = await checkRawSources(loaded);
101
92
  console.log(`Validated ${sources.objects.length} Structured Text objects.`);
102
93
  return;
103
94
  }
@@ -1,54 +1,78 @@
1
- import { existsSync } from "node:fs";
2
1
  import { createHash, randomUUID } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
3
  import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { posix, resolve } from "node:path";
6
6
  import { setTimeout as delay } from "node:timers/promises";
7
+ import type { ResolvedConfig } from "@tsplc/config/build";
7
8
  import { z } from "zod";
8
- import { dockerImage, type ResolvedConfig } from "@tsplc/config/build";
9
9
  import {
10
10
  type Baseline,
11
11
  type ControllerCredentials,
12
12
  type ControllerResult,
13
13
  controllerResultSchema,
14
14
  controllerTarget,
15
+ DownloadRequiredError,
16
+ explicitDownload,
15
17
  failureReason,
16
18
  imageIdSchema,
17
19
  type LoginCommand,
18
20
  loginResultSchema,
21
+ requiresDownload,
22
+ rollbackSchema,
19
23
  sameBaseline,
24
+ TransferFailedError,
20
25
  tracebackFailure,
26
+ transferRollback,
21
27
  type warmOperationSchema,
22
28
  } from "./controller-protocol.ts";
29
+ import { controllerDirectory, jobProgressLog } from "./controller-session.ts";
23
30
  import { controllerFailureFile } from "./diagnostics.ts";
24
31
  import {
32
+ type ContainerEnvironment,
25
33
  captureDocker,
34
+ type ProgressOptions,
35
+ pipeDocker,
26
36
  prepareContainerRun,
27
37
  runDocker,
28
38
  writeOperationRequest,
29
39
  } from "./docker-run.ts";
40
+ import { builderImage } from "./images.ts";
30
41
 
31
- export interface ControllerUpdateOptions {
42
+ /** Where an operation reads the controller user's environment variables from; this process's environment by default. */
43
+ export interface CredentialSource {
44
+ environment?: Readonly<Record<string, string | undefined>>;
45
+ }
46
+
47
+ export interface ControllerUpdateOptions
48
+ extends ProgressOptions,
49
+ CredentialSource {
32
50
  initializeUser?: boolean;
33
51
  read?: string[];
34
52
  }
35
53
 
36
54
  /** The controller user's environment variables, which a container started now passes to CODESYS. */
37
- const credentialEnvironment = (config: ResolvedConfig) => {
55
+ const credentialEnvironment = (
56
+ config: ResolvedConfig,
57
+ { environment = process.env }: CredentialSource,
58
+ ): ContainerEnvironment => {
38
59
  const names = config.online?.credentials
39
60
  ? [
40
61
  config.online.credentials.usernameEnv,
41
62
  config.online.credentials.passwordEnv,
42
63
  ]
43
64
  : [];
44
- for (const name of names) {
45
- if (process.env[name] === undefined) {
46
- throw new Error(
47
- `Controller credential environment variable ${name} is not set`,
48
- );
49
- }
50
- }
51
- return names;
65
+ return Object.fromEntries(
66
+ names.map((name) => {
67
+ const value = environment[name];
68
+ if (value === undefined) {
69
+ throw new Error(
70
+ `Controller credential environment variable ${name} is not set`,
71
+ );
72
+ }
73
+ return [name, value];
74
+ }),
75
+ );
52
76
  };
53
77
 
54
78
  /** Checks the settings every engineering connection needs and names its builder image and target. */
@@ -59,11 +83,11 @@ const controllerConnection = async (config: ResolvedConfig) => {
59
83
  );
60
84
  }
61
85
  const { stdout } = await captureDocker(
62
- ["image", "inspect", "--format", "{{.Id}}", dockerImage],
86
+ ["image", "inspect", "--format", "{{.Id}}", builderImage],
63
87
  config.timeouts.hostCommand,
64
88
  ).catch((cause: unknown) => {
65
89
  throw new Error(
66
- `Cannot inspect Docker builder image ${dockerImage}. Install and start Docker, then run tsplc-build configure if the image is missing`,
90
+ `Cannot inspect Docker builder image ${builderImage}. Install and start Docker, then run tsplc-build configure if the image is missing`,
67
91
  { cause },
68
92
  );
69
93
  });
@@ -98,13 +122,13 @@ const controllerOperation = async (
98
122
  operation: ControllerResult["operation"],
99
123
  options: ControllerUpdateOptions,
100
124
  ): Promise<ControllerResult> => {
101
- const environmentNames = credentialEnvironment(config);
125
+ const credentials = credentialEnvironment(config, options);
102
126
  const { imageId, templateHash, target } = await controllerConnection(config);
103
127
  const operationId = randomUUID();
104
128
  const requestDirectory = await mkdtemp(
105
129
  resolve(tmpdir(), "codesys-controller-"),
106
130
  );
107
- const diagnostics = resolve(config.outDir, ".codesys/controller");
131
+ const diagnostics = controllerDirectory(config.outDir);
108
132
  const failure = resolve(config.outDir, controllerFailureFile);
109
133
  try {
110
134
  await mkdir(config.outDir, { recursive: true });
@@ -115,7 +139,7 @@ const controllerOperation = async (
115
139
  "--rm",
116
140
  ...(await prepareContainerRun(config, requestDirectory, {
117
141
  network: target.network,
118
- environment: environmentNames,
142
+ environment: Object.keys(credentials),
119
143
  sources: operation !== "inspect",
120
144
  })),
121
145
  imageId,
@@ -131,6 +155,7 @@ const controllerOperation = async (
131
155
  ],
132
156
  (status) =>
133
157
  `Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`,
158
+ { progress: options.progress ?? "stdout", environment: credentials },
134
159
  ).catch(async (cause: unknown) => {
135
160
  if (!existsSync(failure)) {
136
161
  throw cause;
@@ -166,20 +191,32 @@ export const updateController = (
166
191
  ) => controllerOperation(config, operation, options);
167
192
 
168
193
  /** Read the controller using the runner's saved compilation baseline. */
169
- export const inspectController = (config: ResolvedConfig, read?: string[]) =>
170
- controllerOperation(config, "inspect", { read });
194
+ export const inspectController = (
195
+ config: ResolvedConfig,
196
+ read?: string[],
197
+ options: ProgressOptions & CredentialSource = {},
198
+ ) => controllerOperation(config, "inspect", { ...options, read });
171
199
 
172
200
  const loginReplySchema = z.discriminatedUnion("ok", [
173
201
  z.strictObject({ ok: z.literal(true), result: z.unknown() }),
174
- z.strictObject({ ok: z.literal(false), error: z.string() }),
202
+ z.strictObject({
203
+ ok: z.literal(false),
204
+ error: z.string(),
205
+ downloadRequired: z.literal(true).optional(),
206
+ rollback: rollbackSchema.optional(),
207
+ }),
175
208
  ]);
176
209
 
177
210
  /** The ports login and warm containers serve on, inside the container. */
178
211
  const loginPort = 4851;
179
212
  const warmPort = 4852;
180
213
 
181
- const docker = (args: string[], timeout: number) =>
182
- captureDocker(args, timeout).then(({ stdout }) => stdout.trim());
214
+ const docker = (
215
+ args: string[],
216
+ timeout: number,
217
+ environment: ContainerEnvironment = {},
218
+ ) =>
219
+ captureDocker(args, timeout, environment).then(({ stdout }) => stdout.trim());
183
220
 
184
221
  /** The end of container `name`'s output, which shows why it stopped. */
185
222
  const recentLogs = async (name: string, timeout: number) => {
@@ -204,9 +241,8 @@ const callContainer = async (
204
241
  method: "GET" | "POST" | "DELETE",
205
242
  body?: unknown,
206
243
  ) => {
207
- const child = Bun.spawn(
244
+ const { stdout, stderr, status } = await pipeDocker(
208
245
  [
209
- "docker",
210
246
  "exec",
211
247
  ...(body === undefined ? [] : ["--interactive"]),
212
248
  name,
@@ -226,23 +262,20 @@ const callContainer = async (
226
262
  ]),
227
263
  `http://127.0.0.1:${port}/`,
228
264
  ],
229
- {
230
- stdin: body === undefined ? "ignore" : new Blob([JSON.stringify(body)]),
231
- stdout: "pipe",
232
- stderr: "pipe",
233
- },
265
+ body === undefined ? null : JSON.stringify(body),
234
266
  );
235
- const [output, errors, code] = await Promise.all([
236
- new Response(child.stdout).text(),
237
- new Response(child.stderr).text(),
238
- child.exited,
239
- ]);
240
- if (code !== 0) {
241
- throw new Error(errors.trim() || `docker exec failed (${code})`);
267
+ if (status !== 0) {
268
+ throw new Error(stderr.trim() || `docker exec failed (${status})`);
242
269
  }
243
- const reply = loginReplySchema.parse(JSON.parse(output));
270
+ const reply = loginReplySchema.parse(JSON.parse(stdout));
244
271
  if (!reply.ok) {
245
- throw new Error(reply.error);
272
+ if (reply.rollback) {
273
+ throw new TransferFailedError(reply.error, reply.rollback);
274
+ }
275
+ // Builder images from before `downloadRequired` existed only end such a refusal with these words.
276
+ throw reply.downloadRequired || reply.error.endsWith(explicitDownload)
277
+ ? new DownloadRequiredError(reply.error)
278
+ : new Error(reply.error);
246
279
  }
247
280
  return reply.result;
248
281
  };
@@ -298,8 +331,9 @@ export const findControllerLogin = async (name: string) =>
298
331
  export const openControllerLogin = async (
299
332
  config: ResolvedConfig,
300
333
  name: string,
334
+ options: CredentialSource = {},
301
335
  ) => {
302
- const environmentNames = credentialEnvironment(config);
336
+ const credentials = credentialEnvironment(config, options);
303
337
  const { imageId, target } = await controllerConnection(config);
304
338
  const timeout = config.timeouts.hostCommand;
305
339
  // A login that failed to open leaves its stopped container for diagnostics until the next one.
@@ -316,7 +350,7 @@ export const openControllerLogin = async (
316
350
  name,
317
351
  ...(await prepareContainerRun(config, requestDirectory, {
318
352
  network: target.network,
319
- environment: environmentNames,
353
+ environment: Object.keys(credentials),
320
354
  sources: false,
321
355
  })),
322
356
  imageId,
@@ -329,6 +363,7 @@ export const openControllerLogin = async (
329
363
  String(loginPort),
330
364
  ],
331
365
  timeout,
366
+ credentials,
332
367
  );
333
368
  const login = attachLogin(name, timeout);
334
369
  const deadline = Date.now() + config.timeouts.startup + config.timeouts.build;
@@ -352,18 +387,13 @@ const warmController = async (
352
387
  config: ResolvedConfig,
353
388
  name: string,
354
389
  connection: Awaited<ReturnType<typeof controllerConnection>>,
390
+ report: (message: string) => void,
355
391
  ) => {
356
392
  const timeout = config.timeouts.hostCommand;
357
393
  const { imageId, target } = connection;
358
394
  const settings = createHash("sha256")
359
- .update(
360
- JSON.stringify({
361
- imageId,
362
- target,
363
- timeouts: config.timeouts,
364
- docker: config.docker,
365
- }),
366
- )
395
+ // Each operation brings its own timeouts, so a release that changes them needn't restart CODESYS.
396
+ .update(JSON.stringify({ imageId, target, docker: config.docker }))
367
397
  .digest("hex");
368
398
  const label = `tsplc.warm=${settings}`;
369
399
  const running = async () =>
@@ -381,6 +411,9 @@ const warmController = async (
381
411
  )) !== "";
382
412
  // One whose CODESYS died, which its server reports, is replaced too.
383
413
  if (!(await running()) || !(await answers(name, warmPort))) {
414
+ report(
415
+ "Starting CODESYS: no running builder matches this image, controller and Docker settings, which takes minutes",
416
+ );
384
417
  await docker(["rm", "--force", name], timeout);
385
418
  // Its own request: the operations' configs come later, one per release.
386
419
  const requestDirectory = resolve(config.outDir, ".codesys/warm-request");
@@ -425,18 +458,50 @@ const warmController = async (
425
458
  throw new Error("CODESYS did not start in time");
426
459
  };
427
460
 
461
+ /**
462
+ * Relays the progress log of one operation, which CODESYS appends to as it works, as messages
463
+ * without their timestamps, until the returned function stops it.
464
+ */
465
+ const followProgress = (log: string, report: (message: string) => void) => {
466
+ const stopped = new AbortController();
467
+ const done = (async () => {
468
+ let offset = 0;
469
+ while (!stopped.signal.aborted) {
470
+ await delay(2000);
471
+ if (!existsSync(log)) {
472
+ continue;
473
+ }
474
+ const text = await readFile(log, "utf8");
475
+ for (const line of text.slice(offset).split("\n").filter(Boolean)) {
476
+ report(line.replace(/^\S+Z /, ""));
477
+ }
478
+ offset = text.length;
479
+ }
480
+ })();
481
+ return async () => {
482
+ stopped.abort();
483
+ await done;
484
+ };
485
+ };
486
+
428
487
  /** Starts warm builder container `name` ahead of the first operation, unless it already runs. */
429
488
  export const startWarmController = async (
430
489
  config: ResolvedConfig,
431
490
  name: string,
432
491
  ) => {
433
- await warmController(config, name, await controllerConnection(config));
492
+ await warmController(
493
+ config,
494
+ name,
495
+ await controllerConnection(config),
496
+ () => {},
497
+ );
434
498
  };
435
499
 
436
500
  /**
437
501
  * A download or online change in builder container `name`, which keeps CODESYS running between
438
502
  * operations so each skips starting the container, Wine and CODESYS. The first operation, or one
439
- * with a new image, target or settings, starts it. Credentials go to CODESYS for this operation only.
503
+ * with a new image, target or Docker settings, starts it. Credentials go to CODESYS for this
504
+ * operation only. A download that fails mid-transfer throws a `TransferFailedError` naming its rollback.
440
505
  */
441
506
  export const updateWarmController = async (
442
507
  config: ResolvedConfig,
@@ -445,19 +510,35 @@ export const updateWarmController = async (
445
510
  options: {
446
511
  initializeUser?: boolean;
447
512
  credentials?: ControllerCredentials;
513
+ /** Receives each step CODESYS reports while this operation runs. */
514
+ onProgress?: (message: string) => void;
448
515
  } = {},
449
516
  ): Promise<ControllerResult> => {
517
+ const report = options.onProgress ?? (() => {});
450
518
  const connection = await controllerConnection(config);
451
- await warmController(config, name, connection);
452
519
  const operationId = randomUUID();
453
- const diagnostics = resolve(config.outDir, ".codesys/controller");
520
+ const diagnostics = controllerDirectory(config.outDir);
454
521
  const directory = resolve(config.outDir, ".codesys/requests", operationId);
455
- try {
456
- const request = await writeOperationRequest(
522
+ report("Copying the release for CODESYS");
523
+ // A container that has to start takes minutes, which the copy needn't wait for.
524
+ const [request] = await Promise.all([
525
+ writeOperationRequest(
457
526
  config,
458
527
  directory,
459
528
  posix.join("/output/.codesys/requests", operationId),
460
- );
529
+ ),
530
+ warmController(config, name, connection, report),
531
+ ]).catch(async (error: unknown) => {
532
+ await rm(directory, { recursive: true, force: true });
533
+ throw error;
534
+ });
535
+ const stopFollowing = options.onProgress
536
+ ? followProgress(
537
+ jobProgressLog(config.outDir, operationId),
538
+ options.onProgress,
539
+ )
540
+ : async () => {};
541
+ try {
461
542
  const result = await callContainer(name, warmPort, "POST", {
462
543
  operation,
463
544
  operationId,
@@ -465,12 +546,14 @@ export const updateWarmController = async (
465
546
  initializeUser: options.initializeUser ?? false,
466
547
  credentials: options.credentials,
467
548
  } satisfies z.input<typeof warmOperationSchema>).catch((error: unknown) => {
468
- throw new Error(
469
- `${failureReason(error)}. Inspect ${diagnostics} for diagnostics`,
470
- {
471
- cause: error,
472
- },
473
- );
549
+ const message = `${failureReason(error)}. Inspect ${diagnostics} for diagnostics`;
550
+ const rollback = transferRollback(error);
551
+ if (rollback) {
552
+ throw new TransferFailedError(message, rollback, { cause: error });
553
+ }
554
+ throw requiresDownload(error)
555
+ ? new DownloadRequiredError(message, { cause: error })
556
+ : new Error(message, { cause: error });
474
557
  });
475
558
  return checkReceipt(
476
559
  controllerResultSchema.parse(result),
@@ -484,6 +567,7 @@ export const updateWarmController = async (
484
567
  diagnostics,
485
568
  );
486
569
  } finally {
570
+ await stopFollowing();
487
571
  await rm(directory, { recursive: true, force: true });
488
572
  }
489
573
  };
@@ -1,13 +1,13 @@
1
1
  // What the host and the builder container exchange for controller operations: the receipt,
2
2
  // the target a baseline is bound to, warm and login commands, and how failures are worded.
3
3
  import { createHash } from "node:crypto";
4
- import { z } from "zod";
5
4
  import {
6
5
  controllerSchema,
6
+ type ResolvedConfig,
7
7
  sha256Digest,
8
8
  tcpPort,
9
- type ResolvedConfig,
10
9
  } from "@tsplc/config/build";
10
+ import { z } from "zod";
11
11
 
12
12
  export const imageIdSchema = z.string().regex(/^sha256:[a-f0-9]{64}$/);
13
13
  const endpointSchema = z.strictObject({
@@ -104,11 +104,54 @@ export const sameBaseline = (state: Baseline, expected: Baseline) =>
104
104
  state.templateHash === expected.templateHash &&
105
105
  JSON.stringify(state.target) === JSON.stringify(expected.target);
106
106
 
107
+ /** Ends the message of every refusal that only a full download resolves. */
108
+ export const explicitDownload = "use an explicit download";
109
+
107
110
  /**
108
- * Ends every refusal that only a full download resolves, so callers can offer one. The Python
109
- * online operations end theirs with the same words.
111
+ * A refusal that only a full download resolves, so callers can offer one instead of failing.
112
+ * Worker and container replies carry it as `downloadRequired: true`.
110
113
  */
111
- export const explicitDownload = "use an explicit download";
114
+ export class DownloadRequiredError extends Error {
115
+ readonly downloadRequired = true;
116
+ }
117
+
118
+ /**
119
+ * What became of the controller after a download failed mid-transfer: it still ran the previous
120
+ * application (`intact`), runs it again from the last committed download (`restored`), or may hold
121
+ * no application, because restoring failed (`failed`) or no committed download exists (`unavailable`).
122
+ */
123
+ export const rollbackSchema = z.enum([
124
+ "intact",
125
+ "restored",
126
+ "failed",
127
+ "unavailable",
128
+ ]);
129
+ export type Rollback = z.infer<typeof rollbackSchema>;
130
+
131
+ /** A download that failed once it had started transferring, and what its rollback did. */
132
+ export class TransferFailedError extends Error {
133
+ constructor(
134
+ message: string,
135
+ readonly rollback: Rollback,
136
+ options?: ErrorOptions,
137
+ ) {
138
+ super(message, options);
139
+ }
140
+ }
141
+
142
+ /** The rollback a failed download reports, from whichever package raised it. */
143
+ export const transferRollback = (error: unknown): Rollback | undefined => {
144
+ if (!(error instanceof Error) || !("rollback" in error)) {
145
+ return undefined;
146
+ }
147
+ return rollbackSchema.safeParse(error.rollback).data;
148
+ };
149
+
150
+ /** Whether `error` is a refusal only a full download resolves, from whichever package raised it. */
151
+ export const requiresDownload = (error: unknown) =>
152
+ error instanceof Error &&
153
+ "downloadRequired" in error &&
154
+ error.downloadRequired === true;
112
155
 
113
156
  export const loginCommandSchema = z.discriminatedUnion("command", [
114
157
  z.strictObject({ command: z.literal("state") }),