@jinshuju/cli 0.12.0 → 0.14.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/local.d.ts CHANGED
@@ -15,6 +15,10 @@ type LocalOptions = {
15
15
  clientId?: string;
16
16
  scopes?: string;
17
17
  noOpen: boolean;
18
+ device: boolean;
19
+ noWait: boolean;
20
+ resume: boolean;
21
+ timeout?: string;
18
22
  verify: boolean;
19
23
  };
20
24
  export declare function localOptions(flags: Record<string, unknown>, stdin: () => string): LocalOptions;
package/dist/local.js CHANGED
@@ -1,4 +1,4 @@
1
- import { loginWithOAuth, logout, refreshOAuthToken } from './auth.js';
1
+ import { loginWithDevice, loginWithOAuth, logout, refreshOAuthToken, resumeDeviceLogin, startDeviceLogin } from './auth.js';
2
2
  import { bindOptions } from './args.js';
3
3
  import { assertConfigKey, CONFIG_KEYS, defaultConfigPath, getConfig, loadConfig, saveAccessToken, setConfigValue, unsetConfigValue } from './config.js';
4
4
  import { AuthError } from './errors.js';
@@ -18,6 +18,10 @@ export function localOptions(flags, stdin) {
18
18
  clientId: bound.client_id,
19
19
  scopes: bound.scopes,
20
20
  noOpen: Boolean(bound.no_open),
21
+ device: Boolean(bound.device),
22
+ noWait: Boolean(bound.no_wait),
23
+ resume: Boolean(bound.resume),
24
+ timeout: bound.timeout,
21
25
  verify: Boolean(bound.verify)
22
26
  };
23
27
  }
@@ -58,26 +62,79 @@ function createClient(options, runtime, accessToken) {
58
62
  async function authLogin(options, runtime) {
59
63
  if (options.accessToken !== undefined)
60
64
  return await tokenLogin(options.accessToken, options, runtime);
61
- const result = await loginWithOAuth({
65
+ if (options.noWait && options.resume)
66
+ throw new UsageError('--no-wait starts a device login and --resume finishes it; pick one');
67
+ const target = {
62
68
  configPath: options.configPath,
63
69
  env: runtime.env,
64
70
  host: options.host,
65
71
  authHost: options.authHost,
66
72
  clientId: options.clientId,
67
73
  scopes: options.scopes
68
- }, options.noOpen ? printLoginUrl : undefined);
74
+ };
75
+ if (options.noWait)
76
+ return pendingLogin(await startDeviceLogin(target), options);
77
+ if (options.resume)
78
+ return loggedIn(await resumeDeviceLogin({ ...target, waitMs: waitMs(options.timeout) }), options);
79
+ if (options.device || (!options.noOpen && headless(runtime.env ?? process.env)))
80
+ return loggedIn(await loginWithDevice(target, printDeviceCode), options);
81
+ const result = await loginWithOAuth(target, options.noOpen ? printLoginUrl : undefined);
82
+ return loggedIn(result.token, options);
83
+ }
84
+ function waitMs(seconds) {
85
+ if (seconds === undefined)
86
+ return undefined;
87
+ if (!/^\d+$/.test(seconds))
88
+ throw new UsageError(`--timeout takes a whole number of seconds, got ${JSON.stringify(seconds)}`);
89
+ return Number.parseInt(seconds, 10) * 1000;
90
+ }
91
+ /**
92
+ * No browser could open here, or none that the person at the keyboard would
93
+ * see: a session over SSH, or a Linux box without a display. The loopback
94
+ * login would wait for a redirect that cannot arrive, so a device login is
95
+ * the one that can work. --no-open still asks for the loopback login by name.
96
+ */
97
+ function headless(env) {
98
+ if (env.SSH_CONNECTION || env.SSH_TTY)
99
+ return true;
100
+ return process.platform === 'linux' && !env.DISPLAY && !env.WAYLAND_DISPLAY;
101
+ }
102
+ function loggedIn(token, options) {
69
103
  const payload = {
70
104
  authenticated: true,
71
105
  mode: 'oauth',
72
- auth_host: result.token.auth_host,
73
- client_id: result.token.client_id,
74
- scope: result.token.scope,
75
- expires_at: result.token.expires_at
106
+ auth_host: token.auth_host,
107
+ client_id: token.client_id,
108
+ scope: token.scope,
109
+ expires_at: token.expires_at
76
110
  };
77
111
  if (options.output !== 'text')
78
112
  return ok(format(payload, options.output, 0));
79
113
  return ok(`Authenticated with OAuth.\nConfig: ${options.configPath}`);
80
114
  }
115
+ /** The link and code go on stdout here: they are the result, and whoever ran this has to pass them on. */
116
+ function pendingLogin(pending, options) {
117
+ const link = pending.verification_uri_complete ?? pending.verification_uri;
118
+ const payload = {
119
+ authenticated: false,
120
+ pending: true,
121
+ user_code: pending.user_code,
122
+ verification_uri: pending.verification_uri,
123
+ verification_uri_complete: pending.verification_uri_complete,
124
+ expires_at: pending.expires_at,
125
+ resume: 'jinshuju auth login --resume'
126
+ };
127
+ if (options.output !== 'text')
128
+ return ok(format(payload, options.output, 0));
129
+ return ok(`To log in, open ${link}\nand check it shows the code ${pending.user_code}, then approve it.\n` +
130
+ `Then run \`jinshuju auth login --resume\` to finish. The code expires at ${pending.expires_at}.`);
131
+ }
132
+ /** While the login waits, so stdout still carries only the result. */
133
+ function printDeviceCode(pending) {
134
+ const link = pending.verification_uri_complete ?? pending.verification_uri;
135
+ process.stderr.write(`To log in, open this link on any device:\n${link}\n` +
136
+ `and check it shows the code ${pending.user_code}, then approve it. Waiting…\n`);
137
+ }
81
138
  /**
82
139
  * A token is checked before it is stored: one pasted wrong would otherwise sit
83
140
  * in the config until the next command failed with it, far from where it was
package/dist/options.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { UsageError } from './errors.js';
3
+ import { choices } from './spec.js';
3
4
  export const OUTPUT_FORMATS = ['text', 'json', 'jsonl'];
4
5
  /** Accepted by every command. */
5
6
  export const GLOBAL_OPTIONS = [
@@ -30,6 +31,23 @@ export const LOCAL_OPTIONS = [
30
31
  { name: '--client-id', type: 'string', placeholder: '<id>', description: 'OAuth public client id' },
31
32
  { name: '--scopes', type: 'string', placeholder: '<scopes>', description: 'Space-separated OAuth scopes' },
32
33
  { name: '--no-open', type: 'boolean', description: 'Print the login URL instead of opening a browser' },
34
+ {
35
+ name: '--device',
36
+ type: 'boolean',
37
+ description: 'Log in by entering a short code on any other device; no browser or open port needed here'
38
+ },
39
+ {
40
+ name: '--no-wait',
41
+ type: 'boolean',
42
+ description: 'Start a device login, print its link and code, and exit; finish it with --resume'
43
+ },
44
+ { name: '--resume', type: 'boolean', description: 'Finish the device login --no-wait started' },
45
+ {
46
+ name: '--timeout',
47
+ type: 'string',
48
+ placeholder: '<seconds>',
49
+ description: 'How long --resume waits for the approval before exiting 9 (default 60)'
50
+ },
33
51
  { name: '--verify', type: 'boolean', description: 'Verify the credentials with a lightweight call' }
34
52
  ];
35
53
  /** The data container a command acts on. Mutually exclusive; both map to form_token. */
@@ -67,13 +85,19 @@ export const CONTAINER_LIST_OPTIONS = [
67
85
  description: 'Table token, repeatable, e.g. Vn4xR8'
68
86
  }
69
87
  ];
88
+ /**
89
+ * The operators a condition takes, off the spec's own ScopeCondition. The
90
+ * list this replaced was written here, and had drifted: it offered `match`,
91
+ * which the spec does not list.
92
+ */
93
+ const FILTER_OPERATORS = choices('listEntries', 'filters[].operator');
70
94
  export const FILTER_OPTION = {
71
95
  name: '--filter',
72
96
  type: 'string',
73
97
  repeatable: true,
74
98
  placeholder: "'<field> <op> [value]'",
75
- description: 'Filter condition, repeatable, AND-combined. Operators: eq ne gte gt lte lt like not_like ' +
76
- 'any_in none_in between not_between null not_null match within_last. ' +
99
+ description: 'Filter condition, repeatable, AND-combined. ' +
100
+ (FILTER_OPERATORS ? `Operators: ${FILTER_OPERATORS.join(' ')}. ` : '') +
77
101
  "e.g. 'field_3 gte 80', 'created_at within_last 30d', 'field_4 between 1,10'"
78
102
  };
79
103
  export const FILTERS_OPTION = {
package/dist/render.js CHANGED
@@ -39,7 +39,7 @@ export function terminalWidth(stream = process.stdout) {
39
39
  return stream.isTTY && stream.columns > 0 ? stream.columns : PIPED_WIDTH;
40
40
  }
41
41
  export function json(value) {
42
- return JSON.stringify(value, null, 2);
42
+ return JSON.stringify(value ?? null, null, 2);
43
43
  }
44
44
  /**
45
45
  * One JSON object per line, which is what `jq -c`, a shell loop and a log
@@ -48,7 +48,7 @@ export function json(value) {
48
48
  */
49
49
  export function jsonl(value, listKey) {
50
50
  const rows = listOf(value, listKey);
51
- return (rows ?? [value]).map((row) => JSON.stringify(row)).join('\n');
51
+ return (rows ?? [value]).map((row) => JSON.stringify(row ?? null)).join('\n');
52
52
  }
53
53
  /** The rows a payload carries, when it is a listing. */
54
54
  function listOf(value, listKey) {
package/dist/spec.d.ts CHANGED
@@ -50,6 +50,12 @@ export interface Parameter {
50
50
  readonly required?: boolean;
51
51
  readonly style?: string;
52
52
  readonly explode?: boolean;
53
+ /**
54
+ * The media type of a document the value carries as text in one query
55
+ * value — `filters=[{"field":…}]` — when it does: `application/json`.
56
+ * `schema` is then the document's.
57
+ */
58
+ readonly content?: string;
53
59
  readonly schema: Schema;
54
60
  }
55
61
  export interface Operation {
@@ -92,12 +98,14 @@ export interface CallParts {
92
98
  export declare function call(id: OperationId, parts?: CallParts): HttpRequest;
93
99
  export declare function unansweredLookups(): readonly string[];
94
100
  /**
95
- * The values a query parameter takes, for the flag that feeds it. A flag
96
- * listing them itself is a second copy, and the second copy was already behind
97
- * once: a view type and two scenes the API had learned were refused by the CLI
98
- * before they reached it.
101
+ * The values a query parameter takes, for the flag that feeds it. `path` is
102
+ * the parameter's name, and walks on into a document the parameter carries
103
+ * the way `bodyChoices` walks a body: `filters[].operator`. A flag listing
104
+ * the values itself is a second copy, and the second copy was already behind
105
+ * once: a view type and two scenes the API had learned were refused by the
106
+ * CLI before they reached it.
99
107
  */
100
- export declare function choices(id: OperationId, name: string): readonly string[] | undefined;
108
+ export declare function choices(id: OperationId, path: string): readonly string[] | undefined;
101
109
  /**
102
110
  * The values a property of a JSON body takes. `path` walks properties with
103
111
  * dots and steps into a list's items with `[]`: `fields[].type`.
package/dist/spec.js CHANGED
@@ -67,6 +67,16 @@ function queryOf(id, op, values) {
67
67
  if (!param) {
68
68
  throw new UsageError(`${op.method} ${BASE_PATH}${op.path} takes no ${name} parameter (${id} in openapi.yaml)`);
69
69
  }
70
+ if (param.content !== undefined) {
71
+ // A document goes as its text in one value, never repeated the way a
72
+ // list is, and as given: it is the caller's payload as often as not,
73
+ // and the API judges it as it does a body. The tests hold the CLI's own
74
+ // to the document's schema.
75
+ if (typeof value !== 'string')
76
+ throw new Error(`${id} ${name} is ${param.content} text, spelled by the command`);
77
+ query[name] = value;
78
+ continue;
79
+ }
70
80
  const texts = typeof value === 'object' ? [...value] : [String(value)];
71
81
  check(param, texts);
72
82
  if (isArray(param.schema)) {
@@ -153,29 +163,39 @@ export function unansweredLookups() {
153
163
  return unanswered;
154
164
  }
155
165
  /**
156
- * The values a query parameter takes, for the flag that feeds it. A flag
157
- * listing them itself is a second copy, and the second copy was already behind
158
- * once: a view type and two scenes the API had learned were refused by the CLI
159
- * before they reached it.
166
+ * The values a query parameter takes, for the flag that feeds it. `path` is
167
+ * the parameter's name, and walks on into a document the parameter carries
168
+ * the way `bodyChoices` walks a body: `filters[].operator`. A flag listing
169
+ * the values itself is a second copy, and the second copy was already behind
170
+ * once: a view type and two scenes the API had learned were refused by the
171
+ * CLI before they reached it.
160
172
  */
161
- export function choices(id, name) {
173
+ export function choices(id, path) {
174
+ const [first, ...rest] = path.split('.');
175
+ const name = first.endsWith('[]') ? first.slice(0, -2) : first;
162
176
  const param = OPERATIONS[id].parameters.find((candidate) => candidate.name === name);
163
- return enumOf(param && (isArray(param.schema) ? itemsOf(param.schema) : param.schema), `${id} ${name}`);
177
+ // A parameter that is a list offers its items' values.
178
+ const start = param && (isArray(param.schema) ? itemsOf(param.schema) : param.schema);
179
+ return enumOf(walk(start, rest), `${id} ${path}`);
164
180
  }
165
181
  /**
166
182
  * The values a property of a JSON body takes. `path` walks properties with
167
183
  * dots and steps into a list's items with `[]`: `fields[].type`.
168
184
  */
169
185
  export function bodyChoices(id, path) {
170
- let schema = OPERATIONS[id].body?.content['application/json'];
171
- for (const step of path.split('.')) {
186
+ return enumOf(walk(OPERATIONS[id].body?.content['application/json'], path.split('.')), `${id} ${path}`);
187
+ }
188
+ /** The schema the steps lead to: each names a property, and `[]` steps into a list's items. */
189
+ function walk(from, steps) {
190
+ let schema = from;
191
+ for (const step of steps) {
172
192
  if (!schema)
173
193
  break;
174
194
  const many = step.endsWith('[]');
175
195
  const property = propertyOf(schema, many ? step.slice(0, -2) : step);
176
196
  schema = property && (many ? itemsOf(property) : property);
177
197
  }
178
- return enumOf(schema, `${id} ${path}`);
198
+ return schema;
179
199
  }
180
200
  /** A property as an object schema or any of its allOf parts declares it. */
181
201
  function propertyOf(schema, name) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jinshuju/cli",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "Command line interface for Jinshuju Open API v1",
5
5
  "homepage": "https://github.com/jinshuju/cli#readme",
6
6
  "bugs": {