@devicecloud.dev/dcd 5.14.1 → 5.16.0-beta.1

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 (44) hide show
  1. package/README.md +25 -2
  2. package/dist/commands/artifacts.d.ts +13 -0
  3. package/dist/commands/artifacts.js +43 -5
  4. package/dist/commands/device.d.ts +39 -0
  5. package/dist/commands/device.js +479 -101
  6. package/dist/e2e/index.d.ts +4 -0
  7. package/dist/e2e/index.js +41 -0
  8. package/dist/e2e/provider.d.ts +80 -0
  9. package/dist/e2e/provider.js +233 -0
  10. package/dist/gateways/api-gateway.d.ts +25 -3
  11. package/dist/gateways/api-gateway.js +68 -6
  12. package/dist/gateways/device-gateway.d.ts +34 -10
  13. package/dist/gateways/device-gateway.js +72 -17
  14. package/dist/mcp/bridge.d.ts +30 -16
  15. package/dist/mcp/bridge.js +201 -64
  16. package/dist/mcp/local-files.d.ts +14 -0
  17. package/dist/mcp/local-files.js +75 -0
  18. package/dist/mcp/tools/download-artifacts.d.ts +4 -1
  19. package/dist/mcp/tools/download-artifacts.js +44 -17
  20. package/dist/services/report-download.service.d.ts +32 -0
  21. package/dist/services/report-download.service.js +51 -2
  22. package/dist/services/telemetry.service.d.ts +20 -1
  23. package/dist/services/telemetry.service.js +27 -6
  24. package/dist/types/domain/device-session.types.d.ts +73 -3
  25. package/dist/types/domain/device-session.types.js +2 -0
  26. package/dist/utils/api-url.d.ts +20 -0
  27. package/dist/utils/api-url.js +49 -0
  28. package/dist/utils/app-upload.d.ts +6 -0
  29. package/dist/utils/app-upload.js +19 -0
  30. package/dist/utils/config-store.d.ts +5 -1
  31. package/dist/utils/config-store.js +18 -2
  32. package/dist/utils/device-artifacts.d.ts +5 -0
  33. package/dist/utils/device-artifacts.js +22 -0
  34. package/dist/utils/device-bundle.d.ts +39 -9
  35. package/dist/utils/device-bundle.js +153 -51
  36. package/dist/utils/device-flags.d.ts +17 -0
  37. package/dist/utils/device-flags.js +145 -0
  38. package/dist/utils/device-output.d.ts +53 -7
  39. package/dist/utils/device-output.js +148 -21
  40. package/dist/utils/device-run.d.ts +8 -3
  41. package/dist/utils/device-run.js +85 -8
  42. package/dist/utils/zip-integrity.d.ts +21 -0
  43. package/dist/utils/zip-integrity.js +45 -0
  44. package/package.json +10 -1
@@ -1,5 +1,5 @@
1
1
  import type { AuthContext } from '../types/domain/auth.types.js';
2
- import type { DeviceHumanStatus, DeviceSession } from '../types/domain/device-session.types.js';
2
+ import type { DeviceHumanStatus, DeviceSession, DeviceSessionStarter } from '../types/domain/device-session.types.js';
3
3
  import { type Field } from './ui.js';
4
4
  /**
5
5
  * Exit codes for `dcd device` (dcd docs/device-v1-plan.md, section 4.2).
@@ -11,7 +11,7 @@ export declare const DEVICE_EXIT: {
11
11
  readonly usage: 1;
12
12
  /** It ran and failed: a flow or action failed, or the API could not do it. */
13
13
  readonly failed: 2;
14
- /** A limit: concurrency, spend cap or rate limit. */
14
+ /** A limit: concurrency, a spend cap or usage limit, or a rate limit. */
15
15
  readonly limit: 3;
16
16
  /** The session has ended, or there is no such session. */
17
17
  readonly gone: 4;
@@ -26,10 +26,15 @@ export interface DeviceEnvelope<T> {
26
26
  ok: boolean;
27
27
  session?: DeviceSession | null;
28
28
  data: T | null;
29
- error: {
29
+ /**
30
+ * With `code` and `message`, whatever else the API said that a script can
31
+ * act on: `retry_after_s`, `limit`, `spent`, `phase`, and `command_id` when
32
+ * a wait for a flow gave up.
33
+ */
34
+ error: ({
30
35
  code: null | string;
31
36
  message: string;
32
- } | null;
37
+ } & Record<string, unknown>) | null;
33
38
  }
34
39
  export interface DeviceOutcome<T> {
35
40
  /** The session the command was about; undefined when it is not about one. */
@@ -60,16 +65,57 @@ export declare function runDeviceCommand<T>(json: boolean, fn: () => Promise<Dev
60
65
  */
61
66
  export declare function deviceProgress(json: boolean): (message: string) => void;
62
67
  /**
63
- * The default-session rule: `<id>` may be left out when the org has exactly
64
- * one open session. With none, or several, the command is a usage error and
65
- * lists what there is to choose from.
68
+ * The default-session rule: `<id>` may be left out when you have exactly one
69
+ * open session. Other people's sessions are never the default: a teammate's
70
+ * agent may be using one. With none of yours, or several, the command is a
71
+ * usage error that lists what there is to choose from.
72
+ *
73
+ * An API that does not say who started each session (no `started_by`) is
74
+ * read the old way: the org's only open session.
66
75
  */
67
76
  export declare function resolveSessionId(apiUrl: string, auth: AuthContext, given: string | undefined): Promise<string>;
77
+ /**
78
+ * The id given, trimmed, or undefined when none was. A value that cannot be
79
+ * a session id is a usage error, never sent: `undefined` from a script's
80
+ * unset variable would otherwise reach the API as a session name.
81
+ */
82
+ export declare function checkSessionId(given: string | undefined): string | undefined;
83
+ /**
84
+ * For commands that read what a session left behind (`artifacts`): the
85
+ * session given, or else your most recent one, ended or not. Others' sessions
86
+ * are never the default. An API that does not say who started each is read
87
+ * the old way: the only session in the list.
88
+ */
89
+ export declare function resolveRecentSessionId(apiUrl: string, auth: AuthContext, given: string | undefined): Promise<string>;
90
+ /** Who started a session, in a few words: "you", an email, or an API key's name. */
91
+ export declare function startedByLabel(starter: DeviceSessionStarter): string;
92
+ /**
93
+ * Text from the device, the app or another client, made safe to print in a
94
+ * terminal: escape sequences and control characters removed, so an element's
95
+ * label, a log line or a note can't retitle the terminal, move the cursor or
96
+ * draw a fake result line. `oneLine` also folds line breaks into spaces, for
97
+ * text shown inside a row. --json output keeps the text exactly as it came.
98
+ */
99
+ export declare function printable(text: string, opts?: {
100
+ oneLine?: boolean;
101
+ }): string;
102
+ /**
103
+ * Dollars for a person. Sessions are billed in units of $0.015, so a cost
104
+ * is shown to the half cent when it has one: $0.015, not $0.01.
105
+ */
106
+ export declare function formatCost(usd: number): string;
68
107
  export declare function formatSeconds(seconds: number): string;
69
108
  /** The rows that describe a session, for {@link ui.fields}. */
70
109
  export declare function sessionFields(session: DeviceSession): Field[];
71
110
  /** A session as a branch group, with its warnings after it. */
72
111
  export declare function printSession(session: DeviceSession): void;
112
+ /**
113
+ * The session's warnings (a crash, the idle timeout or the end of its time
114
+ * coming up, an install still going), after a command's own result: a
115
+ * person or an agent driving it without --json must see them before the
116
+ * session ends under them.
117
+ */
118
+ export declare function printWarnings(session: DeviceSession | null | undefined): void;
73
119
  /**
74
120
  * An API timestamp for a person: how far off it is and the local time, e.g.
75
121
  * "in 12m (14:32)" or "3m ago (14:17)". The text as given when unreadable.
@@ -1,3 +1,4 @@
1
+ import { stripVTControlCharacters } from 'node:util';
1
2
  import { DeviceApiError, DeviceGateway } from '../gateways/device-gateway.js';
2
3
  import { CliError, logger } from './cli.js';
3
4
  import { colors, formatUrl } from './styling.js';
@@ -12,12 +13,19 @@ export const DEVICE_EXIT = {
12
13
  usage: 1,
13
14
  /** It ran and failed: a flow or action failed, or the API could not do it. */
14
15
  failed: 2,
15
- /** A limit: concurrency, spend cap or rate limit. */
16
+ /** A limit: concurrency, a spend cap or usage limit, or a rate limit. */
16
17
  limit: 3,
17
18
  /** The session has ended, or there is no such session. */
18
19
  gone: 4,
19
20
  };
20
- const LIMIT_CODES = new Set(['LIVE_CONCURRENCY_LIMIT', 'LIVE_RATE_LIMITED', 'LIVE_SPEND_CAP']);
21
+ // USAGE_LIMIT_EXCEEDED: the team's overage cap or a usage alert's hard stop
22
+ // refused a session start, as it refuses a test run.
23
+ const LIMIT_CODES = new Set([
24
+ 'LIVE_CONCURRENCY_LIMIT',
25
+ 'LIVE_RATE_LIMITED',
26
+ 'LIVE_SPEND_CAP',
27
+ 'USAGE_LIMIT_EXCEEDED',
28
+ ]);
21
29
  const GONE_CODES = new Set(['LIVE_NOT_FOUND', 'LIVE_SESSION_ENDED']);
22
30
  const USAGE_CODES = new Set([
23
31
  'LIVE_INVALID_ACTION',
@@ -64,7 +72,9 @@ export async function runDeviceCommand(json, fn) {
64
72
  ok: false,
65
73
  session: error instanceof DeviceApiError ? error.session : null,
66
74
  data: null,
67
- error: { code: error instanceof DeviceApiError ? error.code : null, message },
75
+ error: error instanceof DeviceApiError
76
+ ? { ...error.details, code: error.code, message }
77
+ : { code: null, message },
68
78
  };
69
79
  logger.json(envelope);
70
80
  logger.fail(message, exitCode);
@@ -96,24 +106,126 @@ export function deviceProgress(json) {
96
106
  };
97
107
  }
98
108
  /**
99
- * The default-session rule: `<id>` may be left out when the org has exactly
100
- * one open session. With none, or several, the command is a usage error and
101
- * lists what there is to choose from.
109
+ * The default-session rule: `<id>` may be left out when you have exactly one
110
+ * open session. Other people's sessions are never the default: a teammate's
111
+ * agent may be using one. With none of yours, or several, the command is a
112
+ * usage error that lists what there is to choose from.
113
+ *
114
+ * An API that does not say who started each session (no `started_by`) is
115
+ * read the old way: the org's only open session.
102
116
  */
103
117
  export async function resolveSessionId(apiUrl, auth, given) {
104
- const id = given?.trim();
118
+ const id = checkSessionId(given);
105
119
  if (id)
106
120
  return id;
107
121
  const { sessions } = await DeviceGateway.list(apiUrl, auth);
108
- if (sessions.length === 1)
109
- return sessions[0].id;
122
+ const knowsOwners = sessions.some((s) => s.started_by !== undefined);
123
+ const yours = knowsOwners ? sessions.filter((s) => s.started_by?.you) : sessions;
124
+ if (yours.length === 1)
125
+ return yours[0].id;
110
126
  if (sessions.length === 0) {
111
127
  throw new CliError('No open device session. Start one with `dcd device start --platform ios|android`.', DEVICE_EXIT.usage);
112
128
  }
113
- const candidates = sessions
114
- .map((s) => ` ${s.id} ${s.platform} ${s.state}${s.client_label ? ` ${s.client_label}` : ''}`)
129
+ const candidates = (list) => list
130
+ .map((s) => {
131
+ const who = s.started_by ? startedByLabel(s.started_by) : '';
132
+ return ` ${s.id} ${s.platform} ${s.state}${s.client_label ? ` ${s.client_label}` : ''}${who ? ` (${who})` : ''}`;
133
+ })
134
+ .join('\n');
135
+ if (yours.length === 0) {
136
+ throw new CliError(`None of the open device sessions is yours. Start your own, or name one of these (changing it needs --force):\n${candidates(sessions)}`, DEVICE_EXIT.usage);
137
+ }
138
+ throw new CliError(`${yours.length} of your device sessions are open. Name one:\n${candidates(yours)}`, DEVICE_EXIT.usage);
139
+ }
140
+ /**
141
+ * A session id: its name (`brave-teal-otter`, `brave-teal-otter-0042`, or an
142
+ * older `teal-otter-42`), or its number. Words joined by dashes, so a single
143
+ * word is never one.
144
+ */
145
+ const SESSION_ID = /^(?:[a-z][a-z0-9]*(?:-[a-z0-9]+)+|\d+)$/;
146
+ /** What a shell or a script prints for a value it does not have. */
147
+ const UNSET_WORDS = new Set(['', 'null', 'undefined', 'none', 'nan', 'nil', '[object object]']);
148
+ /**
149
+ * The id given, trimmed, or undefined when none was. A value that cannot be
150
+ * a session id is a usage error, never sent: `undefined` from a script's
151
+ * unset variable would otherwise reach the API as a session name.
152
+ */
153
+ export function checkSessionId(given) {
154
+ if (given === undefined)
155
+ return undefined;
156
+ const id = given.trim();
157
+ if (!id)
158
+ return undefined;
159
+ if (SESSION_ID.test(id))
160
+ return id;
161
+ const unset = UNSET_WORDS.has(id.toLowerCase());
162
+ throw new CliError(unset
163
+ ? `"${id}" is not a session id: it looks like a variable that was not set. A session id looks like brave-teal-otter; \`dcd device list\` shows yours.`
164
+ : `"${id}" is not a session id. A session id looks like brave-teal-otter; \`dcd device list\` shows yours.`, DEVICE_EXIT.usage);
165
+ }
166
+ /**
167
+ * For commands that read what a session left behind (`artifacts`): the
168
+ * session given, or else your most recent one, ended or not. Others' sessions
169
+ * are never the default. An API that does not say who started each is read
170
+ * the old way: the only session in the list.
171
+ */
172
+ export async function resolveRecentSessionId(apiUrl, auth, given) {
173
+ const id = checkSessionId(given);
174
+ if (id)
175
+ return id;
176
+ // Open sessions and those that ended in the last day, newest first by start.
177
+ const { sessions } = await DeviceGateway.list(apiUrl, auth, true);
178
+ const knowsOwners = sessions.some((s) => s.started_by !== undefined);
179
+ const newestFirst = (list) => [...list].sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at));
180
+ if (knowsOwners) {
181
+ const [newest] = newestFirst(sessions.filter((s) => s.started_by?.you));
182
+ if (newest)
183
+ return newest.id;
184
+ }
185
+ else if (sessions.length === 1) {
186
+ return sessions[0].id;
187
+ }
188
+ if (sessions.length === 0) {
189
+ throw new CliError('No device session in the last day. Name one: `dcd device artifacts <id>`.', DEVICE_EXIT.usage);
190
+ }
191
+ const listed = newestFirst(sessions)
192
+ .map((s) => ` ${s.id} ${s.platform} ${s.state}${s.started_by ? ` (${startedByLabel(s.started_by)})` : ''}`)
115
193
  .join('\n');
116
- throw new CliError(`${sessions.length} device sessions are open. Name one:\n${candidates}`, DEVICE_EXIT.usage);
194
+ throw new CliError(knowsOwners
195
+ ? `None of the sessions of the last day is yours. Name one:\n${listed}`
196
+ : `Name the session:\n${listed}`, DEVICE_EXIT.usage);
197
+ }
198
+ /** Who started a session, in a few words: "you", an email, or an API key's name. */
199
+ export function startedByLabel(starter) {
200
+ if (starter.you)
201
+ return starter.this_client ? 'you, this connection' : 'you';
202
+ if (starter.email)
203
+ return `started by ${printable(starter.email, { oneLine: true })}`;
204
+ if (starter.key_name)
205
+ return `started with API key "${printable(starter.key_name, { oneLine: true })}"`;
206
+ return 'started by someone else';
207
+ }
208
+ /** Control characters other than tab and newline, C1 controls, and bidirectional overrides. */
209
+ // eslint-disable-next-line no-control-regex
210
+ const CONTROL = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u202A-\u202E\u2066-\u2069]/g;
211
+ /**
212
+ * Text from the device, the app or another client, made safe to print in a
213
+ * terminal: escape sequences and control characters removed, so an element's
214
+ * label, a log line or a note can't retitle the terminal, move the cursor or
215
+ * draw a fake result line. `oneLine` also folds line breaks into spaces, for
216
+ * text shown inside a row. --json output keeps the text exactly as it came.
217
+ */
218
+ export function printable(text, opts = {}) {
219
+ const clean = stripVTControlCharacters(text).replaceAll(CONTROL, '');
220
+ return opts.oneLine ? clean.replaceAll(/[\t\n]+/g, ' ') : clean;
221
+ }
222
+ /**
223
+ * Dollars for a person. Sessions are billed in units of $0.015, so a cost
224
+ * is shown to the half cent when it has one: $0.015, not $0.01.
225
+ */
226
+ export function formatCost(usd) {
227
+ const tenths = Math.round(usd * 1000);
228
+ return tenths % 10 === 0 ? `$${usd.toFixed(2)}` : `$${(tenths / 1000).toFixed(3)}`;
117
229
  }
118
230
  export function formatSeconds(seconds) {
119
231
  if (seconds < 60)
@@ -130,9 +242,11 @@ export function sessionFields(session) {
130
242
  ['platform', session.platform],
131
243
  ];
132
244
  if (session.model)
133
- fields.push(['model', session.model]);
245
+ fields.push(['model', printable(session.model, { oneLine: true })]);
134
246
  if (session.client_label)
135
- fields.push(['client', session.client_label]);
247
+ fields.push(['client', printable(session.client_label, { oneLine: true })]);
248
+ if (session.started_by)
249
+ fields.push(['started', startedByLabel(session.started_by)]);
136
250
  if (session.queue) {
137
251
  const position = session.queue.position === null ? '' : `#${session.queue.position}`;
138
252
  const eta = session.queue.eta_s === null ? '' : `, about ${formatSeconds(session.queue.eta_s)}`;
@@ -145,10 +259,13 @@ export function sessionFields(session) {
145
259
  fields.push(['idle timeout', `in ${formatSeconds(session.idle_remaining_s)}`]);
146
260
  }
147
261
  if (session.cost_so_far_usd !== null) {
148
- fields.push(['cost so far', `$${session.cost_so_far_usd.toFixed(2)}`]);
262
+ fields.push(['cost so far', formatCost(session.cost_so_far_usd)]);
149
263
  }
150
264
  if (session.last_crash) {
151
- fields.push(['last crash', colors.error(`${session.last_crash.summary} (${session.last_crash.at})`)]);
265
+ fields.push([
266
+ 'last crash',
267
+ colors.error(`${printable(session.last_crash.summary, { oneLine: true })} (${session.last_crash.at})`),
268
+ ]);
152
269
  }
153
270
  fields.push(['monitor', formatUrl(session.monitor_url)]);
154
271
  return fields;
@@ -156,8 +273,17 @@ export function sessionFields(session) {
156
273
  /** A session as a branch group, with its warnings after it. */
157
274
  export function printSession(session) {
158
275
  logger.log(ui.branch(ui.fields(sessionFields(session))));
159
- for (const warning of session.warnings)
160
- logger.log(ui.warn(warning));
276
+ printWarnings(session);
277
+ }
278
+ /**
279
+ * The session's warnings (a crash, the idle timeout or the end of its time
280
+ * coming up, an install still going), after a command's own result: a
281
+ * person or an agent driving it without --json must see them before the
282
+ * session ends under them.
283
+ */
284
+ export function printWarnings(session) {
285
+ for (const warning of session?.warnings ?? [])
286
+ logger.log(ui.warn(printable(warning)));
161
287
  }
162
288
  /**
163
289
  * An API timestamp for a person: how far off it is and the local time, e.g.
@@ -189,7 +315,7 @@ export function humanState(human) {
189
315
  export function humanFields(human, now = Date.now()) {
190
316
  const fields = [['state', humanState(human)]];
191
317
  if (human.reason)
192
- fields.push(['reason', human.reason]);
318
+ fields.push(['reason', printable(human.reason, { oneLine: true })]);
193
319
  // A person who took control unasked: the reason is "<email> took control",
194
320
  // and nobody asked for anything.
195
321
  const tookControl = human.human_in_control && !!human.reason?.endsWith(' took control');
@@ -201,7 +327,8 @@ export function humanFields(human, now = Date.now()) {
201
327
  if (human.handed_back && human.handed_back_at) {
202
328
  fields.push(['handed back', formatWhen(human.handed_back_at, now)]);
203
329
  }
204
- if (human.handed_back)
205
- fields.push(['note', human.note ?? colors.dim('none')]);
330
+ if (human.handed_back) {
331
+ fields.push(['note', human.note ? printable(human.note, { oneLine: true }) : colors.dim('none')]);
332
+ }
206
333
  return fields;
207
334
  }
@@ -1,4 +1,4 @@
1
- import type { DeviceCommandResult, DeviceFlowResult } from '../types/domain/device-session.types.js';
1
+ import type { DeviceCommandResult, DeviceFailedAt, DeviceFlowResult } from '../types/domain/device-session.types.js';
2
2
  /**
3
3
  * What `dcd device run` shows a person: one row per flow and a short summary.
4
4
  *
@@ -7,8 +7,11 @@ import type { DeviceCommandResult, DeviceFlowResult } from '../types/domain/devi
7
7
  * JSON: `{ success, device_id, total_flows, total_commands_executed,
8
8
  * results: [{ file, success, error, message }], env_vars, message }`. For one
9
9
  * flow it is the same without `results`. Newer APIs also send
10
- * `result.flows`, which is used when present. None of the runner's own
11
- * fields (device_id, command counts, env_vars) are shown.
10
+ * `result.flows`, which is used when present, and turn a failure's `error`
11
+ * into plain text that says which flows failed, where (`failed_at`), and how
12
+ * to fix a flow sent without the files it uses. That text is preferred to
13
+ * the runner's own. None of the runner's own fields (device_id, command
14
+ * counts, env_vars) are shown.
12
15
  */
13
16
  export interface RunReport {
14
17
  flows: DeviceFlowResult[];
@@ -20,6 +23,8 @@ export interface RunReport {
20
23
  * CLI can read (plain text): then the text is shown as it came.
21
24
  */
22
25
  export declare function parseRunReport(result: DeviceCommandResult): null | RunReport;
26
+ /** `sub/check.yaml:5`, the command if known, and how the flow got there. */
27
+ export declare function describeLocation(where: DeviceFailedAt): null | string;
23
28
  /** The failure message for a failed run: each failing flow and why. */
24
29
  export declare function runFailureMessage(result: DeviceCommandResult, report: null | RunReport): string;
25
30
  /**
@@ -1,3 +1,4 @@
1
+ import { printable } from './device-output.js';
1
2
  import { colors } from './styling.js';
2
3
  import { ui } from './ui.js';
3
4
  function isRecord(value) {
@@ -6,6 +7,28 @@ function isRecord(value) {
6
7
  function text(value) {
7
8
  return typeof value === 'string' && value.trim() ? value.trim() : null;
8
9
  }
10
+ /** Text that is not a JSON document: the API's own wording of a failure. */
11
+ function plainText(value) {
12
+ const t = text(value);
13
+ return t && !t.startsWith('{') ? t : null;
14
+ }
15
+ function location(value) {
16
+ if (!isRecord(value) || typeof value.file !== 'string' || typeof value.line !== 'number')
17
+ return null;
18
+ return {
19
+ call_chain: Array.isArray(value.call_chain) ? value.call_chain.filter((s) => typeof s === 'string') : [],
20
+ command: typeof value.command === 'string' ? value.command : null,
21
+ file: value.file,
22
+ line: value.line,
23
+ };
24
+ }
25
+ function failedAt(raw) {
26
+ const one = location(raw.failed_at);
27
+ if (one)
28
+ return { failed_at: one };
29
+ const many = Array.isArray(raw.failed_at_candidates) ? raw.failed_at_candidates.map(location) : [];
30
+ return many.length > 1 && many.every(Boolean) ? { failed_at_candidates: many } : {};
31
+ }
9
32
  function toFlow(raw, file) {
10
33
  const success = raw.success === true;
11
34
  return {
@@ -13,6 +36,7 @@ function toFlow(raw, file) {
13
36
  success,
14
37
  // A failed flow's reason is in `error`; some reports only have `message`.
15
38
  error: text(raw.error) ?? (success ? null : text(raw.message)),
39
+ ...failedAt(raw),
16
40
  };
17
41
  }
18
42
  /** The runner's JSON report in `body`, or null when it is not one. */
@@ -47,17 +71,60 @@ export function parseRunReport(result) {
47
71
  if (Array.isArray(result.flows)) {
48
72
  return { flows: result.flows.map((f) => toFlow({ ...f }, null)), message: null };
49
73
  }
50
- return parseRunnerJson(result.error) ?? parseRunnerJson(result.output);
74
+ const report = parseRunnerJson(result.error) ?? parseRunnerJson(result.output);
75
+ if (!report || result.success || report.flows.length !== 1)
76
+ return report;
77
+ // One flow that failed: the API's wording says more than the runner's
78
+ // (where it failed, and why a file it uses was missing).
79
+ const [flow] = report.flows;
80
+ return {
81
+ ...report,
82
+ flows: [
83
+ {
84
+ ...flow,
85
+ error: plainText(result.error) ?? flow.error,
86
+ ...(flow.failed_at || flow.failed_at_candidates ? {} : failedAt(result)),
87
+ },
88
+ ],
89
+ };
90
+ }
91
+ /** `sub/check.yaml:5`, the command if known, and how the flow got there. */
92
+ export function describeLocation(where) {
93
+ const at = (l) => `${l.file}:${l.line}`;
94
+ if (where.failed_at) {
95
+ const l = where.failed_at;
96
+ const via = l.call_chain.slice(0, -1);
97
+ return [
98
+ `at ${at(l)}`,
99
+ l.command ? ` ${printable(l.command, { oneLine: true })}` : '',
100
+ via.length > 0 ? ` (via ${via.join(' → ')})` : '',
101
+ ].join('');
102
+ }
103
+ if (where.failed_at_candidates)
104
+ return `at one of ${where.failed_at_candidates.map(at).join(', ')}`;
105
+ return null;
106
+ }
107
+ /** The text names the place already, as the API's wording of a failure does: "... (at login.yaml:7)". */
108
+ function mentions(error, where) {
109
+ const places = where.failed_at ? [where.failed_at] : (where.failed_at_candidates ?? []);
110
+ return Boolean(error) && places.length > 0 && places.every((l) => error.includes(`${l.file}:${l.line}`));
51
111
  }
52
112
  /** The failure message for a failed run: each failing flow and why. */
53
113
  export function runFailureMessage(result, report) {
114
+ // The API's own text names the failing flows and where they failed.
115
+ const own = plainText(result.error);
116
+ if (own)
117
+ return own;
54
118
  if (!report)
55
119
  return result.error || 'The flow failed.';
56
120
  const failed = report.flows.filter((f) => !f.success);
57
121
  if (failed.length === 0)
58
122
  return report.message ?? 'The flow failed.';
59
123
  return failed
60
- .map((f) => `${f.file ?? 'flow'}: ${f.error ?? 'failed'}`)
124
+ .map((f) => {
125
+ const where = describeLocation(f);
126
+ return `${f.file ?? 'flow'}: ${f.error ?? 'failed'}${where ? ` (${where})` : ''}`;
127
+ })
61
128
  .join('; ');
62
129
  }
63
130
  /**
@@ -69,27 +136,32 @@ export function printRunResult(log, passed, result, label) {
69
136
  // What the app showed after the failure: why an assertion missed.
70
137
  if (!passed && result.screen_text?.length) {
71
138
  log(ui.section('On screen after the failure'));
72
- log(ui.branch(result.screen_text.map((t) => `"${t}"`)));
139
+ log(ui.branch(result.screen_text.map((t) => `"${printable(t, { oneLine: true })}"`)));
73
140
  }
74
141
  }
75
142
  function printOutcome(log, passed, result, label) {
76
143
  const report = parseRunReport(result);
77
144
  if (!report || report.flows.length === 0) {
78
145
  log(passed ? ui.success('Flow passed') : `${ui.statusSymbol('FAILED')} Flow failed`);
146
+ const where = describeLocation(result);
79
147
  if (report) {
80
148
  if (report.message)
81
- log(ui.note(report.message));
149
+ log(ui.note(printable(report.message)));
150
+ if (!passed && where)
151
+ log(ui.note(where));
82
152
  return;
83
153
  }
84
154
  // Plain text, not a report the CLI can read: show it as it came.
85
155
  if (result.output) {
86
156
  log(ui.section('Output'));
87
- log(result.output);
157
+ log(printable(result.output));
88
158
  }
89
159
  if (result.error) {
90
160
  log(ui.section('Error'));
91
- log(colors.error(result.error));
161
+ log(colors.error(printable(result.error)));
92
162
  }
163
+ if (!passed && where && !mentions(result.error, result))
164
+ log(ui.note(where));
93
165
  return;
94
166
  }
95
167
  const { flows } = report;
@@ -104,10 +176,15 @@ function printOutcome(log, passed, result, label) {
104
176
  summary = `${failed} of ${total} flows failed`;
105
177
  log(passed && failed === 0 ? ui.success(summary) : `${ui.statusSymbol('FAILED')} ${summary}`);
106
178
  const rows = flows.map((f) => [
107
- f.file ?? label,
179
+ printable(f.file ?? label, { oneLine: true }),
108
180
  f.success
109
181
  ? ui.statusWord('PASSED')
110
- : `${ui.statusWord('FAILED')}${f.error ? ` ${colors.error(f.error)}` : ''}`,
182
+ : `${ui.statusWord('FAILED')}${f.error ? ` ${colors.error(printable(f.error, { oneLine: true }))}` : ''}`,
111
183
  ]);
112
184
  log(ui.branch(ui.fields(rows)));
185
+ for (const f of flows) {
186
+ const where = f.success ? null : describeLocation(f);
187
+ if (where && !mentions(f.error, f))
188
+ log(ui.note(`${printable(f.file ?? label, { oneLine: true })} failed ${where}`));
189
+ }
113
190
  }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * A downloaded ZIP that ends before its central directory, so `unzip` and most
3
+ * tools reject it. A server streams a ZIP's entries first and its central
4
+ * directory last, so a response that stops early, but still closes cleanly,
5
+ * leaves exactly this behind.
6
+ */
7
+ export declare class IncompleteZipError extends Error {
8
+ readonly bytes: number;
9
+ readonly detail?: string | undefined;
10
+ constructor(bytes: number, detail?: string | undefined);
11
+ }
12
+ /**
13
+ * Check that the file at `filePath` is a complete ZIP: its end-of-central-
14
+ * directory record (or the ZIP64 one) is there and every central directory
15
+ * header after it is intact. Only the central directory is read, never the
16
+ * entries' data, so this costs about its size even for a multi-GB archive.
17
+ *
18
+ * Throws {@link IncompleteZipError} when the file is not a complete ZIP,
19
+ * including when it is empty or missing.
20
+ */
21
+ export declare function assertCompleteZip(filePath: string): Promise<void>;
@@ -0,0 +1,45 @@
1
+ import { stat } from 'node:fs/promises';
2
+ import StreamZip from 'node-stream-zip';
3
+ /**
4
+ * A downloaded ZIP that ends before its central directory, so `unzip` and most
5
+ * tools reject it. A server streams a ZIP's entries first and its central
6
+ * directory last, so a response that stops early, but still closes cleanly,
7
+ * leaves exactly this behind.
8
+ */
9
+ export class IncompleteZipError extends Error {
10
+ bytes;
11
+ detail;
12
+ constructor(bytes, detail) {
13
+ super(`the ZIP is incomplete (${bytes} bytes, no valid central directory)`);
14
+ this.bytes = bytes;
15
+ this.detail = detail;
16
+ this.name = 'IncompleteZipError';
17
+ }
18
+ }
19
+ /**
20
+ * Check that the file at `filePath` is a complete ZIP: its end-of-central-
21
+ * directory record (or the ZIP64 one) is there and every central directory
22
+ * header after it is intact. Only the central directory is read, never the
23
+ * entries' data, so this costs about its size even for a multi-GB archive.
24
+ *
25
+ * Throws {@link IncompleteZipError} when the file is not a complete ZIP,
26
+ * including when it is empty or missing.
27
+ */
28
+ export async function assertCompleteZip(filePath) {
29
+ const bytes = await stat(filePath).then((s) => s.size, () => 0);
30
+ const zip = new StreamZip.async({
31
+ file: filePath,
32
+ skipEntryNameValidation: true,
33
+ storeEntries: false,
34
+ });
35
+ try {
36
+ // Resolves only once every central directory header has been read.
37
+ await zip.entriesCount;
38
+ }
39
+ catch (error) {
40
+ throw new IncompleteZipError(bytes, error instanceof Error ? error.message : String(error));
41
+ }
42
+ finally {
43
+ await zip.close().catch(() => { });
44
+ }
45
+ }
package/package.json CHANGED
@@ -66,7 +66,7 @@
66
66
  "test:unit": "node scripts/test-runner.mjs --unit",
67
67
  "typecheck": "tsc --noEmit -p tsconfig.test.json"
68
68
  },
69
- "version": "5.14.1",
69
+ "version": "5.16.0-beta.1",
70
70
  "bugs": {
71
71
  "url": "https://discord.gg/gm3mJwcNw8"
72
72
  },
@@ -79,6 +79,15 @@
79
79
  "testing"
80
80
  ],
81
81
  "types": "dist/index.d.ts",
82
+ "exports": {
83
+ ".": "./dist/index.js",
84
+ "./e2e": {
85
+ "types": "./dist/e2e/index.d.ts",
86
+ "default": "./dist/e2e/index.js"
87
+ },
88
+ "./package.json": "./package.json",
89
+ "./dist/*": "./dist/*"
90
+ },
82
91
  "packageManager": "pnpm@10.17.1",
83
92
  "pnpm": {
84
93
  "overrides": {