@devicecloud.dev/dcd 5.11.0-beta.1 → 5.11.0-beta.10

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 (59) hide show
  1. package/README.md +75 -3
  2. package/dist/commands/cloud.d.ts +1 -1
  3. package/dist/commands/cloud.js +7 -6
  4. package/dist/commands/device.d.ts +36 -0
  5. package/dist/commands/device.js +1151 -0
  6. package/dist/commands/live.d.ts +2 -0
  7. package/dist/commands/live.js +10 -1
  8. package/dist/commands/login.js +2 -17
  9. package/dist/commands/mcp.d.ts +13 -0
  10. package/dist/commands/mcp.js +180 -0
  11. package/dist/commands/upload.js +2 -8
  12. package/dist/config/flags/device.flags.d.ts +1 -1
  13. package/dist/config/flags/device.flags.js +1 -1
  14. package/dist/constants.d.ts +1 -1
  15. package/dist/gateways/device-gateway.d.ts +88 -0
  16. package/dist/gateways/device-gateway.js +140 -0
  17. package/dist/index.js +4 -0
  18. package/dist/mcp/bridge.d.ts +52 -0
  19. package/dist/mcp/bridge.js +288 -0
  20. package/dist/mcp/tools/run-cloud-test.d.ts +13 -0
  21. package/dist/mcp/tools/run-cloud-test.js +18 -8
  22. package/dist/methods.d.ts +24 -0
  23. package/dist/methods.js +147 -169
  24. package/dist/services/device-validation.service.js +1 -1
  25. package/dist/services/execution-plan.service.d.ts +27 -0
  26. package/dist/services/execution-plan.service.js +9 -1
  27. package/dist/services/metadata-extractor.service.d.ts +13 -0
  28. package/dist/services/metadata-extractor.service.js +35 -1
  29. package/dist/services/moropo.service.js +1 -1
  30. package/dist/services/results-polling.service.js +1 -1
  31. package/dist/types/domain/device-session.types.d.ts +211 -0
  32. package/dist/types/domain/device-session.types.js +5 -0
  33. package/dist/types/domain/device.types.d.ts +0 -2
  34. package/dist/types/domain/device.types.js +0 -2
  35. package/dist/types.d.ts +11 -0
  36. package/dist/utils/app-upload.d.ts +19 -0
  37. package/dist/utils/app-upload.js +63 -0
  38. package/dist/utils/auth.d.ts +0 -8
  39. package/dist/utils/auth.js +31 -27
  40. package/dist/utils/b2-retry.d.ts +49 -0
  41. package/dist/utils/b2-retry.js +77 -0
  42. package/dist/utils/browser.d.ts +16 -0
  43. package/dist/utils/browser.js +48 -0
  44. package/dist/utils/compatibility.d.ts +5 -7
  45. package/dist/utils/compatibility.js +5 -13
  46. package/dist/utils/device-artifacts.d.ts +55 -0
  47. package/dist/utils/device-artifacts.js +211 -0
  48. package/dist/utils/device-bundle.d.ts +35 -0
  49. package/dist/utils/device-bundle.js +162 -0
  50. package/dist/utils/device-matrix.js +1 -1
  51. package/dist/utils/device-output.d.ts +81 -0
  52. package/dist/utils/device-output.js +204 -0
  53. package/dist/utils/device-run.d.ts +29 -0
  54. package/dist/utils/device-run.js +113 -0
  55. package/dist/utils/mcp-install.d.ts +50 -0
  56. package/dist/utils/mcp-install.js +132 -0
  57. package/dist/utils/progress.d.ts +4 -0
  58. package/dist/utils/progress.js +45 -21
  59. package/package.json +2 -2
@@ -0,0 +1,211 @@
1
+ export type DeviceSessionState = 'active' | 'expired' | 'failed' | 'needs_human' | 'provisioning' | 'queued' | 'ready' | 'released';
2
+ /** States a session can no longer leave. */
3
+ export declare const ENDED_STATES: readonly DeviceSessionState[];
4
+ /**
5
+ * The compact `session` block every /device/sessions response carries
6
+ * (ILiveSessionSummary in the API). `id` is the session name, which every
7
+ * `dcd device` command takes.
8
+ */
9
+ export interface DeviceSession {
10
+ id: string;
11
+ live_id: number;
12
+ state: DeviceSessionState;
13
+ release_reason: null | string;
14
+ platform: string;
15
+ model: null | string;
16
+ client_label: null | string;
17
+ created_at: string;
18
+ queue: {
19
+ eta_s: null | number;
20
+ position: null | number;
21
+ reason: 'fleet_busy' | 'waiting_for_device';
22
+ } | null;
23
+ time_remaining_s: null | number;
24
+ idle_remaining_s: null | number;
25
+ cost_so_far_usd: null | number;
26
+ last_crash: {
27
+ at: string;
28
+ summary: string;
29
+ } | null;
30
+ /**
31
+ * The build the session asked for and where its install is. Null when no
32
+ * build was asked for; absent from APIs older than this field.
33
+ */
34
+ install?: {
35
+ binary_upload_id: string;
36
+ error: null | string;
37
+ status: 'failed' | 'installed' | 'installing';
38
+ } | null;
39
+ warnings: string[];
40
+ monitor_url: string;
41
+ }
42
+ /**
43
+ * GET .../human and POST .../request-human (ILiveHumanStatus in the API):
44
+ * whether the session waits for a person, and what they said on handing back.
45
+ */
46
+ export interface DeviceHumanStatus {
47
+ /** The session is in needs_human: wait, polling this. */
48
+ waiting: boolean;
49
+ /** Why help was asked for, while waiting. */
50
+ reason: null | string;
51
+ /** When help was asked for, while waiting. */
52
+ since: null | string;
53
+ /** When the session ends unless a person hands it back, while waiting. */
54
+ expires_at: null | string;
55
+ /** A person handed the session back since help was last asked for. */
56
+ handed_back: boolean;
57
+ /** Their note, if they left one. */
58
+ note: null | string;
59
+ handed_back_at: null | string;
60
+ /** A person has taken control in the console; commands answer 409 meanwhile. */
61
+ human_in_control: boolean;
62
+ controller_user_id: null | string;
63
+ }
64
+ /** POST /device/sessions. */
65
+ export interface StartDeviceSessionRequest {
66
+ platform: 'android' | 'ios';
67
+ binaryUploadId?: string;
68
+ model?: string;
69
+ os?: string;
70
+ googlePlay?: boolean;
71
+ deviceLocale?: string;
72
+ clientLabel?: string;
73
+ maxDurationMin?: number;
74
+ record?: boolean;
75
+ }
76
+ /** One entry of GET /device/models. */
77
+ export interface DeviceModel {
78
+ model: string;
79
+ name: string;
80
+ os: string[];
81
+ default_os: string;
82
+ google_play: boolean;
83
+ default: boolean;
84
+ }
85
+ export interface DeviceCatalogue {
86
+ android: DeviceModel[];
87
+ ios: DeviceModel[];
88
+ }
89
+ /** What POST .../install answers with beside the session. */
90
+ export interface DeviceInstalledApp {
91
+ app_id: null | string;
92
+ binary_upload_id: string;
93
+ reused: boolean;
94
+ }
95
+ /** One flow of a run, as newer APIs report it in `result.flows`. */
96
+ export interface DeviceFlowResult {
97
+ error: null | string;
98
+ /** The flow's path inside the bundle; null for a single flow. */
99
+ file: null | string;
100
+ success: boolean;
101
+ }
102
+ /** The result of a typed action, a launch or a run. */
103
+ export interface DeviceCommandResult {
104
+ error?: string;
105
+ /** Each flow of a run. Absent from APIs older than this field. */
106
+ flows?: DeviceFlowResult[];
107
+ output?: string;
108
+ /** A failed run: the app's visible text just after it failed. */
109
+ screen_text?: string[];
110
+ success: boolean;
111
+ }
112
+ /** One element of the compact screen (Maestro's key names). */
113
+ export interface DeviceScreenElement {
114
+ /** Bounds, "[left,top][right,bottom]". */
115
+ b: string;
116
+ a11y?: string;
117
+ checked?: true;
118
+ /** False when disabled; absent when enabled. */
119
+ enabled?: false;
120
+ focused?: true;
121
+ hint?: string;
122
+ rid?: string;
123
+ selected?: true;
124
+ txt?: string;
125
+ }
126
+ /** GET .../inspect: the elements worth targeting, and what each key means. */
127
+ export interface DeviceScreen {
128
+ elements: DeviceScreenElement[];
129
+ /** False when no new frame came in time; this is then the latest. */
130
+ fresh: boolean;
131
+ height: number;
132
+ /** Keyboard keys and System UI left out (only when some were); --all shows them. */
133
+ hidden?: {
134
+ keyboard: number;
135
+ system: number;
136
+ };
137
+ /** An on-screen keyboard is showing (Android). */
138
+ keyboard_open?: true;
139
+ keys: Record<string, string>;
140
+ width: number;
141
+ }
142
+ /** GET .../screenshot. */
143
+ export interface DeviceScreenshot {
144
+ captured_at: null | string;
145
+ /** A JPEG data URL. */
146
+ data_url: string;
147
+ fresh: boolean;
148
+ }
149
+ /** POST .../run and GET .../commands/:id. */
150
+ export interface DeviceRunResponse {
151
+ command_id: string;
152
+ result: DeviceCommandResult | null;
153
+ session: DeviceSession;
154
+ /** `running` when the flow outlasted the API's wait: poll the command. */
155
+ status: 'failed' | 'passed' | 'running';
156
+ }
157
+ /** GET .../logs. */
158
+ export interface DeviceLogs {
159
+ app_id: null | string;
160
+ lines: string[];
161
+ /** logcat, ios-unified-log, or none before an app is installed. */
162
+ source: string;
163
+ }
164
+ /** A short-lived download link for one stored artifact. */
165
+ export interface DeviceArtifactLink {
166
+ bytes: null | number;
167
+ content_type: string;
168
+ created_at: string;
169
+ /** Null when the file could not be signed (e.g. already cleaned up). */
170
+ url: null | string;
171
+ }
172
+ /** GET .../artifacts: one page, newest actions first. */
173
+ export interface DeviceArtifactsPage {
174
+ actions: {
175
+ command_id: null | string;
176
+ created_at: string;
177
+ hierarchy: DeviceArtifactLink | null;
178
+ screenshot: DeviceArtifactLink | null;
179
+ }[];
180
+ logs: DeviceArtifactLink | null;
181
+ /** Pass as `before` for the next (older) page; null on the last page. */
182
+ next_before: null | string;
183
+ /**
184
+ * Files the runner is still uploading after the session ended: the video
185
+ * and the device log land up to a minute or so later. Absent from APIs
186
+ * older than this field.
187
+ */
188
+ pending?: ('logs' | 'recording')[];
189
+ recording: DeviceArtifactLink | null;
190
+ session: DeviceSession;
191
+ }
192
+ /** POST /device/bundles/upload-url: where to PUT the zip (both, when both are given). */
193
+ export interface DeviceBundleUploadUrls {
194
+ id: string;
195
+ mirror: {
196
+ path: string;
197
+ signedUrl: string;
198
+ } | null;
199
+ upload: {
200
+ path: string;
201
+ signedUrl: string;
202
+ } | null;
203
+ }
204
+ /** A registered flow bundle. `run` takes its id as `flowUploadId`. */
205
+ export interface DeviceFlowBundle {
206
+ bytes: number;
207
+ created_at: string;
208
+ encrypted: boolean;
209
+ id: string;
210
+ sha: string;
211
+ }
@@ -0,0 +1,5 @@
1
+ // Hand-defined: the /device/sessions routes are not in the swagger spec the
2
+ // CLI generates schema.types.ts from. They mirror the API's own types in
3
+ // dcd/api/src/apps/live/live.types.ts and device-sessions.controller.ts.
4
+ /** States a session can no longer leave. */
5
+ export const ENDED_STATES = ['released', 'expired', 'failed'];
@@ -30,9 +30,7 @@ export declare enum EiOSDevices {
30
30
  export declare enum EAndroidDevices {
31
31
  'generic-tablet' = "generic-tablet",
32
32
  'pixel-6' = "pixel-6",
33
- 'pixel-6-pro' = "pixel-6-pro",
34
33
  'pixel-7' = "pixel-7",
35
- 'pixel-7-pro' = "pixel-7-pro",
36
34
  'pixel-8' = "pixel-8",
37
35
  'pixel-10' = "pixel-10",
38
36
  'pixel-10-pro' = "pixel-10-pro",
@@ -32,9 +32,7 @@ export var EAndroidDevices;
32
32
  (function (EAndroidDevices) {
33
33
  EAndroidDevices["generic-tablet"] = "generic-tablet";
34
34
  EAndroidDevices["pixel-6"] = "pixel-6";
35
- EAndroidDevices["pixel-6-pro"] = "pixel-6-pro";
36
35
  EAndroidDevices["pixel-7"] = "pixel-7";
37
- EAndroidDevices["pixel-7-pro"] = "pixel-7-pro";
38
36
  EAndroidDevices["pixel-8"] = "pixel-8";
39
37
  EAndroidDevices["pixel-10"] = "pixel-10";
40
38
  EAndroidDevices["pixel-10-pro"] = "pixel-10-pro";
package/dist/types.d.ts CHANGED
@@ -1,6 +1,17 @@
1
+ import type { CpuArchitecture } from './services/metadata-extractor.service.js';
1
2
  import type { BinaryEnvelope } from './utils/envelope.js';
2
3
  export type TAppMetadata = {
4
+ /**
5
+ * APK only: the native ABIs under `lib/<abi>/` (e.g. `arm64-v8a`, `x86_64`).
6
+ * Stored on `binaries.metadata.abis`. Empty when the APK has no native code.
7
+ */
8
+ abis?: string[];
3
9
  appId: string;
10
+ /**
11
+ * APK only: the CPU families the APK can run on, `arm`, `x86` or both.
12
+ * Stored on `binaries.metadata.architectures`. Both when it has no native code.
13
+ */
14
+ architectures?: CpuArchitecture[];
4
15
  platform: 'android' | 'ios';
5
16
  /**
6
17
  * Present when the binary was client-side envelope-encrypted before upload
@@ -0,0 +1,19 @@
1
+ import type { AuthContext } from '../types/domain/auth.types.js';
2
+ /** The platform a local build is for, from its file name; undefined if unknown. */
3
+ export declare function platformOfAppFile(filePath: string): 'android' | 'ios' | undefined;
4
+ export interface UploadLocalAppOptions {
5
+ apiUrl: string;
6
+ auth: AuthContext;
7
+ filePath: string;
8
+ /** Show the upload's progress spinner. Only on a TTY, never under --json. */
9
+ showProgress: boolean;
10
+ /** One line of progress for a person, e.g. the encryption notice. */
11
+ log: (message: string) => void;
12
+ }
13
+ /**
14
+ * Upload a local build the way `dcd upload` does, and return its binary id:
15
+ * an Expo `.tar.gz` is unpacked to its `.app`, a `.zip` is checked, and the
16
+ * org's encryption default applies. URLs are not handled here: `dcd device`
17
+ * hands those to the API's install-from-URL instead.
18
+ */
19
+ export declare function uploadLocalApp(opts: UploadLocalAppOptions): Promise<string>;
@@ -0,0 +1,63 @@
1
+ import { rm } from 'node:fs/promises';
2
+ import { uploadBinary, verifyAppZip } from '../methods.js';
3
+ import { CliError } from './cli.js';
4
+ import { fetchCompatibilityData } from './compatibility.js';
5
+ import { checkKekForEncryption, resolveEncryption } from './envelope.js';
6
+ import { extractTarGz, findAppBundle } from './expo.js';
7
+ const APP_EXTENSIONS = ['.apk', '.app', '.zip', '.tar.gz'];
8
+ /** The platform a local build is for, from its file name; undefined if unknown. */
9
+ export function platformOfAppFile(filePath) {
10
+ const clean = filePath.replace(/\/+$/, '');
11
+ if (clean.endsWith('.apk'))
12
+ return 'android';
13
+ if (['.app', '.zip', '.tar.gz'].some((ext) => clean.endsWith(ext)))
14
+ return 'ios';
15
+ return undefined;
16
+ }
17
+ /**
18
+ * Upload a local build the way `dcd upload` does, and return its binary id:
19
+ * an Expo `.tar.gz` is unpacked to its `.app`, a `.zip` is checked, and the
20
+ * org's encryption default applies. URLs are not handled here: `dcd device`
21
+ * hands those to the API's install-from-URL instead.
22
+ */
23
+ export async function uploadLocalApp(opts) {
24
+ const { apiUrl, auth, log } = opts;
25
+ let filePath = opts.filePath.replace(/\/+$/, '');
26
+ if (!APP_EXTENSIONS.some((ext) => filePath.endsWith(ext))) {
27
+ throw new CliError('The app must be a .apk for Android, or a .app, .zip or .tar.gz (Expo) for iOS.');
28
+ }
29
+ // As in `dcd upload`: a failed compatibility fetch leaves the default off
30
+ // rather than failing the upload.
31
+ let serverDefault;
32
+ try {
33
+ const compatibility = await fetchCompatibilityData(apiUrl, auth);
34
+ serverDefault = compatibility.encryption?.defaultOn;
35
+ }
36
+ catch {
37
+ serverDefault = undefined;
38
+ }
39
+ const encryption = await checkKekForEncryption(resolveEncryption({ serverDefault }), apiUrl);
40
+ if (encryption.notice)
41
+ log(encryption.notice);
42
+ const tempDirs = [];
43
+ try {
44
+ if (filePath.endsWith('.tar.gz')) {
45
+ const dir = await extractTarGz(filePath, false);
46
+ tempDirs.push(dir);
47
+ filePath = await findAppBundle(dir);
48
+ }
49
+ if (filePath.endsWith('.zip'))
50
+ await verifyAppZip(filePath);
51
+ return await uploadBinary({
52
+ apiUrl,
53
+ auth,
54
+ encrypt: encryption.enabled,
55
+ filePath,
56
+ log: opts.showProgress,
57
+ });
58
+ }
59
+ finally {
60
+ for (const dir of tempDirs)
61
+ await rm(dir, { force: true, recursive: true }).catch(() => { });
62
+ }
63
+ }
@@ -44,11 +44,3 @@ export declare function refreshAuth(auth: AuthContext): Promise<AuthContext>;
44
44
  * next attempt may get past.
45
45
  */
46
46
  export declare function isDefinitiveAuthFailure(error: unknown): boolean;
47
- /**
48
- * Remove only the (definitively dead) session from the stored config, keeping
49
- * env/api_url/org so a re-login lands back in the same environment. With the
50
- * dead session gone, subsequent commands report "Not authenticated" instead
51
- * of failing the same refresh, and `dcd login` skips its "already logged in"
52
- * confirm. Exported for tests.
53
- */
54
- export declare function dropStoredSession(): void;
@@ -2,6 +2,7 @@
2
2
  * Resolves which credential a command should use and returns the fetch headers
3
3
  * to send. Precedence: --api-key flag > DEVICE_CLOUD_API_KEY env > stored
4
4
  * Supabase session (refreshed if near expiry). Throws CliError if none found.
5
+ * The headers also carry the CLI's own identity (see clientHeaders).
5
6
  *
6
7
  * The refresh path writes the rotated tokens back to disk atomically. Callers
7
8
  * resolve once per invocation, not per request — except where a process can
@@ -11,7 +12,8 @@
11
12
  import { closeSync, openSync, rmSync, statSync } from 'node:fs';
12
13
  import { CliAuthGateway, SessionRefreshError, } from '../gateways/cli-auth-gateway.js';
13
14
  import { telemetry } from '../services/telemetry.service.js';
14
- import { CliError } from './cli.js';
15
+ import { detectCiContext } from './ci.js';
16
+ import { CliError, getCliVersion } from './cli.js';
15
17
  import { getConfigPath, readConfig, writeConfig, } from './config-store.js';
16
18
  const REFRESH_SKEW_SECONDS = 60;
17
19
  // Refresh lock tuning: a refresh is a single HTTP round-trip, so anything
@@ -31,13 +33,30 @@ export function apiKeyOverride(apiKeyFlag) {
31
33
  return 'DEVICE_CLOUD_API_KEY';
32
34
  return undefined;
33
35
  }
36
+ /**
37
+ * Who is calling, sent with every request next to the credential: the API
38
+ * targets notices by it and records it on each upload and binary.
39
+ * The CI headers are sent only when a DCD wrapper forwarded them or the
40
+ * provider could be inferred.
41
+ */
42
+ function clientHeaders() {
43
+ const headers = {
44
+ 'x-dcd-cli-version': getCliVersion(),
45
+ };
46
+ const ci = detectCiContext();
47
+ if (ci.provider)
48
+ headers['x-dcd-ci-provider'] = ci.provider;
49
+ if (ci.wrapperVersion)
50
+ headers['x-dcd-ci-wrapper-version'] = ci.wrapperVersion;
51
+ return headers;
52
+ }
34
53
  export async function resolveAuth(opts) {
35
54
  if (!opts.sessionOnly) {
36
55
  const flag = opts.apiKeyFlag?.trim();
37
56
  if (flag) {
38
57
  const auth = {
39
58
  mode: 'apiKey',
40
- headers: { 'x-app-api-key': flag },
59
+ headers: { ...clientHeaders(), 'x-app-api-key': flag },
41
60
  };
42
61
  telemetry.configure({ auth });
43
62
  return auth;
@@ -46,7 +65,7 @@ export async function resolveAuth(opts) {
46
65
  if (env) {
47
66
  const auth = {
48
67
  mode: 'apiKey',
49
- headers: { 'x-app-api-key': env },
68
+ headers: { ...clientHeaders(), 'x-app-api-key': env },
50
69
  };
51
70
  telemetry.configure({ auth });
52
71
  return auth;
@@ -75,6 +94,7 @@ export async function resolveAuth(opts) {
75
94
  orgId: config.current_org_id,
76
95
  userEmail: session.user_email,
77
96
  headers: {
97
+ ...clientHeaders(),
78
98
  authorization: `Bearer ${session.access_token}`,
79
99
  'x-dcd-org': config.current_org_id,
80
100
  },
@@ -143,16 +163,14 @@ async function refreshSessionWithLock(initial) {
143
163
  if (session.expires_at > now + REFRESH_SKEW_SECONDS) {
144
164
  return { config: current, session };
145
165
  }
146
- let refreshed;
147
- try {
148
- refreshed = await CliAuthGateway.refresh(current.supabase_url, current.env, session);
149
- }
150
- catch (error) {
151
- if (error instanceof SessionRefreshError && error.definitive) {
152
- dropStoredSession();
153
- }
154
- throw error;
155
- }
166
+ // A failed refresh never deletes the stored session, even one Supabase
167
+ // refused outright. A refusal is not always the session's fault: an old
168
+ // CLI build sending a retired Supabase key gets a 401 ("Legacy API keys
169
+ // are disabled") for a session that is still good, and wiping it then
170
+ // forced a fresh login when an upgrade alone would have fixed it. The
171
+ // error tells the user to log in again; only `dcd logout` (or the next
172
+ // `dcd login`) replaces the stored session.
173
+ const refreshed = await CliAuthGateway.refresh(current.supabase_url, current.env, session);
156
174
  // Re-read again and merge only `session` so a concurrent `switch-org`
157
175
  // write (org fields) isn't reverted by our pre-refresh snapshot.
158
176
  const merged = { ...(readConfig() ?? current), session: refreshed };
@@ -166,20 +184,6 @@ async function refreshSessionWithLock(initial) {
166
184
  catch { /* best effort */ }
167
185
  }
168
186
  }
169
- /**
170
- * Remove only the (definitively dead) session from the stored config, keeping
171
- * env/api_url/org so a re-login lands back in the same environment. With the
172
- * dead session gone, subsequent commands report "Not authenticated" instead
173
- * of failing the same refresh, and `dcd login` skips its "already logged in"
174
- * confirm. Exported for tests.
175
- */
176
- export function dropStoredSession() {
177
- const config = readConfig();
178
- if (!config?.session)
179
- return;
180
- delete config.session;
181
- writeConfig(config);
182
- }
183
187
  async function acquireRefreshLock(lockPath) {
184
188
  const deadline = Date.now() + LOCK_WAIT_MS;
185
189
  for (;;) {
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Retries for direct-to-Backblaze uploads.
3
+ *
4
+ * B2 expects clients to retry: an upload can be answered with 408, 429 or a
5
+ * 5xx, or have its connection dropped, and B2's own guidance is to back off
6
+ * and try again (for a large-file part, on a different upload URL). The CLI
7
+ * used to make exactly one attempt, so a single dropped B2 request failed the
8
+ * B2 upload outright and left the Supabase upload as the only path.
9
+ */
10
+ export declare const B2_RETRY: {
11
+ /** Total attempts per request, the first included. */
12
+ attempts: number;
13
+ baseDelayMs: number;
14
+ maxDelayMs: number;
15
+ };
16
+ /** A B2 (or S3-compatible) response that was not 2xx. */
17
+ export declare class B2HttpError extends Error {
18
+ readonly status: number;
19
+ readonly body: string;
20
+ constructor(message: string, status: number, body: string);
21
+ }
22
+ /**
23
+ * Whether a failed attempt is worth repeating. Network errors (fetch throws a
24
+ * TypeError) and 408 / 429 / 5xx are transient. A 401 is retryable only where
25
+ * the next attempt uses a different upload URL, which B2 hands out with its
26
+ * own token: on the same URL it would fail the same way.
27
+ */
28
+ export declare function isRetryableB2Error(error: unknown, opts?: {
29
+ rotatesUrl?: boolean;
30
+ }): boolean;
31
+ /** Exponential backoff with full jitter, capped at `maxDelayMs`. */
32
+ export declare function b2RetryDelayMs(attempt: number, random?: () => number): number;
33
+ export interface B2RetryOptions {
34
+ /** Each attempt gets a fresh upload URL, so a 401 is worth retrying. */
35
+ rotatesUrl?: boolean;
36
+ /** Called before each retry; the debug logging hook. */
37
+ onRetry?: (attempt: number, error: unknown, delayMs: number) => void;
38
+ /** Test seam. */
39
+ sleep?: (ms: number) => Promise<void>;
40
+ }
41
+ /**
42
+ * Run `attemptFn` until it resolves, a non-retryable error is thrown, or
43
+ * `B2_RETRY.attempts` is used up. `attemptFn` gets the 1-based attempt
44
+ * number so a caller can pick a different upload URL each time. The last
45
+ * error is rethrown unchanged.
46
+ */
47
+ export declare function withB2Retry<T>(attemptFn: (attempt: number) => Promise<T>, opts?: B2RetryOptions): Promise<T>;
48
+ /** Throw a `B2HttpError` for a non-2xx response; return it otherwise. */
49
+ export declare function assertB2Ok(response: Response, what: string): Promise<Response>;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Retries for direct-to-Backblaze uploads.
3
+ *
4
+ * B2 expects clients to retry: an upload can be answered with 408, 429 or a
5
+ * 5xx, or have its connection dropped, and B2's own guidance is to back off
6
+ * and try again (for a large-file part, on a different upload URL). The CLI
7
+ * used to make exactly one attempt, so a single dropped B2 request failed the
8
+ * B2 upload outright and left the Supabase upload as the only path.
9
+ */
10
+ export const B2_RETRY = {
11
+ /** Total attempts per request, the first included. */
12
+ attempts: 4,
13
+ baseDelayMs: 1000,
14
+ maxDelayMs: 8000,
15
+ };
16
+ /** A B2 (or S3-compatible) response that was not 2xx. */
17
+ export class B2HttpError extends Error {
18
+ status;
19
+ body;
20
+ constructor(message, status, body) {
21
+ super(message);
22
+ this.status = status;
23
+ this.body = body;
24
+ this.name = 'B2HttpError';
25
+ }
26
+ }
27
+ /**
28
+ * Whether a failed attempt is worth repeating. Network errors (fetch throws a
29
+ * TypeError) and 408 / 429 / 5xx are transient. A 401 is retryable only where
30
+ * the next attempt uses a different upload URL, which B2 hands out with its
31
+ * own token: on the same URL it would fail the same way.
32
+ */
33
+ export function isRetryableB2Error(error, opts = {}) {
34
+ if (error instanceof B2HttpError) {
35
+ const { status } = error;
36
+ if (status === 401)
37
+ return Boolean(opts.rotatesUrl);
38
+ return status === 408 || status === 429 || status >= 500;
39
+ }
40
+ return error instanceof TypeError;
41
+ }
42
+ /** Exponential backoff with full jitter, capped at `maxDelayMs`. */
43
+ export function b2RetryDelayMs(attempt, random = Math.random) {
44
+ const ceiling = Math.min(B2_RETRY.maxDelayMs, B2_RETRY.baseDelayMs * 2 ** (attempt - 1));
45
+ return Math.round(ceiling / 2 + (random() * ceiling) / 2);
46
+ }
47
+ const defaultSleep = (ms) => new Promise((resolve) => {
48
+ setTimeout(resolve, ms);
49
+ });
50
+ /**
51
+ * Run `attemptFn` until it resolves, a non-retryable error is thrown, or
52
+ * `B2_RETRY.attempts` is used up. `attemptFn` gets the 1-based attempt
53
+ * number so a caller can pick a different upload URL each time. The last
54
+ * error is rethrown unchanged.
55
+ */
56
+ export async function withB2Retry(attemptFn, opts = {}) {
57
+ const sleep = opts.sleep ?? defaultSleep;
58
+ for (let attempt = 1;; attempt++) {
59
+ try {
60
+ return await attemptFn(attempt);
61
+ }
62
+ catch (error) {
63
+ if (attempt >= B2_RETRY.attempts || !isRetryableB2Error(error, opts))
64
+ throw error;
65
+ const delayMs = b2RetryDelayMs(attempt);
66
+ opts.onRetry?.(attempt, error, delayMs);
67
+ await sleep(delayMs);
68
+ }
69
+ }
70
+ }
71
+ /** Throw a `B2HttpError` for a non-2xx response; return it otherwise. */
72
+ export async function assertB2Ok(response, what) {
73
+ if (response.ok)
74
+ return response;
75
+ const body = await response.text().catch(() => '');
76
+ throw new B2HttpError(`${what} failed with status ${response.status}`, response.status, body);
77
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Open `url` in the default browser. False if it isn't an http(s) URL or no
3
+ * opener could be started (none installed, as on a headless box).
4
+ *
5
+ * Only http(s) is opened, so a URL can't name a local file or start with `-`
6
+ * and be read as an option. No opener goes through a shell: Windows uses
7
+ * rundll32, because `cmd /c start` parses the URL again and treats its `&`
8
+ * as a command separator.
9
+ */
10
+ export declare function openBrowser(url: string): Promise<boolean>;
11
+ /**
12
+ * Start `bin` detached. False if it couldn't be started. A missing program is
13
+ * reported as an 'error' event, not thrown, and with no listener it would
14
+ * crash the process, so this waits for 'spawn' or 'error' to know.
15
+ */
16
+ export declare function startOpener(bin: string, args: string[]): Promise<boolean>;
@@ -0,0 +1,48 @@
1
+ import { spawn } from 'node:child_process';
2
+ /**
3
+ * Open `url` in the default browser. False if it isn't an http(s) URL or no
4
+ * opener could be started (none installed, as on a headless box).
5
+ *
6
+ * Only http(s) is opened, so a URL can't name a local file or start with `-`
7
+ * and be read as an option. No opener goes through a shell: Windows uses
8
+ * rundll32, because `cmd /c start` parses the URL again and treats its `&`
9
+ * as a command separator.
10
+ */
11
+ export async function openBrowser(url) {
12
+ let href;
13
+ try {
14
+ const parsed = new URL(url);
15
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
16
+ return false;
17
+ href = parsed.href;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ const cmd = process.platform === 'darwin'
23
+ ? { bin: 'open', args: [href] }
24
+ : process.platform === 'win32'
25
+ ? { bin: 'rundll32', args: ['url.dll,FileProtocolHandler', href] }
26
+ : { bin: 'xdg-open', args: [href] };
27
+ return startOpener(cmd.bin, cmd.args);
28
+ }
29
+ /**
30
+ * Start `bin` detached. False if it couldn't be started. A missing program is
31
+ * reported as an 'error' event, not thrown, and with no listener it would
32
+ * crash the process, so this waits for 'spawn' or 'error' to know.
33
+ */
34
+ export function startOpener(bin, args) {
35
+ return new Promise((resolve) => {
36
+ try {
37
+ const child = spawn(bin, args, { detached: true, stdio: 'ignore' });
38
+ child.once('spawn', () => {
39
+ child.unref();
40
+ resolve(true);
41
+ });
42
+ child.once('error', () => resolve(false));
43
+ }
44
+ catch {
45
+ resolve(false);
46
+ }
47
+ });
48
+ }
@@ -19,11 +19,9 @@ export interface CompatibilityData {
19
19
  defaultOn: boolean;
20
20
  };
21
21
  }
22
- /** Identity the CLI forwards so the API can target notices by version / CI. */
23
- export interface ClientContext {
24
- cliVersion?: string;
25
- ciProvider?: string | null;
26
- ciWrapperVersion?: string | null;
27
- }
28
- export declare function fetchCompatibilityData(apiUrl: string, auth: AuthContext, clientContext?: ClientContext): Promise<CompatibilityData>;
22
+ /**
23
+ * The CLI / CI identity the API version-filters and targets notices by rides
24
+ * on `auth.headers`, like on every other request (see resolveAuth).
25
+ */
26
+ export declare function fetchCompatibilityData(apiUrl: string, auth: AuthContext): Promise<CompatibilityData>;
29
27
  export declare function clearCompatibilityCache(): void;