@refhub/cli 1.8.0 → 1.9.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/client.d.ts CHANGED
@@ -6,6 +6,11 @@ export declare class RefHubError extends Error {
6
6
  readonly retry_after_seconds?: number;
7
7
  constructor(status: number, code: string, message: string, request_id: string, retry_after_seconds?: number);
8
8
  }
9
+ /** A mistake in how a command was called: printed as { error: { code, message } }, exit code 2. */
10
+ export declare class UsageError extends Error {
11
+ readonly code: string;
12
+ constructor(code: string, message: string);
13
+ }
9
14
  export declare class RefHubClient {
10
15
  private readonly baseUrl;
11
16
  private readonly headers;
@@ -221,3 +226,14 @@ export interface PdfUploadSession {
221
226
  }
222
227
  export declare function resolveClient(apiKey?: string): RefHubClient;
223
228
  export declare function run(fn: () => Promise<void>): Promise<void>;
229
+ /** What a command's action gets: its positional arguments, its options, the global options, and
230
+ * the API client, resolved only when first asked for, so usage errors can come first. */
231
+ export interface ActionContext {
232
+ args: string[];
233
+ opts: Record<string, any>;
234
+ g: Record<string, any>;
235
+ getClient: () => RefHubClient;
236
+ }
237
+ /** Wraps a command's action: one place resolves the client and turns errors into output and an
238
+ * exit code (see run()). */
239
+ export declare function action(fn: (ctx: ActionContext) => Promise<void>): (...received: unknown[]) => Promise<void>;
package/dist/client.js CHANGED
@@ -12,6 +12,42 @@ export class RefHubError extends Error {
12
12
  this.retry_after_seconds = retry_after_seconds;
13
13
  }
14
14
  }
15
+ /** The RefHubError for a failed response, with the retry hint when the API gives one. */
16
+ async function errorFromResponse(res) {
17
+ const payload = await res.json().catch(() => ({}));
18
+ const err = (payload['error'] ?? {});
19
+ const details = err['details'];
20
+ const retryAfter = typeof details?.['retry_after_seconds'] === 'number'
21
+ ? Number(details['retry_after_seconds'])
22
+ : typeof payload['retry_after_seconds'] === 'number' ? payload['retry_after_seconds'] : undefined;
23
+ return new RefHubError(res.status, String(err['code'] ?? 'unknown_error'), String(err['message'] ?? `HTTP ${res.status}`), String(payload['meta']?.['request_id'] ?? err['request_id'] ?? ''), retryAfter);
24
+ }
25
+ /** A query string that's already encoded; `path` leaves it as is. */
26
+ class Query {
27
+ value;
28
+ constructor(value) {
29
+ this.value = value;
30
+ }
31
+ }
32
+ const query = (qs) => new Query(qs);
33
+ /** A request path with every interpolated value encoded, so an id can't change the route. */
34
+ function path(strings, ...values) {
35
+ return strings.reduce((out, part, i) => {
36
+ if (i === values.length)
37
+ return out + part;
38
+ const value = values[i];
39
+ return out + part + (value instanceof Query ? value.value : encodeURIComponent(String(value)));
40
+ }, '');
41
+ }
42
+ /** A mistake in how a command was called: printed as { error: { code, message } }, exit code 2. */
43
+ export class UsageError extends Error {
44
+ code;
45
+ constructor(code, message) {
46
+ super(message);
47
+ this.code = code;
48
+ this.name = 'UsageError';
49
+ }
50
+ }
15
51
  export class RefHubClient {
16
52
  baseUrl = process.env['REFHUB_API_BASE_URL'] ?? 'https://refhub-api.netlify.app/api/v1';
17
53
  headers;
@@ -27,22 +63,14 @@ export class RefHubClient {
27
63
  headers: this.headers,
28
64
  body: body !== undefined ? JSON.stringify(body) : undefined,
29
65
  });
30
- if (!res.ok) {
31
- const payload = await res.json().catch(() => ({}));
32
- const err = (payload['error'] ?? {});
33
- throw new RefHubError(res.status, String(err['code'] ?? 'unknown_error'), String(err['message'] ?? `HTTP ${res.status}`), String(payload['meta']?.['request_id'] ?? err['request_id'] ?? ''), typeof err['details']?.['retry_after_seconds'] === 'number'
34
- ? Number(err['details']['retry_after_seconds'])
35
- : typeof payload['retry_after_seconds'] === 'number' ? payload['retry_after_seconds'] : undefined);
36
- }
66
+ if (!res.ok)
67
+ throw await errorFromResponse(res);
37
68
  return res.json();
38
69
  }
39
70
  async reqText(method, path) {
40
71
  const res = await fetch(`${this.baseUrl}${path}`, { method, headers: this.headers });
41
- if (!res.ok) {
42
- const payload = await res.json().catch(() => ({}));
43
- const err = (payload['error'] ?? {});
44
- throw new RefHubError(res.status, String(err['code'] ?? 'unknown_error'), String(err['message'] ?? `HTTP ${res.status}`), String(payload['meta']?.['request_id'] ?? err['request_id'] ?? ''));
45
- }
72
+ if (!res.ok)
73
+ throw await errorFromResponse(res);
46
74
  return res.text();
47
75
  }
48
76
  // ── Vaults ──────────────────────────────────────────────────────────────────
@@ -50,35 +78,35 @@ export class RefHubClient {
50
78
  return this.req('GET', '/vaults');
51
79
  }
52
80
  getVault(vaultId) {
53
- return this.req('GET', `/vaults/${vaultId}`);
81
+ return this.req('GET', path `/vaults/${vaultId}`);
54
82
  }
55
83
  createVault(body) {
56
84
  return this.req('POST', '/vaults', body);
57
85
  }
58
86
  updateVault(vaultId, body) {
59
- return this.req('PATCH', `/vaults/${vaultId}`, body);
87
+ return this.req('PATCH', path `/vaults/${vaultId}`, body);
60
88
  }
61
89
  deleteVault(vaultId) {
62
- return this.req('DELETE', `/vaults/${vaultId}`);
90
+ return this.req('DELETE', path `/vaults/${vaultId}`);
63
91
  }
64
92
  /** Permanently archives the vault. There is no unarchive — this cannot be undone. */
65
93
  archiveVault(vaultId) {
66
- return this.req('POST', `/vaults/${vaultId}/archive`);
94
+ return this.req('POST', path `/vaults/${vaultId}/archive`);
67
95
  }
68
96
  setVaultVisibility(vaultId, body) {
69
- return this.req('PATCH', `/vaults/${vaultId}/visibility`, body);
97
+ return this.req('PATCH', path `/vaults/${vaultId}/visibility`, body);
70
98
  }
71
99
  listShares(vaultId) {
72
- return this.req('GET', `/vaults/${vaultId}/shares`);
100
+ return this.req('GET', path `/vaults/${vaultId}/shares`);
73
101
  }
74
102
  addShare(vaultId, body) {
75
- return this.req('POST', `/vaults/${vaultId}/shares`, body);
103
+ return this.req('POST', path `/vaults/${vaultId}/shares`, body);
76
104
  }
77
105
  updateShare(vaultId, shareId, body) {
78
- return this.req('PATCH', `/vaults/${vaultId}/shares/${shareId}`, body);
106
+ return this.req('PATCH', path `/vaults/${vaultId}/shares/${shareId}`, body);
79
107
  }
80
108
  removeShare(vaultId, shareId) {
81
- return this.req('DELETE', `/vaults/${vaultId}/shares/${shareId}`);
109
+ return this.req('DELETE', path `/vaults/${vaultId}/shares/${shareId}`);
82
110
  }
83
111
  // ── Items ────────────────────────────────────────────────────────────────────
84
112
  listItems(vaultId, params = {}) {
@@ -88,28 +116,28 @@ export class RefHubClient {
88
116
  if (params.limit !== undefined)
89
117
  q.set('per_page', String(params.limit));
90
118
  const qs = q.toString() ? `?${q}` : '';
91
- return this.req('GET', `/vaults/${vaultId}/items${qs}`);
119
+ return this.req('GET', path `/vaults/${vaultId}/items${query(qs)}`);
92
120
  }
93
121
  getItem(vaultId, itemId) {
94
- return this.req('GET', `/vaults/${vaultId}/items/${itemId}`);
122
+ return this.req('GET', path `/vaults/${vaultId}/items/${itemId}`);
95
123
  }
96
124
  addItems(vaultId, items) {
97
- return this.req('POST', `/vaults/${vaultId}/items`, { items });
125
+ return this.req('POST', path `/vaults/${vaultId}/items`, { items });
98
126
  }
99
127
  updateItem(vaultId, itemId, body) {
100
- return this.req('PATCH', `/vaults/${vaultId}/items/${itemId}`, body);
128
+ return this.req('PATCH', path `/vaults/${vaultId}/items/${itemId}`, body);
101
129
  }
102
130
  deleteItem(vaultId, itemId) {
103
- return this.req('DELETE', `/vaults/${vaultId}/items/${itemId}`);
131
+ return this.req('DELETE', path `/vaults/${vaultId}/items/${itemId}`);
104
132
  }
105
133
  upsertItems(vaultId, items, idempotencyKey) {
106
- return this.req('POST', `/vaults/${vaultId}/items/upsert`, {
134
+ return this.req('POST', path `/vaults/${vaultId}/items/upsert`, {
107
135
  items,
108
136
  ...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),
109
137
  });
110
138
  }
111
139
  previewImport(vaultId, items) {
112
- return this.req('POST', `/vaults/${vaultId}/items/import-preview`, { items });
140
+ return this.req('POST', path `/vaults/${vaultId}/items/import-preview`, { items });
113
141
  }
114
142
  searchItems(vaultId, params) {
115
143
  const q = new URLSearchParams();
@@ -128,59 +156,59 @@ export class RefHubClient {
128
156
  if (params.limit !== undefined)
129
157
  q.set('per_page', String(params.limit));
130
158
  const qs = q.toString() ? `?${q}` : '';
131
- return this.req('GET', `/vaults/${vaultId}/search${qs}`);
159
+ return this.req('GET', path `/vaults/${vaultId}/search${query(qs)}`);
132
160
  }
133
161
  getStats(vaultId) {
134
- return this.req('GET', `/vaults/${vaultId}/stats`);
162
+ return this.req('GET', path `/vaults/${vaultId}/stats`);
135
163
  }
136
164
  getChanges(vaultId, since) {
137
- return this.req('GET', `/vaults/${vaultId}/changes?since=${encodeURIComponent(since)}`);
165
+ return this.req('GET', path `/vaults/${vaultId}/changes?since=${since}`);
138
166
  }
139
167
  // ── Tags ─────────────────────────────────────────────────────────────────────
140
168
  listTags(vaultId) {
141
- return this.req('GET', `/vaults/${vaultId}/tags`);
169
+ return this.req('GET', path `/vaults/${vaultId}/tags`);
142
170
  }
143
171
  createTag(vaultId, body) {
144
- return this.req('POST', `/vaults/${vaultId}/tags`, body);
172
+ return this.req('POST', path `/vaults/${vaultId}/tags`, body);
145
173
  }
146
174
  updateTag(vaultId, tagId, body) {
147
- return this.req('PATCH', `/vaults/${vaultId}/tags/${tagId}`, body);
175
+ return this.req('PATCH', path `/vaults/${vaultId}/tags/${tagId}`, body);
148
176
  }
149
177
  deleteTag(vaultId, tagId) {
150
- return this.req('DELETE', `/vaults/${vaultId}/tags/${tagId}`);
178
+ return this.req('DELETE', path `/vaults/${vaultId}/tags/${tagId}`);
151
179
  }
152
180
  attachTags(vaultId, itemId, tagIds) {
153
- return this.req('POST', `/vaults/${vaultId}/tags/attach`, { item_id: itemId, tag_ids: tagIds });
181
+ return this.req('POST', path `/vaults/${vaultId}/tags/attach`, { item_id: itemId, tag_ids: tagIds });
154
182
  }
155
183
  detachTags(vaultId, itemId, tagIds) {
156
- return this.req('POST', `/vaults/${vaultId}/tags/detach`, { item_id: itemId, tag_ids: tagIds });
184
+ return this.req('POST', path `/vaults/${vaultId}/tags/detach`, { item_id: itemId, tag_ids: tagIds });
157
185
  }
158
186
  // ── Sections ─────────────────────────────────────────────────────────────────
159
187
  listSections(vaultId) {
160
- return this.req('GET', `/vaults/${vaultId}/sections`);
188
+ return this.req('GET', path `/vaults/${vaultId}/sections`);
161
189
  }
162
190
  createSection(vaultId, body) {
163
- return this.req('POST', `/vaults/${vaultId}/sections`, body);
191
+ return this.req('POST', path `/vaults/${vaultId}/sections`, body);
164
192
  }
165
193
  updateSection(vaultId, sectionId, body) {
166
- return this.req('PATCH', `/vaults/${vaultId}/sections/${sectionId}`, body);
194
+ return this.req('PATCH', path `/vaults/${vaultId}/sections/${sectionId}`, body);
167
195
  }
168
196
  deleteSection(vaultId, sectionId) {
169
- return this.req('DELETE', `/vaults/${vaultId}/sections/${sectionId}`);
197
+ return this.req('DELETE', path `/vaults/${vaultId}/sections/${sectionId}`);
170
198
  }
171
199
  // ── Relations ────────────────────────────────────────────────────────────────
172
200
  listRelations(vaultId, type) {
173
201
  const qs = type ? `?type=${encodeURIComponent(type)}` : '';
174
- return this.req('GET', `/vaults/${vaultId}/relations${qs}`);
202
+ return this.req('GET', path `/vaults/${vaultId}/relations${query(qs)}`);
175
203
  }
176
204
  createRelation(vaultId, body) {
177
- return this.req('POST', `/vaults/${vaultId}/relations`, body);
205
+ return this.req('POST', path `/vaults/${vaultId}/relations`, body);
178
206
  }
179
207
  updateRelation(vaultId, relationId, body) {
180
- return this.req('PATCH', `/vaults/${vaultId}/relations/${relationId}`, body);
208
+ return this.req('PATCH', path `/vaults/${vaultId}/relations/${relationId}`, body);
181
209
  }
182
210
  deleteRelation(vaultId, relationId) {
183
- return this.req('DELETE', `/vaults/${vaultId}/relations/${relationId}`);
211
+ return this.req('DELETE', path `/vaults/${vaultId}/relations/${relationId}`);
184
212
  }
185
213
  // ── Inbox ────────────────────────────────────────────────────────────────────
186
214
  // Account-scoped, not vault-scoped -- an inbox item has no vault until accept()
@@ -190,9 +218,9 @@ export class RefHubClient {
190
218
  if (params.page !== undefined)
191
219
  q.set('page', String(params.page));
192
220
  if (params.limit !== undefined)
193
- q.set('limit', String(params.limit));
221
+ q.set('per_page', String(params.limit));
194
222
  const qs = q.toString() ? `?${q}` : '';
195
- return this.req('GET', `/inbox${qs}`);
223
+ return this.req('GET', path `/inbox${query(qs)}`);
196
224
  }
197
225
  captureInboxDoi(doi) {
198
226
  return this.req('POST', '/inbox', { source_type: 'doi', source_ref: doi });
@@ -204,33 +232,33 @@ export class RefHubClient {
204
232
  return this.req('POST', '/inbox', { source_type: 'manual', parsed_fields: { title } });
205
233
  }
206
234
  acceptInboxItem(itemId, vaultId, tagIds = []) {
207
- return this.req('POST', `/inbox/${itemId}/accept`, { vault_id: vaultId, tag_ids: tagIds });
235
+ return this.req('POST', path `/inbox/${itemId}/accept`, { vault_id: vaultId, tag_ids: tagIds });
208
236
  }
209
237
  rejectInboxItem(itemId) {
210
- return this.req('POST', `/inbox/${itemId}/reject`);
238
+ return this.req('POST', path `/inbox/${itemId}/reject`);
211
239
  }
212
240
  mergeInboxItem(itemId) {
213
- return this.req('POST', `/inbox/${itemId}/merge`);
241
+ return this.req('POST', path `/inbox/${itemId}/merge`);
214
242
  }
215
243
  postponeInboxItem(itemId) {
216
- return this.req('POST', `/inbox/${itemId}/postpone`);
244
+ return this.req('POST', path `/inbox/${itemId}/postpone`);
217
245
  }
218
246
  deleteInboxItem(itemId) {
219
- return this.req('DELETE', `/inbox/${itemId}`);
247
+ return this.req('DELETE', path `/inbox/${itemId}`);
220
248
  }
221
249
  // ── Import ───────────────────────────────────────────────────────────────────
222
250
  importDoi(vaultId, doi, tagIds = []) {
223
- return this.req('POST', `/vaults/${vaultId}/import/doi`, { doi, tag_ids: tagIds });
251
+ return this.req('POST', path `/vaults/${vaultId}/import/doi`, { doi, tag_ids: tagIds });
224
252
  }
225
253
  importBibtex(vaultId, bibtex, tagIds = []) {
226
- return this.req('POST', `/vaults/${vaultId}/import/bibtex`, { bibtex, tag_ids: tagIds });
254
+ return this.req('POST', path `/vaults/${vaultId}/import/bibtex`, { bibtex, tag_ids: tagIds });
227
255
  }
228
256
  importUrl(vaultId, url, tagIds = []) {
229
- return this.req('POST', `/vaults/${vaultId}/import/url`, { url, tag_ids: tagIds });
257
+ return this.req('POST', path `/vaults/${vaultId}/import/url`, { url, tag_ids: tagIds });
230
258
  }
231
259
  // ── Export ───────────────────────────────────────────────────────────────────
232
260
  exportVault(vaultId, format = 'json') {
233
- return this.reqText('GET', `/vaults/${vaultId}/export?format=${format}`);
261
+ return this.reqText('GET', path `/vaults/${vaultId}/export?format=${format}`);
234
262
  }
235
263
  // ── Audit ────────────────────────────────────────────────────────────────────
236
264
  getAudit(vaultId, params = {}) {
@@ -244,7 +272,7 @@ export class RefHubClient {
244
272
  if (params.page !== undefined)
245
273
  q.set('page', String(params.page));
246
274
  const qs = q.toString() ? `?${q}` : '';
247
- return this.req('GET', `/vaults/${vaultId}/audit${qs}`);
275
+ return this.req('GET', path `/vaults/${vaultId}/audit${query(qs)}`);
248
276
  }
249
277
  // ── Semantic Scholar discovery/enrichment ──────────────────────────────────
250
278
  doiMetadata(doi) {
@@ -257,13 +285,13 @@ export class RefHubClient {
257
285
  return this.req('POST', '/semantic-scholar/search', { query, ...(limit !== undefined ? { limit } : {}) });
258
286
  }
259
287
  semanticScholarPaperList(kind, paperId, limit) {
260
- return this.req('POST', `/semantic-scholar/${kind}`, { paper_id: paperId, ...(limit !== undefined ? { limit } : {}) });
288
+ return this.req('POST', path `/semantic-scholar/${kind}`, { paper_id: paperId, ...(limit !== undefined ? { limit } : {}) });
261
289
  }
262
290
  createItemPdfUploadSession(vaultId, itemId) {
263
- return this.req('POST', `/vaults/${encodeURIComponent(vaultId)}/items/${encodeURIComponent(itemId)}/pdf/session`, {});
291
+ return this.req('POST', path `/vaults/${vaultId}/items/${itemId}/pdf/session`, {});
264
292
  }
265
293
  completeItemPdfUpload(vaultId, itemId, body) {
266
- return this.req('POST', `/vaults/${encodeURIComponent(vaultId)}/items/${encodeURIComponent(itemId)}/pdf/complete`, body);
294
+ return this.req('POST', path `/vaults/${vaultId}/items/${itemId}/pdf/complete`, body);
267
295
  }
268
296
  /**
269
297
  * The only PDF upload mechanism: create a resumable session, PUT the bytes
@@ -308,6 +336,10 @@ export async function run(fn) {
308
336
  await fn();
309
337
  }
310
338
  catch (err) {
339
+ if (err instanceof UsageError) {
340
+ process.stderr.write(JSON.stringify({ error: { code: err.code, message: err.message } }) + '\n');
341
+ process.exit(2);
342
+ }
311
343
  if (err instanceof RefHubError) {
312
344
  process.stderr.write(JSON.stringify({
313
345
  error: {
@@ -323,3 +355,15 @@ export async function run(fn) {
323
355
  process.exit(1);
324
356
  }
325
357
  }
358
+ /** Wraps a command's action: one place resolves the client and turns errors into output and an
359
+ * exit code (see run()). */
360
+ export function action(fn) {
361
+ return async (...received) => {
362
+ const cmd = received[received.length - 1];
363
+ const opts = received[received.length - 2];
364
+ const g = cmd.optsWithGlobals();
365
+ let client;
366
+ const getClient = () => (client ??= resolveClient(g['apiKey']));
367
+ await run(() => fn({ args: received.slice(0, -2), opts, g, getClient }));
368
+ };
369
+ }
@@ -1,4 +1,4 @@
1
- import { resolveClient, run } from '../client.js';
1
+ import { action } from '../client.js';
2
2
  import { format } from '../format.js';
3
3
  export async function handleAudit(client, vaultId, opts, tableMode) {
4
4
  const result = await client.getAudit(vaultId, opts);
@@ -13,9 +13,8 @@ export function registerAudit(program) {
13
13
  .option('--until <ISO>', 'end timestamp (ISO 8601)')
14
14
  .option('--limit <n>', 'results per page (max 200)', (v) => parseInt(v, 10))
15
15
  .option('--page <n>', 'page number', (v) => parseInt(v, 10))
16
- .action(async (opts, cmd) => {
17
- const g = cmd.optsWithGlobals();
18
- const client = resolveClient(g.apiKey);
19
- await run(() => handleAudit(client, opts.vault, { since: opts.since, until: opts.until, limit: opts.limit, page: opts.page }, g.table ?? false));
20
- });
16
+ .action(action(async ({ opts, g, getClient }) => {
17
+ const client = getClient();
18
+ await handleAudit(client, opts.vault, { since: opts.since, until: opts.until, limit: opts.limit, page: opts.page }, g.table ?? false);
19
+ }));
21
20
  }
@@ -1,5 +1,5 @@
1
1
  import { readFileSync } from 'fs';
2
- import { resolveClient, run } from '../client.js';
2
+ import { UsageError, action } from '../client.js';
3
3
  import { format } from '../format.js';
4
4
  function authorsToStrings(paper) {
5
5
  return (paper.authors ?? []).map((a) => a.name).filter((name) => Boolean(name));
@@ -33,8 +33,7 @@ export async function handleDiscoverList(client, kind, paperId, limit, tableMode
33
33
  export async function handleDiscoverAdd(client, vaultId, filePath, idempotencyKey, tableMode) {
34
34
  const papers = JSON.parse(readFileSync(filePath, 'utf8'));
35
35
  if (!Array.isArray(papers)) {
36
- process.stderr.write(JSON.stringify({ error: { code: 'invalid_file', message: 'File must contain a JSON array of Semantic Scholar paper results.' } }) + '\n');
37
- process.exit(2);
36
+ throw new UsageError('invalid_file', 'File must contain a JSON array of Semantic Scholar paper results.');
38
37
  }
39
38
  const result = await client.upsertItems(vaultId, papers.map(paperToItem), idempotencyKey);
40
39
  format(result, tableMode);
@@ -45,11 +44,10 @@ function addPaperListCommand(discover, name, description) {
45
44
  .description(description)
46
45
  .requiredOption('--paper <paperId>', 'Semantic Scholar paper id, DOI:<doi>, or other supported paper identifier')
47
46
  .option('--limit <n>', 'result limit, 1-25', (v) => parseInt(v, 10))
48
- .action(async (opts, cmd) => {
49
- const g = cmd.optsWithGlobals();
50
- const client = resolveClient(g.apiKey);
51
- await run(() => handleDiscoverList(client, name, opts.paper, opts.limit, g.table ?? false));
52
- });
47
+ .action(action(async ({ opts, g, getClient }) => {
48
+ const client = getClient();
49
+ await handleDiscoverList(client, name, opts.paper, opts.limit, g.table ?? false);
50
+ }));
53
51
  }
54
52
  export function registerDiscover(program) {
55
53
  const discover = program.command('discover').description('Semantic Scholar discovery via RefHub API key');
@@ -58,25 +56,22 @@ export function registerDiscover(program) {
58
56
  .description('Search Semantic Scholar by keyword/topic')
59
57
  .requiredOption('--query <query>', 'keyword/topic query')
60
58
  .option('--limit <n>', 'result limit, 1-25', (v) => parseInt(v, 10))
61
- .action(async (opts, cmd) => {
62
- const g = cmd.optsWithGlobals();
63
- const client = resolveClient(g.apiKey);
64
- await run(() => handleDiscoverSearch(client, opts.query, opts.limit, g.table ?? false));
65
- });
59
+ .action(action(async ({ opts, g, getClient }) => {
60
+ const client = getClient();
61
+ await handleDiscoverSearch(client, opts.query, opts.limit, g.table ?? false);
62
+ }));
66
63
  discover
67
64
  .command('lookup')
68
65
  .description('Resolve a DOI or title to a Semantic Scholar paper id')
69
66
  .option('--doi <doi>')
70
67
  .option('--title <title>')
71
- .action(async (opts, cmd) => {
68
+ .action(action(async ({ opts, g, getClient }) => {
72
69
  if ((opts.doi && opts.title) || (!opts.doi && !opts.title)) {
73
- process.stderr.write(JSON.stringify({ error: { code: 'invalid_lookup_request', message: 'Provide exactly one of --doi or --title.' } }) + '\n');
74
- process.exit(2);
70
+ throw new UsageError('invalid_lookup_request', 'Provide exactly one of --doi or --title.');
75
71
  }
76
- const g = cmd.optsWithGlobals();
77
- const client = resolveClient(g.apiKey);
78
- await run(() => handleDiscoverLookup(client, { doi: opts.doi, title: opts.title }, g.table ?? false));
79
- });
72
+ const client = getClient();
73
+ await handleDiscoverLookup(client, { doi: opts.doi, title: opts.title }, g.table ?? false);
74
+ }));
80
75
  addPaperListCommand(discover, 'recommendations', 'Get Semantic Scholar recommendations from a seed paper');
81
76
  addPaperListCommand(discover, 'related', 'Alias for recommendations');
82
77
  addPaperListCommand(discover, 'references', 'Get papers cited by a seed paper');
@@ -88,9 +83,8 @@ export function registerDiscover(program) {
88
83
  .requiredOption('--vault <id>')
89
84
  .requiredOption('--file <path>', 'JSON array of Semantic Scholar paper results')
90
85
  .option('--idempotency-key <key>', 'safe retry key')
91
- .action(async (opts, cmd) => {
92
- const g = cmd.optsWithGlobals();
93
- const client = resolveClient(g.apiKey);
94
- await run(() => handleDiscoverAdd(client, opts.vault, opts.file, opts.idempotencyKey, g.table ?? false));
95
- });
86
+ .action(action(async ({ opts, g, getClient }) => {
87
+ const client = getClient();
88
+ await handleDiscoverAdd(client, opts.vault, opts.file, opts.idempotencyKey, g.table ?? false);
89
+ }));
96
90
  }
@@ -1,4 +1,4 @@
1
- import { resolveClient, run } from '../client.js';
1
+ import { action } from '../client.js';
2
2
  export async function enrichItem(item, client, vaultId, dryRun) {
3
3
  if (!item.doi)
4
4
  return 'skipped';
@@ -39,42 +39,39 @@ export function registerEnrich(program) {
39
39
  .requiredOption('--vault <id>', 'vault to enrich')
40
40
  .option('--item <itemId>', 'enrich a single item instead of the whole vault')
41
41
  .option('--dry-run', 'show what would be updated without writing')
42
- .action(async (opts, cmd) => {
43
- const g = cmd.optsWithGlobals();
44
- const client = resolveClient(g.apiKey);
42
+ .action(action(async ({ opts, g, getClient }) => {
43
+ const client = getClient();
45
44
  const dryRun = opts.dryRun ?? false;
46
- await run(async () => {
47
- let items;
48
- if (opts.item) {
49
- const result = await client.getItem(opts.vault, opts.item);
50
- items = [result.data];
51
- }
52
- else {
53
- const result = await client.listItems(opts.vault);
54
- items = result.data;
55
- }
56
- const withDoi = items.filter((i) => i.doi);
57
- if (withDoi.length === 0) {
58
- process.stdout.write(JSON.stringify({ data: { enriched: 0, skipped: 0, not_found: 0, no_missing_fields: 0, message: 'No items with a DOI found.' } }, null, 2) + '\n');
59
- return;
60
- }
61
- const counts = { enriched: 0, skipped: 0, not_found: 0, no_missing_fields: 0 };
62
- const enriched = [];
63
- for (const item of withDoi) {
64
- const outcome = await enrichItem(item, client, opts.vault, dryRun);
65
- counts[outcome]++;
66
- if (outcome === 'enriched')
67
- enriched.push(item.id);
68
- // 1 req/s to respect Semantic Scholar rate limit
69
- await new Promise((r) => setTimeout(r, 1000));
70
- }
71
- process.stdout.write(JSON.stringify({
72
- data: {
73
- dry_run: dryRun,
74
- ...counts,
75
- enriched_ids: enriched,
76
- },
77
- }, null, 2) + '\n');
78
- });
79
- });
45
+ let items;
46
+ if (opts.item) {
47
+ const result = await client.getItem(opts.vault, opts.item);
48
+ items = [result.data];
49
+ }
50
+ else {
51
+ const result = await client.listItems(opts.vault);
52
+ items = result.data;
53
+ }
54
+ const withDoi = items.filter((i) => i.doi);
55
+ if (withDoi.length === 0) {
56
+ process.stdout.write(JSON.stringify({ data: { enriched: 0, skipped: 0, not_found: 0, no_missing_fields: 0, message: 'No items with a DOI found.' } }, null, 2) + '\n');
57
+ return;
58
+ }
59
+ const counts = { enriched: 0, skipped: 0, not_found: 0, no_missing_fields: 0 };
60
+ const enriched = [];
61
+ for (const item of withDoi) {
62
+ const outcome = await enrichItem(item, client, opts.vault, dryRun);
63
+ counts[outcome]++;
64
+ if (outcome === 'enriched')
65
+ enriched.push(item.id);
66
+ // 1 req/s to respect Semantic Scholar rate limit
67
+ await new Promise((r) => setTimeout(r, 1000));
68
+ }
69
+ process.stdout.write(JSON.stringify({
70
+ data: {
71
+ dry_run: dryRun,
72
+ ...counts,
73
+ enriched_ids: enriched,
74
+ },
75
+ }, null, 2) + '\n');
76
+ }));
80
77
  }
@@ -1,4 +1,4 @@
1
- import { resolveClient, run } from '../client.js';
1
+ import { UsageError, action } from '../client.js';
2
2
  export async function handleExport(client, vaultId, outputFormat) {
3
3
  const raw = await client.exportVault(vaultId, outputFormat);
4
4
  process.stdout.write(raw + '\n');
@@ -9,14 +9,12 @@ export function registerExport(program) {
9
9
  .description('Export a vault as JSON or BibTeX')
10
10
  .requiredOption('--vault <id>')
11
11
  .option('--format <format>', 'json|bibtex', 'json')
12
- .action(async (opts, cmd) => {
13
- const g = cmd.optsWithGlobals();
14
- const client = resolveClient(g.apiKey);
12
+ .action(action(async ({ opts, g, getClient }) => {
13
+ const client = getClient();
15
14
  if (opts.format !== 'json' && opts.format !== 'bibtex') {
16
- process.stderr.write(JSON.stringify({ error: { code: 'invalid_format', message: `Unknown format '${opts.format}'. Use json or bibtex.` } }) + '\n');
17
- process.exit(2);
15
+ throw new UsageError('invalid_format', `Unknown format '${opts.format}'. Use json or bibtex.`);
18
16
  }
19
17
  const fmt = opts.format;
20
- await run(() => handleExport(client, opts.vault, fmt));
21
- });
18
+ await handleExport(client, opts.vault, fmt);
19
+ }));
22
20
  }