@gheima/cli 0.4.0 → 0.6.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,30 +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';
16
- const require = createRequire(import.meta.url);
17
- const pkg = require('../package.json');
17
+ import { callOp, registerGenerated } from './generated.js';
18
+ import { findLink, toDotenv, writeLink } from './link.js';
19
+ import { defaultClientName, openBrowser, pollForApproval, startDeviceLogin, } from './device-login.js';
18
20
  const program = new Command();
19
21
  program
20
22
  .name('gheima')
21
- .description('Gheima platform CLI — deploy and manage services, databases, storage, and more.')
22
- .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')
23
25
  .option('-k, --key <key>', 'API key (overrides env + stored profile)')
24
26
  .option('-u, --url <url>', 'API base URL')
25
27
  .option('-p, --profile <name>', 'config profile to use')
26
- .option('--json', 'output machine-readable JSON')
27
- .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
+ });
28
51
  /** Global options merged across the program + the invoked subcommand. */
29
52
  function globals(cmd) {
30
53
  return cmd.optsWithGlobals();
@@ -36,8 +59,8 @@ function globals(cmd) {
36
59
  async function confirmDestructive(yes, whatWillHappen) {
37
60
  if (yes)
38
61
  return;
39
- if (!process.stdin.isTTY) {
40
- 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.`);
41
64
  }
42
65
  if (!(await confirm(`This will ${whatWillHappen}. Continue?`))) {
43
66
  process.stderr.write('Aborted.\n');
@@ -51,44 +74,108 @@ async function readStdin() {
51
74
  chunks.push(chunk);
52
75
  return Buffer.concat(chunks).toString('utf8');
53
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
+ */
54
81
  function fail(err) {
55
- if (err instanceof GheimaError) {
56
- 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');
57
92
  }
58
93
  else {
59
- 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
+ }
60
101
  }
61
- process.exit(1);
102
+ process.exit(exitCodeFor(err));
62
103
  }
63
104
  // ---------------------------------------------------------------------------
64
105
  // auth
65
106
  // ---------------------------------------------------------------------------
66
107
  program
67
108
  .command('login')
68
- .description('Authenticate with an API key and store it in a profile')
69
- .action(async (_opts, cmd) => {
109
+ .description('Sign in through the browser, or with an existing API key')
110
+ .option('--no-browser', 'print the URL instead of opening a browser')
111
+ .option('--with-key', 'paste an existing API key instead of using the browser')
112
+ .action(async (opts, cmd) => {
70
113
  const g = globals(cmd);
71
114
  const profileName = g.profile || 'default';
115
+ const baseUrl = g.url || process.env.GHEIMA_URL || DEFAULT_API_URL;
116
+ // `--key` on the program means the caller already has a credential and is not asking to
117
+ // be sent through a browser at all.
118
+ const pasteInstead = opts.withKey || Boolean(g.key);
119
+ if (!pasteInstead) {
120
+ try {
121
+ await browserLogin(baseUrl, profileName, opts.browser !== false, g.url);
122
+ return;
123
+ }
124
+ catch (err) {
125
+ fail(err);
126
+ }
127
+ }
72
128
  let key = g.key;
73
129
  if (!key) {
74
- info('Create an API key in the dashboard → Settings → API keys.');
130
+ info('Create an API key in the dashboard under Settings > API keys.');
75
131
  key = await promptHidden('Paste your API key (gh_…): ');
76
132
  }
77
133
  if (!key)
78
134
  fail('No API key provided.');
79
- const client = new GheimaClient({ apiKey: key, baseUrl: g.url });
135
+ const client = new GheimaClient(transportOptions({ apiKey: key, url: g.url }));
80
136
  const spin = spinner('Verifying key…');
81
137
  try {
82
138
  const account = await client.account.get();
83
139
  spin.stop();
84
140
  setProfile(profileName, { apiKey: key, url: g.url });
85
- 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}"`);
86
142
  }
87
143
  catch (err) {
88
144
  spin.stop();
89
145
  fail(err);
90
146
  }
91
147
  });
148
+ /**
149
+ * Browser half of `gheima login`.
150
+ *
151
+ * The user code is printed BEFORE the browser opens, and printed again if opening fails, so
152
+ * the flow never depends on a browser launching. On a headless box `--no-browser` prints the
153
+ * URL and the code and nothing else is needed.
154
+ */
155
+ async function browserLogin(baseUrl, profileName, wantBrowser, urlOverride) {
156
+ const started = await startDeviceLogin(baseUrl, defaultClientName());
157
+ info(`Your code is ${color.bold(started.user_code)}`);
158
+ info(`Open ${color.bold(started.verification_uri_complete)} and approve it.`);
159
+ if (wantBrowser && !openBrowser(started.verification_uri_complete)) {
160
+ info('Could not open a browser. Open the URL above yourself.');
161
+ }
162
+ const spin = spinner('Waiting for approval…');
163
+ try {
164
+ const result = await pollForApproval(baseUrl, started, {
165
+ onSlowDown: (seconds) => info(`The server asked for slower polling. Checking every ${seconds}s now.`),
166
+ });
167
+ spin.stop();
168
+ setProfile(profileName, { apiKey: result.apiKey, url: urlOverride });
169
+ const client = new GheimaClient(transportOptions({ apiKey: result.apiKey, url: urlOverride }));
170
+ const account = await client.account.get();
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.`);
173
+ }
174
+ catch (err) {
175
+ spin.stop();
176
+ throw err;
177
+ }
178
+ }
92
179
  program
93
180
  .command('logout')
94
181
  .description('Remove a stored profile')
@@ -108,10 +195,17 @@ program
108
195
  const client = makeClient(g);
109
196
  try {
110
197
  const account = await client.account.get();
111
- if (g.json)
112
- 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.
113
200
  const auth = resolveAuth(g);
114
- 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}`);
115
209
  table(['Name', 'Slug', 'Plan', 'Type'], [[account.name, account.slug, account.plan, account.type]]);
116
210
  }
117
211
  catch (err) {
@@ -127,7 +221,7 @@ program
127
221
  const res = await makeClient(g).account.getSpendCap();
128
222
  if (g.json)
129
223
  return printJson(res);
130
- 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)]]);
131
225
  }
132
226
  catch (err) {
133
227
  fail(err);
@@ -196,10 +290,12 @@ services
196
290
  services
197
291
  .command('create')
198
292
  .description('Create a service')
199
- .option('--project <id>', 'project folder id (omitted → the service is ungrouped)')
293
+ .option('--project <id>', 'project id (omit it to leave the service ungrouped)')
200
294
  .requiredOption('--name <name>', 'service name')
201
295
  .option('--type <type>', 'WEB | WORKER | STATIC', 'WEB')
202
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)')
203
299
  .action(async (opts, cmd) => {
204
300
  const g = globals(cmd);
205
301
  try {
@@ -208,6 +304,8 @@ services
208
304
  name: opts.name,
209
305
  type: opts.type,
210
306
  repoUrl: opts.repo,
307
+ dockerImage: opts.image,
308
+ port: opts.port === undefined ? undefined : Number(opts.port),
211
309
  });
212
310
  if (g.json)
213
311
  return printJson(created);
@@ -311,7 +409,7 @@ program
311
409
  s.timezone,
312
410
  String(s.retentionCount),
313
411
  s.enabled ? 'yes' : 'no',
314
- s.nextRunAt ?? '—',
412
+ s.nextRunAt ?? '-',
315
413
  ],
316
414
  ]);
317
415
  }
@@ -357,9 +455,7 @@ program
357
455
  fail(err);
358
456
  }
359
457
  });
360
- const search = program
361
- .command('search')
362
- .description('Manage managed search (Meilisearch) instances');
458
+ const search = program.command('search').description('Manage search (Meilisearch) instances');
363
459
  search
364
460
  .command('list', { isDefault: true })
365
461
  .description('List search instances')
@@ -392,7 +488,7 @@ search
392
488
  });
393
489
  search
394
490
  .command('reveal <id>')
395
- .description('Reveal host + scoped API key + index prefix')
491
+ .description('Reveal the host, scoped API key and index prefix')
396
492
  .action(async (id, _opts, cmd) => {
397
493
  const g = globals(cmd);
398
494
  try {
@@ -435,7 +531,7 @@ search
435
531
  });
436
532
  const emailCmd = program
437
533
  .command('email')
438
- .description('Manage transactional email (sending domains + send)');
534
+ .description('Manage transactional email: sending domains and sending');
439
535
  emailCmd
440
536
  .command('domains', { isDefault: true })
441
537
  .description('List sending domains')
@@ -476,7 +572,10 @@ emailCmd
476
572
  const res = await makeClient(g).email.domains.verify(id);
477
573
  if (g.json)
478
574
  return printJson(res);
479
- 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.');
480
579
  }
481
580
  catch (err) {
482
581
  fail(err);
@@ -538,7 +637,10 @@ ssoCmd
538
637
  const res = await makeClient(g).sso.verify(id);
539
638
  if (g.json)
540
639
  return printJson(res);
541
- 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.');
542
644
  }
543
645
  catch (err) {
544
646
  fail(err);
@@ -563,14 +665,22 @@ templates
563
665
  templates
564
666
  .command('deploy <templateId> <name>')
565
667
  .description('Deploy a template (omit --project to leave the service ungrouped)')
566
- .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)")
567
670
  .action(async (templateId, name, opts, cmd) => {
568
671
  const g = globals(cmd);
569
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
+ });
570
679
  const res = await makeClient(g).templates.deploy({
571
680
  templateId,
572
681
  name,
573
682
  projectId: opts.project,
683
+ env: env ? Object.fromEntries(env) : undefined,
574
684
  });
575
685
  if (g.json)
576
686
  return printJson(res);
@@ -580,9 +690,7 @@ templates
580
690
  fail(err);
581
691
  }
582
692
  });
583
- const queues = program
584
- .command('queues')
585
- .description('Manage managed job queues (BullMQ-ready Redis)');
693
+ const queues = program.command('queues').description('Manage job queues (Redis, ready for BullMQ)');
586
694
  queues
587
695
  .command('list', { isDefault: true })
588
696
  .description('List job queues')
@@ -615,7 +723,7 @@ queues
615
723
  });
616
724
  queues
617
725
  .command('reveal <id>')
618
- .description('Reveal the Redis connection string + key prefix')
726
+ .description('Reveal the Redis connection string and key prefix')
619
727
  .action(async (id, _opts, cmd) => {
620
728
  const g = globals(cmd);
621
729
  try {
@@ -697,7 +805,7 @@ storage
697
805
  process.stdout.write(`${color.dim(p)}\n`);
698
806
  table(['Key', 'Size', 'Modified'], objects.map((o) => [o.key, o.size, o.lastModified]));
699
807
  if (token)
700
- 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.`);
701
809
  }
702
810
  catch (err) {
703
811
  fail(err);
@@ -798,7 +906,19 @@ program
798
906
  // deploy / logs / env / open / status
799
907
  // ---------------------------------------------------------------------------
800
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
+ */
801
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
+ }
802
922
  const all = await client.services.list().all();
803
923
  const match = all.find((s) => s.id === ref || s.name === ref || s.slug === ref);
804
924
  if (!match)
@@ -830,28 +950,115 @@ program
830
950
  fail(err);
831
951
  }
832
952
  });
953
+ /** Statuses a deployment never leaves. Anything else, including a status added later, waits. */
954
+ const FINISHED = new Set(['LIVE', 'FAILED', 'CANCELLED', 'SKIPPED']);
833
955
  program
834
- .command('deploy [service]')
835
- .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')
836
958
  .action(async (ref, _opts, cmd) => {
837
959
  const g = globals(cmd);
838
- const client = makeClient(g);
839
960
  try {
840
- if (!ref)
841
- 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
+ }
842
989
  const id = await resolveServiceId(client, ref);
843
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);
844
998
  if (g.json)
845
- return printJson({ deploymentId });
846
- success(`Deployment queued: ${color.bold(deploymentId)}`);
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);
847
1008
  }
848
1009
  catch (err) {
849
1010
  fail(err);
850
1011
  }
851
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` asks for the outcome. Tests shorten it. */
1058
+ const POLL_MS = Number(process.env.GHEIMA_DEPLOY_POLL_MS) || 3000;
852
1059
  program
853
- .command('logs <service>')
854
- .description('Show or tail service logs')
1060
+ .command('logs [service]')
1061
+ .description('Show or tail service logs (the linked service by default)')
855
1062
  .option('-f, --follow', 'stream new log lines')
856
1063
  .option('-b, --build', 'show build logs instead of runtime')
857
1064
  .option('-s, --search <text>', 'filter lines containing text')
@@ -863,8 +1070,11 @@ program
863
1070
  const type = opts.build ? 'build' : 'runtime';
864
1071
  if (opts.follow) {
865
1072
  for await (const entry of client.services.streamLogs(id, { type, search: opts.search })) {
866
- const line = entry.line ?? JSON.stringify(entry);
867
- process.stdout.write(`${line}\n`);
1073
+ // --json: one entry per line (NDJSON), so `| jq` works on a stream that never ends.
1074
+ if (isJsonMode())
1075
+ printJsonLine(entry);
1076
+ else
1077
+ process.stdout.write(`${entry.line ?? JSON.stringify(entry)}\n`);
868
1078
  }
869
1079
  return;
870
1080
  }
@@ -880,8 +1090,9 @@ program
880
1090
  });
881
1091
  const env = program.command('env').description('Manage service environment variables');
882
1092
  env
883
- .command('pull <service>')
884
- .description('List env var keys (values are never returned)')
1093
+ .command('ls [service]')
1094
+ .alias('list')
1095
+ .description('List env var keys, values masked (the linked service by default)')
885
1096
  .action(async (ref, _opts, cmd) => {
886
1097
  const g = globals(cmd);
887
1098
  const client = makeClient(g);
@@ -890,7 +1101,82 @@ env
890
1101
  const vars = await client.services.env.list(id);
891
1102
  if (g.json)
892
1103
  return printJson(vars);
893
- table(['Key', 'Value'], vars.map((v) => [v.key, v.masked]));
1104
+ table(['Key', 'Value'],
1105
+ // A secret's value is never returned; show a marker, never anything value-shaped.
1106
+ vars.map((v) => [v.key, v.secret ? '(secret)' : v.masked]));
1107
+ }
1108
+ catch (err) {
1109
+ fail(err);
1110
+ }
1111
+ });
1112
+ env
1113
+ .command('pull [service]')
1114
+ .description('Write the service’s env vars to .env.local (the linked service by default)')
1115
+ .option('--file <path>', 'where to write', '.env.local')
1116
+ .option('-f, --force', 'overwrite the file if it exists')
1117
+ .option('--stdout', 'print the values instead of writing a file')
1118
+ .action(async (ref, opts, cmd) => {
1119
+ const g = globals(cmd);
1120
+ try {
1121
+ // Checked before anything is fetched, so a refusal reveals nothing.
1122
+ if (!opts.stdout && existsSync(opts.file) && !opts.force) {
1123
+ throw new UsageError(`${opts.file} already exists. Pass --force to overwrite it.`);
1124
+ }
1125
+ const client = makeClient(g);
1126
+ const id = await resolveServiceId(client, ref);
1127
+ const { data: vars } = (await callOp('services.revealEnv', { id }, g));
1128
+ const { text: dotenv, skipped } = toDotenv(vars);
1129
+ if (skipped.length) {
1130
+ process.stderr.write(`${color.yellow('Warning')}: left out ${skipped.join(', ')}: a value holding a ' or a ` +
1131
+ `newline and also a literal \\n or \\t cannot survive a .env round trip.\n`);
1132
+ }
1133
+ // Values reach stdout only when asked for by name: never by default, never via --json.
1134
+ if (opts.stdout)
1135
+ return writeRaw(dotenv);
1136
+ // `mode` applies only when the file is created: an existing one overwritten with
1137
+ // --force keeps whatever it had, which is usually world-readable, so tighten it
1138
+ // BEFORE the values are written.
1139
+ if (existsSync(opts.file))
1140
+ chmodSync(opts.file, 0o600);
1141
+ writeFileSync(opts.file, dotenv, { mode: 0o600 });
1142
+ const count = vars.length - skipped.length;
1143
+ if (g.json)
1144
+ return printJson({ file: opts.file, count, skipped });
1145
+ success(`Wrote ${count} variables to ${opts.file}`);
1146
+ // Exit 1 from check-ignore means "inside a repo, and NOT ignored": one `git add .` from
1147
+ // committing the values. Anything else (ignored, no repo, no git) says nothing.
1148
+ if (spawnSync('git', ['check-ignore', '-q', opts.file], { stdio: 'ignore' }).status === 1) {
1149
+ process.stderr.write(`${color.yellow('Warning')}: ${opts.file} is not ignored by git. Add it to .gitignore.\n`);
1150
+ }
1151
+ info('Variables marked secret cannot be read back, so they are not in the file.');
1152
+ }
1153
+ catch (err) {
1154
+ fail(err);
1155
+ }
1156
+ });
1157
+ env
1158
+ .command('push [service]')
1159
+ .description('Upload a .env file to the service (merges; the linked service by default)')
1160
+ .option('--file <path>', 'the file to upload', '.env.local')
1161
+ .option('--replace', 'discard variables not in the file (secret ones are kept)')
1162
+ .option('-y, --yes', 'skip the confirmation --replace asks for')
1163
+ .action(async (ref, opts, cmd) => {
1164
+ const g = globals(cmd);
1165
+ try {
1166
+ if (!existsSync(opts.file))
1167
+ throw new UsageError(`${opts.file} does not exist. Pass --file.`);
1168
+ const dotenv = readFileSync(opts.file, 'utf8');
1169
+ const client = makeClient(g);
1170
+ const id = await resolveServiceId(client, ref);
1171
+ if (opts.replace) {
1172
+ await confirmDestructive(opts.yes, `replace every non-secret variable with ${opts.file}`);
1173
+ }
1174
+ const res = (await callOp('services.importEnv', { id, dotenv, replace: Boolean(opts.replace) }, g));
1175
+ if (g.json)
1176
+ return printJson(res);
1177
+ success(`Imported ${res.imported} of ${res.total} variables. Redeploy to apply them.`);
1178
+ if (res.invalidLines.length)
1179
+ info(`Skipped unparseable lines: ${res.invalidLines.join(', ')}`);
894
1180
  }
895
1181
  catch (err) {
896
1182
  fail(err);
@@ -901,6 +1187,7 @@ env
901
1187
  .description('Set an env var (KEY=value, or KEY with --stdin / --from-file)')
902
1188
  .option('--stdin', 'read the value from stdin instead of the command line')
903
1189
  .option('--from-file <path>', 'read the value from a file instead of the command line')
1190
+ .option('--secret', 'make the variable write-only: never shown or returned again (one-way)')
904
1191
  .action(async (ref, pair, opts, cmd) => {
905
1192
  const g = globals(cmd);
906
1193
  const client = makeClient(g);
@@ -922,7 +1209,7 @@ env
922
1209
  ? (await readStdin()).replace(/\r?\n$/, '')
923
1210
  : pair.slice(eq + 1);
924
1211
  const id = await resolveServiceId(client, ref);
925
- await client.services.env.set(id, key, value);
1212
+ await client.services.env.set(id, key, value, { secret: opts.secret });
926
1213
  success(`Set ${key}`);
927
1214
  }
928
1215
  catch (err) {
@@ -998,18 +1285,21 @@ envGroups
998
1285
  envGroups
999
1286
  .command('import <groupId> <file>')
1000
1287
  .description('Import a .env file into a group (merges; --replace to overwrite)')
1001
- .option('--replace', 'Replace all variables instead of merging')
1288
+ .option('--replace', 'Replace all variables instead of merging (secret variables are kept)')
1289
+ .option('--secret', 'Mark every imported variable secret (write-only, one-way)')
1002
1290
  .option('-y, --yes', 'skip the confirmation prompt for --replace')
1003
1291
  .action(async (groupId, file, opts, cmd) => {
1004
1292
  const g = globals(cmd);
1005
- // --replace drops every variable already in the group, across every service the
1006
- // group is attached to. Treat it like the other destructive commands.
1293
+ // --replace drops every non-secret variable already in the group, across every service
1294
+ // the group is attached to. Treat it like the other destructive commands.
1007
1295
  if (opts.replace) {
1008
- await confirmDestructive(opts.yes, `replace every variable in env group ${groupId} with the contents of ${file}`);
1296
+ await confirmDestructive(opts.yes, `replace every non-secret variable in env group ${groupId} with the contents of ${file} (secret variables are kept)`);
1009
1297
  }
1010
1298
  try {
1011
1299
  const dotenv = readFileSync(file, 'utf8');
1012
- const res = await makeClient(g).envGroups.import(groupId, dotenv, !!opts.replace);
1300
+ const res = await makeClient(g).envGroups.import(groupId, dotenv, !!opts.replace, {
1301
+ secret: opts.secret,
1302
+ });
1013
1303
  if (g.json)
1014
1304
  return printJson(res);
1015
1305
  success(`Imported ${res.imported} var(s); ${res.total} total`);
@@ -1020,6 +1310,43 @@ envGroups
1020
1310
  fail(err);
1021
1311
  }
1022
1312
  });
1313
+ envGroups
1314
+ .command('set-var <groupId> <pair>')
1315
+ .description('Set one variable of a group (KEY=value, or KEY with --stdin)')
1316
+ .option('--stdin', 'read the value from stdin instead of the command line')
1317
+ .option('--secret', 'make the variable write-only: never shown or returned again (one-way)')
1318
+ .action(async (groupId, pair, opts, cmd) => {
1319
+ const g = globals(cmd);
1320
+ const eq = pair.indexOf('=');
1321
+ if (!opts.stdin && eq < 1)
1322
+ fail('Expected KEY=value (or KEY with --stdin)');
1323
+ if (opts.stdin && eq !== -1)
1324
+ fail('Pass the bare KEY when reading the value from stdin');
1325
+ const key = opts.stdin ? pair : pair.slice(0, eq);
1326
+ try {
1327
+ const value = opts.stdin ? (await readStdin()).replace(/\r?\n$/, '') : pair.slice(eq + 1);
1328
+ await makeClient(g).envGroups.setVar(groupId, key, value, { secret: opts.secret });
1329
+ success(`Set ${key}`);
1330
+ }
1331
+ catch (err) {
1332
+ fail(err);
1333
+ }
1334
+ });
1335
+ envGroups
1336
+ .command('rm-var <groupId> <key>')
1337
+ .description('Remove one variable from a group (the only way a secret one leaves)')
1338
+ .option('-y, --yes', 'skip the confirmation prompt')
1339
+ .action(async (groupId, key, opts, cmd) => {
1340
+ const g = globals(cmd);
1341
+ await confirmDestructive(opts.yes, `remove ${key} from env group ${groupId}`);
1342
+ try {
1343
+ await makeClient(g).envGroups.removeVar(groupId, key);
1344
+ success(`Removed ${key}`);
1345
+ }
1346
+ catch (err) {
1347
+ fail(err);
1348
+ }
1349
+ });
1023
1350
  envGroups
1024
1351
  .command('attach <groupId> <service>')
1025
1352
  .description('Attach a group to a service')
@@ -1082,7 +1409,7 @@ volumes
1082
1409
  const res = await client.services.volumes.add(id, mountPath, opts.name);
1083
1410
  if (g.json)
1084
1411
  return printJson(res);
1085
- success(`Attached volume at ${color.bold(res.mountPath)} (${res.id}) — applies on next deploy`);
1412
+ success(`Attached volume at ${color.bold(res.mountPath)} (${res.id}). Redeploy to apply it.`);
1086
1413
  }
1087
1414
  catch (err) {
1088
1415
  fail(err);
@@ -1090,7 +1417,7 @@ volumes
1090
1417
  });
1091
1418
  volumes
1092
1419
  .command('rm <service> <volumeId>')
1093
- .description('Detach a volume from a service (data retained)')
1420
+ .description('Detach a volume from a service (applies on next deploy; its data is deleted 7 days after detach)')
1094
1421
  .option('-y, --yes', 'skip the confirmation prompt')
1095
1422
  .action(async (ref, volumeId, opts, cmd) => {
1096
1423
  const g = globals(cmd);
@@ -1099,7 +1426,7 @@ volumes
1099
1426
  try {
1100
1427
  const id = await resolveServiceId(client, ref);
1101
1428
  await client.services.volumes.remove(id, volumeId);
1102
- success(`Detached ${volumeId}`);
1429
+ success(`Detached ${volumeId}. Its data will be deleted in 7 days. Redeploy to apply.`);
1103
1430
  }
1104
1431
  catch (err) {
1105
1432
  fail(err);
@@ -1125,7 +1452,7 @@ domainsCmd
1125
1452
  d.id,
1126
1453
  d.domain,
1127
1454
  d.verified ? 'yes' : 'no',
1128
- d.sslExpiresAt ? new Date(d.sslExpiresAt).toISOString().slice(0, 10) : '—',
1455
+ d.sslExpiresAt ? new Date(d.sslExpiresAt).toISOString().slice(0, 10) : '-',
1129
1456
  ]));
1130
1457
  }
1131
1458
  catch (err) {
@@ -1171,15 +1498,21 @@ domainsCmd
1171
1498
  if (g.json)
1172
1499
  return printJson(res);
1173
1500
  success(`Verified ${domainId}`);
1501
+ // Ownership is proven either way, so this stays exit 0; the certificate is what waits.
1502
+ if (res.pointing?.status === 'elsewhere') {
1503
+ const { found, expected } = res.pointing;
1504
+ process.stderr.write(`Points elsewhere (${found.length ? found.join(', ') : 'no records'}): HTTPS cannot ` +
1505
+ `issue until it has CNAME ${expected.cname}${expected.a ? ` or A ${expected.a}` : ''}.\n`);
1506
+ }
1174
1507
  }
1175
1508
  catch (err) {
1176
- // The API only ever answers `{verified: true}` or a 400 — one for "the TXT record is
1509
+ // The API only ever answers `{verified: true, ...}` or a 400 — one for "the TXT record is
1177
1510
  // not visible yet", one for "it does not match". Both mean the domain did not verify,
1178
1511
  // so the non-zero exit is right (it is what makes `until gheima domains verify <id>;
1179
1512
  // do sleep 30; done` terminate). Only the presentation needs help: the server's
1180
1513
  // sentence is actionable, a raw `bad_request` is not.
1181
1514
  if (err instanceof GheimaError && err.status === 400) {
1182
- process.stderr.write(`Not verified — ${err.message}\n`);
1515
+ process.stderr.write(`Not verified: ${err.message}\n`);
1183
1516
  process.exit(1);
1184
1517
  }
1185
1518
  fail(err);
@@ -1204,12 +1537,30 @@ domainsCmd
1204
1537
  });
1205
1538
  program
1206
1539
  .command('open [resource]')
1207
- .description('Open the dashboard (or a resource) in your browser')
1208
- .action((resource, _opts, cmd) => {
1540
+ .description('Open the dashboard, the linked service in it, or (--live) its live URL')
1541
+ .option('--live', 'open the service’s live URL instead (the linked one by default)')
1542
+ .action(async (resource, opts, cmd) => {
1209
1543
  const g = globals(cmd);
1210
1544
  const auth = resolveAuth(g);
1211
- const base = (g.url || auth?.url || 'https://gheima.ma').replace(/\/$/, '');
1212
- const url = resource ? `${base}/${resource.replace(/^\//, '')}` : base;
1545
+ // The dashboard origin. A configured API base (`…/v1`) names no dashboard, so fall back.
1546
+ const configured = (g.url || auth?.url || '').replace(/\/+$/, '');
1547
+ const base = configured && !configured.endsWith('/v1') ? configured : 'https://gheima.ma';
1548
+ const linked = findLink();
1549
+ let url = resource
1550
+ ? `${base}/${resource.replace(/^\//, '')}`
1551
+ : linked
1552
+ ? `${base}/services/${linked.link.serviceId}`
1553
+ : base;
1554
+ if (opts.live) {
1555
+ try {
1556
+ const client = makeClient(g);
1557
+ const service = await client.services.get(await resolveServiceId(client, resource));
1558
+ url = service.url;
1559
+ }
1560
+ catch (err) {
1561
+ fail(err);
1562
+ }
1563
+ }
1213
1564
  if (g.json)
1214
1565
  return printJson({ url });
1215
1566
  // Never interpolate the URL into a shell: `start` needs cmd.exe, so go through
@@ -1227,7 +1578,7 @@ program
1227
1578
  });
1228
1579
  program
1229
1580
  .command('status')
1230
- .description('Show account + resource counts')
1581
+ .description('Show the account and its resource counts')
1231
1582
  .action(async (_opts, cmd) => {
1232
1583
  const g = globals(cmd);
1233
1584
  const client = makeClient(g);
@@ -1255,7 +1606,7 @@ program
1255
1606
  .command('completion [shell]')
1256
1607
  .description('Print a shell completion script (bash | zsh | fish)')
1257
1608
  .action((shell) => {
1258
- process.stdout.write(completionScript(shell || process.env.SHELL?.split('/').pop() || 'bash', program.commands.map((c) => c.name())));
1609
+ writeRaw(completionScript(shell || process.env.SHELL?.split('/').pop() || 'bash', program.commands.map((c) => c.name())));
1259
1610
  });
1260
1611
  /**
1261
1612
  * Everything above is hand-written, because those commands carry the experience: they
@@ -1293,6 +1644,21 @@ function isMainModule() {
1293
1644
  return false;
1294
1645
  }
1295
1646
  }
1296
- if (isMainModule()) {
1297
- program.parseAsync(process.argv).catch(fail);
1647
+ async function main() {
1648
+ await useProxyFromEnv();
1649
+ // The detached child updateNotice spawns: refresh the cache and exit, nothing else.
1650
+ if (process.argv[2] === REFRESH_ARG)
1651
+ return refreshUpdateCache();
1652
+ if (shouldCheck(process.argv)) {
1653
+ const notice = updateNotice(VERSION);
1654
+ if (notice)
1655
+ process.stderr.write(color.dim(`${notice}\n`));
1656
+ }
1657
+ await program.parseAsync(process.argv);
1658
+ }
1659
+ /** Run the CLI and turn any failure into its documented exit code. Both entries call this. */
1660
+ export function runCli() {
1661
+ main().catch(fail);
1298
1662
  }
1663
+ if (isMainModule())
1664
+ runCli();