@jinshuju/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/README.md CHANGED
@@ -29,30 +29,27 @@ its execute bit — `npm run build` restores it.
29
29
 
30
30
  ## Authentication
31
31
 
32
- Three kinds of credential are supported: an access token (personal or account),
33
- an API key and secret pair, and an interactive browser login.
34
-
35
- Write them to the config file (`~/.jinshuju/config.json`, mode 600):
32
+ Two kinds of credential are supported: an interactive browser login (OAuth),
33
+ and an access token (personal or account). Both go in through `auth login`:
36
34
 
37
35
  ```bash
38
- jinshuju config set access_token xxx # access token
39
- jinshuju config set api_key xxx # or API key / secret
40
- jinshuju config set api_secret xxx
36
+ jinshuju auth login # browser login
37
+ jinshuju auth login --access-token xxx # access token, checked before it is stored
41
38
  ```
42
39
 
43
- Environment variables work just as well, which suits CI and scripts:
40
+ Either one is written to the config file (`~/.jinshuju/config.json`, mode 600)
41
+ and replaces whatever credential was stored before. `jinshuju auth logout`
42
+ forgets it (revoking it first, for a browser session).
43
+
44
+ For CI and scripts, an environment variable works without touching the file:
44
45
 
45
46
  ```bash
46
47
  export JINSHUJU_ACCESS_TOKEN=xxx
47
- # or
48
- export JINSHUJU_API_KEY=xxx
49
- export JINSHUJU_API_SECRET=xxx
50
48
  ```
51
49
 
52
- The **precedence** is access token, then API key and secret, then a stored
53
- browser login (`jinshuju auth login`). An explicitly configured credential
54
- always beats a stored session: setting a token and then acting as last week's
55
- login is a surprise nobody wants. `jinshuju auth status` reports which
50
+ The **precedence** is `JINSHUJU_ACCESS_TOKEN`, then the stored credential. A
51
+ token set for this run always beats a stored login: acting as last week's
52
+ login instead is a surprise nobody wants. `jinshuju auth status` reports which
56
53
  credential is in use and where it came from:
57
54
 
58
55
  ```
@@ -60,8 +57,8 @@ $ jinshuju auth status
60
57
  Authenticated with an access token (from env).
61
58
  ```
62
59
 
63
- Access tokens are masked in `config get` like any other secret; pass
64
- `--show-secret` for the full value.
60
+ `config set` holds only `host`, `auth_host` and `client_id`; credentials are
61
+ not config.
65
62
 
66
63
  ## Creating forms
67
64
 
@@ -242,6 +239,8 @@ jinshuju entry search repair --scope-filter 'entries_count gt 100' # picks whi
242
239
 
243
240
  jinshuju entry stats --from 2026-09-01 # how much each form received in the period
244
241
  jinshuju entry stats --from 2026-09-01 --to 2026-09-07 --kind form --limit 10
242
+ jinshuju entry stats --from 2026-09-28 --by day # the same, split into each day, in one call
243
+ jinshuju entry stats --from 2026-01-01 --by month # or by week / month: at most 92 days, 53 weeks, 24 months
245
244
  ```
246
245
 
247
246
  A form that could not be searched stays in the result **with the reason**,
package/dist/auth.d.ts CHANGED
@@ -11,7 +11,6 @@ export type OAuthLoginOptions = LoadConfigOptions & {
11
11
  authHost?: string;
12
12
  clientId?: string;
13
13
  scopes?: string;
14
- openBrowser?: boolean;
15
14
  timeoutMs?: number;
16
15
  port?: number;
17
16
  };
@@ -35,5 +34,9 @@ export declare function buildAuthorizationUrl(params: {
35
34
  }): string;
36
35
  export declare function loginWithOAuth(options?: OAuthLoginOptions, opener?: BrowserOpener): Promise<OAuthLoginResult>;
37
36
  export declare function refreshOAuthToken(config: LoadedConfig): Promise<OAuthConfig>;
38
- export declare function revokeOAuthToken(config: LoadedConfig): Promise<void>;
37
+ /**
38
+ * Revokes a stored OAuth session, then forgets whatever credential is stored.
39
+ * An access token has no revoke endpoint here; it is only forgotten.
40
+ */
41
+ export declare function logout(config: LoadedConfig): Promise<void>;
39
42
  export declare function shouldRefresh(auth: OAuthConfig, skewMs?: number): boolean;
package/dist/auth.js CHANGED
@@ -2,7 +2,7 @@ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
2
  import { createServer } from 'node:http';
3
3
  import { execFile } from 'node:child_process';
4
4
  import { AuthError } from './errors.js';
5
- import { clearOAuthConfig, defaultScopes, loadConfig, saveOAuthConfig } from './config.js';
5
+ import { clearCredential, defaultScopes, loadConfig, saveOAuthConfig } from './config.js';
6
6
  function base64Url(bytes) {
7
7
  return bytes.toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
8
8
  }
@@ -47,8 +47,7 @@ export async function loginWithOAuth(options = {}, opener = openUrl) {
47
47
  // state, a refusal — and a rejection nobody is awaiting yet is reported as
48
48
  // unhandled. It is awaited right below; this only says so in the meantime.
49
49
  callback.code.catch(() => undefined);
50
- if (options.openBrowser !== false)
51
- await opener(authorizeUrl);
50
+ await opener(authorizeUrl);
52
51
  const code = await callback.code;
53
52
  const token = await exchangeAuthorizationCode(config.authHost, clientId, callback.redirectUri, code, verifier);
54
53
  const auth = toOAuthConfig(config, clientId, token);
@@ -67,17 +66,21 @@ export async function refreshOAuthToken(config) {
67
66
  saveOAuthConfig(config.configPath, auth);
68
67
  return auth;
69
68
  }
70
- export async function revokeOAuthToken(config) {
71
- if (!config.auth?.access_token)
72
- return;
73
- const url = new URL('/oauth/revoke', config.auth.auth_host);
74
- await fetch(url, {
75
- method: 'POST',
76
- headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
77
- body: new URLSearchParams({ client_id: config.auth.client_id, token: config.auth.access_token }),
78
- signal: AbortSignal.timeout(config.timeoutMs ?? TOKEN_TIMEOUT_MS)
79
- }).catch(() => undefined);
80
- clearOAuthConfig(config.configPath);
69
+ /**
70
+ * Revokes a stored OAuth session, then forgets whatever credential is stored.
71
+ * An access token has no revoke endpoint here; it is only forgotten.
72
+ */
73
+ export async function logout(config) {
74
+ if (config.auth?.access_token) {
75
+ const url = new URL('/oauth/revoke', config.auth.auth_host);
76
+ await fetch(url, {
77
+ method: 'POST',
78
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
79
+ body: new URLSearchParams({ client_id: config.auth.client_id, token: config.auth.access_token }),
80
+ signal: AbortSignal.timeout(config.timeoutMs ?? TOKEN_TIMEOUT_MS)
81
+ }).catch(() => undefined);
82
+ }
83
+ clearCredential(config.configPath);
81
84
  }
82
85
  export function shouldRefresh(auth, skewMs = 60_000) {
83
86
  if (!auth.expires_at)
package/dist/cli-bin.js CHANGED
@@ -1,6 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import { runCli } from './cli.js';
3
- const result = await runCli(process.argv.slice(2), { stdout: (chunk) => void process.stdout.write(chunk) });
3
+ import { styleFor } from './style.js';
4
+ const result = await runCli(process.argv.slice(2), {
5
+ stdout: (chunk) => void process.stdout.write(chunk),
6
+ terminal: { stdout: styleFor(process.stdout), stderr: styleFor(process.stderr) }
7
+ });
4
8
  if (result.stdout)
5
9
  process.stdout.write(result.stdout);
6
10
  if (result.stderr)
package/dist/cli.js CHANGED
@@ -19,20 +19,21 @@ export async function runCli(args = [], runtime = {}) {
19
19
  const stdin = runtime.stdin ?? readStdin;
20
20
  if (flags['--version'] || flags['-V'])
21
21
  return ok(VERSION);
22
+ const terminal = runtime.terminal ?? {};
22
23
  if (args.length === 0)
23
- return ok(rootHelp());
24
+ return ok(rootHelp(undefined, terminal.stdout));
24
25
  if (flags['--help'] || flags['-h'])
25
- return ok(helpFor(words));
26
+ return ok(helpFor(words, undefined, terminal.stdout));
26
27
  const resource = words[0];
27
28
  try {
28
29
  if (resource === 'auth' || resource === 'config')
29
30
  return await runLocal(words, flags, runtime, stdin);
30
31
  if (!command)
31
- return unknown(words, outputOf(flags));
32
+ return unknown(words, outputOf(flags), terminal.stderr);
32
33
  return await runRemote(command, words, flags, runtime, stdin);
33
34
  }
34
35
  catch (error) {
35
- return fail(error, outputOf(flags));
36
+ return fail(error, outputOf(flags), terminal.stderr);
36
37
  }
37
38
  }
38
39
  async function runRemote(command, words, flags, runtime, stdin) {
@@ -46,11 +47,7 @@ async function runRemote(command, words, flags, runtime, stdin) {
46
47
  new JinshujuHttpClient(loadConfig({
47
48
  configPath: options.config ?? defaultConfigPath,
48
49
  env: runtime.env,
49
- cli: {
50
- apiKey: options.api_key,
51
- apiSecret: options.api_secret,
52
- host: options.host
53
- }
50
+ cli: { host: options.host }
54
51
  }));
55
52
  // A command that needs more than one round trip, or has to decide how many,
56
53
  // runs itself and answers with what should be printed.
@@ -412,10 +412,13 @@ export const ENTRY = [
412
412
  {
413
413
  path: ['entry', 'stats'],
414
414
  summary: 'Count submissions per form over a date range',
415
+ // Split, each bucket's forms are the answer; a table of bucket totals drops them.
416
+ text: { essentialLists: ['data'] },
415
417
  description: 'Not the question `entry count` answers. These are submissions as they happened: an import ' +
416
418
  'lands on the day it ran whatever dates its rows carry, and deletions are never subtracted, ' +
417
419
  'so this is how much arrived rather than how much is still there. A whole day is the ' +
418
- 'smallest window; both ends are inclusive and days are cut in the reported time zone.',
420
+ 'smallest window; both ends are inclusive and days are cut in the reported time zone. For a ' +
421
+ 'day-by-day, weekly or monthly answer pass --by once rather than one call per period.',
419
422
  options: [
420
423
  { name: '--from', type: 'string', placeholder: '<YYYY-MM-DD>', description: 'First day to count, inclusive' },
421
424
  {
@@ -435,7 +438,16 @@ export const ENTRY = [
435
438
  name: '--limit',
436
439
  type: 'integer',
437
440
  placeholder: '<n>',
438
- description: 'How many forms to list, most submissions first (default 100, max 100)'
441
+ description: 'How many forms to list, most submissions first (default 100, or 10 per bucket with --by; max 100)'
442
+ },
443
+ {
444
+ name: '--by',
445
+ type: 'string',
446
+ choices: ['day', 'week', 'month'],
447
+ placeholder: '<unit>',
448
+ description: 'Also split the range into buckets: every one, empty ones with total 0, --limit per bucket. ' +
449
+ 'Weeks start on Monday; the first and last are clipped to the range. ' +
450
+ 'At most 92 days, 53 weeks or 24 months'
439
451
  }
440
452
  ],
441
453
  request: (input) => ({
@@ -445,12 +457,15 @@ export const ENTRY = [
445
457
  from: requiredOption(input, 'from'),
446
458
  to: input.options.to,
447
459
  kind: input.options.kind,
448
- limit: input.options.limit === undefined ? undefined : String(input.options.limit)
460
+ limit: input.options.limit === undefined ? undefined : String(input.options.limit),
461
+ by: input.options.by
449
462
  }
450
463
  }),
451
464
  examples: [
452
465
  'jinshuju entry stats --from 2026-09-01',
453
- 'jinshuju entry stats --from 2026-09-01 --to 2026-09-07 --kind form --limit 10'
466
+ 'jinshuju entry stats --from 2026-09-01 --to 2026-09-07 --kind form --limit 10',
467
+ 'jinshuju entry stats --from 2026-09-28 --by day',
468
+ 'jinshuju entry stats --from 2026-01-01 --by month'
454
469
  ]
455
470
  },
456
471
  {
@@ -24,7 +24,7 @@ export const RESOURCES = [
24
24
  {
25
25
  name: 'auth',
26
26
  summary: 'Manage authentication',
27
- note: 'login is the browser flow. To use a token instead: `jinshuju config set access_token <token>`, ' +
27
+ note: 'login is the browser flow. To use a token instead: `jinshuju auth login --access-token <token>`, ' +
28
28
  'or set JINSHUJU_ACCESS_TOKEN. `auth status --verify` says which account the credential belongs to.'
29
29
  },
30
30
  { name: 'account', summary: 'Account, members, invoices and what the account paid' },
@@ -20,20 +20,21 @@ function local(...names) {
20
20
  export const LOCAL = [
21
21
  {
22
22
  path: ['auth', 'login'],
23
- summary: 'Log in through the browser and store the session',
24
- description: 'Opens the authorization page, waits for the redirect on a loopback port, and writes the ' +
25
- 'session to the config file. An access token or an API key pair, if configured, still ' +
26
- 'outranks what this stores.',
27
- options: local('--auth-host', '--client-id', '--scopes', '--no-open', '--host'),
28
- examples: ['jinshuju auth login', 'jinshuju auth login --no-open']
23
+ summary: 'Log in through the browser, or with an access token, and store the credential',
24
+ description: 'Without --access-token: opens the authorization page, waits for the redirect on a loopback ' +
25
+ 'port, and writes the session to the config file. With it: checks the token with one call, ' +
26
+ 'then stores it; the OAuth options are ignored. Either replaces whatever credential was stored ' +
27
+ 'before. JINSHUJU_ACCESS_TOKEN, if set, still outranks what this stores.',
28
+ options: local('--access-token', '--auth-host', '--client-id', '--scopes', '--no-open', '--host'),
29
+ examples: ['jinshuju auth login', 'jinshuju auth login --no-open', 'jinshuju auth login --access-token <token>']
29
30
  },
30
31
  {
31
32
  path: ['auth', 'status'],
32
33
  summary: 'Show which credential is in use, and where it came from',
33
- description: 'The precedence is access token, then API key and secret, then a stored browser login. ' +
34
+ description: 'The precedence is JINSHUJU_ACCESS_TOKEN, then the credential `auth login` stored. ' +
34
35
  '--verify spends one call to confirm the credential still works, and reports the account it ' +
35
36
  'belongs to — with more than one configured, nothing else here says which is in play.',
36
- options: local('--verify', '--api-key', '--api-secret', '--host', '--auth-host', '--client-id'),
37
+ options: local('--verify', '--host', '--auth-host', '--client-id'),
37
38
  examples: ['jinshuju auth status', 'jinshuju auth status --verify']
38
39
  },
39
40
  {
@@ -44,33 +45,33 @@ export const LOCAL = [
44
45
  },
45
46
  {
46
47
  path: ['auth', 'logout'],
47
- summary: 'Revoke the stored browser session and forget it',
48
- description: "Leaves an access token or API key pair in the config alone: those are not this command's to drop.",
48
+ summary: 'Forget the stored credential, revoking it first if it is a browser session',
49
+ description: 'An access token cannot be revoked from here, only forgotten. JINSHUJU_ACCESS_TOKEN is not ' +
50
+ "this command's to drop.",
49
51
  options: local('--auth-host', '--client-id')
50
52
  },
51
53
  {
52
54
  path: ['config', 'get'],
53
55
  summary: 'Read one configuration value',
54
- description: `Keys: ${CONFIG_KEYS.join(', ')}. Secrets are masked unless --show-secret says otherwise.`,
56
+ description: `Keys: ${CONFIG_KEYS.join(', ')}. Credentials are not config: \`auth login\` stores them.`,
55
57
  args: [{ name: 'key', required: true, description: `One of ${CONFIG_KEYS.join(', ')}` }],
56
- options: local('--show-secret'),
57
- examples: ['jinshuju config get api_key', 'jinshuju config get access_token --show-secret']
58
+ examples: ['jinshuju config get host']
58
59
  },
59
60
  {
60
61
  path: ['config', 'set'],
61
62
  summary: 'Write one configuration value',
62
- description: `Keys: ${CONFIG_KEYS.join(', ')}. The file is written with mode 600. Environment variables ` +
63
- 'of the same name (JINSHUJU_ACCESS_TOKEN, JINSHUJU_API_KEY, …) outrank whatever is stored here.',
63
+ description: `Keys: ${CONFIG_KEYS.join(', ')}. The file is written with mode 600. JINSHUJU_HOST, ` +
64
+ 'JINSHUJU_AUTH_HOST and JINSHUJU_OAUTH_CLIENT_ID outrank whatever is stored here.',
64
65
  args: [
65
66
  { name: 'key', required: true, description: `One of ${CONFIG_KEYS.join(', ')}` },
66
67
  { name: 'value', required: true, description: 'The value to store' }
67
68
  ],
68
- examples: ['jinshuju config set access_token xxx', 'jinshuju config set host https://jinshuju.net']
69
+ examples: ['jinshuju config set host https://jinshuju.net']
69
70
  },
70
71
  {
71
72
  path: ['config', 'unset'],
72
73
  summary: 'Remove one configuration value',
73
74
  args: [{ name: 'key', required: true, description: `One of ${CONFIG_KEYS.join(', ')}` }],
74
- examples: ['jinshuju config unset api_secret']
75
+ examples: ['jinshuju config unset host']
75
76
  }
76
77
  ];
package/dist/config.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type ConfigKey = 'access_token' | 'api_key' | 'api_secret' | 'host' | 'auth_host' | 'client_id';
1
+ export type ConfigKey = 'host' | 'auth_host' | 'client_id';
2
2
  export type ConfigSource = 'cli' | 'env' | 'file' | 'missing';
3
3
  export type OAuthConfig = {
4
4
  type: 'oauth';
@@ -9,14 +9,17 @@ export type OAuthConfig = {
9
9
  expires_at?: string;
10
10
  scope?: string;
11
11
  };
12
+ /** An access token stored by `auth login --access-token`. It takes the same slot as an OAuth session. */
13
+ export type TokenConfig = {
14
+ type: 'access_token';
15
+ access_token: string;
16
+ };
12
17
  export type LoadedConfig = {
13
18
  /**
14
- * A personal or account access token, sent as a bearer. Goldendata accepts it
15
- * on API v1 alongside the API key pair and an OAuth session.
19
+ * A personal or account access token, sent as a bearer: JINSHUJU_ACCESS_TOKEN,
20
+ * or the one `auth login --access-token` stored.
16
21
  */
17
22
  accessToken?: string;
18
- apiKey?: string;
19
- apiSecret?: string;
20
23
  host: string;
21
24
  authHost: string;
22
25
  clientId?: string;
@@ -26,8 +29,6 @@ export type LoadedConfig = {
26
29
  configPath: string;
27
30
  sources: {
28
31
  accessToken: ConfigSource;
29
- apiKey: ConfigSource;
30
- apiSecret: ConfigSource;
31
32
  host: ConfigSource;
32
33
  authHost: ConfigSource;
33
34
  clientId: ConfigSource;
@@ -38,9 +39,6 @@ export type LoadConfigOptions = {
38
39
  configPath?: string;
39
40
  env?: NodeJS.ProcessEnv | Record<string, string | undefined>;
40
41
  cli?: {
41
- accessToken?: string;
42
- apiKey?: string;
43
- apiSecret?: string;
44
42
  host?: string;
45
43
  authHost?: string;
46
44
  clientId?: string;
@@ -51,16 +49,21 @@ export declare const defaultHost = "https://jinshuju.net";
51
49
  export declare const defaultAuthHost = "https://account.jinshuju.net";
52
50
  export declare const defaultOAuthClientId = "jinshuju_cli_public";
53
51
  export declare const defaultScopes = "public forms read_entries write_entries form_setting read_contacts users";
52
+ /**
53
+ * One credential at a time: a login of either kind replaces whatever the last
54
+ * one stored, so the file never holds two that disagree about who is calling.
55
+ */
54
56
  export type RawConfig = Partial<Record<ConfigKey, string>> & {
55
- auth?: OAuthConfig;
57
+ auth?: OAuthConfig | TokenConfig;
56
58
  };
57
59
  export declare function loadConfig(options?: LoadConfigOptions): LoadedConfig;
58
60
  export declare function setConfigValue(configPath: string, key: ConfigKey, value: string): void;
59
61
  export declare function unsetConfigValue(configPath: string, key: ConfigKey): void;
60
62
  export declare function saveOAuthConfig(configPath: string, auth: OAuthConfig): void;
61
- export declare function clearOAuthConfig(configPath: string): void;
63
+ export declare function saveAccessToken(configPath: string, accessToken: string): void;
64
+ /** Forgets the stored credential, whichever kind it is. */
65
+ export declare function clearCredential(configPath: string): void;
62
66
  export declare function getConfig(configPath: string): RawConfig;
63
- export declare function maskSecret(value: string | undefined): string | undefined;
64
67
  /** Every key the config file holds, in the order help should list them. */
65
68
  export declare const CONFIG_KEYS: readonly ConfigKey[];
66
69
  export declare function assertConfigKey(value: string): asserts value is ConfigKey;
package/dist/config.js CHANGED
@@ -53,19 +53,16 @@ export function loadConfig(options = {}) {
53
53
  const configPath = options.configPath ?? defaultConfigPath;
54
54
  const env = options.env ?? process.env;
55
55
  const file = readConfigFile(configPath);
56
- const accessToken = pickValue(options.cli?.accessToken, env.JINSHUJU_ACCESS_TOKEN, file.access_token);
57
- const apiKey = pickValue(options.cli?.apiKey, env.JINSHUJU_API_KEY, file.api_key);
58
- const apiSecret = pickValue(options.cli?.apiSecret, env.JINSHUJU_API_SECRET, file.api_secret);
56
+ const auth = file.auth?.type === 'oauth' ? file.auth : undefined;
57
+ const storedToken = file.auth?.type === 'access_token' ? file.auth.access_token : undefined;
58
+ const accessToken = pickValue(undefined, env.JINSHUJU_ACCESS_TOKEN, storedToken);
59
59
  const host = pickValue(options.cli?.host, env.JINSHUJU_HOST, file.host, defaultHost);
60
- const authHost = pickValue(options.cli?.authHost, env.JINSHUJU_AUTH_HOST, file.auth_host ?? file.auth?.auth_host, defaultAuthHost);
60
+ const authHost = pickValue(options.cli?.authHost, env.JINSHUJU_AUTH_HOST, file.auth_host ?? auth?.auth_host, defaultAuthHost);
61
61
  const defaultClientId = authHost.value === defaultAuthHost ? defaultOAuthClientId : undefined;
62
- const clientId = pickValue(options.cli?.clientId, env.JINSHUJU_OAUTH_CLIENT_ID, file.client_id ?? file.auth?.client_id, defaultClientId);
63
- const auth = file.auth?.type === 'oauth' ? file.auth : undefined;
62
+ const clientId = pickValue(options.cli?.clientId, env.JINSHUJU_OAUTH_CLIENT_ID, file.client_id ?? auth?.client_id, defaultClientId);
64
63
  const timeoutMs = parseTimeout(env.JINSHUJU_TIMEOUT_MS);
65
64
  return {
66
65
  accessToken: accessToken.value,
67
- apiKey: apiKey.value,
68
- apiSecret: apiSecret.value,
69
66
  host: host.value,
70
67
  authHost: authHost.value,
71
68
  clientId: clientId.value,
@@ -74,8 +71,6 @@ export function loadConfig(options = {}) {
74
71
  configPath,
75
72
  sources: {
76
73
  accessToken: accessToken.source,
77
- apiKey: apiKey.source,
78
- apiSecret: apiSecret.source,
79
74
  host: host.source,
80
75
  authHost: authHost.source,
81
76
  clientId: clientId.source,
@@ -108,7 +103,13 @@ export function saveOAuthConfig(configPath, auth) {
108
103
  config.client_id = auth.client_id;
109
104
  writeConfigFile(configPath, config);
110
105
  }
111
- export function clearOAuthConfig(configPath) {
106
+ export function saveAccessToken(configPath, accessToken) {
107
+ const config = readConfigFile(configPath);
108
+ config.auth = { type: 'access_token', access_token: accessToken };
109
+ writeConfigFile(configPath, config);
110
+ }
111
+ /** Forgets the stored credential, whichever kind it is. */
112
+ export function clearCredential(configPath) {
112
113
  const config = readConfigFile(configPath);
113
114
  delete config.auth;
114
115
  writeConfigFile(configPath, config);
@@ -116,22 +117,8 @@ export function clearOAuthConfig(configPath) {
116
117
  export function getConfig(configPath) {
117
118
  return readConfigFile(configPath);
118
119
  }
119
- export function maskSecret(value) {
120
- if (!value)
121
- return undefined;
122
- if (value.length <= 8)
123
- return '••••';
124
- return `${value.slice(0, 4)}…${value.slice(-4)}`;
125
- }
126
120
  /** Every key the config file holds, in the order help should list them. */
127
- export const CONFIG_KEYS = [
128
- 'access_token',
129
- 'api_key',
130
- 'api_secret',
131
- 'host',
132
- 'auth_host',
133
- 'client_id'
134
- ];
121
+ export const CONFIG_KEYS = ['host', 'auth_host', 'client_id'];
135
122
  export function assertConfigKey(value) {
136
123
  if (!CONFIG_KEYS.includes(value)) {
137
124
  throw new UsageError(`Config key must be one of ${CONFIG_KEYS.join(', ')}`);
package/dist/help.d.ts CHANGED
@@ -1,15 +1,21 @@
1
1
  import { type Command } from './commands/index.js';
2
+ import { type Style } from './style.js';
2
3
  /**
3
4
  * Help is rendered from the command table, so a command cannot be reachable
4
5
  * without appearing here, and a flag cannot be accepted without being
5
6
  * described. The root help lists one line per resource, then the global
6
7
  * options.
8
+ *
9
+ * Every help opens with the version, piped or not: help is read by a person,
10
+ * and which version it describes is the first thing worth knowing about it.
7
11
  */
8
- export declare function rootHelp(commands?: readonly Command[]): string;
12
+ /** `jinshuju v0.5.0`, for the top of a help and of an error at a terminal. */
13
+ export declare function versionLine(style?: Style): string;
14
+ export declare function rootHelp(commands?: readonly Command[], style?: Style): string;
9
15
  /** Every verb of one resource, for `jinshuju form --help`. */
10
- export declare function resourceHelp(resource: string, commands?: readonly Command[]): string;
11
- export declare function commandHelp(command: Command): string;
16
+ export declare function resourceHelp(resource: string, commands?: readonly Command[], style?: Style): string;
17
+ export declare function commandHelp(command: Command, style?: Style): string;
12
18
  /** What the caller typed that matched nothing, and the nearest things that do. */
13
- export declare function unknownCommandHelp(words: readonly string[], commands?: readonly Command[]): string;
19
+ export declare function unknownCommandHelp(words: readonly string[], commands?: readonly Command[], style?: Style): string;
14
20
  /** Help for whatever the words point at: a command, a resource, or the root. */
15
- export declare function helpFor(words: readonly string[], commands?: readonly Command[]): string;
21
+ export declare function helpFor(words: readonly string[], commands?: readonly Command[], style?: Style): string;
package/dist/help.js CHANGED
@@ -1,23 +1,34 @@
1
1
  import { COMMANDS, RESOURCES, findCommand } from './commands/index.js';
2
2
  import { EXIT_CODES } from './errors.js';
3
3
  import { GLOBAL_OPTIONS, optionKey } from './options.js';
4
+ import { PLAIN } from './style.js';
5
+ import { VERSION } from './version.js';
4
6
  /**
5
7
  * Help is rendered from the command table, so a command cannot be reachable
6
8
  * without appearing here, and a flag cannot be accepted without being
7
9
  * described. The root help lists one line per resource, then the global
8
10
  * options.
11
+ *
12
+ * Every help opens with the version, piped or not: help is read by a person,
13
+ * and which version it describes is the first thing worth knowing about it.
9
14
  */
10
- export function rootHelp(commands = COMMANDS) {
15
+ /** `jinshuju v0.5.0`, for the top of a help and of an error at a terminal. */
16
+ export function versionLine(style = PLAIN) {
17
+ return `${style.heading('jinshuju')} ${style.dim(`v${VERSION}`)}`;
18
+ }
19
+ export function rootHelp(commands = COMMANDS, style = PLAIN) {
11
20
  const present = new Set(commands.map((command) => command.path[0]));
12
21
  const resources = RESOURCES.filter((resource) => present.has(resource.name) || resource.name === 'auth' || resource.name === 'config');
13
22
  const width = Math.max(...resources.map((resource) => resource.name.length)) + 4;
14
23
  return [
15
- 'Usage: jinshuju <resource> <verb> [args] [flags]',
24
+ versionLine(style),
25
+ '',
26
+ `${style.heading('Usage:')} jinshuju <resource> <verb> [args] [flags]`,
16
27
  '',
17
- 'Commands:',
28
+ style.heading('Commands:'),
18
29
  ...resources.map((resource) => ` ${resource.name.padEnd(width)}${resource.summary}`),
19
30
  '',
20
- 'Global Options:',
31
+ style.heading('Global Options:'),
21
32
  ...GLOBAL_OPTIONS.map((option) => ` ${flagLabel(option).padEnd(width + 12)}${option.description}`),
22
33
  '',
23
34
  'Run `jinshuju <resource> --help` to see its verbs.',
@@ -32,16 +43,18 @@ export function rootHelp(commands = COMMANDS) {
32
43
  ].join('\n');
33
44
  }
34
45
  /** Every verb of one resource, for `jinshuju form --help`. */
35
- export function resourceHelp(resource, commands = COMMANDS) {
46
+ export function resourceHelp(resource, commands = COMMANDS, style = PLAIN) {
36
47
  const owned = commands.filter((command) => command.path[0] === resource);
37
48
  if (owned.length === 0)
38
- return rootHelp(commands);
49
+ return rootHelp(commands, style);
39
50
  const width = Math.max(...owned.map((command) => command.path.join(' ').length)) + 4;
40
51
  const note = RESOURCES.find((entry) => entry.name === resource)?.note;
41
52
  return [
42
- `Usage: jinshuju ${resource} <verb> [args] [flags]`,
53
+ versionLine(style),
43
54
  '',
44
- 'Commands:',
55
+ `${style.heading('Usage:')} jinshuju ${resource} <verb> [args] [flags]`,
56
+ '',
57
+ style.heading('Commands:'),
45
58
  ...owned.map((command) => ` ${command.path.join(' ').padEnd(width)}${command.summary}`),
46
59
  ...(note ? ['', note] : []),
47
60
  '',
@@ -49,9 +62,9 @@ export function resourceHelp(resource, commands = COMMANDS) {
49
62
  ''
50
63
  ].join('\n');
51
64
  }
52
- export function commandHelp(command) {
65
+ export function commandHelp(command, style = PLAIN) {
53
66
  const usage = [
54
- 'Usage: jinshuju',
67
+ `${style.heading('Usage:')} jinshuju`,
55
68
  ...command.path,
56
69
  ...(command.args ?? []).map((arg) => {
57
70
  const name = arg.required ? `<${arg.name}>` : `[${arg.name}]`;
@@ -59,29 +72,34 @@ export function commandHelp(command) {
59
72
  }),
60
73
  '[flags]'
61
74
  ].join(' ');
62
- const parts = [usage, '', command.description ?? command.summary];
75
+ const parts = [versionLine(style), '', usage, '', command.description ?? command.summary];
63
76
  if (command.args?.length) {
64
77
  const width = Math.max(...command.args.map((arg) => arg.name.length)) + 4;
65
- parts.push('', 'Arguments:', ...command.args.map((arg) => ` ${arg.name.padEnd(width)}${arg.description}`));
78
+ parts.push('', style.heading('Arguments:'), ...command.args.map((arg) => ` ${arg.name.padEnd(width)}${arg.description}`));
66
79
  }
67
- const options = [...(command.options ?? []), ...GLOBAL_OPTIONS];
68
- const width = Math.max(...options.map((option) => flagLabel(option).length)) + 4;
69
- parts.push('', 'Flags:', ...options.map((option) => ` ${flagLabel(option).padEnd(width)}${option.description}`));
80
+ // One width across both lists, so the descriptions line up down the page.
81
+ const own = command.options ?? [];
82
+ const width = Math.max(...[...own, ...GLOBAL_OPTIONS].map((option) => flagLabel(option).length)) + 4;
83
+ const describe = (option) => ` ${flagLabel(option).padEnd(width)}${option.description}`;
84
+ if (own.length > 0)
85
+ parts.push('', style.heading('Flags:'), ...own.map(describe));
86
+ parts.push('', style.heading('Global Options:'), ...GLOBAL_OPTIONS.map(describe));
70
87
  if (command.payload?.length)
71
- parts.push('', 'Payload:', ...command.payload.map((line) => ` ${line}`));
72
- if (command.examples?.length)
73
- parts.push('', 'Examples:', ...command.examples.map((example) => ` ${example}`));
88
+ parts.push('', style.heading('Payload:'), ...command.payload.map((line) => ` ${line}`));
89
+ if (command.examples?.length) {
90
+ parts.push('', style.heading('Examples:'), ...command.examples.map((example) => ` ${example}`));
91
+ }
74
92
  return `${parts.join('\n')}\n`;
75
93
  }
76
94
  /** What the caller typed that matched nothing, and the nearest things that do. */
77
- export function unknownCommandHelp(words, commands = COMMANDS) {
95
+ export function unknownCommandHelp(words, commands = COMMANDS, style = PLAIN) {
78
96
  const typed = words.join(' ');
79
97
  const resource = words[0];
80
98
  const siblings = commands.filter((command) => command.path[0] === resource).slice(0, 10);
81
99
  return [
82
100
  `Unknown command: jinshuju ${typed}`,
83
101
  ...(siblings.length > 0
84
- ? ['', 'Did you mean:', ...siblings.map((command) => ` jinshuju ${command.path.join(' ')}`)]
102
+ ? ['', style.heading('Did you mean:'), ...siblings.map((command) => ` jinshuju ${command.path.join(' ')}`)]
85
103
  : []),
86
104
  '',
87
105
  'Run `jinshuju --help` for the full list.',
@@ -89,16 +107,16 @@ export function unknownCommandHelp(words, commands = COMMANDS) {
89
107
  ].join('\n');
90
108
  }
91
109
  /** Help for whatever the words point at: a command, a resource, or the root. */
92
- export function helpFor(words, commands = COMMANDS) {
110
+ export function helpFor(words, commands = COMMANDS, style = PLAIN) {
93
111
  if (words.length === 0)
94
- return rootHelp(commands);
112
+ return rootHelp(commands, style);
95
113
  const command = findCommand(words, commands);
96
114
  if (command)
97
- return commandHelp(command);
115
+ return commandHelp(command, style);
98
116
  const resource = words[0];
99
117
  if (commands.some((candidate) => candidate.path[0] === resource))
100
- return resourceHelp(resource, commands);
101
- return rootHelp(commands);
118
+ return resourceHelp(resource, commands, style);
119
+ return rootHelp(commands, style);
102
120
  }
103
121
  function flagLabel(option) {
104
122
  const flags = option.short ? `${option.short}, ${option.name}` : option.name;
package/dist/http.js CHANGED
@@ -217,16 +217,12 @@ export class JinshujuHttpClient {
217
217
  async authorizationHeader() {
218
218
  if (this.config.accessToken)
219
219
  return `Bearer ${this.config.accessToken}`;
220
- if (this.config.apiKey && this.config.apiSecret) {
221
- const credentials = Buffer.from(`${this.config.apiKey}:${this.config.apiSecret}`).toString('base64');
222
- return `Basic ${credentials}`;
223
- }
224
220
  if (this.config.auth?.access_token) {
225
221
  if (shouldRefresh(this.config.auth) && this.config.auth.refresh_token) {
226
222
  this.config.auth = await refreshOAuthToken(this.config);
227
223
  }
228
224
  return `Bearer ${this.config.auth.access_token}`;
229
225
  }
230
- throw new AuthError('Missing authentication. Run `jinshuju auth login`, or configure JINSHUJU_ACCESS_TOKEN, or JINSHUJU_API_KEY with JINSHUJU_API_SECRET.');
226
+ throw new AuthError('Missing authentication. Run `jinshuju auth login` or `jinshuju auth login --access-token <token>`, or set JINSHUJU_ACCESS_TOKEN.');
231
227
  }
232
228
  }
package/dist/local.d.ts CHANGED
@@ -9,15 +9,13 @@ import { type CliResult, type CliRuntime } from './result.js';
9
9
  type LocalOptions = {
10
10
  output: OutputFormat;
11
11
  configPath: string;
12
- apiKey?: string;
13
- apiSecret?: string;
12
+ accessToken?: string;
14
13
  host?: string;
15
14
  authHost?: string;
16
15
  clientId?: string;
17
16
  scopes?: string;
18
17
  noOpen: boolean;
19
18
  verify: boolean;
20
- showSecret: boolean;
21
19
  };
22
20
  export declare function localOptions(flags: Record<string, unknown>, stdin: () => string): LocalOptions;
23
21
  export declare function runLocal(words: readonly string[], flags: Record<string, unknown>, runtime: CliRuntime, stdin: () => string): Promise<CliResult>;
package/dist/local.js CHANGED
@@ -1,6 +1,7 @@
1
- import { loginWithOAuth, refreshOAuthToken, revokeOAuthToken } from './auth.js';
1
+ import { loginWithOAuth, logout, refreshOAuthToken } from './auth.js';
2
2
  import { bindOptions } from './args.js';
3
- import { assertConfigKey, defaultConfigPath, getConfig, loadConfig, maskSecret, setConfigValue, unsetConfigValue } from './config.js';
3
+ import { assertConfigKey, CONFIG_KEYS, defaultConfigPath, getConfig, loadConfig, saveAccessToken, setConfigValue, unsetConfigValue } from './config.js';
4
+ import { AuthError } from './errors.js';
4
5
  import { JinshujuHttpClient } from './http.js';
5
6
  import { GLOBAL_OPTIONS, LOCAL_OPTIONS, UsageError } from './options.js';
6
7
  import { format } from './render.js';
@@ -11,15 +12,13 @@ export function localOptions(flags, stdin) {
11
12
  return {
12
13
  output: bound.output ?? 'text',
13
14
  configPath: bound.config ?? defaultConfigPath,
14
- apiKey: bound.api_key,
15
- apiSecret: bound.api_secret,
15
+ accessToken: bound.access_token,
16
16
  host: bound.host,
17
17
  authHost: bound.auth_host,
18
18
  clientId: bound.client_id,
19
19
  scopes: bound.scopes,
20
20
  noOpen: Boolean(bound.no_open),
21
- verify: Boolean(bound.verify),
22
- showSecret: Boolean(bound.show_secret)
21
+ verify: Boolean(bound.verify)
23
22
  };
24
23
  }
25
24
  export async function runLocal(words, flags, runtime, stdin) {
@@ -41,7 +40,7 @@ export async function runLocal(words, flags, runtime, stdin) {
41
40
  case 'config unset':
42
41
  return configUnset(words, options);
43
42
  default:
44
- return unknown(words, options.output);
43
+ return unknown(words, options.output, runtime.terminal?.stderr);
45
44
  }
46
45
  }
47
46
  function requireArg(value, name) {
@@ -49,24 +48,24 @@ function requireArg(value, name) {
49
48
  throw new UsageError(`Missing argument <${name}>`);
50
49
  return value;
51
50
  }
52
- function createClient(options, runtime) {
53
- return (runtime.client ??
54
- new JinshujuHttpClient(loadConfig({
55
- configPath: options.configPath,
56
- env: runtime.env,
57
- cli: { apiKey: options.apiKey, apiSecret: options.apiSecret, host: options.host }
58
- })));
51
+ /** A client that sends `accessToken` when one is given, and the configured credential otherwise. */
52
+ function createClient(options, runtime, accessToken) {
53
+ if (runtime.client)
54
+ return runtime.client;
55
+ const config = loadConfig({ configPath: options.configPath, env: runtime.env, cli: { host: options.host } });
56
+ return new JinshujuHttpClient(accessToken ? { ...config, accessToken } : config);
59
57
  }
60
58
  async function authLogin(options, runtime) {
59
+ if (options.accessToken !== undefined)
60
+ return await tokenLogin(options.accessToken, options, runtime);
61
61
  const result = await loginWithOAuth({
62
62
  configPath: options.configPath,
63
63
  env: runtime.env,
64
64
  host: options.host,
65
65
  authHost: options.authHost,
66
66
  clientId: options.clientId,
67
- scopes: options.scopes,
68
- openBrowser: !options.noOpen
69
- });
67
+ scopes: options.scopes
68
+ }, options.noOpen ? printLoginUrl : undefined);
70
69
  const payload = {
71
70
  authenticated: true,
72
71
  mode: 'oauth',
@@ -79,39 +78,39 @@ async function authLogin(options, runtime) {
79
78
  return ok(format(payload, options.output, 0));
80
79
  return ok(`Authenticated with OAuth.\nConfig: ${options.configPath}`);
81
80
  }
81
+ /**
82
+ * A token is checked before it is stored: one pasted wrong would otherwise sit
83
+ * in the config until the next command failed with it, far from where it was
84
+ * typed. The same call says whose token it is.
85
+ */
86
+ /** --no-open: the URL goes to stderr, so stdout still carries only the result. */
87
+ async function printLoginUrl(url) {
88
+ process.stderr.write(`Open this URL in a browser to log in:\n${url}\n`);
89
+ }
90
+ async function tokenLogin(accessToken, options, runtime) {
91
+ if (!accessToken)
92
+ throw new UsageError('--access-token needs a token');
93
+ const account = await identify(createClient(options, runtime, accessToken));
94
+ saveAccessToken(options.configPath, accessToken);
95
+ if (options.output !== 'text')
96
+ return ok(format({ authenticated: true, mode: 'access_token', account }, options.output, 0));
97
+ return ok(`Authenticated with an access token.${describeAccount(account)}\nConfig: ${options.configPath}`);
98
+ }
82
99
  async function authStatus(options, runtime) {
83
100
  const config = loadConfig({
84
101
  configPath: options.configPath,
85
102
  env: runtime.env,
86
- cli: {
87
- apiKey: options.apiKey,
88
- apiSecret: options.apiSecret,
89
- host: options.host,
90
- authHost: options.authHost,
91
- clientId: options.clientId
92
- }
103
+ cli: { host: options.host, authHost: options.authHost, clientId: options.clientId }
93
104
  });
94
- const authenticated = Boolean(config.accessToken || (config.apiKey && config.apiSecret) || config.auth?.access_token);
95
- const mode = config.accessToken
96
- ? 'access_token'
97
- : config.apiKey && config.apiSecret
98
- ? 'api_key_secret'
99
- : config.auth?.access_token
100
- ? 'oauth'
101
- : 'none';
105
+ const authenticated = Boolean(config.accessToken || config.auth?.access_token);
106
+ const mode = config.accessToken ? 'access_token' : config.auth?.access_token ? 'oauth' : 'none';
102
107
  const payload = {
103
108
  authenticated,
104
109
  mode,
105
110
  host: config.host,
106
111
  auth_host: config.authHost,
107
112
  sources: config.sources,
108
- source: mode === 'access_token'
109
- ? config.sources.accessToken
110
- : mode === 'api_key_secret'
111
- ? config.sources.apiKey
112
- : mode === 'oauth'
113
- ? config.sources.auth
114
- : 'missing',
113
+ source: mode === 'access_token' ? config.sources.accessToken : mode === 'oauth' ? config.sources.auth : 'missing',
115
114
  oauth: config.auth
116
115
  ? {
117
116
  client_id: config.auth.client_id,
@@ -129,14 +128,16 @@ async function authStatus(options, runtime) {
129
128
  const full = { ...payload, ...(account ? { account } : {}) };
130
129
  if (options.output !== 'text')
131
130
  return ok(format(full, options.output, 0));
132
- const whose = account ? ` Account: ${account.name}${account.plan ? ` (${account.plan})` : ''}.` : '';
131
+ const whose = describeAccount(account);
133
132
  if (mode === 'access_token')
134
133
  return ok(`Authenticated with an access token (from ${config.sources.accessToken}).${whose}`);
135
134
  if (mode === 'oauth')
136
135
  return ok(`Authenticated with OAuth.${whose}`);
137
- if (mode === 'api_key_secret')
138
- return ok(`Authenticated with API Key / Secret.${whose}`);
139
- return ok('Missing authentication. Run `jinshuju auth login`, or set an access token, or configure API Key / Secret.');
136
+ return ok('Missing authentication. Run `jinshuju auth login` or `jinshuju auth login --access-token <token>`, ' +
137
+ 'or set JINSHUJU_ACCESS_TOKEN.');
138
+ }
139
+ function describeAccount(account) {
140
+ return account ? ` Account: ${account.name}${account.plan ? ` (${account.plan})` : ''}.` : '';
140
141
  }
141
142
  /**
142
143
  * Who the credential belongs to. Reading the account proves the credential works
@@ -158,6 +159,8 @@ async function authRefresh(options, runtime) {
158
159
  env: runtime.env,
159
160
  cli: { host: options.host, authHost: options.authHost, clientId: options.clientId }
160
161
  });
162
+ if (!config.auth && config.accessToken)
163
+ throw new AuthError('An access token cannot be refreshed; log in again with a new one if it stopped working.');
161
164
  const auth = await refreshOAuthToken(config);
162
165
  if (options.output !== 'text')
163
166
  return ok(format({ authenticated: true, mode: 'oauth', expires_at: auth.expires_at, scope: auth.scope }, options.output, 0));
@@ -165,7 +168,7 @@ async function authRefresh(options, runtime) {
165
168
  }
166
169
  async function authLogout(options, runtime) {
167
170
  const config = loadConfig({ configPath: options.configPath, env: runtime.env });
168
- await revokeOAuthToken(config);
171
+ await logout(config);
169
172
  return ok(options.output !== 'text' ? format({ authenticated: false }, options.output, 0) : 'Logged out.');
170
173
  }
171
174
  function configGet(positionals, options) {
@@ -173,20 +176,8 @@ function configGet(positionals, options) {
173
176
  if (requestedKey)
174
177
  assertConfigKey(requestedKey);
175
178
  const config = getConfig(options.configPath);
176
- const secrets = new Set(['access_token', 'api_key', 'api_secret']);
177
- const renderValue = (key, value) => options.showSecret || !secrets.has(key) ? value : maskSecret(value);
178
- let payload;
179
- if (requestedKey) {
180
- const configKey = requestedKey;
181
- payload = { [configKey]: renderValue(configKey, config[configKey]) };
182
- }
183
- else {
184
- payload = {
185
- access_token: renderValue('access_token', config.access_token),
186
- api_key: renderValue('api_key', config.api_key),
187
- api_secret: renderValue('api_secret', config.api_secret)
188
- };
189
- }
179
+ const keys = requestedKey ? [requestedKey] : CONFIG_KEYS;
180
+ const payload = Object.fromEntries(keys.map((key) => [key, config[key]]));
190
181
  if (options.output !== 'text')
191
182
  return ok(format(payload, options.output, 0));
192
183
  return ok(Object.entries(payload)
package/dist/options.d.ts CHANGED
@@ -42,7 +42,7 @@ export declare const PAGINATION_OPTIONS: readonly OptionSpec[];
42
42
  export declare const JSON_OPTION: OptionSpec;
43
43
  export declare const MINE_OPTION: OptionSpec;
44
44
  export { UsageError } from './errors.js';
45
- /** `--api-key` reads back as `api_key`. */
45
+ /** `--auth-host` reads back as `auth_host`. */
46
46
  export declare function optionKey(spec: OptionSpec): string;
47
47
  export interface FilterCondition {
48
48
  readonly field: string;
package/dist/options.js CHANGED
@@ -24,15 +24,13 @@ export const GLOBAL_OPTIONS = [
24
24
  * in it is a flag nobody knows about.
25
25
  */
26
26
  export const LOCAL_OPTIONS = [
27
- { name: '--api-key', type: 'string', placeholder: '<key>', description: 'Override API key' },
28
- { name: '--api-secret', type: 'string', placeholder: '<secret>', description: 'Override API secret' },
27
+ { name: '--access-token', type: 'string', placeholder: '<token>', description: 'Log in with an access token' },
29
28
  { name: '--host', type: 'string', placeholder: '<url>', description: 'API host' },
30
29
  { name: '--auth-host', type: 'string', placeholder: '<url>', description: 'OAuth host' },
31
30
  { name: '--client-id', type: 'string', placeholder: '<id>', description: 'OAuth public client id' },
32
31
  { name: '--scopes', type: 'string', placeholder: '<scopes>', description: 'Space-separated OAuth scopes' },
33
32
  { name: '--no-open', type: 'boolean', description: 'Print the login URL instead of opening a browser' },
34
- { name: '--verify', type: 'boolean', description: 'Verify the credentials with a lightweight call' },
35
- { name: '--show-secret', type: 'boolean', description: 'Show secrets unmasked' }
33
+ { name: '--verify', type: 'boolean', description: 'Verify the credentials with a lightweight call' }
36
34
  ];
37
35
  /** The data container a command acts on. Mutually exclusive; both map to form_token. */
38
36
  export const CONTAINER_OPTIONS = [
@@ -120,7 +118,7 @@ export const MINE_OPTION = {
120
118
  description: 'Switch to what the current user submitted'
121
119
  };
122
120
  export { UsageError } from './errors.js';
123
- /** `--api-key` reads back as `api_key`. */
121
+ /** `--auth-host` reads back as `auth_host`. */
124
122
  export function optionKey(spec) {
125
123
  return spec.name.replace(/^--/, '').replace(/-/g, '_');
126
124
  }
package/dist/result.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { HttpClient } from './http.js';
2
2
  import type { OutputFormat } from './options.js';
3
+ import type { Style } from './style.js';
3
4
  export type CliResult = {
4
5
  exitCode: number;
5
6
  stdout: string;
@@ -16,6 +17,14 @@ export type CliRuntime = {
16
17
  stdout?: (chunk: string) => void;
17
18
  /** How wide a table may be. Defaults to the terminal, or 120 through a pipe. */
18
19
  width?: number;
20
+ /**
21
+ * How each stream is styled when it is a terminal; a stream left out is a
22
+ * pipe, and gets neither colour nor the version line on an error.
23
+ */
24
+ terminal?: {
25
+ stdout?: Style;
26
+ stderr?: Style;
27
+ };
19
28
  };
20
29
  export declare function ok(stdout: string): CliResult;
21
30
  /**
@@ -23,9 +32,12 @@ export declare function ok(stdout: string): CliResult;
23
32
  * anything being parsed; with `--output json` stderr carries the same in
24
33
  * words, plus whatever status and body the server answered with, so a script
25
34
  * that reads JSON on the way in reads JSON on the way out as well.
35
+ *
36
+ * At a terminal a text failure opens with the version, since "which version"
37
+ * is the first question about any error. Only there: JSON stays JSON.
26
38
  */
27
- export declare function fail(error: unknown, output: OutputFormat): CliResult;
39
+ export declare function fail(error: unknown, output: OutputFormat, terminal?: Style): CliResult;
28
40
  /** An unknown command is a usage error, and in text mode the help is the message. */
29
- export declare function unknown(words: readonly string[], output: OutputFormat): CliResult;
41
+ export declare function unknown(words: readonly string[], output: OutputFormat, terminal?: Style): CliResult;
30
42
  /** What `--output` asked for, read before the flags are checked so a failure can honour it. */
31
43
  export declare function outputOf(flags: Record<string, unknown>): OutputFormat;
package/dist/result.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { EXIT_CODES, UsageError, classify } from './errors.js';
2
- import { unknownCommandHelp } from './help.js';
2
+ import { unknownCommandHelp, versionLine } from './help.js';
3
3
  import { json } from './render.js';
4
4
  export function ok(stdout) {
5
5
  return { exitCode: 0, stdout: stdout.endsWith('\n') ? stdout : `${stdout}\n`, stderr: '' };
@@ -9,21 +9,31 @@ export function ok(stdout) {
9
9
  * anything being parsed; with `--output json` stderr carries the same in
10
10
  * words, plus whatever status and body the server answered with, so a script
11
11
  * that reads JSON on the way in reads JSON on the way out as well.
12
+ *
13
+ * At a terminal a text failure opens with the version, since "which version"
14
+ * is the first question about any error. Only there: JSON stays JSON.
12
15
  */
13
- export function fail(error, output) {
16
+ export function fail(error, output, terminal) {
14
17
  const sorted = classify(error);
15
18
  if (output !== 'text') {
16
19
  const { exitCode, ...envelope } = sorted;
17
20
  return { exitCode, stdout: '', stderr: `${json({ error: envelope })}\n` };
18
21
  }
19
22
  const wait = sorted.retry_after === undefined ? '' : ` Retry after ${sorted.retry_after}s.`;
20
- return { exitCode: sorted.exitCode, stdout: '', stderr: `Error: ${sorted.message}${wait}\n` };
23
+ return { exitCode: sorted.exitCode, stdout: '', stderr: `${banner(terminal)}Error: ${sorted.message}${wait}\n` };
21
24
  }
22
25
  /** An unknown command is a usage error, and in text mode the help is the message. */
23
- export function unknown(words, output) {
26
+ export function unknown(words, output, terminal) {
24
27
  if (output !== 'text')
25
28
  return fail(new UsageError(`Unknown command: jinshuju ${words.join(' ')}`), output);
26
- return { exitCode: EXIT_CODES.usage, stdout: '', stderr: unknownCommandHelp(words) };
29
+ return {
30
+ exitCode: EXIT_CODES.usage,
31
+ stdout: '',
32
+ stderr: banner(terminal) + unknownCommandHelp(words, undefined, terminal)
33
+ };
34
+ }
35
+ function banner(terminal) {
36
+ return terminal ? `${versionLine(terminal)}\n\n` : '';
27
37
  }
28
38
  /** What `--output` asked for, read before the flags are checked so a failure can honour it. */
29
39
  export function outputOf(flags) {
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Colour for the person at a terminal, and nothing for anyone else.
3
+ *
4
+ * A style exists only for a stream that is a terminal; a pipe gets none, so
5
+ * what a script or an agent reads is byte-for-byte what it was. NO_COLOR
6
+ * (https://no-color.org) keeps the terminal but drops the colour.
7
+ *
8
+ * The orange is the Jinshuju logo's, #FF8533. A terminal that does not say it
9
+ * takes 24-bit colour gets the nearest of the 256.
10
+ */
11
+ export type Style = {
12
+ /** A section heading, and the name on the version line. */
13
+ heading(text: string): string;
14
+ /** What is there to be glanced at, not read: the version. */
15
+ dim(text: string): string;
16
+ };
17
+ export declare const PLAIN: Style;
18
+ type Env = NodeJS.ProcessEnv | Record<string, string | undefined>;
19
+ export declare function styleFor(stream: {
20
+ isTTY?: boolean;
21
+ }, env?: Env): Style | undefined;
22
+ export {};
package/dist/style.js ADDED
@@ -0,0 +1,12 @@
1
+ export const PLAIN = { heading: (text) => text, dim: (text) => text };
2
+ export function styleFor(stream, env = process.env) {
3
+ if (!stream.isTTY)
4
+ return undefined;
5
+ if (env.NO_COLOR)
6
+ return PLAIN;
7
+ const orange = /^(truecolor|24bit)$/i.test(env.COLORTERM ?? '') ? '38;2;255;133;51' : '38;5;209';
8
+ return {
9
+ heading: (text) => `\x1b[${orange}m${text}\x1b[39m`,
10
+ dim: (text) => `\x1b[90m${text}\x1b[39m`
11
+ };
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jinshuju/cli",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Command line interface for Jinshuju Open API v1",
5
5
  "homepage": "https://github.com/jinshuju/cli#readme",
6
6
  "bugs": {