@gheima/cli 0.5.0 → 0.7.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.
package/dist/cli.js CHANGED
@@ -1,31 +1,53 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire } from 'node:module';
3
- import { spawn } from 'node:child_process';
4
- import { readFileSync, createReadStream, createWriteStream, existsSync, statSync } from 'node:fs';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { readFileSync, createReadStream, createWriteStream, existsSync, statSync, writeFileSync, chmodSync, } from 'node:fs';
5
4
  import { Readable } from 'node:stream';
6
5
  import { pipeline } from 'node:stream/promises';
7
6
  import { basename } from 'node:path';
8
7
  import { Command } from 'commander';
9
- import { GheimaError, GheimaClient } from '@gheima/sdk';
10
- import { makeClient } from './client.js';
8
+ import { GheimaError, GheimaClient, DEFAULT_API_URL } from '@gheima/sdk';
9
+ import { makeClient, transportOptions, VERSION } from './client.js';
10
+ import { EXIT, UsageError, exitCodeFor } from './exit.js';
11
+ import { useProxyFromEnv } from './proxy.js';
12
+ import { REFRESH_ARG, refreshUpdateCache, shouldCheck, updateNotice } from './update-check.js';
11
13
  import { resolveAuth, setProfile, removeProfile, loadConfig } from './config.js';
12
- import { prompt, promptHidden, confirm } from './prompt.js';
13
- import { table, printJson, spinner, success, info, color } from './ui.js';
14
+ import { promptHidden, confirm } from './prompt.js';
15
+ import { table, printJson, printJsonLine, spinner, success, info, color, isInteractive, isJsonMode, setJsonMode, hasWrittenResult, writeRaw, } from './ui.js';
14
16
  import { completionScript } from './completion.js';
15
- import { registerGenerated } from './generated.js';
17
+ import { callOp, registerGenerated } from './generated.js';
18
+ import { findLink, toDotenv, writeLink } from './link.js';
16
19
  import { defaultClientName, openBrowser, pollForApproval, startDeviceLogin, } from './device-login.js';
17
- const require = createRequire(import.meta.url);
18
- const pkg = require('../package.json');
19
20
  const program = new Command();
20
21
  program
21
22
  .name('gheima')
22
- .description('Gheima platform CLI — deploy and manage services, databases, storage, and more.')
23
- .version(pkg.version, '-v, --version')
23
+ .description('The Gheima CLI. Deploy and manage services, databases, storage and the rest of your account.')
24
+ .version(VERSION, '-v, --version')
24
25
  .option('-k, --key <key>', 'API key (overrides env + stored profile)')
25
26
  .option('-u, --url <url>', 'API base URL')
26
27
  .option('-p, --profile <name>', 'config profile to use')
27
- .option('--json', 'output machine-readable JSON')
28
- .showHelpAfterError();
28
+ .option('--json', 'output machine-readable JSON (one document on stdout; NDJSON for streams)')
29
+ .showHelpAfterError(!process.argv.includes('--json'))
30
+ // A usage error under --json is the same envelope as any other error, so a script parsing
31
+ // stderr does not need a second format for the one class of failure commander reports.
32
+ .configureOutput({
33
+ outputError: (str, write) => write(process.argv.includes('--json')
34
+ ? JSON.stringify({
35
+ error: { code: 'usage', message: str.replace(/^error: /, '').trim() },
36
+ }) + '\n'
37
+ : str),
38
+ })
39
+ // Inherited by every command added below. Help and --version are not failures; anything
40
+ // else commander rejects (an unknown flag, a missing argument) is a usage error, exit 2.
41
+ .exitOverride((err) => process.exit(err.exitCode === 0 ? EXIT.ok : EXIT.usage))
42
+ .hook('preAction', (_program, action) => {
43
+ setJsonMode(Boolean(action.optsWithGlobals().json));
44
+ })
45
+ // Under --json stdout is ALWAYS one JSON document, so a command that only reports
46
+ // success on stderr still answers a script with something it can parse.
47
+ .hook('postAction', () => {
48
+ if (isJsonMode() && !hasWrittenResult())
49
+ printJson({ ok: true });
50
+ });
29
51
  /** Global options merged across the program + the invoked subcommand. */
30
52
  function globals(cmd) {
31
53
  return cmd.optsWithGlobals();
@@ -37,8 +59,8 @@ function globals(cmd) {
37
59
  async function confirmDestructive(yes, whatWillHappen) {
38
60
  if (yes)
39
61
  return;
40
- if (!process.stdin.isTTY) {
41
- fail(new Error(`Refusing to ${whatWillHappen} in a non-interactive shell without --yes`));
62
+ if (!isInteractive()) {
63
+ throw new UsageError(`Refusing to ${whatWillHappen} in a non-interactive shell. Pass --yes to confirm.`);
42
64
  }
43
65
  if (!(await confirm(`This will ${whatWillHappen}. Continue?`))) {
44
66
  process.stderr.write('Aborted.\n');
@@ -52,14 +74,32 @@ async function readStdin() {
52
74
  chunks.push(chunk);
53
75
  return Buffer.concat(chunks).toString('utf8');
54
76
  }
77
+ /**
78
+ * Report a failure and exit with its code (see exit.ts). The API's code and request id are
79
+ * always shown, because the request id is what support needs to find the request.
80
+ */
55
81
  function fail(err) {
56
- if (err instanceof GheimaError) {
57
- process.stderr.write(`${color.red('Error')} (${err.status} ${err.code}): ${err.message}\n`);
82
+ const message = err instanceof Error ? err.message : String(err);
83
+ const api = err instanceof GheimaError ? err : null;
84
+ if (isJsonMode()) {
85
+ process.stderr.write(JSON.stringify({
86
+ error: {
87
+ code: api?.code ?? (err instanceof UsageError ? 'usage' : 'error'),
88
+ message,
89
+ ...(api ? { status: api.status, requestId: api.requestId ?? null } : {}),
90
+ },
91
+ }) + '\n');
58
92
  }
59
93
  else {
60
- process.stderr.write(`${color.red('Error')}: ${err instanceof Error ? err.message : String(err)}\n`);
94
+ process.stderr.write(`${color.red('Error')}: ${message}\n`);
95
+ if (api) {
96
+ const facts = [`code ${api.code}`, api.status ? `status ${api.status}` : null];
97
+ if (api.requestId)
98
+ facts.push(`request ${api.requestId}`);
99
+ process.stderr.write(color.dim(` ${facts.filter(Boolean).join(' · ')}\n`));
100
+ }
61
101
  }
62
- process.exit(1);
102
+ process.exit(exitCodeFor(err));
63
103
  }
64
104
  // ---------------------------------------------------------------------------
65
105
  // auth
@@ -72,7 +112,7 @@ program
72
112
  .action(async (opts, cmd) => {
73
113
  const g = globals(cmd);
74
114
  const profileName = g.profile || 'default';
75
- const baseUrl = (g.url || process.env.GHEIMA_URL || 'https://gheima.ma').replace(/\/$/, '');
115
+ const baseUrl = g.url || process.env.GHEIMA_URL || DEFAULT_API_URL;
76
116
  // `--key` on the program means the caller already has a credential and is not asking to
77
117
  // be sent through a browser at all.
78
118
  const pasteInstead = opts.withKey || Boolean(g.key);
@@ -87,18 +127,18 @@ program
87
127
  }
88
128
  let key = g.key;
89
129
  if (!key) {
90
- info('Create an API key in the dashboard → Settings → API keys.');
130
+ info('Create an API key in the dashboard under Settings > API keys.');
91
131
  key = await promptHidden('Paste your API key (gh_…): ');
92
132
  }
93
133
  if (!key)
94
134
  fail('No API key provided.');
95
- const client = new GheimaClient({ apiKey: key, baseUrl: g.url });
135
+ const client = new GheimaClient(transportOptions({ apiKey: key, url: g.url }));
96
136
  const spin = spinner('Verifying key…');
97
137
  try {
98
138
  const account = await client.account.get();
99
139
  spin.stop();
100
140
  setProfile(profileName, { apiKey: key, url: g.url });
101
- success(`Logged in as ${color.bold(account.name)} (${account.slug}) → profile "${profileName}"`);
141
+ success(`Signed in as ${color.bold(account.name)} (${account.slug}), saved as profile "${profileName}"`);
102
142
  }
103
143
  catch (err) {
104
144
  spin.stop();
@@ -117,19 +157,19 @@ async function browserLogin(baseUrl, profileName, wantBrowser, urlOverride) {
117
157
  info(`Your code is ${color.bold(started.user_code)}`);
118
158
  info(`Open ${color.bold(started.verification_uri_complete)} and approve it.`);
119
159
  if (wantBrowser && !openBrowser(started.verification_uri_complete)) {
120
- info('Could not open a browser — open the URL above by hand.');
160
+ info('Could not open a browser. Open the URL above yourself.');
121
161
  }
122
162
  const spin = spinner('Waiting for approval…');
123
163
  try {
124
164
  const result = await pollForApproval(baseUrl, started, {
125
- onSlowDown: (seconds) => info(`Server asked for a slower poll — now every ${seconds}s.`),
165
+ onSlowDown: (seconds) => info(`The server asked for slower polling. Checking every ${seconds}s now.`),
126
166
  });
127
167
  spin.stop();
128
168
  setProfile(profileName, { apiKey: result.apiKey, url: urlOverride });
129
- const client = new GheimaClient({ apiKey: result.apiKey, baseUrl: urlOverride });
169
+ const client = new GheimaClient(transportOptions({ apiKey: result.apiKey, url: urlOverride }));
130
170
  const account = await client.account.get();
131
- success(`Logged in as ${color.bold(account.name)} (${account.slug}) → profile "${profileName}"`);
132
- info(`Key "${result.keyName}" created. Revoke it any time in Settings → API keys.`);
171
+ success(`Signed in as ${color.bold(account.name)} (${account.slug}), saved as profile "${profileName}"`);
172
+ info(`Key "${result.keyName}" created. Revoke it any time in Settings > API keys.`);
133
173
  }
134
174
  catch (err) {
135
175
  spin.stop();
@@ -155,10 +195,17 @@ program
155
195
  const client = makeClient(g);
156
196
  try {
157
197
  const account = await client.account.get();
158
- if (g.json)
159
- return printJson(account);
198
+ // Which of flag > env > profile supplied the key: the first question when a script is
199
+ // acting as the wrong account.
160
200
  const auth = resolveAuth(g);
161
- info(`source: ${auth?.source}${auth?.profile ? ` (profile ${auth.profile})` : ''}`);
201
+ const via = {
202
+ source: auth?.source,
203
+ ...(auth?.profile ? { profile: auth.profile } : {}),
204
+ url: client.baseUrl,
205
+ };
206
+ if (g.json)
207
+ return printJson({ ...account, auth: via });
208
+ info(`source: ${via.source}${auth?.profile ? ` (profile ${auth.profile})` : ''} · ${via.url}`);
162
209
  table(['Name', 'Slug', 'Plan', 'Type'], [[account.name, account.slug, account.plan, account.type]]);
163
210
  }
164
211
  catch (err) {
@@ -174,7 +221,7 @@ program
174
221
  const res = await makeClient(g).account.getSpendCap();
175
222
  if (g.json)
176
223
  return printJson(res);
177
- table(['Cap (MAD)', 'Alert %', 'Spent (MAD)'], [[res.spendCapMad ?? '—', res.spendAlertPct ?? '—', String(res.currentSpendMad)]]);
224
+ table(['Cap (MAD)', 'Alert %', 'Spent (MAD)'], [[res.spendCapMad ?? '-', res.spendAlertPct ?? '-', String(res.currentSpendMad)]]);
178
225
  }
179
226
  catch (err) {
180
227
  fail(err);
@@ -243,10 +290,12 @@ services
243
290
  services
244
291
  .command('create')
245
292
  .description('Create a service')
246
- .option('--project <id>', 'project folder id (omitted → the service is ungrouped)')
293
+ .option('--project <id>', 'project id (omit it to leave the service ungrouped)')
247
294
  .requiredOption('--name <name>', 'service name')
248
295
  .option('--type <type>', 'WEB | WORKER | STATIC', 'WEB')
249
296
  .option('--repo <url>', 'git repo URL')
297
+ .option('--image <ref>', 'prebuilt public image to run instead of a repo, e.g. nginx:1.27')
298
+ .option('--port <port>', 'port the app listens on (an image defaults to 8080)')
250
299
  .action(async (opts, cmd) => {
251
300
  const g = globals(cmd);
252
301
  try {
@@ -255,6 +304,8 @@ services
255
304
  name: opts.name,
256
305
  type: opts.type,
257
306
  repoUrl: opts.repo,
307
+ dockerImage: opts.image,
308
+ port: opts.port === undefined ? undefined : Number(opts.port),
258
309
  });
259
310
  if (g.json)
260
311
  return printJson(created);
@@ -358,7 +409,7 @@ program
358
409
  s.timezone,
359
410
  String(s.retentionCount),
360
411
  s.enabled ? 'yes' : 'no',
361
- s.nextRunAt ?? '—',
412
+ s.nextRunAt ?? '-',
362
413
  ],
363
414
  ]);
364
415
  }
@@ -404,9 +455,7 @@ program
404
455
  fail(err);
405
456
  }
406
457
  });
407
- const search = program
408
- .command('search')
409
- .description('Manage managed search (Meilisearch) instances');
458
+ const search = program.command('search').description('Manage search (Meilisearch) instances');
410
459
  search
411
460
  .command('list', { isDefault: true })
412
461
  .description('List search instances')
@@ -439,7 +488,7 @@ search
439
488
  });
440
489
  search
441
490
  .command('reveal <id>')
442
- .description('Reveal host + scoped API key + index prefix')
491
+ .description('Reveal the host, scoped API key and index prefix')
443
492
  .action(async (id, _opts, cmd) => {
444
493
  const g = globals(cmd);
445
494
  try {
@@ -482,7 +531,7 @@ search
482
531
  });
483
532
  const emailCmd = program
484
533
  .command('email')
485
- .description('Manage transactional email (sending domains + send)');
534
+ .description('Manage transactional email: sending domains and sending');
486
535
  emailCmd
487
536
  .command('domains', { isDefault: true })
488
537
  .description('List sending domains')
@@ -523,7 +572,10 @@ emailCmd
523
572
  const res = await makeClient(g).email.domains.verify(id);
524
573
  if (g.json)
525
574
  return printJson(res);
526
- success(res.verified ? 'Verified' : 'Not verified yet — DNS may still be propagating');
575
+ if (res.verified)
576
+ success('Verified');
577
+ else
578
+ info('Not verified yet. DNS may still be propagating, so try again in a few minutes.');
527
579
  }
528
580
  catch (err) {
529
581
  fail(err);
@@ -585,7 +637,10 @@ ssoCmd
585
637
  const res = await makeClient(g).sso.verify(id);
586
638
  if (g.json)
587
639
  return printJson(res);
588
- success(res.verified ? 'Verified and active' : 'Not verified yet — DNS may still be propagating');
640
+ if (res.verified)
641
+ success('Verified and active');
642
+ else
643
+ info('Not verified yet. DNS may still be propagating, so try again in a few minutes.');
589
644
  }
590
645
  catch (err) {
591
646
  fail(err);
@@ -610,14 +665,22 @@ templates
610
665
  templates
611
666
  .command('deploy <templateId> <name>')
612
667
  .description('Deploy a template (omit --project to leave the service ungrouped)')
613
- .option('--project <id>', 'project folder id (omitted → the service is ungrouped)')
668
+ .option('--project <id>', 'project id (omit it to leave the service ungrouped)')
669
+ .option('-e, --env <KEY=VALUE...>', "answer one of the template's inputs (repeatable)")
614
670
  .action(async (templateId, name, opts, cmd) => {
615
671
  const g = globals(cmd);
616
672
  try {
673
+ const env = opts.env?.map((pair) => {
674
+ const eq = pair.indexOf('=');
675
+ if (eq < 1)
676
+ fail('Expected --env KEY=value');
677
+ return [pair.slice(0, eq), pair.slice(eq + 1)];
678
+ });
617
679
  const res = await makeClient(g).templates.deploy({
618
680
  templateId,
619
681
  name,
620
682
  projectId: opts.project,
683
+ env: env ? Object.fromEntries(env) : undefined,
621
684
  });
622
685
  if (g.json)
623
686
  return printJson(res);
@@ -627,9 +690,7 @@ templates
627
690
  fail(err);
628
691
  }
629
692
  });
630
- const queues = program
631
- .command('queues')
632
- .description('Manage managed job queues (BullMQ-ready Redis)');
693
+ const queues = program.command('queues').description('Manage job queues (Redis, ready for BullMQ)');
633
694
  queues
634
695
  .command('list', { isDefault: true })
635
696
  .description('List job queues')
@@ -662,7 +723,7 @@ queues
662
723
  });
663
724
  queues
664
725
  .command('reveal <id>')
665
- .description('Reveal the Redis connection string + key prefix')
726
+ .description('Reveal the Redis connection string and key prefix')
666
727
  .action(async (id, _opts, cmd) => {
667
728
  const g = globals(cmd);
668
729
  try {
@@ -744,7 +805,7 @@ storage
744
805
  process.stdout.write(`${color.dim(p)}\n`);
745
806
  table(['Key', 'Size', 'Modified'], objects.map((o) => [o.key, o.size, o.lastModified]));
746
807
  if (token)
747
- info(`more objects remain — re-run without --page to list them all`);
808
+ info(`More objects remain. Run again without --page to list them all.`);
748
809
  }
749
810
  catch (err) {
750
811
  fail(err);
@@ -845,7 +906,19 @@ program
845
906
  // deploy / logs / env / open / status
846
907
  // ---------------------------------------------------------------------------
847
908
  /** Resolve a service by id or name to its id. */
909
+ /**
910
+ * A service by id, name or slug — or, with no argument, the one this directory is linked to
911
+ * (`gheima link`). With neither, a usage error that names both ways out.
912
+ */
848
913
  async function resolveServiceId(client, ref) {
914
+ if (!ref) {
915
+ const linked = findLink();
916
+ if (!linked) {
917
+ throw new UsageError('No service given, and this directory is not linked. Pass the service as an argument, ' +
918
+ 'or run `gheima link <service>` once.');
919
+ }
920
+ ref = linked.link.serviceId;
921
+ }
849
922
  const all = await client.services.list().all();
850
923
  const match = all.find((s) => s.id === ref || s.name === ref || s.slug === ref);
851
924
  if (!match)
@@ -877,28 +950,189 @@ program
877
950
  fail(err);
878
951
  }
879
952
  });
953
+ /** Statuses a deployment never leaves. Anything else, including a status added later, waits. */
954
+ const FINISHED = new Set(['LIVE', 'FAILED', 'CANCELLED', 'SKIPPED']);
880
955
  program
881
- .command('deploy [service]')
882
- .description('Trigger a deployment (by service id or name)')
956
+ .command('link <service>')
957
+ .description('Link this directory to a service, so commands run here default to it')
883
958
  .action(async (ref, _opts, cmd) => {
884
959
  const g = globals(cmd);
885
- const client = makeClient(g);
886
960
  try {
887
- if (!ref)
888
- ref = await prompt('Service id or name: ');
961
+ const client = makeClient(g);
962
+ const id = await resolveServiceId(client, ref);
963
+ const service = await client.services.get(id);
964
+ const ignored = writeLink(process.cwd(), { serviceId: id, serviceName: service.name });
965
+ if (g.json)
966
+ return printJson({ serviceId: id, serviceName: service.name, dir: process.cwd() });
967
+ success(`Linked ${color.bold(service.name)} to ${process.cwd()}`);
968
+ if (ignored)
969
+ info('Added .gheima/ to .gitignore.');
970
+ }
971
+ catch (err) {
972
+ fail(err);
973
+ }
974
+ });
975
+ program
976
+ .command('deploy [service]')
977
+ .description('Deploy, stream the build, and exit with the outcome (the linked service by default)')
978
+ .option('--no-wait', 'queue the deployment and exit without waiting for it')
979
+ .option('--timeout <minutes>', 'stop waiting after this long (exit 7)', '30')
980
+ .action(async (ref, opts, cmd) => {
981
+ const g = globals(cmd);
982
+ try {
983
+ const client = makeClient(g);
984
+ const timeout = Number(opts.timeout);
985
+ // Checked before anything is queued: NaN would skip the wait and report a timeout.
986
+ if (opts.wait && !(timeout > 0)) {
987
+ throw new UsageError(`--timeout must be a positive number of minutes, not ${opts.timeout}.`);
988
+ }
889
989
  const id = await resolveServiceId(client, ref);
890
990
  const { deploymentId } = await client.services.deploy(id);
991
+ if (!opts.wait) {
992
+ if (g.json)
993
+ return printJson({ deploymentId, status: 'QUEUED' });
994
+ return success(`Deployment queued: ${color.bold(deploymentId)}`);
995
+ }
996
+ info(`Deployment ${deploymentId} queued. Streaming the build…`);
997
+ const final = await waitForDeployment(client, id, deploymentId, timeout * 60_000);
998
+ if (g.json)
999
+ printJson(final);
1000
+ if (final.status === 'LIVE') {
1001
+ if (!g.json)
1002
+ success(`Live: ${deploymentId}`);
1003
+ return;
1004
+ }
1005
+ process.stderr.write(`${color.red('Deployment')} ${deploymentId} ended ${final.status}` +
1006
+ `${final.errorMessage ? `: ${final.errorMessage}` : ''}\n`);
1007
+ process.exit(EXIT.deployFailed);
1008
+ }
1009
+ catch (err) {
1010
+ fail(err);
1011
+ }
1012
+ });
1013
+ /**
1014
+ * Wait for a deployment to finish, streaming its build output meanwhile. The stream is for
1015
+ * people; the OUTCOME comes from polling the deployment by id, because the stream follows the
1016
+ * service's latest deployment and carries no id of its own. Build lines go to stdout, or to
1017
+ * stderr under --json so stdout stays one document.
1018
+ */
1019
+ async function waitForDeployment(client, serviceId, deploymentId, timeoutMs) {
1020
+ const stop = new AbortController();
1021
+ const out = isJsonMode() ? process.stderr : process.stdout;
1022
+ void (async () => {
1023
+ try {
1024
+ for await (const msg of client.services.streamLogs(serviceId, {
1025
+ type: 'build',
1026
+ signal: stop.signal,
1027
+ })) {
1028
+ const line = msg.line;
1029
+ if (line !== undefined)
1030
+ out.write(`${line}\n`);
1031
+ }
1032
+ }
1033
+ catch {
1034
+ /* the stream is a courtesy: polling below still decides the outcome */
1035
+ }
1036
+ })();
1037
+ const deadline = Date.now() + timeoutMs;
1038
+ try {
1039
+ while (Date.now() < deadline) {
1040
+ const d = (await client.services.deployments(serviceId)).find((x) => x.id === deploymentId);
1041
+ if (d && FINISHED.has(d.status)) {
1042
+ return { id: d.id, status: d.status, errorMessage: d.errorMessage ?? null };
1043
+ }
1044
+ await new Promise((r) => setTimeout(r, POLL_MS));
1045
+ }
1046
+ throw new GheimaError({
1047
+ status: 0,
1048
+ code: 'timeout',
1049
+ message: `Deployment ${deploymentId} was still running after ${timeoutMs / 60_000} minutes. ` +
1050
+ 'It keeps going; follow it with `gheima logs --build`.',
1051
+ });
1052
+ }
1053
+ finally {
1054
+ stop.abort();
1055
+ }
1056
+ }
1057
+ /** How often `deploy` and `run` ask for the outcome. Tests shorten it. */
1058
+ const POLL_MS = Number(process.env.GHEIMA_DEPLOY_POLL_MS) || 3000;
1059
+ /** Statuses a one-off run never leaves (the `CronStatus` values its row reuses). */
1060
+ const RUN_FINISHED = new Set(['SUCCESS', 'FAILED', 'SKIPPED']);
1061
+ /** How long `run` waits beyond the command's own timeout, for the run to leave the queue. */
1062
+ const RUN_QUEUE_SLACK_MS = 10 * 60_000;
1063
+ program
1064
+ .command('run <service> <command...>')
1065
+ .description("Run a one-off command against the service's live image and environment, print its log, " +
1066
+ 'and exit with its exit code. Put the command after `--`. The words are joined and run by the ' +
1067
+ 'remote /bin/sh -c, so quote the whole command when an argument holds spaces')
1068
+ .option('--timeout <seconds>', 'stop the command after this long (1-3600)', '300')
1069
+ .option('--no-wait', 'queue the run and exit without waiting for it')
1070
+ .action(async (ref, words, opts, cmd) => {
1071
+ const g = globals(cmd);
1072
+ try {
1073
+ const timeout = Number(opts.timeout);
1074
+ // Checked before anything is queued: the API would refuse it, but only after a lookup.
1075
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 3600) {
1076
+ throw new UsageError(`--timeout must be a whole number of seconds from 1 to 3600, not ${opts.timeout}.`);
1077
+ }
1078
+ const client = makeClient(g);
1079
+ const id = await resolveServiceId(client, ref);
1080
+ // Joined as typed, like `heroku run`: the remote shell does the word splitting, so
1081
+ // `gheima run web -- 'npm run migrate && npm run seed'` means what it says.
1082
+ const { run } = (await callOp('services.createRun', { id, command: words.join(' '), timeoutSeconds: timeout }, g));
1083
+ if (!opts.wait) {
1084
+ if (g.json)
1085
+ return printJson(run);
1086
+ return success(`Run queued: ${color.bold(run.id)}`);
1087
+ }
1088
+ info(`Run ${run.id} queued. Waiting for it to finish…`);
1089
+ const final = await waitForRun(id, run.id, timeout * 1000 + RUN_QUEUE_SLACK_MS, g);
1090
+ // Written only once the run has finished, so the log comes in one piece at the end.
1091
+ const { logs } = (await callOp('services.runLogs', { id, runId: run.id }, g));
891
1092
  if (g.json)
892
- return printJson({ deploymentId });
893
- success(`Deployment queued: ${color.bold(deploymentId)}`);
1093
+ printJson({ run: final, logs });
1094
+ else if (logs)
1095
+ writeRaw(logs.endsWith('\n') ? logs : `${logs}\n`);
1096
+ // exitCode, not exit(): a long log on a pipe must drain before the process ends.
1097
+ if (final.exitCode !== null) {
1098
+ if (!g.json && final.exitCode !== 0) {
1099
+ process.stderr.write(`${color.red('Run')} ${run.id} exited ${final.exitCode}\n`);
1100
+ }
1101
+ process.exitCode = final.exitCode;
1102
+ return;
1103
+ }
1104
+ process.stderr.write(`${color.red('Run')} ${run.id} ended ${final.status}` +
1105
+ `${final.error ? `: ${final.error}` : ''}\n`);
1106
+ process.exitCode = EXIT.runFailed;
894
1107
  }
895
1108
  catch (err) {
896
1109
  fail(err);
897
1110
  }
898
1111
  });
1112
+ /** Poll a one-off run until it finishes, saying so on stderr when it starts. */
1113
+ async function waitForRun(serviceId, runId, timeoutMs, g) {
1114
+ const deadline = Date.now() + timeoutMs;
1115
+ let started = false;
1116
+ while (Date.now() < deadline) {
1117
+ const { run } = (await callOp('services.getRun', { id: serviceId, runId }, g));
1118
+ if (RUN_FINISHED.has(run.status))
1119
+ return run;
1120
+ if (!started && run.status === 'RUNNING') {
1121
+ started = true;
1122
+ info('Running…');
1123
+ }
1124
+ await new Promise((r) => setTimeout(r, POLL_MS));
1125
+ }
1126
+ throw new GheimaError({
1127
+ status: 0,
1128
+ code: 'timeout',
1129
+ message: `Run ${runId} had not finished after ${Math.round(timeoutMs / 60_000)} minutes. ` +
1130
+ `Read it later with \`gheima services get-run ${serviceId} ${runId}\`.`,
1131
+ });
1132
+ }
899
1133
  program
900
- .command('logs <service>')
901
- .description('Show or tail service logs')
1134
+ .command('logs [service]')
1135
+ .description('Show or tail service logs (the linked service by default)')
902
1136
  .option('-f, --follow', 'stream new log lines')
903
1137
  .option('-b, --build', 'show build logs instead of runtime')
904
1138
  .option('-s, --search <text>', 'filter lines containing text')
@@ -910,8 +1144,11 @@ program
910
1144
  const type = opts.build ? 'build' : 'runtime';
911
1145
  if (opts.follow) {
912
1146
  for await (const entry of client.services.streamLogs(id, { type, search: opts.search })) {
913
- const line = entry.line ?? JSON.stringify(entry);
914
- process.stdout.write(`${line}\n`);
1147
+ // --json: one entry per line (NDJSON), so `| jq` works on a stream that never ends.
1148
+ if (isJsonMode())
1149
+ printJsonLine(entry);
1150
+ else
1151
+ process.stdout.write(`${entry.line ?? JSON.stringify(entry)}\n`);
915
1152
  }
916
1153
  return;
917
1154
  }
@@ -927,8 +1164,9 @@ program
927
1164
  });
928
1165
  const env = program.command('env').description('Manage service environment variables');
929
1166
  env
930
- .command('pull <service>')
931
- .description('List env var keys (values are never returned)')
1167
+ .command('ls [service]')
1168
+ .alias('list')
1169
+ .description('List env var keys, values masked (the linked service by default)')
932
1170
  .action(async (ref, _opts, cmd) => {
933
1171
  const g = globals(cmd);
934
1172
  const client = makeClient(g);
@@ -937,7 +1175,82 @@ env
937
1175
  const vars = await client.services.env.list(id);
938
1176
  if (g.json)
939
1177
  return printJson(vars);
940
- table(['Key', 'Value'], vars.map((v) => [v.key, v.masked]));
1178
+ table(['Key', 'Value'],
1179
+ // A secret's value is never returned; show a marker, never anything value-shaped.
1180
+ vars.map((v) => [v.key, v.secret ? '(secret)' : v.masked]));
1181
+ }
1182
+ catch (err) {
1183
+ fail(err);
1184
+ }
1185
+ });
1186
+ env
1187
+ .command('pull [service]')
1188
+ .description('Write the service’s env vars to .env.local (the linked service by default)')
1189
+ .option('--file <path>', 'where to write', '.env.local')
1190
+ .option('-f, --force', 'overwrite the file if it exists')
1191
+ .option('--stdout', 'print the values instead of writing a file')
1192
+ .action(async (ref, opts, cmd) => {
1193
+ const g = globals(cmd);
1194
+ try {
1195
+ // Checked before anything is fetched, so a refusal reveals nothing.
1196
+ if (!opts.stdout && existsSync(opts.file) && !opts.force) {
1197
+ throw new UsageError(`${opts.file} already exists. Pass --force to overwrite it.`);
1198
+ }
1199
+ const client = makeClient(g);
1200
+ const id = await resolveServiceId(client, ref);
1201
+ const { data: vars } = (await callOp('services.revealEnv', { id }, g));
1202
+ const { text: dotenv, skipped } = toDotenv(vars);
1203
+ if (skipped.length) {
1204
+ process.stderr.write(`${color.yellow('Warning')}: left out ${skipped.join(', ')}: a value holding a ' or a ` +
1205
+ `newline and also a literal \\n or \\t cannot survive a .env round trip.\n`);
1206
+ }
1207
+ // Values reach stdout only when asked for by name: never by default, never via --json.
1208
+ if (opts.stdout)
1209
+ return writeRaw(dotenv);
1210
+ // `mode` applies only when the file is created: an existing one overwritten with
1211
+ // --force keeps whatever it had, which is usually world-readable, so tighten it
1212
+ // BEFORE the values are written.
1213
+ if (existsSync(opts.file))
1214
+ chmodSync(opts.file, 0o600);
1215
+ writeFileSync(opts.file, dotenv, { mode: 0o600 });
1216
+ const count = vars.length - skipped.length;
1217
+ if (g.json)
1218
+ return printJson({ file: opts.file, count, skipped });
1219
+ success(`Wrote ${count} variables to ${opts.file}`);
1220
+ // Exit 1 from check-ignore means "inside a repo, and NOT ignored": one `git add .` from
1221
+ // committing the values. Anything else (ignored, no repo, no git) says nothing.
1222
+ if (spawnSync('git', ['check-ignore', '-q', opts.file], { stdio: 'ignore' }).status === 1) {
1223
+ process.stderr.write(`${color.yellow('Warning')}: ${opts.file} is not ignored by git. Add it to .gitignore.\n`);
1224
+ }
1225
+ info('Variables marked secret cannot be read back, so they are not in the file.');
1226
+ }
1227
+ catch (err) {
1228
+ fail(err);
1229
+ }
1230
+ });
1231
+ env
1232
+ .command('push [service]')
1233
+ .description('Upload a .env file to the service (merges; the linked service by default)')
1234
+ .option('--file <path>', 'the file to upload', '.env.local')
1235
+ .option('--replace', 'discard variables not in the file (secret ones are kept)')
1236
+ .option('-y, --yes', 'skip the confirmation --replace asks for')
1237
+ .action(async (ref, opts, cmd) => {
1238
+ const g = globals(cmd);
1239
+ try {
1240
+ if (!existsSync(opts.file))
1241
+ throw new UsageError(`${opts.file} does not exist. Pass --file.`);
1242
+ const dotenv = readFileSync(opts.file, 'utf8');
1243
+ const client = makeClient(g);
1244
+ const id = await resolveServiceId(client, ref);
1245
+ if (opts.replace) {
1246
+ await confirmDestructive(opts.yes, `replace every non-secret variable with ${opts.file}`);
1247
+ }
1248
+ const res = (await callOp('services.importEnv', { id, dotenv, replace: Boolean(opts.replace) }, g));
1249
+ if (g.json)
1250
+ return printJson(res);
1251
+ success(`Imported ${res.imported} of ${res.total} variables. Redeploy to apply them.`);
1252
+ if (res.invalidLines.length)
1253
+ info(`Skipped unparseable lines: ${res.invalidLines.join(', ')}`);
941
1254
  }
942
1255
  catch (err) {
943
1256
  fail(err);
@@ -948,6 +1261,7 @@ env
948
1261
  .description('Set an env var (KEY=value, or KEY with --stdin / --from-file)')
949
1262
  .option('--stdin', 'read the value from stdin instead of the command line')
950
1263
  .option('--from-file <path>', 'read the value from a file instead of the command line')
1264
+ .option('--secret', 'make the variable write-only: never shown or returned again (one-way)')
951
1265
  .action(async (ref, pair, opts, cmd) => {
952
1266
  const g = globals(cmd);
953
1267
  const client = makeClient(g);
@@ -969,7 +1283,7 @@ env
969
1283
  ? (await readStdin()).replace(/\r?\n$/, '')
970
1284
  : pair.slice(eq + 1);
971
1285
  const id = await resolveServiceId(client, ref);
972
- await client.services.env.set(id, key, value);
1286
+ await client.services.env.set(id, key, value, { secret: opts.secret });
973
1287
  success(`Set ${key}`);
974
1288
  }
975
1289
  catch (err) {
@@ -1045,18 +1359,21 @@ envGroups
1045
1359
  envGroups
1046
1360
  .command('import <groupId> <file>')
1047
1361
  .description('Import a .env file into a group (merges; --replace to overwrite)')
1048
- .option('--replace', 'Replace all variables instead of merging')
1362
+ .option('--replace', 'Replace all variables instead of merging (secret variables are kept)')
1363
+ .option('--secret', 'Mark every imported variable secret (write-only, one-way)')
1049
1364
  .option('-y, --yes', 'skip the confirmation prompt for --replace')
1050
1365
  .action(async (groupId, file, opts, cmd) => {
1051
1366
  const g = globals(cmd);
1052
- // --replace drops every variable already in the group, across every service the
1053
- // group is attached to. Treat it like the other destructive commands.
1367
+ // --replace drops every non-secret variable already in the group, across every service
1368
+ // the group is attached to. Treat it like the other destructive commands.
1054
1369
  if (opts.replace) {
1055
- await confirmDestructive(opts.yes, `replace every variable in env group ${groupId} with the contents of ${file}`);
1370
+ await confirmDestructive(opts.yes, `replace every non-secret variable in env group ${groupId} with the contents of ${file} (secret variables are kept)`);
1056
1371
  }
1057
1372
  try {
1058
1373
  const dotenv = readFileSync(file, 'utf8');
1059
- const res = await makeClient(g).envGroups.import(groupId, dotenv, !!opts.replace);
1374
+ const res = await makeClient(g).envGroups.import(groupId, dotenv, !!opts.replace, {
1375
+ secret: opts.secret,
1376
+ });
1060
1377
  if (g.json)
1061
1378
  return printJson(res);
1062
1379
  success(`Imported ${res.imported} var(s); ${res.total} total`);
@@ -1067,6 +1384,43 @@ envGroups
1067
1384
  fail(err);
1068
1385
  }
1069
1386
  });
1387
+ envGroups
1388
+ .command('set-var <groupId> <pair>')
1389
+ .description('Set one variable of a group (KEY=value, or KEY with --stdin)')
1390
+ .option('--stdin', 'read the value from stdin instead of the command line')
1391
+ .option('--secret', 'make the variable write-only: never shown or returned again (one-way)')
1392
+ .action(async (groupId, pair, opts, cmd) => {
1393
+ const g = globals(cmd);
1394
+ const eq = pair.indexOf('=');
1395
+ if (!opts.stdin && eq < 1)
1396
+ fail('Expected KEY=value (or KEY with --stdin)');
1397
+ if (opts.stdin && eq !== -1)
1398
+ fail('Pass the bare KEY when reading the value from stdin');
1399
+ const key = opts.stdin ? pair : pair.slice(0, eq);
1400
+ try {
1401
+ const value = opts.stdin ? (await readStdin()).replace(/\r?\n$/, '') : pair.slice(eq + 1);
1402
+ await makeClient(g).envGroups.setVar(groupId, key, value, { secret: opts.secret });
1403
+ success(`Set ${key}`);
1404
+ }
1405
+ catch (err) {
1406
+ fail(err);
1407
+ }
1408
+ });
1409
+ envGroups
1410
+ .command('rm-var <groupId> <key>')
1411
+ .description('Remove one variable from a group (the only way a secret one leaves)')
1412
+ .option('-y, --yes', 'skip the confirmation prompt')
1413
+ .action(async (groupId, key, opts, cmd) => {
1414
+ const g = globals(cmd);
1415
+ await confirmDestructive(opts.yes, `remove ${key} from env group ${groupId}`);
1416
+ try {
1417
+ await makeClient(g).envGroups.removeVar(groupId, key);
1418
+ success(`Removed ${key}`);
1419
+ }
1420
+ catch (err) {
1421
+ fail(err);
1422
+ }
1423
+ });
1070
1424
  envGroups
1071
1425
  .command('attach <groupId> <service>')
1072
1426
  .description('Attach a group to a service')
@@ -1129,7 +1483,7 @@ volumes
1129
1483
  const res = await client.services.volumes.add(id, mountPath, opts.name);
1130
1484
  if (g.json)
1131
1485
  return printJson(res);
1132
- success(`Attached volume at ${color.bold(res.mountPath)} (${res.id}) — applies on next deploy`);
1486
+ success(`Attached volume at ${color.bold(res.mountPath)} (${res.id}). Redeploy to apply it.`);
1133
1487
  }
1134
1488
  catch (err) {
1135
1489
  fail(err);
@@ -1137,7 +1491,7 @@ volumes
1137
1491
  });
1138
1492
  volumes
1139
1493
  .command('rm <service> <volumeId>')
1140
- .description('Detach a volume from a service (data retained)')
1494
+ .description('Detach a volume from a service (applies on next deploy; its data is deleted 7 days after detach)')
1141
1495
  .option('-y, --yes', 'skip the confirmation prompt')
1142
1496
  .action(async (ref, volumeId, opts, cmd) => {
1143
1497
  const g = globals(cmd);
@@ -1146,7 +1500,7 @@ volumes
1146
1500
  try {
1147
1501
  const id = await resolveServiceId(client, ref);
1148
1502
  await client.services.volumes.remove(id, volumeId);
1149
- success(`Detached ${volumeId}`);
1503
+ success(`Detached ${volumeId}. Its data will be deleted in 7 days. Redeploy to apply.`);
1150
1504
  }
1151
1505
  catch (err) {
1152
1506
  fail(err);
@@ -1172,7 +1526,7 @@ domainsCmd
1172
1526
  d.id,
1173
1527
  d.domain,
1174
1528
  d.verified ? 'yes' : 'no',
1175
- d.sslExpiresAt ? new Date(d.sslExpiresAt).toISOString().slice(0, 10) : '—',
1529
+ d.sslExpiresAt ? new Date(d.sslExpiresAt).toISOString().slice(0, 10) : '-',
1176
1530
  ]));
1177
1531
  }
1178
1532
  catch (err) {
@@ -1218,15 +1572,21 @@ domainsCmd
1218
1572
  if (g.json)
1219
1573
  return printJson(res);
1220
1574
  success(`Verified ${domainId}`);
1575
+ // Ownership is proven either way, so this stays exit 0; the certificate is what waits.
1576
+ if (res.pointing?.status === 'elsewhere') {
1577
+ const { found, expected } = res.pointing;
1578
+ process.stderr.write(`Points elsewhere (${found.length ? found.join(', ') : 'no records'}): HTTPS cannot ` +
1579
+ `issue until it has CNAME ${expected.cname}${expected.a ? ` or A ${expected.a}` : ''}.\n`);
1580
+ }
1221
1581
  }
1222
1582
  catch (err) {
1223
- // The API only ever answers `{verified: true}` or a 400 — one for "the TXT record is
1583
+ // The API only ever answers `{verified: true, ...}` or a 400 — one for "the TXT record is
1224
1584
  // not visible yet", one for "it does not match". Both mean the domain did not verify,
1225
1585
  // so the non-zero exit is right (it is what makes `until gheima domains verify <id>;
1226
1586
  // do sleep 30; done` terminate). Only the presentation needs help: the server's
1227
1587
  // sentence is actionable, a raw `bad_request` is not.
1228
1588
  if (err instanceof GheimaError && err.status === 400) {
1229
- process.stderr.write(`Not verified — ${err.message}\n`);
1589
+ process.stderr.write(`Not verified: ${err.message}\n`);
1230
1590
  process.exit(1);
1231
1591
  }
1232
1592
  fail(err);
@@ -1251,12 +1611,35 @@ domainsCmd
1251
1611
  });
1252
1612
  program
1253
1613
  .command('open [resource]')
1254
- .description('Open the dashboard (or a resource) in your browser')
1255
- .action((resource, _opts, cmd) => {
1614
+ .description('Open the dashboard, the linked service in it, or (--live) its live URL')
1615
+ .option('--live', 'open the service’s live URL instead (the linked one by default)')
1616
+ .action(async (resource, opts, cmd) => {
1256
1617
  const g = globals(cmd);
1257
1618
  const auth = resolveAuth(g);
1258
- const base = (g.url || auth?.url || 'https://gheima.ma').replace(/\/$/, '');
1259
- const url = resource ? `${base}/${resource.replace(/^\//, '')}` : base;
1619
+ // The dashboard origin. A configured API base (`…/v1`) names no dashboard, so fall back.
1620
+ const configured = (g.url || auth?.url || '').replace(/\/+$/, '');
1621
+ const base = configured && !configured.endsWith('/v1') ? configured : 'https://gheima.ma';
1622
+ const linked = findLink();
1623
+ let url = resource
1624
+ ? `${base}/${resource.replace(/^\//, '')}`
1625
+ : linked
1626
+ ? `${base}/services/${linked.link.serviceId}`
1627
+ : base;
1628
+ if (opts.live) {
1629
+ let live = null;
1630
+ try {
1631
+ const client = makeClient(g);
1632
+ const service = await client.services.get(await resolveServiceId(client, resource));
1633
+ live = service.url;
1634
+ }
1635
+ catch (err) {
1636
+ fail(err);
1637
+ }
1638
+ // A service with no route yet (never deployed, or a worker) has no live URL.
1639
+ if (!live)
1640
+ fail(new Error('This service has no live URL yet'));
1641
+ url = live;
1642
+ }
1260
1643
  if (g.json)
1261
1644
  return printJson({ url });
1262
1645
  // Never interpolate the URL into a shell: `start` needs cmd.exe, so go through
@@ -1274,7 +1657,7 @@ program
1274
1657
  });
1275
1658
  program
1276
1659
  .command('status')
1277
- .description('Show account + resource counts')
1660
+ .description('Show the account and its resource counts')
1278
1661
  .action(async (_opts, cmd) => {
1279
1662
  const g = globals(cmd);
1280
1663
  const client = makeClient(g);
@@ -1302,7 +1685,7 @@ program
1302
1685
  .command('completion [shell]')
1303
1686
  .description('Print a shell completion script (bash | zsh | fish)')
1304
1687
  .action((shell) => {
1305
- process.stdout.write(completionScript(shell || process.env.SHELL?.split('/').pop() || 'bash', program.commands.map((c) => c.name())));
1688
+ writeRaw(completionScript(shell || process.env.SHELL?.split('/').pop() || 'bash', program.commands.map((c) => c.name())));
1306
1689
  });
1307
1690
  /**
1308
1691
  * Everything above is hand-written, because those commands carry the experience: they
@@ -1340,6 +1723,21 @@ function isMainModule() {
1340
1723
  return false;
1341
1724
  }
1342
1725
  }
1343
- if (isMainModule()) {
1344
- program.parseAsync(process.argv).catch(fail);
1726
+ async function main() {
1727
+ await useProxyFromEnv();
1728
+ // The detached child updateNotice spawns: refresh the cache and exit, nothing else.
1729
+ if (process.argv[2] === REFRESH_ARG)
1730
+ return refreshUpdateCache();
1731
+ if (shouldCheck(process.argv)) {
1732
+ const notice = updateNotice(VERSION);
1733
+ if (notice)
1734
+ process.stderr.write(color.dim(`${notice}\n`));
1735
+ }
1736
+ await program.parseAsync(process.argv);
1737
+ }
1738
+ /** Run the CLI and turn any failure into its documented exit code. Both entries call this. */
1739
+ export function runCli() {
1740
+ main().catch(fail);
1345
1741
  }
1742
+ if (isMainModule())
1743
+ runCli();