maritime-cli 1.8.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +17 -0
  2. package/bin/maritime.js +40 -0
  3. package/install.js +118 -0
  4. package/package.json +22 -36
  5. package/AGENTS.md +0 -309
  6. package/dist/api.d.ts +0 -30
  7. package/dist/api.js +0 -240
  8. package/dist/commands/chat.d.ts +0 -2
  9. package/dist/commands/chat.js +0 -120
  10. package/dist/commands/create.d.ts +0 -2
  11. package/dist/commands/create.js +0 -310
  12. package/dist/commands/delete.d.ts +0 -2
  13. package/dist/commands/delete.js +0 -43
  14. package/dist/commands/deploy.d.ts +0 -2
  15. package/dist/commands/deploy.js +0 -180
  16. package/dist/commands/env.d.ts +0 -2
  17. package/dist/commands/env.js +0 -368
  18. package/dist/commands/exec.d.ts +0 -2
  19. package/dist/commands/exec.js +0 -31
  20. package/dist/commands/guide.d.ts +0 -2
  21. package/dist/commands/guide.js +0 -87
  22. package/dist/commands/history.d.ts +0 -2
  23. package/dist/commands/history.js +0 -56
  24. package/dist/commands/info.d.ts +0 -2
  25. package/dist/commands/info.js +0 -78
  26. package/dist/commands/init.d.ts +0 -2
  27. package/dist/commands/init.js +0 -114
  28. package/dist/commands/keys.d.ts +0 -2
  29. package/dist/commands/keys.js +0 -90
  30. package/dist/commands/link.d.ts +0 -4
  31. package/dist/commands/link.js +0 -65
  32. package/dist/commands/list.d.ts +0 -2
  33. package/dist/commands/list.js +0 -55
  34. package/dist/commands/login.d.ts +0 -2
  35. package/dist/commands/login.js +0 -209
  36. package/dist/commands/logout.d.ts +0 -2
  37. package/dist/commands/logout.js +0 -12
  38. package/dist/commands/logs.d.ts +0 -2
  39. package/dist/commands/logs.js +0 -89
  40. package/dist/commands/message.d.ts +0 -8
  41. package/dist/commands/message.js +0 -75
  42. package/dist/commands/open.d.ts +0 -2
  43. package/dist/commands/open.js +0 -25
  44. package/dist/commands/restart.d.ts +0 -2
  45. package/dist/commands/restart.js +0 -26
  46. package/dist/commands/signup.d.ts +0 -2
  47. package/dist/commands/signup.js +0 -45
  48. package/dist/commands/sleep.d.ts +0 -2
  49. package/dist/commands/sleep.js +0 -22
  50. package/dist/commands/start.d.ts +0 -2
  51. package/dist/commands/start.js +0 -27
  52. package/dist/commands/status.d.ts +0 -2
  53. package/dist/commands/status.js +0 -69
  54. package/dist/commands/stop.d.ts +0 -2
  55. package/dist/commands/stop.js +0 -26
  56. package/dist/commands/templates.d.ts +0 -2
  57. package/dist/commands/templates.js +0 -40
  58. package/dist/commands/triggers.d.ts +0 -2
  59. package/dist/commands/triggers.js +0 -89
  60. package/dist/commands/whoami.d.ts +0 -2
  61. package/dist/commands/whoami.js +0 -76
  62. package/dist/config.d.ts +0 -2
  63. package/dist/config.js +0 -14
  64. package/dist/context.d.ts +0 -39
  65. package/dist/context.js +0 -110
  66. package/dist/index.d.ts +0 -2
  67. package/dist/index.js +0 -186
  68. package/dist/interactive.d.ts +0 -1
  69. package/dist/interactive.js +0 -66
  70. package/dist/output.d.ts +0 -80
  71. package/dist/output.js +0 -176
  72. package/dist/prompt.d.ts +0 -2
  73. package/dist/prompt.js +0 -62
  74. package/dist/resolve.d.ts +0 -16
  75. package/dist/resolve.js +0 -59
  76. package/dist/version-check.d.ts +0 -20
  77. package/dist/version-check.js +0 -81
  78. package/dist/websocket.d.ts +0 -22
  79. package/dist/websocket.js +0 -89
@@ -1,66 +0,0 @@
1
- import { select } from '@inquirer/prompts';
2
- import chalk from 'chalk';
3
- import { authGet } from './api.js';
4
- const COMMANDS = [
5
- { name: 'list', value: 'list', description: 'List your agents', needsAgent: false },
6
- { name: 'create', value: 'create', description: 'Create a new agent', needsAgent: false },
7
- { name: 'status', value: 'status', description: 'Show agent status', needsAgent: true },
8
- { name: 'info', value: 'info', description: 'Show full agent details', needsAgent: true },
9
- { name: 'logs', value: 'logs', description: 'View agent logs', needsAgent: true },
10
- { name: 'deploy', value: 'deploy', description: 'Deploy an agent', needsAgent: true },
11
- { name: 'start', value: 'start', description: 'Start an agent', needsAgent: true },
12
- { name: 'stop', value: 'stop', description: 'Stop an agent', needsAgent: true },
13
- { name: 'sleep', value: 'sleep', description: 'Put agent to sleep', needsAgent: true },
14
- { name: 'restart', value: 'restart', description: 'Restart an agent', needsAgent: true },
15
- { name: 'env', value: 'env', description: 'Manage environment variables', needsAgent: false },
16
- { name: 'triggers', value: 'triggers', description: 'Manage triggers', needsAgent: false },
17
- { name: 'templates', value: 'templates', description: 'Browse templates', needsAgent: false },
18
- { name: 'history', value: 'history', description: 'View deploy history', needsAgent: true },
19
- { name: 'open', value: 'open', description: 'Open agent in browser', needsAgent: true },
20
- { name: 'whoami', value: 'whoami', description: 'Show current user', needsAgent: false },
21
- { name: 'logout', value: 'logout', description: 'Log out', needsAgent: false },
22
- ];
23
- export async function runInteractive() {
24
- console.log(chalk.hex('#8B5CF6')('\n Maritime') + chalk.dim(' · interactive mode\n'));
25
- const command = await select({
26
- message: 'What would you like to do?',
27
- choices: COMMANDS.map((c) => ({
28
- name: `${c.name.padEnd(12)} ${chalk.dim(c.description)}`,
29
- value: c.value,
30
- })),
31
- });
32
- const chosen = COMMANDS.find((c) => c.value === command);
33
- if (!chosen?.needsAgent) {
34
- return [command];
35
- }
36
- // For agent-targeting commands, show agent picker
37
- try {
38
- const agents = await authGet('/api/agents');
39
- if (agents.length === 0) {
40
- console.log(chalk.yellow('No agents found.') + ' Run `maritime create` first.');
41
- return [command];
42
- }
43
- const agentName = await select({
44
- message: 'Select an agent:',
45
- choices: agents.map((a) => ({
46
- name: `${a.name.padEnd(24)} ${statusBadge(a.status)}`,
47
- value: a.name,
48
- })),
49
- });
50
- return [command, agentName];
51
- }
52
- catch {
53
- // If auth fails, run command without agent (it will show auth error)
54
- return [command];
55
- }
56
- }
57
- function statusBadge(status) {
58
- switch (status) {
59
- case 'active': return chalk.green(status);
60
- case 'sleeping': return chalk.blue(status);
61
- case 'deploying': return chalk.yellow(status);
62
- case 'error': return chalk.red(status);
63
- case 'stopped': return chalk.gray(status);
64
- default: return status;
65
- }
66
- }
package/dist/output.d.ts DELETED
@@ -1,80 +0,0 @@
1
- /**
2
- * Output + error helpers.
3
- *
4
- * Two audiences share this CLI: humans at a terminal, and programs/AI agents
5
- * that shell out and parse stdout. The `--json` flag switches to a strict
6
- * machine contract:
7
- *
8
- * - success → a single JSON object on STDOUT, nothing else
9
- * - failure → a single JSON object on STDERR, nothing else
10
- * - spinners, colors, and the update notice are suppressed
11
- * - exit code reflects the outcome (see EXIT)
12
- *
13
- * In human mode, errors go to STDERR (not stdout) so that even without --json,
14
- * stdout stays clean enough to pipe.
15
- */
16
- /** Stable exit codes so callers can branch on outcome without parsing text. */
17
- export declare const EXIT: {
18
- readonly OK: 0;
19
- readonly ERROR: 1;
20
- readonly AUTH: 2;
21
- readonly NOT_FOUND: 3;
22
- readonly USAGE: 4;
23
- };
24
- /**
25
- * Thrown instead of calling process.exit(). The entrypoint catches it, sets
26
- * process.exitCode, and lets the event loop drain naturally.
27
- *
28
- * Why: hard process.exit() while libuv handles are still live (undici
29
- * keep-alive sockets, an in-flight fetch, raw-mode stdin) races handle
30
- * teardown on Windows and dies with
31
- * "Assertion failed: !(handle->flags & UV_HANDLE_CLOSING), src\\win\\async.c"
32
- * (nodejs/node#56645). Draining the loop is the fix; unwinding via a throw
33
- * also runs finally blocks (spinners, tty restore) that process.exit skips.
34
- */
35
- export declare class ExitSignal extends Error {
36
- readonly exitCode: number;
37
- constructor(exitCode: number);
38
- }
39
- export declare function isJsonMode(): boolean;
40
- /** Emit a success payload on stdout (used by --json). */
41
- export declare function outputJson(data: unknown): void;
42
- /**
43
- * Print a result. In --json mode, emits `jsonData` as JSON on stdout.
44
- * Otherwise runs `human` (a string or a function that prints).
45
- */
46
- export declare function outputResult(jsonData: unknown, human: string | (() => void)): void;
47
- interface FailOptions {
48
- /** Override the exit code (defaults to EXIT.ERROR). */
49
- exitCode?: number;
50
- /** Machine-stable error code for --json consumers. */
51
- code?: string;
52
- /** Optional HTTP status to surface in --json. */
53
- status?: number;
54
- }
55
- /**
56
- * Print an error and end the command. JSON mode → `{ok:false, error:{...}}`
57
- * on stderr. Human mode → red "Error:" line on stderr. Never returns: it
58
- * throws ExitSignal, which the entrypoint turns into process.exitCode so the
59
- * event loop drains before the process ends (see ExitSignal).
60
- */
61
- export declare function fail(message: string, opts?: FailOptions): never;
62
- /**
63
- * Centralized catch-block handler. Maps CliHttpError → fail() with the right
64
- * code/exit, and turns any other Error into a structured failure too, so an
65
- * AI agent never has to scrape an uncaught stack trace.
66
- */
67
- export declare function handleError(error: unknown): never;
68
- /**
69
- * A spinner that disappears in --json / non-TTY contexts so it can never
70
- * corrupt machine output. Lazily loads `ora` only when actually needed.
71
- */
72
- export interface Spinner {
73
- /** Live status line (mirrors ora's `.text`); ignored in degraded modes. */
74
- text?: string;
75
- succeed(text?: string): void;
76
- fail(text?: string): void;
77
- stop(): void;
78
- }
79
- export declare function makeSpinner(text: string): Promise<Spinner>;
80
- export {};
package/dist/output.js DELETED
@@ -1,176 +0,0 @@
1
- /**
2
- * Output + error helpers.
3
- *
4
- * Two audiences share this CLI: humans at a terminal, and programs/AI agents
5
- * that shell out and parse stdout. The `--json` flag switches to a strict
6
- * machine contract:
7
- *
8
- * - success → a single JSON object on STDOUT, nothing else
9
- * - failure → a single JSON object on STDERR, nothing else
10
- * - spinners, colors, and the update notice are suppressed
11
- * - exit code reflects the outcome (see EXIT)
12
- *
13
- * In human mode, errors go to STDERR (not stdout) so that even without --json,
14
- * stdout stays clean enough to pipe.
15
- */
16
- import chalk from 'chalk';
17
- import { CliHttpError } from './api.js';
18
- /** Stable exit codes so callers can branch on outcome without parsing text. */
19
- export const EXIT = {
20
- OK: 0,
21
- ERROR: 1,
22
- AUTH: 2,
23
- NOT_FOUND: 3,
24
- USAGE: 4,
25
- };
26
- /**
27
- * Thrown instead of calling process.exit(). The entrypoint catches it, sets
28
- * process.exitCode, and lets the event loop drain naturally.
29
- *
30
- * Why: hard process.exit() while libuv handles are still live (undici
31
- * keep-alive sockets, an in-flight fetch, raw-mode stdin) races handle
32
- * teardown on Windows and dies with
33
- * "Assertion failed: !(handle->flags & UV_HANDLE_CLOSING), src\\win\\async.c"
34
- * (nodejs/node#56645). Draining the loop is the fix; unwinding via a throw
35
- * also runs finally blocks (spinners, tty restore) that process.exit skips.
36
- */
37
- export class ExitSignal extends Error {
38
- exitCode;
39
- constructor(exitCode) {
40
- super(`exit ${exitCode}`);
41
- this.exitCode = exitCode;
42
- this.name = 'ExitSignal';
43
- }
44
- }
45
- export function isJsonMode() {
46
- return process.argv.includes('--json');
47
- }
48
- /** Emit a success payload on stdout (used by --json). */
49
- export function outputJson(data) {
50
- process.stdout.write(JSON.stringify(data, null, 2) + '\n');
51
- }
52
- /**
53
- * Print a result. In --json mode, emits `jsonData` as JSON on stdout.
54
- * Otherwise runs `human` (a string or a function that prints).
55
- */
56
- export function outputResult(jsonData, human) {
57
- if (isJsonMode()) {
58
- outputJson(jsonData);
59
- return;
60
- }
61
- if (typeof human === 'function')
62
- human();
63
- else
64
- console.log(human);
65
- }
66
- /** Map an HTTP status to one of our stable exit codes. */
67
- function exitCodeForStatus(status) {
68
- if (status === 401 || status === 403)
69
- return EXIT.AUTH;
70
- if (status === 404)
71
- return EXIT.NOT_FOUND;
72
- return EXIT.ERROR;
73
- }
74
- /** Short machine-stable error code, paired with the human message. */
75
- function errorCodeForStatus(status) {
76
- switch (status) {
77
- case 0:
78
- return 'network_error';
79
- case 401:
80
- case 403:
81
- return 'unauthorized';
82
- case 402:
83
- return 'payment_required';
84
- case 404:
85
- return 'not_found';
86
- case 409:
87
- return 'conflict';
88
- case 503:
89
- return 'unavailable';
90
- default:
91
- return status >= 500 ? 'server_error' : 'request_failed';
92
- }
93
- }
94
- /**
95
- * Print an error and end the command. JSON mode → `{ok:false, error:{...}}`
96
- * on stderr. Human mode → red "Error:" line on stderr. Never returns: it
97
- * throws ExitSignal, which the entrypoint turns into process.exitCode so the
98
- * event loop drains before the process ends (see ExitSignal).
99
- */
100
- export function fail(message, opts = {}) {
101
- const exitCode = opts.exitCode ?? EXIT.ERROR;
102
- if (isJsonMode()) {
103
- process.stderr.write(JSON.stringify({
104
- ok: false,
105
- error: {
106
- code: opts.code ?? 'error',
107
- message,
108
- ...(opts.status !== undefined ? { status: opts.status } : {}),
109
- },
110
- }, null, 2) + '\n');
111
- }
112
- else {
113
- process.stderr.write(chalk.red('Error:') + ` ${message}\n`);
114
- }
115
- throw new ExitSignal(exitCode);
116
- }
117
- /**
118
- * Centralized catch-block handler. Maps CliHttpError → fail() with the right
119
- * code/exit, and turns any other Error into a structured failure too, so an
120
- * AI agent never has to scrape an uncaught stack trace.
121
- */
122
- export function handleError(error) {
123
- // ExitSignal is control flow, not a failure to report: a nested fail()
124
- // already printed its message and chose its exit code. Re-wrapping it
125
- // here would clobber the code (usage errors became exit 1) and print a
126
- // second, useless "exit 4" error line.
127
- if (error instanceof ExitSignal)
128
- throw error;
129
- if (error instanceof CliHttpError) {
130
- // The server's own code wins when it sent one: a 402 that says
131
- // `seat_limit` tells the caller exactly which gate closed, where the
132
- // status-derived fallback would only say `payment_required`. The
133
- // message is always the server's detail verbatim, which for billing
134
- // gates is already a complete sentence naming the fix.
135
- fail(error.detail, {
136
- status: error.status,
137
- code: error.code ?? errorCodeForStatus(error.status),
138
- exitCode: exitCodeForStatus(error.status),
139
- });
140
- }
141
- if (error instanceof Error) {
142
- fail(error.message, { code: 'error' });
143
- }
144
- fail(String(error), { code: 'error' });
145
- }
146
- export async function makeSpinner(text) {
147
- if (isJsonMode() || !process.stderr.isTTY) {
148
- return { succeed() { }, fail() { }, stop() { } };
149
- }
150
- // Degenerate PTYs — script(1), some CI wrappers — report a 0×0 winsize.
151
- // ora's line-wrap math then clears "text ÷ 0" lines per frame: a multi-MB/s
152
- // ANSI write storm whose backpressure starves the event loop, so the await
153
- // the spinner is covering never resolves. Degrade to static lines instead.
154
- const cols = process.stderr.columns;
155
- if (!cols || cols < 20) {
156
- process.stderr.write(`${text}\n`);
157
- return {
158
- succeed: (t) => process.stderr.write(`✔ ${t ?? 'done'}\n`),
159
- fail: (t) => process.stderr.write(`✖ ${t ?? 'failed'}\n`),
160
- stop() { },
161
- };
162
- }
163
- const { default: ora } = await import('ora');
164
- // discardStdin grabs stdin in raw mode; in wrapped PTYs that can keep the
165
- // process alive after the command finishes. We never need it.
166
- const spinner = ora({ text, stream: process.stderr, discardStdin: false }).start();
167
- return {
168
- set text(t) {
169
- if (t !== undefined)
170
- spinner.text = t;
171
- },
172
- succeed: (t) => spinner.succeed(t),
173
- fail: (t) => spinner.fail(t),
174
- stop: () => spinner.stop(),
175
- };
176
- }
package/dist/prompt.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export declare function promptForValue(label: string, preset?: string): Promise<string>;
2
- export declare function promptForPassword(preset?: string): Promise<string>;
package/dist/prompt.js DELETED
@@ -1,62 +0,0 @@
1
- import { createInterface } from 'node:readline/promises';
2
- import { stdin as input, stdout as output } from 'node:process';
3
- function createPrompt() {
4
- return createInterface({ input, output });
5
- }
6
- export async function promptForValue(label, preset) {
7
- if (preset) {
8
- return preset;
9
- }
10
- const rl = createPrompt();
11
- try {
12
- return (await rl.question(`${label}: `)).trim();
13
- }
14
- finally {
15
- rl.close();
16
- }
17
- }
18
- export async function promptForPassword(preset) {
19
- if (preset) {
20
- return preset;
21
- }
22
- if (!input.isTTY || !output.isTTY) {
23
- return promptForValue('Password');
24
- }
25
- output.write('Password: ');
26
- const wasRaw = input.isRaw;
27
- const chunks = [];
28
- return await new Promise((resolve) => {
29
- input.setRawMode?.(true);
30
- input.resume();
31
- const cleanup = () => {
32
- input.removeListener('data', onData);
33
- input.setRawMode?.(Boolean(wasRaw));
34
- output.write('\n');
35
- };
36
- const finish = () => {
37
- cleanup();
38
- resolve(chunks.join('').trim());
39
- };
40
- const onData = (buffer) => {
41
- const value = buffer.toString('utf8');
42
- if (value === '\u0003') {
43
- cleanup();
44
- // Deliberate hard exit: Ctrl-C during a password prompt must be
45
- // immediate. Pause stdin first so the only live handle is gone;
46
- // this path runs before any network work, so nothing is in flight.
47
- input.pause();
48
- process.exit(130);
49
- }
50
- if (value === '\r' || value === '\n') {
51
- finish();
52
- return;
53
- }
54
- if (value === '\u007f') {
55
- chunks.pop();
56
- return;
57
- }
58
- chunks.push(value);
59
- };
60
- input.on('data', onData);
61
- });
62
- }
package/dist/resolve.d.ts DELETED
@@ -1,16 +0,0 @@
1
- export interface AgentSummary {
2
- id: string;
3
- name: string;
4
- status: string;
5
- framework: string;
6
- createdAt?: string;
7
- }
8
- /**
9
- * Resolve an agent for a command.
10
- *
11
- * - With a name/ID: exact-name match first, then unique ID-prefix match.
12
- * - Without one: fall back to the agent this directory is linked to
13
- * (`.maritime/project.json`), so `maritime logs`, `maritime chat "…"`, etc.
14
- * "just work" in a linked project — the Vercel/Railway model.
15
- */
16
- export declare function resolveAgent(nameOrId?: string): Promise<AgentSummary>;
package/dist/resolve.js DELETED
@@ -1,59 +0,0 @@
1
- import { authGet } from './api.js';
2
- import { fail, EXIT } from './output.js';
3
- import { getLink } from './context.js';
4
- // Simple in-memory cache for the full agent list (5-second TTL)
5
- let cachedAgents = null;
6
- let cacheTime = 0;
7
- const CACHE_TTL = 5_000;
8
- async function fetchAllAgents() {
9
- const now = Date.now();
10
- if (cachedAgents && now - cacheTime < CACHE_TTL) {
11
- return cachedAgents;
12
- }
13
- cachedAgents = await authGet('/api/agents');
14
- cacheTime = now;
15
- return cachedAgents;
16
- }
17
- /**
18
- * Resolve an agent for a command.
19
- *
20
- * - With a name/ID: exact-name match first, then unique ID-prefix match.
21
- * - Without one: fall back to the agent this directory is linked to
22
- * (`.maritime/project.json`), so `maritime logs`, `maritime chat "…"`, etc.
23
- * "just work" in a linked project — the Vercel/Railway model.
24
- */
25
- export async function resolveAgent(nameOrId) {
26
- if (!nameOrId || !nameOrId.trim()) {
27
- return resolveLinkedAgent();
28
- }
29
- // 1. Try server-side exact name match first (single API call, no full list)
30
- const byName = await authGet(`/api/agents?name=${encodeURIComponent(nameOrId)}`);
31
- if (byName.length === 1)
32
- return byName[0];
33
- // 2. Fall back to full list and match by ID prefix
34
- const agents = await fetchAllAgents();
35
- const byId = agents.filter((a) => a.id.startsWith(nameOrId));
36
- if (byId.length === 1)
37
- return byId[0];
38
- if (byId.length > 1) {
39
- fail(`Ambiguous agent "${nameOrId}". Multiple ID prefix matches.`, {
40
- code: 'ambiguous_agent',
41
- });
42
- }
43
- fail(`Agent "${nameOrId}" not found.`, { code: 'not_found', exitCode: EXIT.NOT_FOUND });
44
- }
45
- /** The agent linked to the current directory, or a helpful error if none. */
46
- function resolveLinkedAgent() {
47
- const link = getLink();
48
- if (!link) {
49
- fail("No agent given and this directory isn't linked. Pass an agent name, or run `maritime link` / `maritime init`.", { code: 'no_agent', exitCode: EXIT.USAGE });
50
- }
51
- // Return straight from the link file — no API round-trip. Downstream calls
52
- // that hit the agent will surface a clear 404 if it was deleted.
53
- return {
54
- id: link.agentId,
55
- name: link.name ?? link.agentId,
56
- status: 'unknown',
57
- framework: 'unknown',
58
- };
59
- }
@@ -1,20 +0,0 @@
1
- /**
2
- * Daily check against the npm registry.
3
- *
4
- * Runs at most once per 24h (throttled at ATTEMPT time, not success time,
5
- * so an offline machine doesn't re-fire the request on every command), and
6
- * never in machine/CI contexts where the notice would not be printed
7
- * anyway. Returns immediately; await versionCheckSettled() before exit.
8
- */
9
- export declare function checkForUpdates(currentVersion: string): void;
10
- /**
11
- * Resolves when the (at most one) in-flight update check has settled.
12
- * Bounded by the fetch's own 3s AbortSignal; resolves immediately when no
13
- * check ran this invocation (the usual case, 24h throttle).
14
- */
15
- export declare function versionCheckSettled(): Promise<void>;
16
- /**
17
- * Print update notice if a newer version was found.
18
- * Call at the end of command execution.
19
- */
20
- export declare function printUpdateNotice(currentVersion: string): void;
@@ -1,81 +0,0 @@
1
- import chalk from 'chalk';
2
- import { config } from './config.js';
3
- const ONE_DAY = 24 * 60 * 60 * 1000;
4
- /** True when `a` is a strictly newer semver than `b` (numeric x.y.z compare). */
5
- function isNewer(a, b) {
6
- const pa = a.split('.').map((n) => parseInt(n, 10) || 0);
7
- const pb = b.split('.').map((n) => parseInt(n, 10) || 0);
8
- for (let i = 0; i < 3; i++) {
9
- if ((pa[i] || 0) !== (pb[i] || 0))
10
- return (pa[i] || 0) > (pb[i] || 0);
11
- }
12
- return false;
13
- }
14
- // The single in-flight registry request (at most one per day). The
15
- // entrypoint awaits this before finishing so the process never exits with
16
- // the fetch's DNS/TLS work still on the libuv threadpool: that in-flight
17
- // work racing a hard exit was the most common trigger of the Windows
18
- // `uv_async_send during close` assertion, because this check used to run
19
- // unawaited on EVERY command.
20
- let inflight = null;
21
- /**
22
- * Daily check against the npm registry.
23
- *
24
- * Runs at most once per 24h (throttled at ATTEMPT time, not success time,
25
- * so an offline machine doesn't re-fire the request on every command), and
26
- * never in machine/CI contexts where the notice would not be printed
27
- * anyway. Returns immediately; await versionCheckSettled() before exit.
28
- */
29
- export function checkForUpdates(currentVersion) {
30
- // Machine mode / non-interactive: the notice is suppressed there, so the
31
- // network request is pure liability (latency + teardown race).
32
- if (process.argv.includes('--json') || !process.stderr.isTTY || process.env.CI)
33
- return;
34
- const lastCheck = config.get('lastVersionCheck');
35
- if (lastCheck && Date.now() - lastCheck < ONE_DAY)
36
- return;
37
- config.set('lastVersionCheck', Date.now());
38
- inflight = fetch('https://registry.npmjs.org/maritime-cli/latest', {
39
- signal: AbortSignal.timeout(3000),
40
- })
41
- .then((r) => r.json())
42
- .then((data) => {
43
- const latest = data.version;
44
- // Store only genuinely-newer versions, and clear anything stale;
45
- // otherwise an old cached value survives upgrades forever and the
46
- // banner suggests a "downgrade" (the 1.x to 0.2.1 bug).
47
- if (latest && isNewer(latest, currentVersion)) {
48
- config.set('latestVersion', latest);
49
- }
50
- else {
51
- config.delete('latestVersion');
52
- }
53
- })
54
- .catch(() => {
55
- // Silently ignore: this is a best-effort check.
56
- });
57
- }
58
- /**
59
- * Resolves when the (at most one) in-flight update check has settled.
60
- * Bounded by the fetch's own 3s AbortSignal; resolves immediately when no
61
- * check ran this invocation (the usual case, 24h throttle).
62
- */
63
- export function versionCheckSettled() {
64
- return inflight ?? Promise.resolve();
65
- }
66
- /**
67
- * Print update notice if a newer version was found.
68
- * Call at the end of command execution.
69
- */
70
- export function printUpdateNotice(currentVersion) {
71
- // Never emit chatter on stdout in machine mode — it corrupts JSON output.
72
- if (process.argv.includes('--json'))
73
- return;
74
- const latest = config.get('latestVersion');
75
- if (latest && isNewer(latest, currentVersion)) {
76
- console.log(chalk.dim(`\n Update available: ${currentVersion} → ${chalk.bold(latest)}`) +
77
- chalk.dim(' Run ') +
78
- chalk.bold('npm i -g maritime-cli') +
79
- chalk.dim(' to update'));
80
- }
81
- }
@@ -1,22 +0,0 @@
1
- export interface WsOptions {
2
- /** Called for each text message received */
3
- onMessage: (data: string) => void;
4
- /** Called when connection closes cleanly */
5
- onClose?: () => void;
6
- /** Max reconnect attempts on transient failures */
7
- maxReconnects?: number;
8
- }
9
- /**
10
- * Connect to a Maritime WebSocket endpoint with auth token.
11
- * Returns a cleanup function that closes the connection.
12
- *
13
- * Teardown rules (Windows-safe: no handle may outlive the command):
14
- * - a pending reconnect timer is cleared on cleanup;
15
- * - CONNECTING sockets are terminated, not orphaned;
16
- * - a server close with code 1000 is final (the deploy-status endpoint
17
- * closes with 1000 on terminal status): reconnecting would just replay
18
- * the terminal frame and burn the backoff;
19
- * - the SIGINT listener is removed as soon as the connection is done,
20
- * whether via cleanup() or the server ending the stream.
21
- */
22
- export declare function connectWs(path: string, opts: WsOptions): () => void;
package/dist/websocket.js DELETED
@@ -1,89 +0,0 @@
1
- import { WebSocket } from 'ws';
2
- import chalk from 'chalk';
3
- import { getApiUrl, requireAuth } from './api.js';
4
- /**
5
- * Connect to a Maritime WebSocket endpoint with auth token.
6
- * Returns a cleanup function that closes the connection.
7
- *
8
- * Teardown rules (Windows-safe: no handle may outlive the command):
9
- * - a pending reconnect timer is cleared on cleanup;
10
- * - CONNECTING sockets are terminated, not orphaned;
11
- * - a server close with code 1000 is final (the deploy-status endpoint
12
- * closes with 1000 on terminal status): reconnecting would just replay
13
- * the terminal frame and burn the backoff;
14
- * - the SIGINT listener is removed as soon as the connection is done,
15
- * whether via cleanup() or the server ending the stream.
16
- */
17
- export function connectWs(path, opts) {
18
- const token = requireAuth();
19
- const baseUrl = getApiUrl().replace(/^http/, 'ws');
20
- const sep = path.includes('?') ? '&' : '?';
21
- const url = `${baseUrl}${path}${sep}token=${token}`;
22
- const maxReconnects = opts.maxReconnects ?? 2;
23
- let reconnects = 0;
24
- let closed = false;
25
- let finished = false;
26
- let reconnectTimer;
27
- let ws;
28
- function finish() {
29
- if (finished)
30
- return;
31
- finished = true;
32
- process.removeListener('SIGINT', sigHandler);
33
- opts.onClose?.();
34
- }
35
- function connect() {
36
- ws = new WebSocket(url);
37
- ws.on('message', (raw) => {
38
- opts.onMessage(raw.toString());
39
- });
40
- ws.on('close', (code) => {
41
- if (closed || code === 1000) {
42
- finish();
43
- return;
44
- }
45
- if (reconnects < maxReconnects) {
46
- reconnects++;
47
- reconnectTimer = setTimeout(connect, 1000 * reconnects);
48
- }
49
- else {
50
- finish();
51
- }
52
- });
53
- ws.on('error', (err) => {
54
- if (!closed) {
55
- console.error(chalk.dim(`WebSocket error: ${err.message}`));
56
- }
57
- });
58
- }
59
- connect();
60
- // Clean shutdown on SIGINT
61
- const sigHandler = () => {
62
- cleanup();
63
- };
64
- process.on('SIGINT', sigHandler);
65
- function cleanup() {
66
- closed = true;
67
- if (reconnectTimer) {
68
- clearTimeout(reconnectTimer);
69
- reconnectTimer = undefined;
70
- // No socket is open when a reconnect was pending; end the stream now.
71
- finish();
72
- return;
73
- }
74
- if (ws) {
75
- if (ws.readyState === WebSocket.OPEN) {
76
- ws.close();
77
- }
78
- else if (ws.readyState === WebSocket.CONNECTING) {
79
- // close() during the handshake leaves the socket to finish
80
- // connecting in the background; terminate() drops it now.
81
- ws.terminate();
82
- }
83
- else {
84
- finish();
85
- }
86
- }
87
- }
88
- return cleanup;
89
- }