@ant0/cli 0.0.0-stage → 0.3.22-beta.8

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 (67) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +97 -2
  3. package/dist/api/generated/schema.d.ts +11615 -0
  4. package/dist/api/generated/schema.js +6 -0
  5. package/dist/api/index.d.ts +219 -0
  6. package/dist/api/index.js +342 -0
  7. package/dist/bin.d.ts +3 -0
  8. package/dist/bin.js +12 -0
  9. package/dist/bulk.d.ts +38 -0
  10. package/dist/bulk.js +66 -0
  11. package/dist/commands/account.d.ts +48 -0
  12. package/dist/commands/account.js +337 -0
  13. package/dist/commands/api-keys.d.ts +5 -0
  14. package/dist/commands/api-keys.js +310 -0
  15. package/dist/commands/browsers.d.ts +4 -0
  16. package/dist/commands/browsers.js +165 -0
  17. package/dist/commands/daemon.d.ts +15 -0
  18. package/dist/commands/daemon.js +202 -0
  19. package/dist/commands/events.d.ts +8 -0
  20. package/dist/commands/events.js +81 -0
  21. package/dist/commands/extensions.d.ts +4 -0
  22. package/dist/commands/extensions.js +74 -0
  23. package/dist/commands/profiles.d.ts +36 -0
  24. package/dist/commands/profiles.js +552 -0
  25. package/dist/commands/proxies.d.ts +23 -0
  26. package/dist/commands/proxies.js +170 -0
  27. package/dist/commands/sync.d.ts +4 -0
  28. package/dist/commands/sync.js +435 -0
  29. package/dist/commands/team.d.ts +7 -0
  30. package/dist/commands/team.js +403 -0
  31. package/dist/commands/trash.d.ts +10 -0
  32. package/dist/commands/trash.js +54 -0
  33. package/dist/commands/workspace.d.ts +10 -0
  34. package/dist/commands/workspace.js +56 -0
  35. package/dist/context.d.ts +111 -0
  36. package/dist/context.js +300 -0
  37. package/dist/errors.d.ts +27 -0
  38. package/dist/errors.js +96 -0
  39. package/dist/format.d.ts +23 -0
  40. package/dist/format.js +85 -0
  41. package/dist/index.d.ts +19 -0
  42. package/dist/index.js +35 -0
  43. package/dist/inventory.d.ts +50 -0
  44. package/dist/inventory.js +202 -0
  45. package/dist/management-transport.d.ts +3 -0
  46. package/dist/management-transport.js +90 -0
  47. package/dist/native-terminal.d.ts +50 -0
  48. package/dist/native-terminal.js +228 -0
  49. package/dist/program.d.ts +10 -0
  50. package/dist/program.js +217 -0
  51. package/dist/runtime-types.d.ts +20 -0
  52. package/dist/runtime-types.js +2 -0
  53. package/dist/set.d.ts +15 -0
  54. package/dist/set.js +87 -0
  55. package/dist/shared/parse-error.d.ts +6 -0
  56. package/dist/shared/parse-error.js +8 -0
  57. package/dist/shared/proxy-parse.d.ts +72 -0
  58. package/dist/shared/proxy-parse.js +294 -0
  59. package/dist/shared/proxy-types.d.ts +21 -0
  60. package/dist/shared/proxy-types.js +2 -0
  61. package/dist/shared/recovery-code.d.ts +7 -0
  62. package/dist/shared/recovery-code.js +53 -0
  63. package/dist/version.d.ts +8 -0
  64. package/dist/version.js +18 -0
  65. package/licenses/README.md +5 -0
  66. package/licenses/THIRD_PARTY_NOTICES +96 -0
  67. package/package.json +63 -4
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Per-invocation state shared by every command: the streams, the environment, the global flags
3
+ * (`--home`, `--port`, `--json`) and a lazily created API client.
4
+ */
5
+ import { checkDiscoveredToken, createAnt0Client, discoverDaemon, unwrap, } from "./api/index.js";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { execFile } from "node:child_process";
8
+ import { promisify } from "node:util";
9
+ import { join } from "node:path";
10
+ import { DaemonNotRunningError, UsageError } from "./errors.js";
11
+ import { toJson } from "./format.js";
12
+ import { openNativeTerminal } from "./native-terminal.js";
13
+ import { daemonClient, discoverConnection } from "@ant0/mcp";
14
+ import { apiKeyId, fileGrant, grantFromStatus, rejectCredentialEcho, } from "@ant0/mcp/credentials";
15
+ export class Context {
16
+ io;
17
+ runtime;
18
+ globalsFn = () => ({});
19
+ cached;
20
+ cachedKey = "";
21
+ delegated;
22
+ secret;
23
+ grant;
24
+ credential;
25
+ apiKey;
26
+ constructor(io, runtime) {
27
+ this.io = io;
28
+ this.runtime = runtime;
29
+ }
30
+ /** Installed by the program builder once the root command exists. */
31
+ bindGlobals(fn) {
32
+ this.globalsFn = fn;
33
+ }
34
+ get globals() {
35
+ return this.globalsFn();
36
+ }
37
+ get json() {
38
+ return this.globals.json === true;
39
+ }
40
+ /** Where the daemon should be, according to flags, pid file and environment. */
41
+ connection() {
42
+ const g = this.globals;
43
+ return discoverDaemon({
44
+ env: this.io.env,
45
+ ...(g.home !== undefined ? { home: g.home } : {}),
46
+ ...(g.port !== undefined ? { port: g.port } : {}),
47
+ });
48
+ }
49
+ /**
50
+ * `connection()` for a command that sends the token: a token file that is not private is
51
+ * refused here (or warned about with ANT0_ALLOW_SHARED_TOKEN_FILE=1), not during discovery, so
52
+ * daemon start/stop/status and health checks keep working.
53
+ */
54
+ authenticatedConnection() {
55
+ const conn = this.connection();
56
+ checkDiscoveredToken(conn, {
57
+ env: this.io.env,
58
+ warn: (message) => this.io.stderr.write(message),
59
+ });
60
+ return conn;
61
+ }
62
+ keyMode() {
63
+ const g = this.globals;
64
+ return (g.credentialFile !== undefined ||
65
+ g.apiKeyStdin === true ||
66
+ this.io.env.ANT0_API_KEY !== undefined);
67
+ }
68
+ /** Authenticated client; throws `DaemonNotRunningError` when there is no token to send. */
69
+ client() {
70
+ if (!this.keyMode())
71
+ return this.managementClient();
72
+ if (!this.delegated) {
73
+ const g = this.globals;
74
+ if (g.credentialFile === undefined) {
75
+ const key = g.apiKeyStdin ? this.apiKey : this.io.env.ANT0_API_KEY;
76
+ if (key === undefined || apiKeyId(key) === undefined)
77
+ throw new UsageError(g.apiKeyStdin
78
+ ? "stdin does not hold a valid Ant0 API key"
79
+ : "ANT0_API_KEY is not a valid Ant0 API key");
80
+ }
81
+ const connection = discoverConnection({
82
+ ...(g.credentialFile !== undefined ? { credentialFile: g.credentialFile } : {}),
83
+ ...(g.apiKeyStdin && this.apiKey !== undefined ? { apiKey: this.apiKey } : {}),
84
+ env: this.io.env,
85
+ ...(g.home !== undefined ? { home: g.home } : {}),
86
+ ...(g.port !== undefined ? { port: g.port } : {}),
87
+ });
88
+ this.credential = connection.credential?.value;
89
+ this.secret = connection.token;
90
+ // The adapter types its client from its own, smaller API description; at runtime both are
91
+ // the same openapi-fetch client.
92
+ this.delegated = daemonClient(connection, this.io.signal ?? new AbortController().signal, "api");
93
+ }
94
+ return this.delegated;
95
+ }
96
+ /** Scopes come from the private file, or from the key's own status in env/stdin mode. */
97
+ async keyGrant() {
98
+ if (!this.keyMode())
99
+ return undefined;
100
+ if (this.grant)
101
+ return this.grant;
102
+ const client = this.client();
103
+ if (this.credential) {
104
+ this.grant = fileGrant(this.credential);
105
+ return this.grant;
106
+ }
107
+ const status = unwrap(await client.GET("/v1/automation/status"));
108
+ this.grant = grantFromStatus(status, this.secret, "api").grant;
109
+ return this.grant;
110
+ }
111
+ /** Provisioning's credential-file is an output/recovery record, never its authentication. */
112
+ managementClient() {
113
+ const conn = this.authenticatedConnection();
114
+ if (conn.token === undefined)
115
+ throw new DaemonNotRunningError();
116
+ return this.clientFor(conn.baseUrl, conn.token);
117
+ }
118
+ /** Unauthenticated client (health checks). */
119
+ openClient() {
120
+ if (this.globals.credentialFile !== undefined)
121
+ throw new UsageError("credential file is not supported for this command");
122
+ return this.clientFor(this.connection().baseUrl, undefined);
123
+ }
124
+ clientFor(baseUrl, token) {
125
+ const key = `${baseUrl}\n${token ?? ""}`;
126
+ if (this.cached && this.cachedKey === key)
127
+ return this.cached;
128
+ this.cached = createAnt0Client({
129
+ baseUrl,
130
+ ...(token !== undefined ? { token } : { anonymous: true }),
131
+ ...(this.io.fetch ? { fetch: this.io.fetch } : {}),
132
+ });
133
+ this.cachedKey = key;
134
+ return this.cached;
135
+ }
136
+ async openBrowser(url) {
137
+ if (!/^https:\/\/ant0\.link\/account\/authorize#code=[A-HJ-NP-Z2-9]{5}-[A-HJ-NP-Z2-9]{5}$/.test(url))
138
+ throw new UsageError("invalid browser authorization URL");
139
+ if (this.io.openBrowser)
140
+ return this.io.openBrowser(url);
141
+ const executable = process.platform === "win32"
142
+ ? join(process.env.SystemRoot ?? "C:\\Windows", "System32", "rundll32.exe")
143
+ : "xdg-open";
144
+ const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
145
+ try {
146
+ await promisify(execFile)(executable, args, { timeout: 10000, windowsHide: true });
147
+ }
148
+ catch {
149
+ throw new UsageError("could not open the browser; start a new login with --device-code");
150
+ }
151
+ }
152
+ async wait(milliseconds) {
153
+ if (this.io.wait)
154
+ return this.io.wait(milliseconds, this.io.signal);
155
+ const { setTimeout } = await import("node:timers/promises");
156
+ await setTimeout(milliseconds, undefined, { signal: this.io.signal });
157
+ }
158
+ fetch() {
159
+ return this.io.fetch ?? globalThis.fetch;
160
+ }
161
+ out(text) {
162
+ this.io.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
163
+ }
164
+ err(text) {
165
+ this.io.stderr.write(text.endsWith("\n") ? text : `${text}\n`);
166
+ }
167
+ /**
168
+ * Gate an irreversible action. `--yes` skips the question; on a terminal the user is asked on
169
+ * stderr; without a terminal the command refuses (exit 2) so scripts never hang or destroy data
170
+ * by accident.
171
+ */
172
+ /** `refusal` replaces the generic "pass --yes" message when there is no terminal to ask on. */
173
+ async confirm(question, yes, refusal) {
174
+ if (yes)
175
+ return;
176
+ const stdin = this.stdin;
177
+ if (!stdin.isTTY) {
178
+ throw new UsageError(refusal ?? `${question} — pass --yes to confirm (stdin is not a terminal)`);
179
+ }
180
+ const rl = createInterface({ input: stdin, output: process.stderr });
181
+ try {
182
+ const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
183
+ if (answer !== "y" && answer !== "yes")
184
+ throw new UsageError("aborted");
185
+ }
186
+ finally {
187
+ rl.close();
188
+ }
189
+ }
190
+ get stdin() {
191
+ return this.io.stdin ?? process.stdin;
192
+ }
193
+ /** Whether prompts are possible (stdin is a terminal). */
194
+ interactive() {
195
+ return this.stdin.isTTY === true;
196
+ }
197
+ /** Ask one line on the terminal (echoed); refuses without one (exit 2). */
198
+ async prompt(question) {
199
+ if (!this.interactive()) {
200
+ throw new UsageError(`${question.trim()} — stdin is not a terminal; pass it as an argument`);
201
+ }
202
+ const rl = createInterface({ input: this.stdin, output: process.stderr });
203
+ try {
204
+ return (await rl.question(question)).trim();
205
+ }
206
+ finally {
207
+ rl.close();
208
+ }
209
+ }
210
+ /**
211
+ * Ask a secret on the terminal without echo (raw mode, Backspace edits, Ctrl-C aborts with exit
212
+ * 2). Without a terminal the command must take `--password-stdin` instead.
213
+ */
214
+ async promptSecret(question) {
215
+ return this.readSecret(question, `${question.trim()} — stdin is not a terminal; pipe the password with --password-stdin`);
216
+ }
217
+ /** Run a native-secret operation on the controlling terminal, never stdin/stdout/stderr. */
218
+ async withNativeTerminal(operation, action) {
219
+ let terminal = this.io.nativeTerminal ?? undefined;
220
+ const owned = this.io.nativeTerminal === undefined;
221
+ if (this.io.nativeTerminal === null) {
222
+ throw new UsageError(`${operation} requires the desktop app or a controlling terminal`);
223
+ }
224
+ if (!terminal) {
225
+ try {
226
+ terminal = openNativeTerminal();
227
+ }
228
+ catch {
229
+ throw new UsageError(`${operation} requires the desktop app or a controlling terminal. Run this in a terminal window, or use the app.`);
230
+ }
231
+ }
232
+ try {
233
+ return await action(terminal);
234
+ }
235
+ finally {
236
+ if (owned)
237
+ terminal.close();
238
+ }
239
+ }
240
+ async readSecret(question, unavailable) {
241
+ const stdin = this.stdin;
242
+ if (!this.interactive() || typeof stdin.setRawMode !== "function") {
243
+ throw new UsageError(unavailable);
244
+ }
245
+ const setRaw = stdin.setRawMode.bind(stdin);
246
+ this.io.stderr.write(question);
247
+ const wasRaw = stdin.isRaw === true;
248
+ setRaw(true);
249
+ stdin.resume();
250
+ return new Promise((resolve, reject) => {
251
+ let value = "";
252
+ const finish = (done) => {
253
+ stdin.off("data", onData);
254
+ setRaw(wasRaw);
255
+ stdin.pause();
256
+ this.io.stderr.write("\n");
257
+ done();
258
+ };
259
+ const onData = (chunk) => {
260
+ for (const ch of chunk.toString("utf8")) {
261
+ if (ch === "\r" || ch === "\n")
262
+ return finish(() => resolve(value));
263
+ if (ch === "\u0003" || ch === "\u0004") {
264
+ return finish(() => reject(new UsageError("aborted")));
265
+ }
266
+ if (ch === "\u007f" || ch === "\b")
267
+ value = value.slice(0, -1);
268
+ else if (ch >= " ")
269
+ value += ch;
270
+ }
271
+ };
272
+ stdin.on("data", onData);
273
+ });
274
+ }
275
+ /** The first line of stdin (`--password-stdin`): everything up to the first newline or EOF. */
276
+ async readStdinLine() {
277
+ let text = "";
278
+ for await (const chunk of this.stdin) {
279
+ text += typeof chunk === "string" ? chunk : chunk.toString("utf8");
280
+ const nl = text.indexOf("\n");
281
+ if (nl !== -1)
282
+ return text.slice(0, nl).replace(/\r$/, "");
283
+ }
284
+ return text.replace(/\r?\n?$/, "");
285
+ }
286
+ /** `--json`: the payload verbatim (nothing for a 204); otherwise the human rendering. */
287
+ emit(payload, human) {
288
+ if (this.secret !== undefined)
289
+ rejectCredentialEcho(payload, this.secret);
290
+ if (this.json) {
291
+ if (payload !== undefined)
292
+ this.out(toJson(payload));
293
+ return;
294
+ }
295
+ const text = human();
296
+ if (text !== undefined && text.length > 0)
297
+ this.out(text);
298
+ }
299
+ }
300
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1,27 @@
1
+ export declare const EXIT_OK = 0;
2
+ export declare const EXIT_ERROR = 1;
3
+ export declare const EXIT_USAGE = 2;
4
+ export declare const EXIT_NOT_RUNNING = 3;
5
+ export declare const EXIT_APP_MANAGED = 4;
6
+ export declare class CliError extends Error {
7
+ readonly exitCode: number;
8
+ constructor(message: string, exitCode?: number);
9
+ }
10
+ export declare class UsageError extends CliError {
11
+ constructor(message: string);
12
+ }
13
+ /** A host with its own lifecycle commands names its start command in the "not running" hint. */
14
+ export declare function setStartCommand(command: string): void;
15
+ export declare function notRunningMessage(): string;
16
+ export declare class DaemonNotRunningError extends CliError {
17
+ constructor(message?: string);
18
+ }
19
+ /** `fetch` rejected because nothing listens on the daemon port (Node wraps it in `cause`). */
20
+ export declare function isConnectionRefused(err: unknown): boolean;
21
+ export interface DescribedError {
22
+ /** Lines for stderr, without the `ant0: ` prefix on the first one. Empty = print nothing. */
23
+ lines: string[];
24
+ exitCode: number;
25
+ }
26
+ export declare function describeError(err: unknown): DescribedError;
27
+ //# sourceMappingURL=errors.d.ts.map
package/dist/errors.js ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Exit codes: 0 ok, 1 error, 2 usage, 3 daemon not running,
3
+ * 4 the Ant0 app manages the background service.
4
+ * Every failure funnels through `describeError`, which maps a thrown value onto a message for
5
+ * stderr and one of those codes.
6
+ */
7
+ import { CommanderError } from "commander";
8
+ import { isAnt0ApiError } from "./api/index.js";
9
+ export const EXIT_OK = 0;
10
+ export const EXIT_ERROR = 1;
11
+ export const EXIT_USAGE = 2;
12
+ export const EXIT_NOT_RUNNING = 3;
13
+ export const EXIT_APP_MANAGED = 4;
14
+ export class CliError extends Error {
15
+ exitCode;
16
+ constructor(message, exitCode = EXIT_ERROR) {
17
+ super(message);
18
+ this.exitCode = exitCode;
19
+ this.name = new.target.name;
20
+ }
21
+ }
22
+ export class UsageError extends CliError {
23
+ constructor(message) {
24
+ super(message, EXIT_USAGE);
25
+ }
26
+ }
27
+ let startCommand = "ant0 daemon start";
28
+ /** A host with its own lifecycle commands names its start command in the "not running" hint. */
29
+ export function setStartCommand(command) {
30
+ startCommand = command;
31
+ }
32
+ export function notRunningMessage() {
33
+ return `daemon not running (start it with \`${startCommand}\`)`;
34
+ }
35
+ export class DaemonNotRunningError extends CliError {
36
+ constructor(message = notRunningMessage()) {
37
+ super(message, EXIT_NOT_RUNNING);
38
+ }
39
+ }
40
+ /** `fetch` rejected because nothing listens on the daemon port (Node wraps it in `cause`). */
41
+ export function isConnectionRefused(err) {
42
+ const seen = new Set();
43
+ const visit = (value) => {
44
+ if (value === null || typeof value !== "object" || seen.has(value))
45
+ return false;
46
+ seen.add(value);
47
+ const e = value;
48
+ if (e.code === "ECONNREFUSED")
49
+ return true;
50
+ if (Array.isArray(e.errors) && e.errors.some((inner) => visit(inner)))
51
+ return true;
52
+ return visit(e.cause);
53
+ };
54
+ return visit(err);
55
+ }
56
+ /** Render Ajv issues (`details` of a 400) as one indented line each. */
57
+ function detailLines(details) {
58
+ if (!Array.isArray(details)) {
59
+ return details === undefined ? [] : [` ${JSON.stringify(details)}`];
60
+ }
61
+ return details.map((issue) => {
62
+ if (issue === null || typeof issue !== "object")
63
+ return ` ${String(issue)}`;
64
+ const d = issue;
65
+ const where = typeof d.instancePath === "string" && d.instancePath.length > 0
66
+ ? d.instancePath.replace(/^\//, "").replaceAll("/", ".")
67
+ : typeof d.path === "string" && d.path.length > 0
68
+ ? d.path
69
+ : "(body)";
70
+ const message = typeof d.message === "string" ? d.message : JSON.stringify(issue);
71
+ return ` ${where}: ${message}`;
72
+ });
73
+ }
74
+ export function describeError(err) {
75
+ if (err instanceof CommanderError) {
76
+ // Commander already wrote its message (help, version, or the usage error).
77
+ const informational = err.code === "commander.helpDisplayed" ||
78
+ err.code === "commander.version" ||
79
+ err.exitCode === 0;
80
+ return { lines: [], exitCode: informational ? EXIT_OK : EXIT_USAGE };
81
+ }
82
+ if (err instanceof CliError)
83
+ return { lines: [err.message], exitCode: err.exitCode };
84
+ if (isAnt0ApiError(err)) {
85
+ const lines = [`${err.code}: ${err.message}`];
86
+ if (err.status === 400)
87
+ lines.push(...detailLines(err.details));
88
+ return { lines, exitCode: EXIT_ERROR };
89
+ }
90
+ if (isConnectionRefused(err))
91
+ return { lines: [notRunningMessage()], exitCode: EXIT_NOT_RUNNING };
92
+ if (err instanceof Error)
93
+ return { lines: [err.message], exitCode: EXIT_ERROR };
94
+ return { lines: [String(err)], exitCode: EXIT_ERROR };
95
+ }
96
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Human output helpers: aligned columns, key/value listings and a generic flattener for API
3
+ * documents. No colors, no terminal tricks; output is stable enough to grep.
4
+ */
5
+ export type Cell = string | number | boolean | null | undefined;
6
+ /** Render one cell: `-` for null/undefined, `true`/`false` for booleans. */
7
+ export declare function cell(value: Cell): string;
8
+ /**
9
+ * Aligned columns separated by two spaces, header in upper case, no trailing whitespace.
10
+ * With no rows only the header line is printed.
11
+ */
12
+ export declare function table(headers: string[], rows: Cell[][]): string;
13
+ /** `key value` lines with keys padded to the longest key. */
14
+ export declare function keyValues(pairs: [string, Cell][]): string;
15
+ /**
16
+ * Flatten a JSON document into dotted-path/value pairs for `show`-style commands. Arrays of
17
+ * scalars become comma-separated lists; other arrays and empty containers are shown as JSON.
18
+ */
19
+ export declare function flatten(value: unknown, prefix?: string): [string, Cell][];
20
+ export declare function formatBytes(n: number | null | undefined): string;
21
+ export declare function formatDuration(seconds: number): string;
22
+ export declare function toJson(value: unknown): string;
23
+ //# sourceMappingURL=format.d.ts.map
package/dist/format.js ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Human output helpers: aligned columns, key/value listings and a generic flattener for API
3
+ * documents. No colors, no terminal tricks; output is stable enough to grep.
4
+ */
5
+ /** Render one cell: `-` for null/undefined, `true`/`false` for booleans. */
6
+ export function cell(value) {
7
+ if (value === null || value === undefined)
8
+ return "-";
9
+ if (typeof value === "string")
10
+ return value.length === 0 ? '""' : value;
11
+ return String(value);
12
+ }
13
+ /**
14
+ * Aligned columns separated by two spaces, header in upper case, no trailing whitespace.
15
+ * With no rows only the header line is printed.
16
+ */
17
+ export function table(headers, rows) {
18
+ const text = [headers.map((h) => h.toUpperCase()), ...rows.map((r) => r.map(cell))];
19
+ const widths = headers.map((_, i) => Math.max(...text.map((row) => (row[i] ?? "").length)));
20
+ return text
21
+ .map((row) => row
22
+ .map((v, i) => (i === row.length - 1 ? v : v.padEnd(widths[i] ?? 0)))
23
+ .join(" ")
24
+ .trimEnd())
25
+ .join("\n");
26
+ }
27
+ /** `key value` lines with keys padded to the longest key. */
28
+ export function keyValues(pairs) {
29
+ const width = Math.max(0, ...pairs.map(([k]) => k.length));
30
+ return pairs.map(([k, v]) => `${k.padEnd(width)} ${cell(v)}`.trimEnd()).join("\n");
31
+ }
32
+ /**
33
+ * Flatten a JSON document into dotted-path/value pairs for `show`-style commands. Arrays of
34
+ * scalars become comma-separated lists; other arrays and empty containers are shown as JSON.
35
+ */
36
+ export function flatten(value, prefix = "") {
37
+ if (value === null || typeof value !== "object") {
38
+ return [[prefix || "value", value]];
39
+ }
40
+ if (Array.isArray(value)) {
41
+ if (value.every((v) => v === null || typeof v !== "object")) {
42
+ return [[prefix, value.length === 0 ? "[]" : value.map((v) => cell(v)).join(", ")]];
43
+ }
44
+ return [[prefix, JSON.stringify(value)]];
45
+ }
46
+ const entries = Object.entries(value);
47
+ if (entries.length === 0)
48
+ return [[prefix, "{}"]];
49
+ const out = [];
50
+ for (const [k, v] of entries) {
51
+ const key = prefix ? `${prefix}.${k}` : k;
52
+ if (v !== null && typeof v === "object" && !Array.isArray(v))
53
+ out.push(...flatten(v, key));
54
+ else
55
+ out.push(...flatten(v, key));
56
+ }
57
+ return out;
58
+ }
59
+ export function formatBytes(n) {
60
+ if (n === null || n === undefined)
61
+ return "-";
62
+ const units = ["B", "KiB", "MiB", "GiB", "TiB"];
63
+ let value = n;
64
+ let unit = 0;
65
+ while (value >= 1024 && unit < units.length - 1) {
66
+ value /= 1024;
67
+ unit += 1;
68
+ }
69
+ return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`;
70
+ }
71
+ export function formatDuration(seconds) {
72
+ const s = Math.max(0, Math.floor(seconds));
73
+ const h = Math.floor(s / 3600);
74
+ const m = Math.floor((s % 3600) / 60);
75
+ const sec = s % 60;
76
+ if (h > 0)
77
+ return `${h}h ${m}m ${sec}s`;
78
+ if (m > 0)
79
+ return `${m}m ${sec}s`;
80
+ return `${sec}s`;
81
+ }
82
+ export function toJson(value) {
83
+ return JSON.stringify(value, null, 2) ?? "";
84
+ }
85
+ //# sourceMappingURL=format.js.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `@ant0/cli`: the `ant0` command. `run(argv, io)` executes one invocation in-process and returns
3
+ * the exit code; `bin.ts` is the executable wrapper around it.
4
+ */
5
+ import { type RunIo } from "./context.js";
6
+ import type { RuntimeCommands } from "./runtime-types.js";
7
+ export type { RunIo, Writer, GlobalOptions } from "./context.js";
8
+ export type { NativeTerminal } from "./native-terminal.js";
9
+ export { CliError, DaemonNotRunningError, UsageError, EXIT_OK, EXIT_ERROR, EXIT_USAGE, EXIT_NOT_RUNNING, describeError, } from "./errors.js";
10
+ export { table, keyValues, flatten } from "./format.js";
11
+ export { parseSetArgs, parseSetPair, parseSetValue } from "./set.js";
12
+ export { buildProgram, CLI_VERSION } from "./program.js";
13
+ /**
14
+ * Run `ant0 <argv...>` (user arguments only, no node/script prefix). Never throws and never calls
15
+ * `process.exit`; errors are written to `io.stderr` as `ant0: <message>` and mapped to the
16
+ * exit codes (0 ok, 1 error, 2 usage, 3 daemon not running).
17
+ */
18
+ export declare function run(argv: readonly string[], io: RunIo, runtime?: RuntimeCommands): Promise<number>;
19
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * `@ant0/cli`: the `ant0` command. `run(argv, io)` executes one invocation in-process and returns
3
+ * the exit code; `bin.ts` is the executable wrapper around it.
4
+ */
5
+ import { Context } from "./context.js";
6
+ import { describeError, EXIT_OK } from "./errors.js";
7
+ import { buildProgram } from "./program.js";
8
+ export { CliError, DaemonNotRunningError, UsageError, EXIT_OK, EXIT_ERROR, EXIT_USAGE, EXIT_NOT_RUNNING, describeError, } from "./errors.js";
9
+ export { table, keyValues, flatten } from "./format.js";
10
+ export { parseSetArgs, parseSetPair, parseSetValue } from "./set.js";
11
+ export { buildProgram, CLI_VERSION } from "./program.js";
12
+ /**
13
+ * Run `ant0 <argv...>` (user arguments only, no node/script prefix). Never throws and never calls
14
+ * `process.exit`; errors are written to `io.stderr` as `ant0: <message>` and mapped to the
15
+ * exit codes (0 ok, 1 error, 2 usage, 3 daemon not running).
16
+ */
17
+ export async function run(argv, io, runtime) {
18
+ const ctx = new Context(io, runtime);
19
+ const program = buildProgram(ctx);
20
+ try {
21
+ await program.parseAsync([...argv], { from: "user" });
22
+ return EXIT_OK;
23
+ }
24
+ catch (err) {
25
+ const { lines, exitCode } = describeError(err);
26
+ if (lines.length > 0) {
27
+ const [first, ...rest] = lines;
28
+ io.stderr.write(`ant0: ${first}\n`);
29
+ for (const line of rest)
30
+ io.stderr.write(`${line}\n`);
31
+ }
32
+ return exitCode;
33
+ }
34
+ }
35
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,50 @@
1
+ import { type components } from "./api/index.js";
2
+ type ProfileInventory = components["schemas"]["ProfileInventory"];
3
+ export declare function projectProfileInventory(value: unknown, readOnly?: boolean): ProfileInventory;
4
+ export declare function projectProfileList(value: unknown, limit?: number, offset?: number, running?: boolean, readOnly?: boolean): {
5
+ items: {
6
+ id: string;
7
+ name: string;
8
+ group: string | null;
9
+ local_folder_id: string | null;
10
+ tags: string[];
11
+ notes: string;
12
+ status: string | null;
13
+ pinned: boolean;
14
+ platform: "windows" | "linux" | "macos" | "android" | null;
15
+ proxy_id: string | null;
16
+ browser_version: string | null;
17
+ identity_mode: "synthetic" | "captured" | "native";
18
+ created_at: string;
19
+ updated_at: string;
20
+ last_launched_at: string | null;
21
+ deleted_at: string | null;
22
+ }[];
23
+ total: number;
24
+ };
25
+ export declare function projectProfileStatus(value: unknown, ref: string, readOnly?: boolean): {
26
+ state: "starting" | "running" | "stopping" | "stopped" | "crashed";
27
+ session: {
28
+ profile_id: string;
29
+ started_at: string;
30
+ browser_version: string | null;
31
+ headless: boolean | null;
32
+ } | null;
33
+ };
34
+ export declare function projectProxyList(value: unknown, limit: number, offset: number): {
35
+ items: {
36
+ id: string;
37
+ type: "http" | "https" | "socks5" | "socks4";
38
+ last_check: {
39
+ ok: boolean;
40
+ country: string | null;
41
+ latency_ms: number | null;
42
+ at: string;
43
+ } | null;
44
+ }[];
45
+ total: number;
46
+ };
47
+ /** Keep API error identity/status while rejecting raw upstream diagnostics on metadata reads. */
48
+ export declare function inventoryRead<T>(read: () => Promise<T>): Promise<T>;
49
+ export {};
50
+ //# sourceMappingURL=inventory.d.ts.map