@jacebenson/jsn 5.2.0 → 5.3.0-dev.136.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.
@@ -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
+ }
@@ -10,10 +10,11 @@ import { AppError, CodeConfirmationRequired, errAPI, errUsage, errConfirmationRe
10
10
  import { declareCapabilities } from '../capabilities.js';
11
11
  import { resolveScope } from './scopes.js';
12
12
  import { unwrapSysId } from '../resolve-record.js';
13
+ import { assertNoUnresolvedProblems, DEFAULT_OPERATION_TIMEOUT_MS } from '../update-set-apply.js';
13
14
 
14
15
  declareCapabilities('updatesets', {
15
- mutationSubcommands: ['create', 'set', 'complete', 'ignore', 'parent', 'import', 'reopen'],
16
- mutationContextExemptSubcommands: ['create', 'set', 'import', 'reopen'],
16
+ mutationSubcommands: ['create', 'set', 'complete', 'ignore', 'parent', 'import', 'reopen', 'preview', 'commit'],
17
+ mutationContextExemptSubcommands: ['create', 'set', 'import', 'reopen', 'preview', 'commit'],
17
18
  localPreviewSubcommands: ['import'],
18
19
  });
19
20
 
@@ -97,6 +98,121 @@ export async function resolveUpdateSetByName(app, name) {
97
98
  throw errUsage(`Multiple update sets named "${name}" (${records.length}): ${scopes}.${scopeNote}\nRun bare "jsn updatesets set" and pick by scope.`);
98
99
  }
99
100
 
101
+ const RETRIEVED_FIELDS = 'sys_id,name,state,remote_sys_id,update_set,sys_created_on,sys_updated_on';
102
+
103
+ function remoteState(record) {
104
+ const raw = record?.state;
105
+ return String(raw?.value ?? raw ?? '').toLowerCase();
106
+ }
107
+
108
+ /**
109
+ * Resolve a *retrieved* update set (sys_remote_update_set) by exact name or
110
+ * sys_id. Imported XML lives here; local capture sets live in sys_update_set.
111
+ * @returns {Promise<object>} raw record
112
+ */
113
+ export async function resolveRetrievedUpdateSet(app, identifier) {
114
+ assertSafeExactMatch(identifier);
115
+ const isSysID = /^[0-9a-f]{32}$/i.test(identifier);
116
+ const params = new URLSearchParams();
117
+ params.set('sysparm_query', isSysID ? `sys_id=${identifier}` : `name=${identifier}`);
118
+ params.set('sysparm_limit', isSysID ? '1' : '20');
119
+ params.set('sysparm_display_value', 'all');
120
+ params.set('sysparm_fields', RETRIEVED_FIELDS);
121
+ const records = await app.sdk.list('sys_remote_update_set', params);
122
+ if (!records.length) {
123
+ throw errUsage(
124
+ `Retrieved update set not found: ${identifier}`,
125
+ `Load the XML first (jsn updatesets import <file>), or pass the sys_id of the retrieved set.`,
126
+ );
127
+ }
128
+ if (records.length > 1) {
129
+ throw errUsage(`Multiple retrieved update sets named "${identifier}". Pass the sys_id instead:\n${records.map((r) => ` ${getStringField(r, 'sys_id')} ${remoteState(r)}`).join('\n')}`);
130
+ }
131
+ return records[0];
132
+ }
133
+
134
+ async function fetchRetrievedUpdateSet(app, sysID) {
135
+ const params = new URLSearchParams();
136
+ params.set('sysparm_query', `sys_id=${sysID}`);
137
+ params.set('sysparm_limit', '1');
138
+ params.set('sysparm_display_value', 'all');
139
+ params.set('sysparm_fields', RETRIEVED_FIELDS);
140
+ const [record] = await app.sdk.list('sys_remote_update_set', params);
141
+ return record || null;
142
+ }
143
+
144
+ /**
145
+ * Confirmation gate shared by updatesets mutations. Automation gets a
146
+ * confirmation-required error with a rerun command instead of a prompt.
147
+ * @returns {Promise<boolean>} false when the human declined
148
+ */
149
+ async function confirmUpdateSetMutation(argv, app, question, rerun) {
150
+ if (argv.yes) return true;
151
+ if (!canPrompt() || argv.json || argv.get || (argv.format && argv.format !== FormatAuto)) {
152
+ throw new AppError(CodeConfirmationRequired, `${question} — confirmation required. Pass --yes after approving this target.`,
153
+ `Rerun: ${buildRerunCommand(argv, { rerun })}`);
154
+ }
155
+ return confirm({ message: question, default: false });
156
+ }
157
+
158
+ function timeoutFrom(argv) {
159
+ const seconds = Number(argv.timeout ?? DEFAULT_OPERATION_TIMEOUT_MS / 1000);
160
+ if (!Number.isFinite(seconds) || seconds <= 0) throw errUsage('--timeout must be a positive number of seconds');
161
+ return Math.round(seconds * 1000);
162
+ }
163
+
164
+ /**
165
+ * The platform records the local update set a commit produced on the retrieved
166
+ * record itself (`sys_remote_update_set.update_set`). Prefer that exact
167
+ * reference; only fall back to a name lookup when it is absent.
168
+ */
169
+ function localReferenceID(reference) {
170
+ if (!reference) return '';
171
+ if (typeof reference === 'object') {
172
+ const value = String(reference.value ?? '').trim();
173
+ if (/^[0-9a-f]{32}$/i.test(value)) return value;
174
+ const link = String(reference.link ?? '');
175
+ const match = link.match(/\/([0-9a-f]{32})(?:\/)?$/i);
176
+ return match ? match[1] : '';
177
+ }
178
+ return /^[0-9a-f]{32}$/i.test(String(reference).trim()) ? String(reference).trim() : '';
179
+ }
180
+
181
+ /**
182
+ * Find the local update set a commit created. Ambiguity is reported, not
183
+ * guessed: duplicate names are legitimate on ServiceNow.
184
+ */
185
+ async function findLocalUpdateSet(app, name, reference) {
186
+ const referenceID = localReferenceID(reference);
187
+ if (referenceID) {
188
+ try {
189
+ const record = await app.sdk.get('sys_update_set', referenceID);
190
+ if (record) {
191
+ return {
192
+ sys_id: getStringField(record, 'sys_id') || referenceID,
193
+ name: getStringField(record, 'name') || name,
194
+ state: String(record.state?.value ?? record.state ?? ''),
195
+ ambiguous: false,
196
+ };
197
+ }
198
+ } catch { /* fall back to the name lookup */ }
199
+ }
200
+ const params = new URLSearchParams();
201
+ params.set('sysparm_query', `name=${name}^ORDERBYDESCsys_created_on`);
202
+ params.set('sysparm_display_value', 'all');
203
+ params.set('sysparm_limit', '2');
204
+ params.set('sysparm_fields', 'sys_id,name,state,sys_created_on');
205
+ try {
206
+ const records = await app.sdk.list('sys_update_set', params);
207
+ if (records.length === 1) {
208
+ return { sys_id: getStringField(records[0], 'sys_id'), name: getStringField(records[0], 'name'), state: String(records[0].state?.value ?? records[0].state ?? ''), ambiguous: false };
209
+ }
210
+ return { ambiguous: true, count: records.length, note: records.length ? 'Multiple local update sets share this name' : 'No local update set with this name was found' };
211
+ } catch (error) {
212
+ return { ambiguous: false, unverified: true, note: `Could not read local update sets: ${error.message}` };
213
+ }
214
+ }
215
+
100
216
 
101
217
  function rawReferenceId(value) {
102
218
  if (!value) return '';
@@ -546,8 +662,23 @@ export function updateSetsCmd(wrap) {
546
662
  builder: y => y
547
663
  .positional('file', { type: 'string', describe: 'Update set XML export' })
548
664
  .option('dry-run', { type: 'boolean', describe: 'Inspect locally without any instance requests' })
549
- .option('yes', { type: 'boolean', describe: 'Confirm loading the displayed XML into the selected target' }),
665
+ .option('yes', { type: 'boolean', describe: 'Confirm loading the displayed XML into the selected target' })
666
+ .option('name', { type: 'string', describe: 'Unsupported: the set keeps the name in its XML envelope' })
667
+ .option('local', { type: 'boolean', describe: 'Unsupported: import always loads a retrieved update set' })
668
+ .option('state', { type: 'string', describe: 'Unsupported: import never changes state' }),
550
669
  handler: wrap(async (argv, app) => {
670
+ // The proposed import modifiers are refused explicitly so none of
671
+ // them can silently rewrite identity, convert the target table, or
672
+ // flip state. Preview/commit/reopen are the supported transitions.
673
+ if (argv.name !== undefined) {
674
+ throw errUsage('Import cannot rename a retrieved update set: its name, sys_id, and remote_sys_id come from the exported envelope, so rewriting them would change the set\'s identity.\nLoad it unchanged, then rename the retrieved set in ServiceNow if you need a different name.');
675
+ }
676
+ if (argv.local) {
677
+ throw errUsage('Import always creates a retrieved update set (sys_remote_update_set); it does not convert XML into a local capture set.\nPreview and commit it to apply the changes (jsn updatesets preview / commit).');
678
+ }
679
+ if (argv.state !== undefined) {
680
+ throw errUsage('Import never sets state. A loaded retrieved set is previewed and committed explicitly; a local set is reopened with "jsn updatesets reopen".');
681
+ }
551
682
  const stat = await fs.promises.stat(argv.file);
552
683
  if (!stat.isFile() || stat.size > MAX_UPDATE_SET_BYTES) throw errUsage('Expected an XML file no larger than 50 MiB');
553
684
  const xml = await fs.promises.readFile(argv.file, 'utf8');
@@ -556,15 +687,123 @@ export function updateSetsCmd(wrap) {
556
687
  if (argv.dryRun) return app.ok({ ...summary, members, dry_run: true }, { summary: `XML: ${inspection.name}; ${inspection.count} updates (local inspection only)` });
557
688
  app.requireInstance();
558
689
  const question = `Load "${inspection.name}" (${inspection.count} updates) into ${app.getEffectiveInstance()} as a retrieved update set? This does not commit its changes.`;
559
- if (!argv.yes) {
560
- if (!canPrompt() || argv.json || argv.get || (argv.format && argv.format !== FormatAuto)) {
561
- throw new AppError(CodeConfirmationRequired, `${question} — confirmation required. Pass --yes after approving this target.`,
562
- `Rerun: ${buildRerunCommand(argv, { rerun: ['updatesets', 'import', argv.file, '--yes'] })}`);
563
- }
564
- if (!await confirm({ message: question, default: false })) return;
565
- }
690
+ if (!await confirmUpdateSetMutation(argv, app, question, ['updatesets', 'import', argv.file, '--yes'])) return;
566
691
  const result = await app.sdk.importUpdateSet(xml, inspection, path.basename(argv.file));
567
- app.ok({ ...summary, ...result, committed: false }, { summary: `Loaded retrieved update set "${inspection.name}" (${result.count} updates); not committed` });
692
+ app.ok({ ...summary, ...result, committed: false }, {
693
+ summary: `Loaded retrieved update set "${inspection.name}" (${result.count} updates); not committed`,
694
+ breadcrumbs: [
695
+ { action: 'preview', cmd: `jsn updatesets preview ${quoteShellArg(result.sys_id)}`, description: 'Preview against this instance before committing' },
696
+ { action: 'problems', cmd: `jsn updatesets problems ${quoteShellArg(result.sys_id)}`, description: 'Review preview problems' },
697
+ ],
698
+ });
699
+ }),
700
+ })
701
+ .command({
702
+ command: 'preview <name>',
703
+ describe: 'Run the platform preview for a loaded retrieved update set and report its problems',
704
+ builder: y => y
705
+ .positional('name', { type: 'string', describe: 'Retrieved update set name or sys_id' })
706
+ .option('yes', { type: 'boolean', describe: 'Confirm starting the preview on the selected target' })
707
+ .option('timeout', { type: 'number', describe: 'Seconds to wait for the preview tracker (default 600)' }),
708
+ handler: wrap(async (argv, app) => {
709
+ app.requireInstance();
710
+ const target = await resolveRetrievedUpdateSet(app, argv.name);
711
+ const sysID = getStringField(target, 'sys_id');
712
+ const state = remoteState(target);
713
+ if (!['loaded', 'previewed'].includes(state)) {
714
+ throw errUsage(`Cannot preview a retrieved update set in state "${state}"; expected loaded or previewed.\nInspect it first: jsn records get sys_remote_update_set ${sysID}`);
715
+ }
716
+ const question = `Preview retrieved update set "${getStringField(target, 'name')}" (state: ${state}) on ${app.getEffectiveInstance()}? Preview does not commit changes.`;
717
+ if (!await confirmUpdateSetMutation(argv, app, question, ['updatesets', 'preview', sysID, '--yes'])) return;
718
+ const progress = await app.sdk.previewUpdateSet(sysID, { timeoutMs: timeoutFrom(argv) });
719
+ const verified = await fetchRetrievedUpdateSet(app, sysID);
720
+ if (!verified || remoteState(verified) !== 'previewed') {
721
+ throw errAPI(200, `Preview reported "${progress.label}" but the retrieved update set is in state "${verified ? remoteState(verified) || 'unknown' : 'unreadable'}".\nInspect it in ServiceNow before committing; jsn will not commit a set the platform has not previewed.`);
722
+ }
723
+ const { problems, count, unresolved, truncated } = await app.sdk.listUpdateSetPreviewProblems(sysID);
724
+ app.ok({
725
+ update_set: getStringField(target, 'name'),
726
+ sys_id: sysID,
727
+ state: 'previewed',
728
+ preview: { status: progress.label, percent_complete: progress.percent_complete, message: progress.message, tracked: progress.tracked !== false },
729
+ problems: count,
730
+ unresolved: unresolved.length,
731
+ truncated,
732
+ problems_detail: problems,
733
+ }, {
734
+ summary: `Previewed retrieved update set "${getStringField(target, 'name')}": ${unresolved.length} unresolved problem(s) of ${count}`,
735
+ breadcrumbs: unresolved.length
736
+ ? [{ action: 'problems', cmd: `jsn updatesets problems ${quoteShellArg(sysID)}`, description: 'Review the problems a human must resolve' }]
737
+ : [{ action: 'commit', cmd: `jsn updatesets commit ${quoteShellArg(sysID)} --yes`, description: 'Commit after reviewing the preview' }],
738
+ });
739
+ }),
740
+ })
741
+ .command({
742
+ command: 'problems <name>',
743
+ aliases: ['preview-problems'],
744
+ describe: 'List preview problems for a retrieved update set (read-only; never resolves them)',
745
+ builder: y => y
746
+ .positional('name', { type: 'string', describe: 'Retrieved update set name or sys_id' })
747
+ .option('include-resolved', { type: 'boolean', describe: 'Include problems a human already accepted or skipped' }),
748
+ handler: wrap(async (argv, app) => {
749
+ app.requireInstance();
750
+ const target = await resolveRetrievedUpdateSet(app, argv.name);
751
+ const sysID = getStringField(target, 'sys_id');
752
+ const { problems, count, unresolved, truncated } = await app.sdk.listUpdateSetPreviewProblems(sysID);
753
+ const shown = argv.includeResolved ? problems : unresolved;
754
+ app.ok({
755
+ update_set: getStringField(target, 'name'),
756
+ sys_id: sysID,
757
+ state: remoteState(target),
758
+ count,
759
+ unresolved: unresolved.length,
760
+ truncated,
761
+ problems: shown,
762
+ }, {
763
+ summary: `${unresolved.length} unresolved preview problem(s) for "${getStringField(target, 'name')}" (${count} total)`,
764
+ breadcrumbs: [{ action: 'show', cmd: `jsn records get sys_remote_update_set ${quoteShellArg(sysID)}`, description: 'Open the retrieved update set record' }],
765
+ });
766
+ }),
767
+ })
768
+ .command({
769
+ command: 'commit <name>',
770
+ describe: 'Commit a previewed retrieved update set once its preview problems are resolved',
771
+ builder: y => y
772
+ .positional('name', { type: 'string', describe: 'Retrieved update set name or sys_id' })
773
+ .option('yes', { type: 'boolean', describe: 'Confirm applying the update set to the selected target' })
774
+ .option('timeout', { type: 'number', describe: 'Seconds to wait for the commit tracker (default 600)' }),
775
+ handler: wrap(async (argv, app) => {
776
+ app.requireInstance();
777
+ const target = await resolveRetrievedUpdateSet(app, argv.name);
778
+ const sysID = getStringField(target, 'sys_id');
779
+ const name = getStringField(target, 'name');
780
+ const state = remoteState(target);
781
+ if (state === 'loaded') {
782
+ throw errUsage(`Retrieved update set "${name}" has not been previewed yet.\nRun: jsn updatesets preview ${quoteShellArg(sysID)}`);
783
+ }
784
+ if (state !== 'previewed') {
785
+ throw errUsage(`Cannot commit a retrieved update set in state "${state}"; expected previewed.`);
786
+ }
787
+ const previewProblems = await app.sdk.listUpdateSetPreviewProblems(sysID);
788
+ assertNoUnresolvedProblems(previewProblems);
789
+ const question = `Commit retrieved update set "${name}" (${previewProblems.count} preview problem(s), none unresolved) to ${app.getEffectiveInstance()}? This applies its changes to the instance.`;
790
+ if (!await confirmUpdateSetMutation(argv, app, question, ['updatesets', 'commit', sysID, '--yes'])) return;
791
+ const progress = await app.sdk.commitUpdateSet(sysID, { timeoutMs: timeoutFrom(argv) });
792
+ const verified = await fetchRetrievedUpdateSet(app, sysID);
793
+ if (!verified || remoteState(verified) !== 'committed') {
794
+ throw errAPI(200, `Commit reported "${progress.label}" but the retrieved update set is in state "${verified ? remoteState(verified) || 'unknown' : 'unreadable'}".\nThe commit may still be running; inspect Retrieved Update Sets on the target before retrying. jsn does not retry it.`);
795
+ }
796
+ const local = await findLocalUpdateSet(app, name, verified.update_set);
797
+ app.ok({
798
+ update_set: name,
799
+ sys_id: sysID,
800
+ state: 'committed',
801
+ commit: { status: progress.label, percent_complete: progress.percent_complete, message: progress.message, tracked: progress.tracked !== false },
802
+ preview_problems: previewProblems.count,
803
+ local_update_set: local,
804
+ }, {
805
+ summary: `Committed retrieved update set "${name}"${local.sys_id ? ` as local update set ${local.sys_id}` : ` (${local.note || 'local update set not confirmed'})`}`,
806
+ });
568
807
  }),
569
808
  })
570
809
  .command({
@@ -789,6 +1028,9 @@ export function updateSetsCmd(wrap) {
789
1028
  console.log(' show <name> Show an update set (type counts + risky items)');
790
1029
  console.log(' export <name> Export an update set to XML (stdout or --out)');
791
1030
  console.log(' import <file> Load retrieved XML (--dry-run inspects locally; --yes confirms)');
1031
+ console.log(' preview <set> Platform preview of a loaded retrieved set; reports problems');
1032
+ console.log(' problems <set> List preview problems (read-only; never resolves them)');
1033
+ console.log(' commit <set> Commit a previewed retrieved set after problems are resolved');
792
1034
  console.log(' reopen <name> Explicitly return a closed set to in progress');
793
1035
  console.log(' set [name] Set the current update set (picker when run bare)');
794
1036
  console.log(' create Create a new update set (auto-sets as current)');
package/src/errors.js CHANGED
@@ -54,6 +54,11 @@ export function errAuth(msg) {
54
54
  return new AppError(CodeAuth, msg, 'Run: jsn auth login');
55
55
  }
56
56
 
57
+ /** Authentication failure with domain-specific recovery guidance. */
58
+ export function errAuthHint(msg, hint) {
59
+ return new AppError(CodeAuth, msg, hint);
60
+ }
61
+
57
62
  export function errForbidden(msg) {
58
63
  return new AppError(CodeForbidden, msg, '', 403);
59
64
  }
@@ -265,9 +270,11 @@ export function renderAppError(err, { app = null, argv = null, identifier = '' }
265
270
 
266
271
  if (code === CodeNotFound) {
267
272
  let text = `Error (${code}): ${err.message}\n`;
268
- if (identifier) {
269
- text += `\nHint: The identifier "${identifier}" was not found. Check the name or sys_id.\n`;
270
- }
273
+ // A command that knows why the identifier missed says so; the generic line
274
+ // is only the fallback (it used to replace every command-specific hint, and
275
+ // interpolated the subcommand name as if it were the identifier).
276
+ if (err.hint) text += `\nHint: ${err.hint}\n`;
277
+ else if (identifier) text += `\nHint: The identifier "${identifier}" was not found. Check the name or sys_id.\n`;
271
278
  return { stream: 'stderr', text, exitCode: 1 };
272
279
  }
273
280