@jacebenson/jsn 5.2.0 → 5.3.0-dev.135.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.
@@ -141,8 +141,8 @@ export function catalogCmd(wrap) {
141
141
  })
142
142
  .command({
143
143
  command: 'show <id>',
144
- aliases: ['get'],
145
- describe: 'Show a catalog item',
144
+ aliases: ['get', 'describe', 'inputs'],
145
+ describe: 'Show a catalog item, its questions and required answers',
146
146
  handler: wrap(async (argv, app) => {
147
147
  app.requireInstance();
148
148
  const id = await resolveSysId(app.sdk, { table: 'sc_cat_item', identifier: argv.id, matchField: 'name', resource: 'Catalog item' });
@@ -158,7 +158,7 @@ export function catalogCmd(wrap) {
158
158
  }
159
159
 
160
160
  async function showItem(app, sysID) {
161
- const { data, standalone, setVars, totalVars } = await enrichCatalogItem({
161
+ const { data, variables, totalVars, source } = await enrichCatalogItem({
162
162
  sdk: app.sdk,
163
163
  instanceUrl: app.getEffectiveInstance(),
164
164
  sysID,
@@ -166,15 +166,16 @@ async function showItem(app, sysID) {
166
166
 
167
167
  // Styled-mode rendering (non-enumerable so JSON output stays clean)
168
168
  Object.defineProperty(data, '_formatted', {
169
- value: buildCatalogFormatted(data, standalone, setVars, totalVars),
169
+ value: buildCatalogFormatted(data, variables, source),
170
170
  enumerable: false,
171
171
  configurable: true,
172
172
  });
173
173
 
174
174
  app.ok(data, {
175
- summary: `${data.name} — ${totalVars} variable(s)`,
175
+ summary: `${data.name} — ${totalVars} question(s) from ${source === 'catalog_api' ? 'the catalog API' : 'item_option_new'}`,
176
176
  breadcrumbs: [
177
177
  { action: 'list', cmd: 'jsn catalogitems list', description: 'Back to all catalog items' },
178
+ ...(totalVars ? [{ action: 'order', cmd: `jsn catalogitems order ${sysID} --dry-run`, description: 'Preview an order without submitting' }] : []),
178
179
  ],
179
180
  });
180
181
  }
@@ -1,7 +1,9 @@
1
1
  import { formatCommandList, formatRecordForDisplay, buildQuerySuffix, buildRecordPayload, getStringField, interactiveList, resolveFieldsParam, checkDerivedFields, confirmDelete, verifyWriteBack } from '../helpers.js';
2
2
  import { listRecords, recordListParams, getRecord, createRecord, updateRecord, deleteRecord } from '../records-engine.js';
3
- import { unwrapSysId } from '../resolve-record.js';
3
+ import { resolveRecord, unwrapSysId } from '../resolve-record.js';
4
4
  import { errUsage } from '../errors.js';
5
+ import { AmbClient } from '../amb.js';
6
+ import { watchRecord } from '../record-watch.js';
5
7
  import { declareCapabilities } from '../capabilities.js';
6
8
 
7
9
  declareCapabilities('records', {
@@ -197,6 +199,113 @@ export function recordsCmd(wrap) {
197
199
  });
198
200
  }),
199
201
  })
202
+ .command({
203
+ command: 'watch',
204
+ describe: 'Stream change events for one record through ServiceNow AMB record watchers',
205
+ builder: (y) => y
206
+ .option('table', { type: 'string', demandOption: true, describe: 'Table name' })
207
+ .option('sys-id', { type: 'string', describe: 'Record sys_id' })
208
+ .option('identifier', { type: 'string', describe: 'Identifier value; use --identifier-field number/name/etc for human identifiers' })
209
+ .option('identifier-field', { type: 'string', describe: 'Exact identifier field (default sys_id); disambiguates names and legacy sys_ids' })
210
+ .option('timeout', { type: 'number', default: 0, describe: 'Stop after this many seconds (0 = until interrupted)' })
211
+ .option('max-events', { type: 'number', default: 0, describe: 'Stop after this many change events (0 = unlimited)' })
212
+ .option('state', { type: 'string', choices: ['auto', 'always', 'never'], default: 'auto', describe: 'Fetch current record state after an event: auto (only when the notification lacks detail), always, never' })
213
+ .option('fields', { type: 'string', describe: 'Comma-separated fields for the fetched state (default all readable fields)' })
214
+ .option('reconnect', { type: 'boolean', default: true, describe: 'Reconnect after a dropped connection and report the gap; use --no-reconnect to fail fast' })
215
+ .option('poll-timeout', { type: 'number', default: 60000, describe: 'Long-poll hold timeout in milliseconds (advanced)' })
216
+ .epilogue([
217
+ 'Emits newline-delimited JSON events (type record_change, gap, subscribed, reconnected, watch_summary) with --json or when piped.',
218
+ 'The notification is emitted as the event; a fetched record is attached separately as event.state (source: "fetched").',
219
+ 'Record watchers are best effort: after a reconnect the stream reports a gap and does not replay missed events.',
220
+ 'Requires an interactive ServiceNow session (jsn auth login --browser). Not a durable queue or scheduler.',
221
+ 'Example: jsn records watch --table incident --sys-id <sys_id> --timeout 300 --json',
222
+ 'Example: jsn records watch --table incident --identifier INC0010001 --identifier-field number --max-events 1 --json',
223
+ ].join('\n')),
224
+ handler: wrap(async (argv, app) => {
225
+ const lookup = recordLookup(argv);
226
+ const record = await resolveRecord(app.sdk, { ...lookup, fields: ['sys_id'] });
227
+ const sysID = unwrapSysId(record);
228
+ if (!sysID) throw errUsage('The matched record has no readable sys_id; check field ACLs before retrying.');
229
+ const stateFields = argv.fields ? argv.fields.split(',').filter(Boolean) : null;
230
+
231
+ const controller = new AbortController();
232
+ const cancel = () => controller.abort();
233
+ process.once('SIGINT', cancel);
234
+ process.once('SIGTERM', cancel);
235
+
236
+ const emit = (data, line) => app.output.writeEvent(data, { line });
237
+ // A live record-watcher notification carries `record`: a map of the
238
+ // fields that changed plus sys_* audit fields. It does not carry the
239
+ // `changes` array. Render the changed fields so human output names
240
+ // what moved; the values are current, because the platform does not
241
+ // send the previous value.
242
+ const describeRecord = record => Object.entries(record && typeof record === 'object' ? record : {})
243
+ .filter(([field]) => !field.startsWith('sys_'))
244
+ .slice(0, 5)
245
+ .map(([field, entry]) => {
246
+ const value = entry && typeof entry === 'object' ? (entry.display_value ?? entry.value) : entry;
247
+ return `${field}: ${value === '' || value == null ? '(empty)' : value}`;
248
+ })
249
+ .join(', ');
250
+ const formatEventLine = event => {
251
+ if (event.type === 'record_change') {
252
+ const id = event.display_value || event.sys_id;
253
+ const changes = (event.changes || [])
254
+ .map(c => `${c.field}: ${c.previous_value ?? '?'} → ${c.display_value ?? c.value ?? '?'}`)
255
+ .join(', ');
256
+ const detail = changes || describeRecord(event.record);
257
+ return `${event.received_at} ${event.table} ${id} ${event.operation}${detail ? ` — ${detail}` : ''}`;
258
+ }
259
+ if (event.type === 'unsubscribed') return `unsubscribed${event.reason ? ` (${event.reason})` : ''}`;
260
+ if (event.type === 'gap') return `⚠ connection gap since ${event.since}: ${event.reason} (events in this window were not observed)`;
261
+ if (event.type === 'reconnected') return `⚠ reconnected after ${event.gaps} gap(s); missed events are not replayed`;
262
+ if (event.type === 'watch_summary') {
263
+ return `watch ended (${event.reason}) — ${event.events} event(s), ${event.gaps} gap(s), ${Math.round(event.duration_ms / 1000)}s`;
264
+ }
265
+ if (event.type === 'subscribed') return `watching ${event.channel}`;
266
+ return `${event.type}: ${event.channel || ''}`;
267
+ };
268
+ const onStatus = status => emit(status, formatEventLine(status));
269
+ const onEvent = async event => emit(event, formatEventLine(event));
270
+
271
+ const fetchState = async () => {
272
+ const params = new URLSearchParams({
273
+ sysparm_query: `sys_id=${sysID}`,
274
+ sysparm_limit: '1',
275
+ sysparm_display_value: 'all',
276
+ });
277
+ if (stateFields) params.set('sysparm_fields', [...new Set(['sys_id', ...stateFields])].join(','));
278
+ const rows = await app.sdk.list(argv.table, params);
279
+ return rows[0] ?? null;
280
+ };
281
+
282
+ const client = new AmbClient({
283
+ baseUrl: app.getEffectiveInstance(),
284
+ session: () => app.sdk.ambSession(),
285
+ connectTimeoutMs: argv['poll-timeout'] ?? argv.pollTimeout,
286
+ });
287
+
288
+ try {
289
+ const summary = await watchRecord({
290
+ client,
291
+ table: argv.table,
292
+ sysID,
293
+ timeoutMs: argv.timeout > 0 ? argv.timeout * 1000 : 0,
294
+ maxEvents: argv['max-events'] ?? argv.maxEvents,
295
+ signal: controller.signal,
296
+ statePolicy: argv.state,
297
+ fetchState,
298
+ reconnect: argv.reconnect !== false,
299
+ onStatus,
300
+ onEvent,
301
+ });
302
+ emit(summary, formatEventLine(summary));
303
+ } finally {
304
+ process.removeListener('SIGINT', cancel);
305
+ process.removeListener('SIGTERM', cancel);
306
+ }
307
+ }),
308
+ })
200
309
  .command({
201
310
  command: 'get',
202
311
  describe: 'Get one record by sys_id or an explicit identifier field',
@@ -0,0 +1,312 @@
1
+ import { confirmDelete, quoteShellArg, truncateString } from '../helpers.js';
2
+ import { declareCapabilities } from '../capabilities.js';
3
+ import { AppError, errUsage } from '../errors.js';
4
+ import {
5
+ STORE_TABS, listApplications, showApplication, operationStatus, prepareInstall, prepareUpdate,
6
+ dispatchOperation, waitForOperation, verifyInstalledVersion, boundedLimit, boundedOffset,
7
+ boundedPoll, boundedTimeout,
8
+ } from '../store.js';
9
+
10
+ // Only the lifecycle verbs mutate. search/list/show/status are discovery and
11
+ // inspection: they send no mutation even though the App Client search endpoint
12
+ // is POST-shaped.
13
+ //
14
+ // Install/update are exempt from development capture-context approval for the
15
+ // same reason as catalog ordering: they hand a runtime install request to the
16
+ // App Client, which writes installed-application state rather than capturing
17
+ // metadata into the selected application/update set.
18
+ declareCapabilities('store', {
19
+ mutationSubcommands: ['install', 'update'],
20
+ mutationContextExemptSubcommands: ['install', 'update'],
21
+ });
22
+
23
+ const hint = (action, cmd, description) => ({ action, cmd, description });
24
+
25
+ // Styled views. The generic renderer only prints `data.records` or a flat
26
+ // record, so a store payload (`apps[]` / nested installed+available blocks)
27
+ // rendered as nothing but its summary line. `_formatted` is the documented
28
+ // escape hatch; it is non-enumerable, so --json/--csv are unchanged.
29
+ const cell = (value, width) => truncateString(String(value ?? ''), width).padEnd(width);
30
+
31
+ function attachFormatted(data, text) {
32
+ Object.defineProperty(data, '_formatted', { value: text, enumerable: false, configurable: true });
33
+ return data;
34
+ }
35
+
36
+ function styledApplications(page) {
37
+ const lines = [
38
+ `${page.count} Store application${page.count === 1 ? '' : 's'} (${page.tab}${page.term ? `, search "${page.term}"` : ''})${page.page_full ? '; page full, more may exist' : ''}`,
39
+ '',
40
+ ];
41
+ if (!page.apps.length) {
42
+ lines.push(' (no applications reported for this tab)');
43
+ return lines.join('\n');
44
+ }
45
+ lines.push(`${cell('NAME', 34)} ${cell('SCOPE', 22)} ${cell('INSTALLED', 9)} ${cell('LATEST', 9)} FLAGS`);
46
+ for (const app of page.apps) {
47
+ const blocked = (app.indicators || []).find(item => item.type === 'error');
48
+ const flags = [
49
+ app.installed ? 'installed' : 'not installed',
50
+ app.update_available ? 'update' : '',
51
+ app.blocked ? `blocked${blocked?.message ? `: ${blocked.message}` : ''}` : '',
52
+ ].filter(Boolean).join(', ');
53
+ lines.push(`${cell(app.name, 34)} ${cell(app.scope, 22)} ${cell(app.version || '-', 9)} ${cell(app.latest_version || '-', 9)} ${flags}`);
54
+ }
55
+ return lines.join('\n');
56
+ }
57
+
58
+ function styledApplication(data) {
59
+ const line = (label, value) => ` ${label.padEnd(12)} ${value}`;
60
+ const lines = [
61
+ `${data.name || data.sys_id}${data.scope ? ` (${data.scope})` : ''}`,
62
+ data.installed ? ` installed ${data.installed.version || 'version unknown'}` : ' not installed on this instance',
63
+ '',
64
+ ];
65
+ if (data.installed) {
66
+ lines.push(line('active', data.installed.active === null ? 'unknown' : String(data.installed.active)));
67
+ if (data.installed.install_date) lines.push(line('installed on', data.installed.install_date));
68
+ if (data.installed.update_date) lines.push(line('updated on', data.installed.update_date));
69
+ }
70
+ if (data.available) {
71
+ lines.push(line('latest', data.available.latest_version || 'unknown'));
72
+ lines.push(line('update', data.available.update_available ? 'available' : 'none reported'));
73
+ lines.push(line('versions', data.available.versions?.length ? data.available.versions.join(', ') : 'none reported'));
74
+ if (data.available.compatibilities) lines.push(line('compatible', String(data.available.compatibilities)));
75
+ } else {
76
+ lines.push(line('store data', `unavailable (${data.detail_unavailable || 'no detail returned'})`));
77
+ }
78
+ if (data.entitlement) {
79
+ lines.push(line('installable', data.entitlement.can_install_or_upgrade === null ? 'not reported' : String(data.entitlement.can_install_or_upgrade)));
80
+ if (data.entitlement.price_type) lines.push(line('price', data.entitlement.price_type));
81
+ }
82
+ if (data.blocked) {
83
+ const reasons = (data.indicators || []).map(item => item.message || item.tooltip).filter(Boolean).join('; ');
84
+ lines.push(line('blocked', reasons || 'yes'));
85
+ }
86
+ if (data.dependencies) lines.push(line('depends on', String(data.dependencies)));
87
+ for (const note of data.notes || []) lines.push('', ` note: ${note}`);
88
+ return lines.join('\n');
89
+ }
90
+
91
+ function styledTracker(data) {
92
+ const line = (label, value) => ` ${label.padEnd(10)} ${value}`;
93
+ const lines = [
94
+ `Tracker ${data.tracker_id}`,
95
+ line('status', `${data.status_label || data.status || 'unknown'}${data.status ? ` (${data.status})` : ''}`),
96
+ line('progress', data.percent_complete === null ? 'unknown' : `${data.percent_complete}%`),
97
+ ];
98
+ if (data.status_message) lines.push(line('message', data.status_message));
99
+ if (data.error) lines.push(line('error', data.error));
100
+ if (data.status_detail) lines.push(line('detail', data.status_detail));
101
+ lines.push(line('finished', data.terminal ? 'yes' : 'no'));
102
+ return lines.join('\n');
103
+ }
104
+
105
+ function report(app, argv, data, options) {
106
+ const connection = argv.profile ? ` --profile ${quoteShellArg(argv.profile)}`
107
+ : argv.instance ? ` --instance ${quoteShellArg(argv.instance)}` : '';
108
+ app.ok(data, { ...options, breadcrumbs: (options.breadcrumbs || []).map(item => ({ ...item, cmd: item.cmd + connection })) });
109
+ }
110
+
111
+ const tabOption = p => p.option('tab', { type: 'string', default: 'available', choices: Object.keys(STORE_TABS), describe: 'Store tab context' });
112
+ const pageOptions = p => p.option('limit', { type: 'number', default: 20, describe: 'Maximum applications (1–200)' })
113
+ .option('offset', { type: 'number', default: 0, describe: 'Pagination offset' });
114
+ // The positional is NOT named `app`: cli.js attaches the command's App context
115
+ // as argv.app on every command, so a positional called `app` is overwritten
116
+ // before the handler runs and every identifier arrives as the context object.
117
+ const appOption = p => p.positional('application', { type: 'string', describe: 'Application name, scope, or sys_id' });
118
+ const waitOptions = p => p.option('wait', { type: 'boolean', default: false, describe: 'Poll the tracker until it finishes' })
119
+ .option('timeout', { type: 'number', default: 1800, describe: 'Maximum wait in seconds (1–14400); expiry does not cancel the operation' })
120
+ .option('poll-interval', { type: 'number', default: 5, describe: 'Seconds between progress reads (0–300)' })
121
+ .option('dry-run', { type: 'boolean', default: false, describe: 'Resolve and report the intended operation; send nothing' });
122
+
123
+ function appHints(app) {
124
+ const name = app.scope || app.sys_id;
125
+ return [
126
+ hint('show', `jsn store show ${quoteShellArg(name)}`, 'Inspect installed version, available versions, entitlement and dependencies'),
127
+ hint('status', `jsn store status <tracker-id>`, 'Read operation progress after a submission'),
128
+ ];
129
+ }
130
+
131
+ function listHints(page) {
132
+ const base = page.term ? `jsn store search ${quoteShellArg(page.term)}` : 'jsn store list';
133
+ return [
134
+ ...page.apps.slice(0, 5).map(app => hint('show', `jsn store show ${quoteShellArg(app.scope || app.sys_id)}`, `Inspect ${app.name || app.sys_id}`)),
135
+ ...(page.page_full ? [hint('next', `${base} --tab ${page.tab} --offset ${page.offset + page.limit} --limit ${page.limit}`, 'Next page')] : []),
136
+ hint('updates', 'jsn store list --tab updates', 'List applications with an available update'),
137
+ ];
138
+ }
139
+
140
+ function emitList(app, argv, page) {
141
+ report(app, argv, attachFormatted(page, styledApplications(page)), {
142
+ summary: `${page.count} Store application${page.count === 1 ? '' : 's'} (${page.tab}${page.term ? `, search "${page.term}"` : ''})${page.page_full ? '; page full, more may exist' : ''}`,
143
+ breadcrumbs: listHints(page),
144
+ });
145
+ }
146
+
147
+ async function runLifecycle(argv, app, operation) {
148
+ const prepare = operation === 'install' ? prepareInstall : prepareUpdate;
149
+ const plan = await prepare(app.sdk, argv.application, operation === 'install'
150
+ ? { version: argv.version, demoData: argv.demoData === true }
151
+ : { version: argv.version });
152
+ const publicPlan = {
153
+ operation: plan.operation,
154
+ app: plan.app,
155
+ requested_version: plan.requested_version,
156
+ ...(plan.from_version ? { from_version: plan.from_version } : {}),
157
+ ...(plan.operation === 'install' ? { demo_data: plan.demo_data } : {}),
158
+ versions: plan.versions,
159
+ installable_checked: plan.installable_checked,
160
+ detail_unavailable: plan.detail_unavailable,
161
+ };
162
+ if (argv.dryRun) {
163
+ report(app, argv, { ...publicPlan, dry_run: true, dispatched: false }, {
164
+ summary: `Would ${operation} ${plan.app.name || plan.app.sys_id} version ${plan.requested_version}; nothing was sent`,
165
+ breadcrumbs: appHints(plan.app),
166
+ });
167
+ return;
168
+ }
169
+ const action = operation === 'install' ? 'Install' : `Update ${plan.app.name || plan.app.sys_id}${plan.from_version ? ` from ${plan.from_version}` : ''} to`;
170
+ await confirmDelete(app, argv, `${action} ServiceNow Store application "${plan.app.name || plan.app.sys_id}" version ${plan.requested_version}?`);
171
+ const started = await dispatchOperation(app.sdk, plan);
172
+ const data = { ...publicPlan, ...started, terminal: false, succeeded: null, verification: null };
173
+ if (!argv.wait) {
174
+ report(app, argv, data, {
175
+ summary: `${operation === 'install' ? 'Installation' : 'Update'} submitted: tracker ${started.tracker_id} — not a completed ${operation === 'install' ? 'installation' : 'update'}`,
176
+ breadcrumbs: [hint('status', `jsn store status ${started.tracker_id}`, 'Poll the tracker'), ...appHints(plan.app)],
177
+ });
178
+ return;
179
+ }
180
+ const timeoutMs = boundedTimeout(argv.timeout) * 1000;
181
+ const pollIntervalMs = boundedPoll(argv.pollInterval) * 1000;
182
+ let progress;
183
+ try {
184
+ progress = await waitForOperation(app.sdk, started.tracker_id, { pollIntervalMs, timeoutMs });
185
+ } catch (error) {
186
+ throw new AppError('store_progress_unavailable',
187
+ `${operation === 'install' ? 'Installation' : 'Update'} ${started.tracker_id} was submitted but progress could not be read: ${error.message}. It may still be running.`,
188
+ `Check jsn store status ${started.tracker_id} before doing anything else; do not resubmit automatically.`);
189
+ }
190
+ Object.assign(data, progress);
191
+ if (data.wait_timed_out) {
192
+ report(app, argv, data, {
193
+ summary: `${operation === 'install' ? 'Installation' : 'Update'} ${started.tracker_id}: still running after ${argv.timeout}s (${data.percent_complete ?? 'unknown'}%); not verified`,
194
+ breadcrumbs: [hint('status', `jsn store status ${started.tracker_id}`, 'Read progress again'), ...appHints(plan.app)],
195
+ });
196
+ return;
197
+ }
198
+ if (!data.succeeded) {
199
+ throw new AppError('store_operation_failed',
200
+ // status_label is the tracker's generic verdict ("Failed"); status_message
201
+ // carries the reason ("Unable to download app package"). Report the reason.
202
+ `${operation === 'install' ? 'Installation' : 'Update'} ${started.tracker_id} failed: ${data.status_message || data.status_label || data.error || 'the tracker reported failure'}.`,
203
+ `Read jsn store status ${started.tracker_id} for progress and the application's upgrade history. The application may be partially installed; do not resubmit automatically.`);
204
+ }
205
+ // Readback can lag the tracker. Reuse the operator's poll interval, capped at
206
+ // the module default, so a fast poll also shortens verification.
207
+ const verification = await verifyInstalledVersion(app.sdk, plan.app, plan.requested_version, {
208
+ intervalMs: pollIntervalMs === 0 ? 0 : Math.min(pollIntervalMs, 2000),
209
+ });
210
+ data.verification = verification;
211
+ if (verification.verified === false) {
212
+ throw new AppError('store_verification_failed',
213
+ `${operation === 'install' ? 'Installation' : 'Update'} ${started.tracker_id} reported success, but sys_store_app reads back version ${verification.installed_version ?? '(none)'} instead of ${plan.requested_version}.`,
214
+ `Inspect the application with jsn store show ${quoteShellArg(plan.app.scope || plan.app.sys_id)} and its upgrade history before retrying; a reported success is not a completed ${operation === 'install' ? 'installation' : 'update'}.`);
215
+ }
216
+ const verifiedText = verification.verified === true
217
+ ? `version ${plan.requested_version} verified on sys_store_app`
218
+ : `version not verified (${verification.reason})`;
219
+ report(app, argv, data, {
220
+ summary: `${operation === 'install' ? 'Installed' : 'Updated'} ${plan.app.name || plan.app.sys_id} ${plan.requested_version}; ${verifiedText}`,
221
+ breadcrumbs: [hint('show', `jsn store show ${quoteShellArg(plan.app.scope || plan.app.sys_id)}`, 'Inspect the installed application'), ...appHints(plan.app)],
222
+ });
223
+ }
224
+
225
+ export function storeCmd(wrap) {
226
+ return {
227
+ command: 'store [subcommand]',
228
+ describe: 'Discover ServiceNow Store applications, inspect versions and entitlement, and request explicit installs/updates',
229
+ builder: y => y
230
+ .command({
231
+ command: 'list',
232
+ describe: 'List Store applications for a tab (read-only)',
233
+ builder: p => pageOptions(tabOption(p)),
234
+ handler: wrap(async (argv, app) => {
235
+ const limit = boundedLimit(argv.limit);
236
+ const offset = boundedOffset(argv.offset);
237
+ emitList(app, argv, await listApplications(app.sdk, { tab: argv.tab, limit, offset }));
238
+ }),
239
+ })
240
+ .command({
241
+ command: 'search <term>',
242
+ describe: 'Search Store applications for this instance by term (read-only)',
243
+ builder: p => pageOptions(tabOption(p)).positional('term', { type: 'string', describe: 'Search term' }),
244
+ handler: wrap(async (argv, app) => {
245
+ const term = String(argv.term ?? '').trim();
246
+ if (!term) throw errUsage('Provide a nonempty search term.');
247
+ const limit = boundedLimit(argv.limit);
248
+ const offset = boundedOffset(argv.offset);
249
+ emitList(app, argv, await listApplications(app.sdk, { tab: argv.tab, term, limit, offset }));
250
+ }),
251
+ })
252
+ .command({
253
+ command: 'show <application>',
254
+ describe: 'Inspect installed version, available versions, entitlement, dependencies and compatibility (read-only)',
255
+ builder: appOption,
256
+ handler: wrap(async (argv, app) => {
257
+ const data = await showApplication(app.sdk, argv.application);
258
+ attachFormatted(data, styledApplication(data));
259
+ report(app, argv, data, {
260
+ summary: `Store application: ${data.name || data.sys_id}${data.installed ? ` (installed ${data.installed.version || 'version unknown'})` : ' (not installed)'}`,
261
+ breadcrumbs: [
262
+ hint('show', `jsn store show ${quoteShellArg(data.scope || data.sys_id)}`, 'Inspect this application'),
263
+ ...(data.installed
264
+ ? [hint('update', `jsn store update ${quoteShellArg(data.scope || data.sys_id)} --version <version> --dry-run`, 'Resolve an exact update without sending it')]
265
+ : [hint('install', `jsn store install ${quoteShellArg(data.scope || data.sys_id)} --version <version> --dry-run`, 'Resolve an exact install without sending it')]),
266
+ hint('list', 'jsn store list --tab updates', 'List applications with an available update'),
267
+ ],
268
+ });
269
+ }),
270
+ })
271
+ .command({
272
+ command: 'status <tracker>',
273
+ describe: 'Read asynchronous install/update progress (read-only)',
274
+ builder: p => p.positional('tracker', { type: 'string', describe: 'Tracker sys_id reported by install/update' }),
275
+ handler: wrap(async (argv, app) => {
276
+ const data = await operationStatus(app.sdk, argv.tracker);
277
+ attachFormatted(data, styledTracker(data));
278
+ report(app, argv, data, {
279
+ summary: `Tracker ${data.tracker_id}: ${data.status_label || data.status || 'unknown'}${data.percent_complete === null ? '' : ` ${data.percent_complete}%`}${data.terminal ? '' : ' (running)'}${data.status_message ? ` — ${data.status_message}` : data.error ? ` — ${data.error}` : ''}`,
280
+ breadcrumbs: [
281
+ ...(data.terminal ? [] : [hint('status', `jsn store status ${data.tracker_id}`, 'Read progress again')]),
282
+ hint('list', 'jsn store list --tab updates', 'List applications with an available update'),
283
+ ],
284
+ });
285
+ }),
286
+ })
287
+ .command({
288
+ command: 'install <application>',
289
+ describe: 'Install an exact Store application version (declared mutation; contract verified, completion unverified)',
290
+ builder: p => waitOptions(appOption(p))
291
+ .option('version', { type: 'string', describe: 'Exact version to install (required)' })
292
+ .option('demo-data', { type: 'boolean', default: false, describe: 'Load demo data during installation' }),
293
+ handler: wrap(async (argv, app) => runLifecycle(argv, app, 'install')),
294
+ })
295
+ .command({
296
+ command: 'update <application>',
297
+ describe: 'Update an installed Store application to an exact version (declared mutation; contract verified, completion unverified)',
298
+ builder: p => waitOptions(appOption(p))
299
+ .option('version', { type: 'string', describe: 'Exact target version; defaults to the reported latest_version' }),
300
+ handler: wrap(async (argv, app) => runLifecycle(argv, app, 'update')),
301
+ }),
302
+ handler: wrap(async (argv, app) => {
303
+ report(app, argv, { commands: ['search', 'list', 'show', 'status', 'install', 'update'] }, {
304
+ summary: 'ServiceNow Store applications',
305
+ breadcrumbs: [hint('list', 'jsn store list --tab installed', 'List installed applications'),
306
+ hint('search', 'jsn store search "<term>"', 'Search applications available to this instance'),
307
+ hint('show', 'jsn store show <app>', 'Inspect one application'),
308
+ hint('status', 'jsn store status <tracker>', 'Read install/update progress')],
309
+ });
310
+ }),
311
+ };
312
+ }