@jacebenson/jsn 5.5.1-dev.160.1 → 5.5.1-dev.162.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.1-dev.160.1",
3
+ "version": "5.5.1-dev.162.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/app.js CHANGED
@@ -59,6 +59,7 @@ export class App {
59
59
  username: session?.username, authMethod: session?.profile?.auth_method,
60
60
  }), {
61
61
  domain: session?.domain || '',
62
+ includeReferenceLinks: this._authArgv?.includeReferenceLinks === true,
62
63
  username: session?.username || '',
63
64
  recovery: createAuthRecovery({ app: this, session }),
64
65
  onMutation: event => this.recordMutation(instance, session?.profileName, event),
@@ -4,6 +4,10 @@ import { renderSubcommandHelp } from './help.js';
4
4
 
5
5
  const camel = (name) => name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
6
6
  const names = (x) => typeof x === 'string' ? [x] : (x || []);
7
+ // Query shorthand belongs only to commands that declare the query option.
8
+ const optionSpec = (name, config = {}) => ({ ...config, name,
9
+ ...(name === 'query' ? { alias: [...new Set([...names(config.alias), 'q'])] } : {}),
10
+ });
7
11
 
8
12
  /**
9
13
  * A repeatable option may be declared either way: `type: 'array'` (this
@@ -89,7 +93,7 @@ class CommandNode {
89
93
  node.register(new CommandNode(typeof definition === 'string' ? { command: definition, builder, handler } : definition));
90
94
  return this;
91
95
  },
92
- option(name, config = {}) { node.options.set(name, { ...config, name }); return this; },
96
+ option(name, config = {}) { node.options.set(name, optionSpec(name, config)); return this; },
93
97
  options(config = {}) { for (const [name, value] of Object.entries(config)) this.option(name, value); return this; },
94
98
  positional(name, config = {}) { node.positionals.set(name, { ...config, name }); return this; },
95
99
  demandCommand(count, message) { node.demand = { count, message }; return this; },
@@ -119,7 +123,7 @@ export class LocalCLI {
119
123
  usage(value) { this.root.usageText = value; return this; }
120
124
  epilogue(value) { this.root.epilogueText = value; return this; }
121
125
  middleware(fn) { this.middlewares.push(...(Array.isArray(fn) ? fn : [fn])); return this; }
122
- option(name, config) { this.root.options.set(name, { ...config, name }); return this; }
126
+ option(name, config) { this.root.options.set(name, optionSpec(name, config)); return this; }
123
127
  options(config) { for (const [name, value] of Object.entries(config)) this.option(name, value); return this; }
124
128
  command(definition, builder, handler) {
125
129
  this.root.register(new CommandNode(typeof definition === 'string' ? { command: definition, builder, handler } : definition));
@@ -238,6 +242,10 @@ export class LocalCLI {
238
242
  catch (err) { this._fail(err.message, err); return { values: {}, positionals: [] }; }
239
243
  const argv = { _: path.map((n) => n.name) };
240
244
  for (const [key, value] of Object.entries(parsed.values)) {
245
+ if (opts.validate !== false && key === 'q' && !options.has('q')) {
246
+ this._fail('Option -q (--query) is not supported by this command.');
247
+ return null;
248
+ }
241
249
  const spec = this._specFor(options, key, value);
242
250
  if (this._assign(argv, key, value, spec, opts) === false) return null;
243
251
  }
package/src/cli.js CHANGED
@@ -187,14 +187,18 @@ export function buildCLI() {
187
187
  description: 'Output in CSV format (shortcut for --format=csv)',
188
188
  },
189
189
  get: {
190
+ alias: 'select',
190
191
  type: 'string',
191
192
  description: 'Extract a JSON path from the output envelope (e.g. --get "data.records.0.number"); no jq needed',
192
193
  },
193
194
  quiet: {
194
195
  type: 'boolean',
195
196
  description: 'Output only data, no envelope (shortcut for --format=quiet)',
196
- alias: 'q',
197
+ alias: 'S',
197
198
  },
199
+ verbose: { type: 'boolean', description: 'Keep machine-output coaching and pretty-print JSON' },
200
+ raw: { type: 'boolean', description: 'Print extracted strings without JSON quotes' },
201
+ 'include-reference-links': { type: 'boolean', description: 'Include Table API reference links on reads' },
198
202
  styled: {
199
203
  type: 'boolean',
200
204
  description: 'Force styled output even when piped',
@@ -209,6 +213,8 @@ export function buildCLI() {
209
213
  // resolveRequestedFormat so the parse-time failure path applies the
210
214
  // identical policy instead of approximating it from raw tokens.
211
215
  (argv) => {
216
+ app.output.verbose = argv.verbose === true;
217
+ app.output.raw = argv.raw === true;
212
218
  const requested = resolveRequestedFormat(argv);
213
219
  if (requested) {
214
220
  argv.format = requested;
@@ -216,6 +222,10 @@ export function buildCLI() {
216
222
  }
217
223
  if (argv.get) {
218
224
  app.output.setJqFilter(argv.get);
225
+ if (!requested || requested === 'auto') {
226
+ app.output.setFormat('json');
227
+ argv.format = 'json';
228
+ }
219
229
  }
220
230
  },
221
231
  // --profile / --instance resolve through the SESSION (src/session.js).
@@ -234,6 +244,7 @@ export function buildCLI() {
234
244
  }
235
245
  app._authArgv = argv;
236
246
  applySession(app, session);
247
+ if (app.sdk) app.sdk.includeReferenceLinks = argv.includeReferenceLinks === true;
237
248
  } catch (err) {
238
249
  guardExit(argv, { code: err.code || 'usage', message: err.message, hint: err.hint });
239
250
  }
@@ -548,6 +559,8 @@ export function buildCLI() {
548
559
  // negation) instead of re-scanning raw argv — one policy, one answer for
549
560
  // this command line no matter which layer rejects it.
550
561
  const formatArgv = cliInstance.parseGlobalOptions(raw);
562
+ app.output.verbose = formatArgv?.verbose === true;
563
+ app.output.raw = formatArgv?.raw === true;
551
564
  const requestedFormat = resolveRequestedFormat(formatArgv);
552
565
  if (msg === 'You must specify a command') {
553
566
  const hasLoneProfile = raw.some((a, i, arr) => {
@@ -56,7 +56,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
56
56
  count: 0,
57
57
  columns: pickerColumns,
58
58
  records: [],
59
- pagination: { limit, offset: 0 },
59
+ pagination: { limit, offset: 0, hasMore: false },
60
60
  context: { instance_url: app.getEffectiveInstance() },
61
61
  }, {
62
62
  summary: `0 ${table}(s)`,
@@ -115,7 +115,7 @@ export function buildTicketCommands(table, displayName, alias, defaultColumns, s
115
115
  count: records.length,
116
116
  columns,
117
117
  records: displayRecords,
118
- pagination: { limit, offset },
118
+ pagination: { limit, offset, hasMore: records.length === limit },
119
119
  context: { instance_url: app.getEffectiveInstance() },
120
120
  }, {
121
121
  summary: `${records.length} ${table}(s)`,
@@ -112,7 +112,7 @@ async function listCases(app, argv, resolved, query) {
112
112
  count: records.length,
113
113
  columns,
114
114
  records: displayRecords,
115
- pagination: { limit: argv.limit, offset: argv.offset },
115
+ pagination: { limit: argv.limit, offset: argv.offset, hasMore: records.length === argv.limit },
116
116
  context: { instance_url: app.getEffectiveInstance() },
117
117
  }, { summary: `${records.length} ${resolved.table}(s)`, breadcrumbs });
118
118
  }
@@ -454,7 +454,7 @@ export function cmdbCmd(wrap) {
454
454
  count: records.length,
455
455
  columns,
456
456
  records: displayRecords,
457
- pagination: { limit: argv.limit, offset: argv.offset, ...(total != null ? { total } : {}) },
457
+ pagination: { limit: argv.limit, offset: argv.offset, ...(total != null ? { total, hasMore: argv.offset + argv.limit < total } : {}) },
458
458
  context: { instance_url: app.getEffectiveInstance() },
459
459
  }, {
460
460
  summary: `${records.length} CI(s) from cmdb_ci${total != null ? ` of ${total}` : ''}`,
@@ -191,7 +191,7 @@ export function recordsCmd(wrap) {
191
191
  count: records.length,
192
192
  columns,
193
193
  records: displayRecords,
194
- pagination: { limit: argv.limit, offset: argv.offset, ...(total != null ? { total } : {}) },
194
+ pagination: { limit: argv.limit, offset: argv.offset, ...(total != null ? { total, hasMore: argv.offset + argv.limit < total } : {}) },
195
195
  context: { instance_url: app.getEffectiveInstance() },
196
196
  }, {
197
197
  summary: `${records.length} record(s) from ${table}${total != null ? ` of ${total}` : ''}`,
@@ -51,7 +51,7 @@ export function ticketsCmd(wrap) {
51
51
  count: records.length,
52
52
  columns,
53
53
  records: displayRecords,
54
- pagination: { limit: argv.limit, offset: argv.offset },
54
+ pagination: { limit: argv.limit, offset: argv.offset, hasMore: records.length === argv.limit },
55
55
  context: { instance_url: app.getEffectiveInstance() },
56
56
  }, { summary: `${records.length} ticket(s)`, breadcrumbs });
57
57
  }),
package/src/help.js CHANGED
@@ -192,11 +192,12 @@ function renderFlags(options) {
192
192
  const lines = [];
193
193
  for (const spec of options) {
194
194
  if (spec.name === 'help') continue;
195
- const alias = spec.alias.length ? `-${spec.alias.join(', -')}, ` : '';
195
+ const alias = spec.alias.map(name => `${name.length === 1 ? '-' : '--'}${name}`).join(', ');
196
+ const label = `${alias ? `${alias}, ` : ''}--${spec.name}`;
196
197
  const suffix = spec.name === 'format' && spec.choices.length
197
198
  ? ` [string: ${spec.choices.join(', ')}]`
198
199
  : ` [${spec.type}]`;
199
- lines.push(` ${`${alias}--${spec.name}`.padEnd(24)}${spec.description}${suffix}`);
200
+ lines.push(` ${label.padEnd(Math.max(24, label.length + 1))}${spec.description}${suffix}`);
200
201
  }
201
202
  lines.push(` ${'--help'.padEnd(24)}Show help${' [boolean]'}`);
202
203
  return `\nFLAGS\n${lines.join('\n')}`;
package/src/output.js CHANGED
@@ -94,6 +94,8 @@ export class OutputWriter {
94
94
  this.format = opts.format || FormatAuto;
95
95
  this.writer = opts.writer || process.stdout;
96
96
  this.jqFilter = opts.jqFilter || '';
97
+ this.verbose = opts.verbose === true;
98
+ this.raw = opts.raw === true;
97
99
  }
98
100
 
99
101
  getFormat() {
@@ -135,7 +137,9 @@ export class OutputWriter {
135
137
  const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [] };
136
138
  const value = resolvePath(envelope, this.jqFilter);
137
139
  if (value === undefined) throw errExtractionNotFound(this.jqFilter);
138
- this.writer.write(JSON.stringify(value, null, 2) + '\n');
140
+ const indent = this.verbose && !this.raw ? 2 : undefined;
141
+ const text = this.raw && typeof value === 'string' ? value : JSON.stringify(value, null, indent);
142
+ this.writer.write(text + '\n');
139
143
  return;
140
144
  }
141
145
 
@@ -173,7 +177,7 @@ export class OutputWriter {
173
177
  switch (format) {
174
178
  case FormatJSON:
175
179
  case FormatQuiet:
176
- this.writer.write(JSON.stringify(resp, null, 2) + '\n');
180
+ this.writer.write(JSON.stringify(resp, null, this.verbose ? 2 : undefined) + '\n');
177
181
  break;
178
182
  case FormatMarkdown:
179
183
  this.writer.write(`**Error (${e.code})**: ${e.message}\n`);
@@ -184,7 +188,7 @@ export class OutputWriter {
184
188
  this.writer.write(colorRed(`Error (${e.code}): ${e.message}\n`));
185
189
  if (e.hint) this.writer.write(colorYellow(`Hint: ${e.hint}\n`));
186
190
  } else {
187
- this.writer.write(JSON.stringify(resp, null, 2) + '\n');
191
+ this.writer.write(JSON.stringify(resp, null, this.verbose ? 2 : undefined) + '\n');
188
192
  }
189
193
  }
190
194
  }
@@ -217,11 +221,15 @@ export class OutputWriter {
217
221
  }
218
222
 
219
223
  writeJSON(data, opts) {
220
- const resp = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [] };
224
+ const resp = { ok: true, data };
225
+ if (this.verbose) {
226
+ resp.summary = opts.summary || '';
227
+ resp.breadcrumbs = opts.breadcrumbs || [];
228
+ }
221
229
  if (opts.notice) resp.notice = opts.notice;
222
230
  if (opts.context) resp.context = opts.context;
223
231
  if (opts.meta) resp.meta = opts.meta;
224
- this.writer.write(JSON.stringify(resp, null, 2) + '\n');
232
+ this.writer.write(JSON.stringify(resp, null, this.verbose ? 2 : undefined) + '\n');
225
233
  }
226
234
 
227
235
  writeQuiet(data) {
@@ -2,6 +2,7 @@
2
2
  // Policy (confirmation, scope, payload and output shape) stays with callers.
3
3
  import { resolveRecord, unwrapSysId } from './resolve-record.js';
4
4
  import { errUsage } from './errors.js';
5
+ import { tableReadParams } from './table-read-params.js';
5
6
 
6
7
  export function displayValue(mode, fallback = 'all') {
7
8
  if (mode === undefined) return fallback;
@@ -20,7 +21,7 @@ export function recordListParams({ limit, offset, query, fields, displayValue: r
20
21
  }
21
22
 
22
23
  export function listRecords(sdk, { table, params, displayValues, ...options }) {
23
- const query = params ? new URLSearchParams(params) : recordListParams(options);
24
+ const query = tableReadParams(params || recordListParams(options), sdk);
24
25
  if (displayValues !== undefined) query.set('sysparm_display_value', displayValue(displayValues));
25
26
  return sdk.list(table, query);
26
27
  }
package/src/sdk.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // ServiceNow REST API client
2
2
 
3
3
  import { batchRead } from './sdk-batch.js';
4
+ import { tableReadParams } from './table-read-params.js';
4
5
  import { gunzipSync } from 'node:zlib';
5
6
  import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork, errUsage } from './errors.js';
6
7
  import { getStringField } from './helpers.js';
@@ -60,6 +61,7 @@ export class SDKClient {
60
61
  this.onMutation = opts.onMutation;
61
62
  this.timeout = opts.timeout || DEFAULT_TIMEOUT;
62
63
  this.domain = opts.domain || '';
64
+ this.includeReferenceLinks = opts.includeReferenceLinks === true;
63
65
  // Expected identity, used only to reject a recovery that lands on a
64
66
  // different account. Never serialized.
65
67
  this.username = opts.username || '';
@@ -380,7 +382,7 @@ export class SDKClient {
380
382
  }
381
383
 
382
384
  async list(table, params = {}, opts = {}) {
383
- const query = new URLSearchParams(params).toString();
385
+ const query = tableReadParams(params, this).toString();
384
386
  const endpoint = `${this.baseURL}/api/now/table/${table}${query ? '?' + query : ''}`;
385
387
  const result = await this.request(endpoint, { method: 'GET', ...opts });
386
388
  return result?.result || [];
@@ -391,7 +393,7 @@ export class SDKClient {
391
393
  // table. Capture paths use this so an unexpected body becomes an unavailable
392
394
  // source instead of a complete-looking empty inventory.
393
395
  async listStrict(table, params = {}, opts = {}) {
394
- const query = new URLSearchParams(params).toString();
396
+ const query = tableReadParams(params, this).toString();
395
397
  const endpoint = `${this.baseURL}/api/now/table/${table}${query ? '?' + query : ''}`;
396
398
  const response = await this.request(endpoint, { method: 'GET', ...opts });
397
399
  if (!response || typeof response !== 'object' || !Array.isArray(response.result)) {
@@ -0,0 +1,9 @@
1
+ // Table API reads omit reference URLs by default. Explicit provider parameters
2
+ // take precedence, including inspection callers that require a particular shape.
3
+ export function tableReadParams(params, { includeReferenceLinks = false } = {}) {
4
+ const query = new URLSearchParams(params);
5
+ if (!includeReferenceLinks && !query.has('sysparm_exclude_reference_link')) {
6
+ query.set('sysparm_exclude_reference_link', 'true');
7
+ }
8
+ return query;
9
+ }