@catalyst-cloud/cli 0.14.4 → 0.14.6

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.14.6
4
+
5
+ - A current Catalyst data folder no longer triggers a legacy-runtime cleanup warning. Legacy checks and removal keep current shared data and report it separately.
6
+
7
+ ## 0.14.5
8
+
9
+ - Onboarding checks the server's advertised support before provider and repository setup. An unavailable route waits with a public web link instead of reporting declined consent.
10
+ - GitHub App installation can open a verified browser handoff and checks every installation with fresh live probes. It remains separate from your personal GitHub connection and repository selection.
11
+ - A route removed during browser approval stops with a waiting result. Signed provider approval links remain out of logs and receipts.
12
+
3
13
  ## 0.14.4
4
14
 
5
15
  - Personal Linear and GitHub approval links stay out of logs and receipts. Setup validates the signed browser destination and its expiry before opening it.
package/dist/legacy.js CHANGED
@@ -7,7 +7,7 @@
7
7
  // The list is fixed on purpose. A prefix match would one day catch a current job (the housekeeping
8
8
  // job, the sandbox credit guard, jobs a person made); this matches names the old runtime installed,
9
9
  // read at the source commit below, and nothing else. Shared data folders are always kept. The historical --data flag cannot remove them.
10
- import { existsSync, lstatSync, readFileSync, readdirSync, unlinkSync } from "node:fs";
10
+ import { existsSync, lstatSync, readFileSync, readdirSync, unlinkSync, } from "node:fs";
11
11
  import { spawnSync } from "node:child_process";
12
12
  import { join } from "node:path";
13
13
  import { flagBool, positionals } from "./args.js";
@@ -44,17 +44,34 @@ export const OLD_LAUNCHD_LABELS = [
44
44
  const OLD_ROLE_PREFIX = "com.catalyst.role.";
45
45
  /** systemd user units (~/.config/systemd/user) the old runtime's workstation pieces used on Linux. System
46
46
  * units under /etc/systemd/system are a host's, current, and never looked at. */
47
- export const OLD_USER_UNITS = ["catalyst.service", "catalyst-monitor.service"];
47
+ export const OLD_USER_UNITS = [
48
+ "catalyst.service",
49
+ "catalyst-monitor.service",
50
+ ];
48
51
  /** Command files the old runtime put on the person's PATH. `~/.local/bin/catalyst` is NOT one: that
49
52
  * name belongs to the current CLI wherever npm put it. */
50
- export const OLD_BINS = [".local/bin/catalyst-events", ".local/bin/catalyst-filter", ".local/bin/catalyst-hud", ".local/bin/catalyst-monitor", ".local/bin/catalyst-myown"];
53
+ export const OLD_BINS = [
54
+ ".local/bin/catalyst-events",
55
+ ".local/bin/catalyst-filter",
56
+ ".local/bin/catalyst-hud",
57
+ ".local/bin/catalyst-monitor",
58
+ ".local/bin/catalyst-myown",
59
+ ];
51
60
  /** Shared roots also hold current skills, logs, hosts and seats. Never remove these directories. */
52
- export const OLD_DATA_DIRS = [".catalyst", ".config/catalyst", ".local/state/catalyst", ".local/state/catalyst-fleet-runner", ".local/state/catalyst-ledger"];
61
+ export const OLD_DATA_DIRS = [
62
+ ".catalyst",
63
+ ".config/catalyst",
64
+ ".local/state/catalyst",
65
+ ".local/state/catalyst-fleet-runner",
66
+ ".local/state/catalyst-ledger",
67
+ ];
53
68
  const RECOMMEND = "Remove them: the cloud runtime replaced them, and left in place they can start old jobs or shadow current commands.";
54
69
  function readJson(path) {
55
70
  try {
56
71
  const v = JSON.parse(readFileSync(path, "utf8"));
57
- return v !== null && typeof v === "object" ? v : null;
72
+ return v !== null && typeof v === "object"
73
+ ? v
74
+ : null;
58
75
  }
59
76
  catch {
60
77
  return null;
@@ -67,7 +84,8 @@ function findPlugins(home) {
67
84
  const old = Object.entries(marketplaces)
68
85
  .filter(([, v]) => {
69
86
  const src = v?.source;
70
- return typeof src?.repo === "string" && src.repo.toLowerCase() === OLD_MARKETPLACE_REPO;
87
+ return (typeof src?.repo === "string" &&
88
+ src.repo.toLowerCase() === OLD_MARKETPLACE_REPO);
71
89
  })
72
90
  .map(([name]) => name);
73
91
  if (old.length === 0)
@@ -77,10 +95,18 @@ function findPlugins(home) {
77
95
  for (const key of Object.keys(installed)) {
78
96
  const at = key.lastIndexOf("@");
79
97
  if (at > 0 && old.includes(key.slice(at + 1)))
80
- items.push({ kind: "plugin", name: key, path: join(dir, "installed_plugins.json") });
98
+ items.push({
99
+ kind: "plugin",
100
+ name: key,
101
+ path: join(dir, "installed_plugins.json"),
102
+ });
81
103
  }
82
104
  for (const name of old)
83
- items.push({ kind: "marketplace", name, path: join(dir, "known_marketplaces.json") });
105
+ items.push({
106
+ kind: "marketplace",
107
+ name,
108
+ path: join(dir, "known_marketplaces.json"),
109
+ });
84
110
  return items;
85
111
  }
86
112
  function findJobs(home, platform) {
@@ -96,35 +122,63 @@ function findJobs(home, platform) {
96
122
  return files
97
123
  .filter((f) => f.endsWith(".plist"))
98
124
  .map((f) => f.slice(0, -".plist".length))
99
- .filter((label) => OLD_LAUNCHD_LABELS.includes(label) || label.startsWith(OLD_ROLE_PREFIX))
125
+ .filter((label) => OLD_LAUNCHD_LABELS.includes(label) ||
126
+ label.startsWith(OLD_ROLE_PREFIX))
100
127
  .sort()
101
- .map((label) => ({ kind: "job", name: label, path: join(dir, `${label}.plist`) }));
128
+ .map((label) => ({
129
+ kind: "job",
130
+ name: label,
131
+ path: join(dir, `${label}.plist`),
132
+ }));
102
133
  }
103
134
  if (platform === "linux") {
104
135
  const dir = join(home, ".config", "systemd", "user");
105
- return OLD_USER_UNITS.filter((u) => existsSync(join(dir, u))).map((u) => ({ kind: "job", name: u, path: join(dir, u) }));
136
+ return OLD_USER_UNITS.filter((u) => existsSync(join(dir, u))).map((u) => ({
137
+ kind: "job",
138
+ name: u,
139
+ path: join(dir, u),
140
+ }));
106
141
  }
107
142
  return [];
108
143
  }
109
144
  const tilde = (rel) => `~/${rel}`;
110
145
  function findFiles(home) {
111
- const bins = OLD_BINS.filter((rel) => existsSync(join(home, rel))).map((rel) => ({ kind: "bin", name: tilde(rel), path: join(home, rel) }));
112
- const data = OLD_DATA_DIRS.filter((rel) => existsSync(join(home, rel))).map((rel) => ({ kind: "data", name: tilde(rel), path: join(home, rel), data: true }));
146
+ const bins = OLD_BINS.filter((rel) => existsSync(join(home, rel))).map((rel) => ({
147
+ kind: "bin",
148
+ name: tilde(rel),
149
+ path: join(home, rel),
150
+ }));
151
+ const data = OLD_DATA_DIRS.filter((rel) => existsSync(join(home, rel))).map((rel) => ({
152
+ kind: "data",
153
+ name: tilde(rel),
154
+ path: join(home, rel),
155
+ data: true,
156
+ }));
113
157
  return [...bins, ...data];
114
158
  }
115
159
  /** Every old piece on this machine, in removal order: plugins, their marketplace, jobs, bins, data. Never writes. */
116
160
  export function findLegacy(home, platform) {
117
- return [...findPlugins(home), ...findJobs(home, platform), ...findFiles(home)];
161
+ return [
162
+ ...findPlugins(home),
163
+ ...findJobs(home, platform),
164
+ ...findFiles(home),
165
+ ];
118
166
  }
119
167
  const defaultRun = (cmd, args) => {
120
168
  const r = spawnSync(cmd, args, { encoding: "utf8", timeout: 60_000 });
121
- return { status: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.error ? r.error.message : (r.stderr ?? "") };
169
+ return {
170
+ status: r.status ?? 1,
171
+ stdout: r.stdout ?? "",
172
+ stderr: r.error ? r.error.message : (r.stderr ?? ""),
173
+ };
122
174
  };
123
175
  /** Remove one item through the tool that owns it. Returns null on success, else the reason it is still there. */
124
176
  function remove(item, run, platform, uid) {
125
177
  const tool = (cmd, args, what) => {
126
178
  const r = run(cmd, args);
127
- return r.status === 0 ? null : `${what} failed: ${(r.stderr || r.stdout).trim().split("\n")[0] || `exit ${r.status}`}`;
179
+ return r.status === 0
180
+ ? null
181
+ : `${what} failed: ${(r.stderr || r.stdout).trim().split("\n")[0] || `exit ${r.status}`}`;
128
182
  };
129
183
  try {
130
184
  if (item.kind === "plugin")
@@ -132,7 +186,9 @@ function remove(item, run, platform, uid) {
132
186
  if (item.kind === "marketplace")
133
187
  return tool("claude", ["plugin", "marketplace", "remove", item.name], "claude plugin marketplace remove");
134
188
  if (item.kind === "job") {
135
- const why = platform === "darwin" ? tool("launchctl", ["bootout", `gui/${uid}/${item.name}`], "launchctl bootout") : tool("systemctl", ["--user", "disable", "--now", item.name], "systemctl --user disable --now");
189
+ const why = platform === "darwin"
190
+ ? tool("launchctl", ["bootout", `gui/${uid}/${item.name}`], "launchctl bootout")
191
+ : tool("systemctl", ["--user", "disable", "--now", item.name], "systemctl --user disable --now");
136
192
  if (why !== null)
137
193
  return why;
138
194
  unlinkSync(item.path);
@@ -159,21 +215,51 @@ export async function cmdLegacy(args, ctx, deps = {}) {
159
215
  const uid = deps.uid ?? (typeof process.getuid === "function" ? process.getuid() : 0);
160
216
  const run = deps.run ?? defaultRun;
161
217
  const found = findLegacy(ctx.home, platform);
162
- const emit = (body, lines) => { if (args.json)
163
- ctx.stdout(JSON.stringify(body));
164
- else
165
- for (const l of lines)
166
- ctx.stdout(l); };
167
- if (found.length === 0) {
168
- emit({ sourceCommit: LEGACY_SOURCE_COMMIT, found: [], removed: [], remaining: [] }, ["no leftovers of the old local Catalyst runtime on this machine"]);
218
+ const legacy = found.filter((item) => !item.data);
219
+ const shared = found.filter((item) => item.data);
220
+ const emit = (body, lines) => {
221
+ if (args.json)
222
+ ctx.stdout(JSON.stringify(body));
223
+ else
224
+ for (const l of lines)
225
+ ctx.stdout(l);
226
+ };
227
+ if (legacy.length === 0) {
228
+ emit({
229
+ sourceCommit: LEGACY_SOURCE_COMMIT,
230
+ found: [],
231
+ removed: [],
232
+ remaining: [],
233
+ kept: shared,
234
+ }, [
235
+ "no leftovers of the old local Catalyst runtime on this machine",
236
+ ...(shared.length
237
+ ? ["shared current Catalyst data folders are present and kept"]
238
+ : []),
239
+ ]);
169
240
  return 0;
170
241
  }
171
242
  const listLines = [
172
- `Leftovers of the old local Catalyst runtime on this machine (${found.length}):`,
173
- ...found.map((f) => ` ${f.kind}: ${f.name}${f.kind === "job" ? ` — ${f.path}` : f.data ? " (kept: shared current state)" : ""}`),
243
+ `Leftovers of the old local Catalyst runtime on this machine (${legacy.length}):`,
244
+ ...legacy.map((f) => ` ${f.kind}: ${f.name}${f.kind === "job" ? ` — ${f.path}` : ""}`),
245
+ ...(shared.length
246
+ ? [
247
+ "Shared current data folders (kept):",
248
+ ...shared.map((f) => ` ${f.kind}: ${f.name} (kept: shared current state)`),
249
+ ]
250
+ : []),
174
251
  ];
175
252
  if (!wantRemove) {
176
- emit({ sourceCommit: LEGACY_SOURCE_COMMIT, found, removed: [], remaining: found }, [...listLines, RECOMMEND, "Run: catalyst legacy --remove (all data folders are kept)"]);
253
+ emit({
254
+ sourceCommit: LEGACY_SOURCE_COMMIT,
255
+ found,
256
+ removed: [],
257
+ remaining: found,
258
+ }, [
259
+ ...listLines,
260
+ RECOMMEND,
261
+ "Run: catalyst legacy --remove (all data folders are kept)",
262
+ ]);
177
263
  return 1;
178
264
  }
179
265
  // the one question, only on a terminal; --yes answers it without asking
@@ -181,16 +267,34 @@ export async function cmdLegacy(args, ctx, deps = {}) {
181
267
  if (!go) {
182
268
  const tty = (deps.isTty ?? stdinIsTty)();
183
269
  if (!tty) {
184
- emit({ sourceCommit: LEGACY_SOURCE_COMMIT, found, removed: [], remaining: found, asked: false }, [...listLines, RECOMMEND, "nothing removed: no terminal to ask on; run catalyst legacy --remove --yes to remove these without a question (all data folders are kept)"]);
270
+ emit({
271
+ sourceCommit: LEGACY_SOURCE_COMMIT,
272
+ found,
273
+ removed: [],
274
+ remaining: found,
275
+ asked: false,
276
+ }, [
277
+ ...listLines,
278
+ RECOMMEND,
279
+ "nothing removed: no terminal to ask on; run catalyst legacy --remove --yes to remove these without a question (all data folders are kept)",
280
+ ]);
185
281
  return 1;
186
282
  }
187
283
  for (const l of listLines)
188
284
  ctx.stdout(l);
189
285
  ctx.stdout(RECOMMEND);
190
- const answer = (await (deps.prompt ?? ((q) => promptSecret(q)))(`Remove ${found.length} item${found.length === 1 ? "" : "s"}, keeping all data folders? [y/N] `)).trim().toLowerCase();
286
+ const answer = (await (deps.prompt ?? ((q) => promptSecret(q)))(`Remove ${legacy.length} item${legacy.length === 1 ? "" : "s"}, keeping all data folders? [y/N] `))
287
+ .trim()
288
+ .toLowerCase();
191
289
  go = answer === "y" || answer === "yes";
192
290
  if (!go) {
193
- emit({ sourceCommit: LEGACY_SOURCE_COMMIT, found, removed: [], remaining: found, asked: true }, ["nothing removed; run catalyst legacy --remove again when ready"]);
291
+ emit({
292
+ sourceCommit: LEGACY_SOURCE_COMMIT,
293
+ found,
294
+ removed: [],
295
+ remaining: found,
296
+ asked: true,
297
+ }, ["nothing removed; run catalyst legacy --remove again when ready"]);
194
298
  return 1;
195
299
  }
196
300
  }
@@ -217,7 +321,16 @@ export async function cmdLegacy(args, ctx, deps = {}) {
217
321
  // re-check from the same list, so the report says what the machine holds now, not what was attempted
218
322
  const remaining = findLegacy(ctx.home, platform).filter((f) => !f.data);
219
323
  const keptNote = kept.length > 0 ? "; all shared data folders were kept" : "";
220
- lines.push(remaining.length === 0 ? `re-checked: nothing of the old runtime remains${keptNote}` : `re-checked: ${remaining.length} item${remaining.length === 1 ? "" : "s"} of the old runtime remain${remaining.length === 1 ? "s" : ""}${keptNote}: ${remaining.map((r) => `${r.kind} ${r.name}`).join(", ")}`);
221
- emit({ sourceCommit: LEGACY_SOURCE_COMMIT, found, removed, remaining: [...remaining, ...kept], kept, failed }, lines);
324
+ lines.push(remaining.length === 0
325
+ ? `re-checked: nothing of the old runtime remains${keptNote}`
326
+ : `re-checked: ${remaining.length} item${remaining.length === 1 ? "" : "s"} of the old runtime remain${remaining.length === 1 ? "s" : ""}${keptNote}: ${remaining.map((r) => `${r.kind} ${r.name}`).join(", ")}`);
327
+ emit({
328
+ sourceCommit: LEGACY_SOURCE_COMMIT,
329
+ found,
330
+ removed,
331
+ remaining: [...remaining, ...kept],
332
+ kept,
333
+ failed,
334
+ }, lines);
222
335
  return remaining.length === 0 ? 0 : 1;
223
336
  }
@@ -0,0 +1,177 @@
1
+ import { loadConfig, normalizeBaseUrl, readManifest, } from "./config.js";
2
+ import { contractVersionInRange } from "./contract.js";
3
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
4
+ ? value
5
+ : null;
6
+ const safePages = {
7
+ connections: "/a/account/connections",
8
+ personalConnections: "/settings/connected-accounts",
9
+ };
10
+ const routeKey = (route) => `${route.method} ${route.path}`;
11
+ const waiting = (reason, path) => ({
12
+ state: "waiting",
13
+ reason,
14
+ ...(path ? { evidence: { path } } : {}),
15
+ });
16
+ /** Fresh contract advertisement proves route availability, never consent or resource readiness.
17
+ * No cache, token refresh or local write may create a stale positive capability. */
18
+ async function read(ctx, journal, timeoutMs, external) {
19
+ if (external?.aborted)
20
+ return { reason: "interrupted" };
21
+ const cfg = loadConfig(ctx.home);
22
+ if (!cfg?.user)
23
+ return { reason: "personal_login_required" };
24
+ const personId = cfg.user.id;
25
+ if ((journal.account ?? journal.tenant) !== cfg.account ||
26
+ journal.membershipId !== cfg.user.id ||
27
+ !journal.baseUrl ||
28
+ normalizeBaseUrl(journal.baseUrl) !== normalizeBaseUrl(cfg.baseUrl))
29
+ return { reason: "onboarding_capability_identity_unverified" };
30
+ let origin;
31
+ try {
32
+ const url = new URL(cfg.baseUrl);
33
+ if (url.protocol !== "https:" ||
34
+ url.username ||
35
+ url.password ||
36
+ url.search ||
37
+ url.hash ||
38
+ url.pathname !== "/")
39
+ throw new Error();
40
+ origin = url.origin;
41
+ }
42
+ catch {
43
+ return { reason: "onboarding_capability_identity_unverified" };
44
+ }
45
+ const expiry = cfg.auth
46
+ ? Date.parse(cfg.auth.expiresAt) - ctx.now().getTime()
47
+ : 0;
48
+ const bearer = cfg.key ||
49
+ (cfg.auth && Number.isFinite(expiry) && expiry > 30_000
50
+ ? cfg.auth.accessToken
51
+ : undefined);
52
+ if (!bearer)
53
+ return { reason: "onboarding_capability_login_refresh_required", origin };
54
+ const owned = new AbortController();
55
+ const signal = external
56
+ ? AbortSignal.any([external, owned.signal])
57
+ : owned.signal;
58
+ const timer = setTimeout(() => owned.abort(), timeoutMs);
59
+ let remove = () => { };
60
+ try {
61
+ return await new Promise((resolve) => {
62
+ const stopped = () => resolve({
63
+ reason: external?.aborted
64
+ ? "interrupted"
65
+ : "onboarding_capability_unavailable",
66
+ origin,
67
+ });
68
+ if (signal.aborted) {
69
+ stopped();
70
+ return;
71
+ }
72
+ signal.addEventListener("abort", stopped, { once: true });
73
+ remove = () => signal.removeEventListener("abort", stopped);
74
+ Promise.resolve()
75
+ .then(async () => {
76
+ if (signal.aborted)
77
+ return { reason: "interrupted", origin };
78
+ const response = await ctx.fetch(`${origin}/api/v1/agent/contract`, {
79
+ method: "GET",
80
+ redirect: "error",
81
+ signal,
82
+ headers: {
83
+ authorization: `Bearer ${bearer}`,
84
+ accept: "application/json",
85
+ "cache-control": "no-cache",
86
+ },
87
+ });
88
+ if (response.status !== 200)
89
+ return { reason: "onboarding_capability_unavailable", origin };
90
+ const body = object(await response.json());
91
+ const current = loadConfig(ctx.home);
92
+ if (!current?.user ||
93
+ current.account !== cfg.account ||
94
+ current.user.id !== personId ||
95
+ normalizeBaseUrl(current.baseUrl) !== origin ||
96
+ object(body?.account)?.id !== cfg.account)
97
+ return {
98
+ reason: "onboarding_capability_identity_unverified",
99
+ origin,
100
+ };
101
+ if (!body ||
102
+ typeof body.contractVersion !== "string" ||
103
+ contractVersionInRange(body.contractVersion, readManifest().tenantContractRange) !== true)
104
+ return { reason: "onboarding_capability_unavailable", origin };
105
+ const advertised = object(body.onboarding), web = object(advertised?.web);
106
+ if (!advertised)
107
+ return { reason: "cloud_capability_unavailable", origin };
108
+ if (advertised.schema !== 1 ||
109
+ !Array.isArray(advertised.routes) ||
110
+ advertised.routes.length > 100 ||
111
+ !web ||
112
+ web.connections !== safePages.connections ||
113
+ web.personalConnections !== safePages.personalConnections)
114
+ return { reason: "onboarding_capability_unavailable", origin };
115
+ const routes = new Set();
116
+ for (const value of advertised.routes) {
117
+ const row = object(value);
118
+ if (!row ||
119
+ !["GET", "POST"].includes(row.method) ||
120
+ typeof row.path !== "string" ||
121
+ row.path.length > 240 ||
122
+ !/^\/(?:api\/v1\/|connect\/|me\/)[A-Za-z0-9_/-]+$/.test(row.path) ||
123
+ row.personalBearer !== true)
124
+ return { reason: "onboarding_capability_unavailable", origin };
125
+ const key = `${row.method} ${row.path}`;
126
+ if (routes.has(key))
127
+ return { reason: "onboarding_capability_unavailable", origin };
128
+ routes.add(key);
129
+ }
130
+ return { capabilities: { routes, web: { ...safePages } }, origin };
131
+ })
132
+ .then((result) => (signal.aborted ? stopped() : resolve(result)), () => signal.aborted
133
+ ? stopped()
134
+ : resolve({
135
+ reason: "onboarding_capability_unavailable",
136
+ origin,
137
+ }));
138
+ });
139
+ }
140
+ finally {
141
+ clearTimeout(timer);
142
+ remove();
143
+ }
144
+ }
145
+ /** Guard both the observation and action before their first endpoint request. A route's real
146
+ * refusal is preserved only after the same-account cloud advertised personal bearer support. */
147
+ export function guardOnboardCapabilities(adapter, options) {
148
+ const timeoutMs = options.requestTimeoutMs ?? 30_000;
149
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30_000)
150
+ throw new Error("onboarding_capability_timeout_invalid");
151
+ const run = async (ctx, journal, signal, requirements, work) => {
152
+ const advertised = await read(ctx, journal, timeoutMs, signal);
153
+ if ("reason" in advertised ||
154
+ requirements.some((route) => !advertised.capabilities.routes.has(routeKey(route)))) {
155
+ const reason = "reason" in advertised
156
+ ? advertised.reason
157
+ : "cloud_capability_unavailable";
158
+ const url = advertised.origin
159
+ ? `${advertised.origin}${safePages[options.fallback]}`
160
+ : undefined;
161
+ if (reason === "cloud_capability_unavailable" && url)
162
+ options.message?.(`This setup step is not available on this server yet. Continue in the web app: ${url}`);
163
+ return waiting(reason, reason === "cloud_capability_unavailable" ? url : undefined);
164
+ }
165
+ if (signal?.aborted)
166
+ return waiting("interrupted");
167
+ return work();
168
+ };
169
+ return {
170
+ check: (ctx, journal, signal) => run(ctx, journal, signal, options.check, () => adapter.check(ctx, journal, signal)),
171
+ ...(adapter.act
172
+ ? {
173
+ act: (ctx, journal, signal) => run(ctx, journal, signal, options.act ?? options.check, () => adapter.act(ctx, journal, signal)),
174
+ }
175
+ : {}),
176
+ };
177
+ }
@@ -9,7 +9,9 @@ function bounded(work, signal) {
9
9
  return;
10
10
  }
11
11
  signal.addEventListener("abort", abort, { once: true });
12
- work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
12
+ work
13
+ .then(resolve, reject)
14
+ .finally(() => signal.removeEventListener("abort", abort));
13
15
  });
14
16
  }
15
17
  function safeReason(reason, fallback) {
@@ -19,17 +21,27 @@ function safeReason(reason, fallback) {
19
21
  export async function pollConsent(options) {
20
22
  const timeoutMs = options.timeoutMs ?? 600_000;
21
23
  const intervalMs = options.intervalMs ?? 2_000;
22
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 600_000 ||
23
- !Number.isSafeInteger(intervalMs) || intervalMs <= 0)
24
+ if (!Number.isSafeInteger(timeoutMs) ||
25
+ timeoutMs <= 0 ||
26
+ timeoutMs > 600_000 ||
27
+ !Number.isSafeInteger(intervalMs) ||
28
+ intervalMs <= 0)
24
29
  throw new UsageError("consent timeout must be 1 to 600000 milliseconds, with a positive poll interval");
25
30
  const now = options.now ?? (() => performance.now());
26
31
  const started = now();
27
32
  const deadline = new AbortController();
28
33
  const timer = setTimeout(() => deadline.abort(), timeoutMs);
29
- const signal = options.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signal;
34
+ const signal = options.signal
35
+ ? AbortSignal.any([options.signal, deadline.signal])
36
+ : deadline.signal;
30
37
  const elapsedMs = () => Math.max(0, Math.round(now() - started));
31
- const waiting = () => ({ state: "waiting", reason: options.signal?.aborted ? "interrupted" : "consent_timeout", elapsedMs: elapsedMs() });
32
- const sleep = options.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
38
+ const waiting = () => ({
39
+ state: "waiting",
40
+ reason: options.signal?.aborted ? "interrupted" : "consent_timeout",
41
+ elapsedMs: elapsedMs(),
42
+ });
43
+ const sleep = options.sleep ??
44
+ ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
33
45
  try {
34
46
  while (!signal.aborted && elapsedMs() < timeoutMs) {
35
47
  let status;
@@ -39,16 +51,31 @@ export async function pollConsent(options) {
39
51
  catch (error) {
40
52
  if (signal.aborted)
41
53
  return waiting();
42
- if (error instanceof CliError && (error.status === 401 || error.status === 403))
43
- return { state: "refused", reason: "consent_identity_refused", elapsedMs: elapsedMs() };
44
- return { state: "failed", reason: "consent_status_failed", elapsedMs: elapsedMs() };
54
+ if (error instanceof CliError &&
55
+ (error.status === 401 || error.status === 403))
56
+ return {
57
+ state: "refused",
58
+ reason: "consent_identity_refused",
59
+ elapsedMs: elapsedMs(),
60
+ };
61
+ return {
62
+ state: "failed",
63
+ reason: "consent_status_failed",
64
+ elapsedMs: elapsedMs(),
65
+ };
45
66
  }
46
67
  if (elapsedMs() >= timeoutMs || signal.aborted)
47
68
  return waiting();
48
69
  if (status.outcome === "connected")
49
70
  return { state: "done", elapsedMs: elapsedMs() };
50
- if (status.outcome === "refused" || status.outcome === "failed")
51
- return { state: status.outcome, reason: safeReason(status.reason, `consent_${status.outcome}`), elapsedMs: elapsedMs() };
71
+ if (status.outcome === "waiting" ||
72
+ status.outcome === "refused" ||
73
+ status.outcome === "failed")
74
+ return {
75
+ state: status.outcome,
76
+ reason: safeReason(status.reason, `consent_${status.outcome}`),
77
+ elapsedMs: elapsedMs(),
78
+ };
52
79
  const remaining = timeoutMs - elapsedMs();
53
80
  try {
54
81
  await bounded(sleep(Math.min(intervalMs, remaining)), signal);