@jacebenson/jsn 5.5.9-dev.223.1 → 5.5.9-dev.225.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 +1 -1
- package/skills/servicenow/SKILL.md +3 -0
- package/src/commands/flows.js +2 -1
- package/src/commands/records.js +76 -2
- package/src/commands/updatesets.js +6 -1
- package/src/flow-search.js +34 -9
- package/src/help.js +24 -7
- package/src/sdk.js +85 -8
package/package.json
CHANGED
|
@@ -18,6 +18,9 @@ Discover commands with `jsn --help`, `jsn discover "search words"`, and
|
|
|
18
18
|
approval before using eval; avoid bypassing ServiceNow protections.
|
|
19
19
|
- Honor delete confirmations. Get approval for destructive work and Global +
|
|
20
20
|
Default mutations; use `--force` only for the approved operation.
|
|
21
|
+
- Deleting several records by filter is `jsn records delete-many`, not `eval`.
|
|
22
|
+
It previews without `--yes`, and a real delete requires the exact
|
|
23
|
+
`--expect-count` from that preview.
|
|
21
24
|
|
|
22
25
|
For development:
|
|
23
26
|
|
package/src/commands/flows.js
CHANGED
|
@@ -97,6 +97,7 @@ export function flowsCmd(wrap) {
|
|
|
97
97
|
builder: y => y
|
|
98
98
|
.positional('term', { type: 'string', describe: 'Case-insensitive literal text to find in readable definitions' })
|
|
99
99
|
.option('refresh', { type: 'boolean', default: false, describe: 'Rebuild the decoded cache; warm searches still revalidate source access' })
|
|
100
|
+
.option('concurrency', { type: 'number', default: 6, describe: 'Parallel definition downloads (1 = one at a time); instance reads still happen for every visible flow' })
|
|
100
101
|
.epilogue(`Example:
|
|
101
102
|
jsn flows search approval
|
|
102
103
|
Interactive use can pick a flow; scripts pass the term.
|
|
@@ -105,7 +106,7 @@ Documentation: ${docLink('flows')}`),
|
|
|
105
106
|
app.requireInstance();
|
|
106
107
|
const session = app.session || {};
|
|
107
108
|
const result = await searchFlows({
|
|
108
|
-
sdk: app.sdk, term: argv.term, refresh: argv.refresh,
|
|
109
|
+
sdk: app.sdk, term: argv.term, refresh: argv.refresh, concurrency: argv.concurrency,
|
|
109
110
|
context: { profile: session.profileName, username: session.username, domain: session.domain, authMethod: session.profile?.auth_method },
|
|
110
111
|
progress: message => {
|
|
111
112
|
if (!argv.json && !argv.get && (!argv.format || ['auto', 'pretty', 'styled'].includes(argv.format))) process.stderr.write(`${message}\n`);
|
package/src/commands/records.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { formatCommandList, formatRecordForDisplay, findOmittedColumns, buildQuerySuffix, buildRecordPayload, getStringField, interactiveList, resolveFieldsParam, checkDerivedFields, confirmDelete, verifyWriteBack } from '../helpers.js';
|
|
1
|
+
import { formatCommandList, formatRecordForDisplay, findOmittedColumns, buildQuerySuffix, buildRecordPayload, getStringField, interactiveList, resolveFieldsParam, checkDerivedFields, confirmDelete, verifyWriteBack, quoteShellArg } from '../helpers.js';
|
|
2
2
|
import { listRecords, recordListParams, getRecord, createRecord, updateRecord, deleteRecord } from '../records-engine.js';
|
|
3
3
|
import { resolveRecord, unwrapSysId } from '../resolve-record.js';
|
|
4
4
|
import { errUsage } from '../errors.js';
|
|
@@ -9,7 +9,7 @@ import { assertMutationRecordScope, assertMutationScope } from '../intended-cont
|
|
|
9
9
|
|
|
10
10
|
declareCapabilities('records', {
|
|
11
11
|
mutationContext: 'table',
|
|
12
|
-
mutationSubcommands: ['create', 'update', 'delete', 'bulk'],
|
|
12
|
+
mutationSubcommands: ['create', 'update', 'delete', 'delete-many', 'bulk'],
|
|
13
13
|
});
|
|
14
14
|
|
|
15
15
|
const tableDefaultColumns = {
|
|
@@ -429,6 +429,80 @@ export function recordsCmd(wrap) {
|
|
|
429
429
|
app.ok({ message: 'Record deleted', table: argv.table, sys_id: sysID }, { summary: `Deleted record from ${argv.table}` });
|
|
430
430
|
}),
|
|
431
431
|
})
|
|
432
|
+
.command({
|
|
433
|
+
command: 'delete-many',
|
|
434
|
+
describe: 'Delete records matching a filter; preview by default, verify after deletion',
|
|
435
|
+
builder: (y) => y
|
|
436
|
+
.option('table', { type: 'string', demandOption: true, describe: 'Table name' })
|
|
437
|
+
.option('query', { type: 'string', describe: 'Required nonempty encoded query; use records delete for a single record' })
|
|
438
|
+
.option('expect-count', { type: 'number', describe: 'Required for deletion: exact expected matching count' })
|
|
439
|
+
.option('yes', { type: 'boolean', default: false, describe: 'Confirm deletion (requires --expect-count)' })
|
|
440
|
+
.option('dry-run', { type: 'boolean', default: false, describe: 'Preview only, even with --yes' })
|
|
441
|
+
.option('limit', { type: 'number', default: 200, describe: 'Safety cap: refuse if matches exceed this count' })
|
|
442
|
+
.epilogue('Without --yes, reports count and up to 10 sample records without writes.\nDeletion uses per-record Table API DELETE, then re-counts the query. Concurrent changes cannot be made atomic.'),
|
|
443
|
+
handler: wrap(async (argv, app) => {
|
|
444
|
+
if (!argv.query?.trim()) throw errUsage('--query must be nonempty. Use records delete for a single record.');
|
|
445
|
+
if (!Number.isSafeInteger(argv.limit) || argv.limit < 1) throw errUsage('--limit must be a positive safe integer.');
|
|
446
|
+
const dryRun = !argv.yes || argv['dry-run'];
|
|
447
|
+
const expected = argv['expect-count'];
|
|
448
|
+
if (!dryRun && (!Number.isSafeInteger(expected) || expected < 0)) throw errUsage('Deletion requires --expect-count as a nonnegative safe integer.');
|
|
449
|
+
const countMatches = async () => {
|
|
450
|
+
const count = await app.sdk.aggregateCount(argv.table, argv.query);
|
|
451
|
+
if (!Number.isSafeInteger(count) || count < 0) throw new Error('Cannot verify matching count; refusing deletion.');
|
|
452
|
+
return count;
|
|
453
|
+
};
|
|
454
|
+
const count = await countMatches();
|
|
455
|
+
if (count > argv.limit) throw errUsage(`Matched ${count} records, exceeding --limit ${argv.limit}. Raise --limit explicitly to proceed.`);
|
|
456
|
+
if (!dryRun && count !== expected) throw errUsage(`Count mismatch: --expect-count ${expected}, live count ${count}. No records deleted.`);
|
|
457
|
+
const readPage = (limit, offset) => listRecords(app.sdk, { table: argv.table,
|
|
458
|
+
params: recordListParams({ query: argv.query, limit, offset, fields: ['sys_id', 'number'], displayValue: 'false' }) });
|
|
459
|
+
const rerun = ['jsn', 'records', 'delete-many', '--table', argv.table, '--query', argv.query,
|
|
460
|
+
'--expect-count', String(count), '--limit', String(argv.limit), '--yes'].map(quoteShellArg).join(' ');
|
|
461
|
+
const breadcrumbs = [{ action: 'verify', cmd: `jsn records aggregate --table ${quoteShellArg(argv.table)} --query ${quoteShellArg(argv.query)}`, description: 'Re-check matching records' }];
|
|
462
|
+
if (dryRun) {
|
|
463
|
+
const sample = count ? await readPage(Math.min(10, count), 0) : [];
|
|
464
|
+
return app.ok({ table: argv.table, query: argv.query, count, dry_run: true, sample, rerun }, {
|
|
465
|
+
summary: `Dry run: ${count} record(s) in ${argv.table} would be deleted`,
|
|
466
|
+
breadcrumbs: [{ action: 'delete', cmd: rerun, description: 'Delete with this exact expected count' }],
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
// Snapshot all targets before deleting: offset paging over a shrinking set skips rows.
|
|
470
|
+
const targets = [];
|
|
471
|
+
while (targets.length < count) {
|
|
472
|
+
const rows = await readPage(Math.min(1000, count - targets.length), targets.length);
|
|
473
|
+
if (!rows.length) break;
|
|
474
|
+
targets.push(...rows);
|
|
475
|
+
if (targets.length > count) break;
|
|
476
|
+
}
|
|
477
|
+
const ids = targets.map(unwrapSysId);
|
|
478
|
+
if (targets.length !== count || ids.some(id => !id) || new Set(ids).size !== count) {
|
|
479
|
+
throw errUsage('Enumeration differs from the counted targets or contains unreadable/duplicate sys_ids. No records deleted.');
|
|
480
|
+
}
|
|
481
|
+
if (await countMatches() !== count) throw errUsage('Matching count changed during enumeration. No records deleted.');
|
|
482
|
+
// Preflight all customization scopes before the first write, as bulk does.
|
|
483
|
+
if (app.mutationContext?.verified) {
|
|
484
|
+
for (const id of ids) await assertMutationRecordScope(app, argv.table, id);
|
|
485
|
+
}
|
|
486
|
+
const deleted = [];
|
|
487
|
+
const failed = [];
|
|
488
|
+
for (const record of targets) {
|
|
489
|
+
try { deleted.push(await deleteRecord(app.sdk, { table: argv.table, record })); }
|
|
490
|
+
catch (error) { failed.push({ sys_id: unwrapSysId(record), error: error.message || String(error) }); }
|
|
491
|
+
}
|
|
492
|
+
let remaining = null;
|
|
493
|
+
let verificationError;
|
|
494
|
+
try { remaining = await countMatches(); }
|
|
495
|
+
catch (error) { verificationError = error.message; }
|
|
496
|
+
const verified = failed.length === 0 && remaining === 0;
|
|
497
|
+
app.ok({ table: argv.table, query: argv.query, matched: count, deleted, failed, remaining,
|
|
498
|
+
verified, ...(verificationError ? { verification_error: verificationError } : {}) }, {
|
|
499
|
+
summary: verified ? `Deleted ${deleted.length} record(s) from ${argv.table}; verified zero remaining`
|
|
500
|
+
: `Deletion incomplete or unverified: ${deleted.length} deleted, ${failed.length} failed, ${remaining ?? 'unknown'} remaining`,
|
|
501
|
+
breadcrumbs,
|
|
502
|
+
});
|
|
503
|
+
if (!verified) process.exitCode = 1;
|
|
504
|
+
}),
|
|
505
|
+
})
|
|
432
506
|
.command({
|
|
433
507
|
command: 'aggregate',
|
|
434
508
|
describe: 'Run ServiceNow Stats API aggregation with optional grouping',
|
|
@@ -700,8 +700,13 @@ export function updateSetsCmd(wrap) {
|
|
|
700
700
|
const question = `Load "${inspection.name}" (${inspection.count} updates) into ${app.getEffectiveInstance()} as a retrieved update set? This does not commit its changes.`;
|
|
701
701
|
if (!await confirmUpdateSetMutation(argv, app, question, ['updatesets', 'import', argv.file, '--yes'])) return;
|
|
702
702
|
const result = await app.sdk.importUpdateSet(xml, inspection, path.basename(argv.file));
|
|
703
|
+
const summaryText = result.already_loaded
|
|
704
|
+
? `Retrieved update set "${inspection.name}" was already loaded on this target (${result.state}); nothing was uploaded again`
|
|
705
|
+
: result.recovered_after_error
|
|
706
|
+
? `Retrieved update set "${inspection.name}" is loaded (${result.count} updates); confirmed after a transport error, not committed`
|
|
707
|
+
: `Loaded retrieved update set "${inspection.name}" (${result.count} updates); not committed`;
|
|
703
708
|
app.ok({ ...summary, ...result, committed: false }, {
|
|
704
|
-
summary:
|
|
709
|
+
summary: summaryText,
|
|
705
710
|
breadcrumbs: [
|
|
706
711
|
{ action: 'preview', cmd: `jsn updatesets preview ${quoteShellArg(result.sys_id)}`, description: 'Preview against this instance before committing' },
|
|
707
712
|
{ action: 'problems', cmd: `jsn updatesets problems ${quoteShellArg(result.sys_id)}`, description: 'Review preview problems' },
|
package/src/flow-search.js
CHANGED
|
@@ -52,9 +52,10 @@ export function formatFlowSearch(report) {
|
|
|
52
52
|
].join('\n');
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
-
export async function searchFlows({ sdk, term, context = {}, refresh = false, cacheRoot, platform = process.platform, pageSize = 100, maxPages = 10000, progress = () => {} }) {
|
|
55
|
+
export async function searchFlows({ sdk, term, context = {}, refresh = false, cacheRoot, platform = process.platform, pageSize = 100, maxPages = 10000, concurrency = 6, progress = () => {} }) {
|
|
56
56
|
if (!String(term || '').trim()) throw new Error('A nonempty literal search term is required');
|
|
57
57
|
if (!Number.isInteger(pageSize) || pageSize < 1 || !Number.isInteger(maxPages) || maxPages < 1) throw new Error('Invalid flow pagination bounds');
|
|
58
|
+
if (!Number.isInteger(concurrency) || concurrency < 1) throw new Error('Invalid flow download concurrency');
|
|
58
59
|
const instance = new URL(sdk.baseURL).origin;
|
|
59
60
|
const directory = path.join(cacheRoot || process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'), 'jsn', 'flow-search');
|
|
60
61
|
// Node's Windows mode bits cannot establish a private DACL. Do not touch
|
|
@@ -109,12 +110,19 @@ export async function searchFlows({ sdk, term, context = {}, refresh = false, ca
|
|
|
109
110
|
const flows = [];
|
|
110
111
|
let downloaded = 0;
|
|
111
112
|
let reused = 0;
|
|
112
|
-
|
|
113
|
+
/**
|
|
114
|
+
* A fresh source read is deliberately mandatory even on a cache hit. A
|
|
115
|
+
* profile/role fingerprint cannot detect field ACLs, impersonation or a
|
|
116
|
+
* revoked permission. Never release old source on a failed live read.
|
|
117
|
+
*
|
|
118
|
+
* The reads are independent, so they run through a bounded pool. Serially,
|
|
119
|
+
* an instance with ~370 visible flows spent minutes in this loop: one
|
|
120
|
+
* processflow GET at a time. Each read still happens; the bound keeps the
|
|
121
|
+
* instance from being flooded and keeps the failure isolation per flow.
|
|
122
|
+
*/
|
|
123
|
+
const fetchDefinition = async (row) => {
|
|
113
124
|
let data;
|
|
114
125
|
try {
|
|
115
|
-
// A fresh source read is deliberately mandatory even on a cache hit. A
|
|
116
|
-
// profile/role fingerprint cannot detect field ACLs, impersonation or a
|
|
117
|
-
// revoked permission. Never release old source on a failed live read.
|
|
118
126
|
const response = await get(`/api/now/processflow/flow/${row.sys_id}`);
|
|
119
127
|
const code = response?.result?.errorCode;
|
|
120
128
|
if (response?.result?.errorMessage || (code != null && code !== '' && String(code) !== '0')) throw new Error('Provider refused the flow definition');
|
|
@@ -123,8 +131,7 @@ export async function searchFlows({ sdk, term, context = {}, refresh = false, ca
|
|
|
123
131
|
if (!data || typeof data !== 'object') throw new Error('No readable ProcessFlow definition');
|
|
124
132
|
downloaded++;
|
|
125
133
|
} catch (error) {
|
|
126
|
-
|
|
127
|
-
continue;
|
|
134
|
+
return { failure: { ...row, stage: 'download', message: error.status === 403 || /403|forbidden/i.test(error.message) ? 'Access denied reading definition' : 'Definition download failed or unavailable', status: error.status || null } };
|
|
128
135
|
}
|
|
129
136
|
try {
|
|
130
137
|
const sourceDigest = digest(data);
|
|
@@ -132,8 +139,26 @@ export async function searchFlows({ sdk, term, context = {}, refresh = false, ca
|
|
|
132
139
|
const entries = cached?.source_digest === sourceDigest && Array.isArray(cached.entries) ? cached.entries : decodeFlowSearchDefinition(data);
|
|
133
140
|
const unchanged = entries === cached?.entries;
|
|
134
141
|
if (unchanged) reused++;
|
|
135
|
-
|
|
136
|
-
} catch (error) {
|
|
142
|
+
return { flow: { ...row, source: `/api/now/processflow/flow/${row.sys_id}`, source_digest: sourceDigest, decoded_at: unchanged ? cached.decoded_at : new Date().toISOString(), entries } };
|
|
143
|
+
} catch (error) { return { failure: { ...row, stage: 'decode', message: error.message } }; }
|
|
144
|
+
};
|
|
145
|
+
const rowList = [...rows.values()];
|
|
146
|
+
// Results are collected by inventory position, not completion order, so a
|
|
147
|
+
// faster flow can never reorder matches or failures between runs.
|
|
148
|
+
const results = new Array(rowList.length);
|
|
149
|
+
let nextIndex = 0;
|
|
150
|
+
const worker = async () => {
|
|
151
|
+
while (true) {
|
|
152
|
+
const index = nextIndex++;
|
|
153
|
+
if (index >= rowList.length) return;
|
|
154
|
+
results[index] = await fetchDefinition(rowList[index]);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
const poolSize = Math.max(1, Math.min(concurrency, rowList.length));
|
|
158
|
+
await Promise.all(Array.from({ length: poolSize }, worker));
|
|
159
|
+
for (const result of results) {
|
|
160
|
+
if (!result || result.failure) { if (result?.failure) failures.push(result.failure); continue; }
|
|
161
|
+
flows.push(result.flow);
|
|
137
162
|
}
|
|
138
163
|
const captured = new Date().toISOString();
|
|
139
164
|
if (diskCache) await writeCache(file, { schema: 1, captured_at: captured, flows });
|
package/src/help.js
CHANGED
|
@@ -25,11 +25,11 @@ const CONCISE_EXAMPLES = [
|
|
|
25
25
|
];
|
|
26
26
|
|
|
27
27
|
const CONCISE_MORE = [
|
|
28
|
-
{ label: `${SITE_ORIGIN}${ROOT_DOC_LINK}`, description: 'Guides:
|
|
28
|
+
{ label: `${SITE_ORIGIN}${ROOT_DOC_LINK}`, description: 'Guides: setup, safety, output, agents, features' },
|
|
29
29
|
{ label: 'jsn <command> <action> --help', description: 'Options for one command or action' },
|
|
30
30
|
{ label: 'jsn discover <word>', description: 'Find commands by task words' },
|
|
31
31
|
{ label: 'jsn discover --table <table>', description: 'Find commands configured for a table' },
|
|
32
|
-
{ label: 'jsn --all-commands --help', description: 'Every
|
|
32
|
+
{ label: 'jsn --all-commands --help', description: 'Every command and global flag' },
|
|
33
33
|
{ label: 'jsn --json', description: 'Registered command surface as JSON' },
|
|
34
34
|
];
|
|
35
35
|
|
|
@@ -256,11 +256,28 @@ function renderConciseHelp(config, registry, width) {
|
|
|
256
256
|
desc: command.summary || command.description || '',
|
|
257
257
|
}));
|
|
258
258
|
|
|
259
|
+
const used = new Set();
|
|
260
|
+
const groups = Object.entries(COMMAND_GROUPS)
|
|
261
|
+
.map(([label, hint]) => ({
|
|
262
|
+
label,
|
|
263
|
+
description: rowsFor(hint, byName, used, config)
|
|
264
|
+
.filter((row) => !row.divider).map((row) => row.name).join(' '),
|
|
265
|
+
}))
|
|
266
|
+
.filter((row) => row.description);
|
|
267
|
+
const other = commands
|
|
268
|
+
.filter((command) => !used.has(command.name) && !isCapabilityHidden(command.name, config))
|
|
269
|
+
.map((command) => command.name);
|
|
270
|
+
if (other.length) groups.push({ label: 'OTHER', description: other.join(' ') });
|
|
271
|
+
|
|
259
272
|
return [
|
|
260
273
|
'Usage: jsn <command> [options]',
|
|
261
274
|
'',
|
|
262
275
|
'Command-line interface for ServiceNow',
|
|
263
|
-
|
|
276
|
+
`\nCOMMON COMMANDS\n${renderRows(common.map((command) => ({ label: command.name, description: command.desc })), { width, indent: 2 })}`,
|
|
277
|
+
'',
|
|
278
|
+
'ALL COMMANDS BY GROUP',
|
|
279
|
+
...wrapText('names only; jsn --all-commands --help has descriptions and flags', { width }),
|
|
280
|
+
renderRows(groups, { width, indent: 2 }),
|
|
264
281
|
'',
|
|
265
282
|
'EXAMPLES',
|
|
266
283
|
...CONCISE_EXAMPLES.map((example) => wrapText(example, { width: width - 2, firstIndent: 2 }).join(' \\\n')),
|
|
@@ -268,12 +285,12 @@ function renderConciseHelp(config, registry, width) {
|
|
|
268
285
|
'',
|
|
269
286
|
'OUTPUT',
|
|
270
287
|
...[
|
|
271
|
-
'
|
|
272
|
-
'CSV
|
|
273
|
-
'Use JSON for pagination
|
|
288
|
+
'Bound lists with --columns and --limit.',
|
|
289
|
+
'CSV/TSV save tokens; JSON preserves metadata and nesting.',
|
|
290
|
+
'Use JSON for pagination or reference IDs with display labels.',
|
|
274
291
|
].flatMap(text => wrapText(text, { width, firstIndent: 2 })),
|
|
275
292
|
'',
|
|
276
|
-
'
|
|
293
|
+
'NEXT',
|
|
277
294
|
renderRows(CONCISE_MORE, { width, indent: 2 }),
|
|
278
295
|
'',
|
|
279
296
|
].join('\n');
|
package/src/sdk.js
CHANGED
|
@@ -21,6 +21,17 @@ import {
|
|
|
21
21
|
|
|
22
22
|
const DEFAULT_TIMEOUT = 30000;
|
|
23
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Node reports every network-layer problem as "fetch failed" and hides the
|
|
26
|
+
* reason in `cause`. That message cannot tell a reset from a proxy rejection or
|
|
27
|
+
* a timeout, so the code is appended when one is available.
|
|
28
|
+
*/
|
|
29
|
+
function describeTransportError(error) {
|
|
30
|
+
const base = error?.message || String(error);
|
|
31
|
+
const code = error?.cause?.code || error?.code;
|
|
32
|
+
return code && !base.includes(code) ? `${base} (${code})` : base;
|
|
33
|
+
}
|
|
34
|
+
|
|
24
35
|
function collectSetCookies(cookieJar, response) {
|
|
25
36
|
const values = response.headers.getSetCookie?.() || [];
|
|
26
37
|
const raw = Array.isArray(values) && values.length
|
|
@@ -933,15 +944,41 @@ export class SDKClient {
|
|
|
933
944
|
});
|
|
934
945
|
}
|
|
935
946
|
|
|
936
|
-
/**
|
|
947
|
+
/**
|
|
948
|
+
* Load through the native XML upload processor, then verify the exact envelope.
|
|
949
|
+
*
|
|
950
|
+
* Loading is the step that changes the instance, and it is not transactional
|
|
951
|
+
* with the HTTP response that reports it: `sys_upload.do` can commit the
|
|
952
|
+
* retrieved update set and still fail in transport. Treating any later error
|
|
953
|
+
* as "the import failed" made agents retry a load that had already happened,
|
|
954
|
+
* so every failure path now re-reads for the set before deciding, and a
|
|
955
|
+
* second attempt at the same XML reports what is already there instead of
|
|
956
|
+
* dead-ending.
|
|
957
|
+
*/
|
|
937
958
|
async importUpdateSet(xml, inspection, filename = 'update-set.xml') {
|
|
938
959
|
const { sys_id: id, remote_sys_id: sourceID } = inspection;
|
|
939
960
|
const params = new URLSearchParams({
|
|
940
961
|
sysparm_query: `sys_id=${id}^ORremote_sys_id=${sourceID}`,
|
|
941
962
|
sysparm_fields: 'sys_id,name,state', sysparm_limit: '2', sysparm_display_value: 'false',
|
|
942
963
|
});
|
|
943
|
-
|
|
944
|
-
|
|
964
|
+
const existing = await this.list('sys_remote_update_set', params);
|
|
965
|
+
if (existing.length > 1) {
|
|
966
|
+
throw errUsage('More than one retrieved update set matches this XML identity; refusing to guess. Inspect Retrieved Update Sets before retrying.');
|
|
967
|
+
}
|
|
968
|
+
if (existing.length === 1) {
|
|
969
|
+
const name = getStringField(existing[0], 'name');
|
|
970
|
+
// Same XML, already loaded: an interrupted or retried attempt lands here.
|
|
971
|
+
// Reporting the existing set is the useful answer; refusing to overwrite
|
|
972
|
+
// it is only right when the identity collides with different content.
|
|
973
|
+
if (name === inspection.name) {
|
|
974
|
+
const sysID = getStringField(existing[0], 'sys_id');
|
|
975
|
+
const state = getStringField(existing[0], 'state');
|
|
976
|
+
return {
|
|
977
|
+
sys_id: sysID, state, count: inspection.count, already_loaded: true, members_verified: false,
|
|
978
|
+
link: `${this.baseURL}/sys_remote_update_set.do?sys_id=${sysID}`,
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
throw errUsage(`A retrieved update set for this XML identity already exists on the target as "${name}"; refusing to overwrite it. Inspect it before retrying.`);
|
|
945
982
|
}
|
|
946
983
|
// Native INSERT_OR_UPDATE must not move/overwrite a member belonging to another set.
|
|
947
984
|
for (let offset = 0; offset < inspection.members.length; offset += 50) {
|
|
@@ -964,16 +1001,24 @@ export class SDKClient {
|
|
|
964
1001
|
form.set('sysparm_upload_prefix', '');
|
|
965
1002
|
form.set('sysparm_referring_url', 'sys_remote_update_set_list.do');
|
|
966
1003
|
form.set('attachFile', new Blob([xml], { type: 'application/xml' }), filename);
|
|
1004
|
+
// A verification disagreement is knowledge about the instance, not a lost
|
|
1005
|
+
// response: the upload landed and its contents are wrong. Those must stay
|
|
1006
|
+
// failures, so they are tagged and exempted from post-error reconciliation.
|
|
1007
|
+
const mismatch = (message) => {
|
|
1008
|
+
const error = new Error(message);
|
|
1009
|
+
error.verificationMismatch = true;
|
|
1010
|
+
return error;
|
|
1011
|
+
};
|
|
967
1012
|
try {
|
|
968
1013
|
await this.rawRequest(`${this.baseURL}/sys_upload.do`, { method: 'POST', body: form,
|
|
969
1014
|
headers: { ...(cookies ? { Cookie: cookies } : {}), 'X-UserToken': csrf, Referer: formURL },
|
|
970
1015
|
});
|
|
971
1016
|
const records = await this.list('sys_remote_update_set', params);
|
|
972
|
-
if (records.length !== 1) throw
|
|
1017
|
+
if (records.length !== 1) throw mismatch('Could not identify exactly one uploaded retrieved update set');
|
|
973
1018
|
const record = records[0];
|
|
974
1019
|
const importedID = getStringField(record, 'sys_id');
|
|
975
1020
|
const state = getStringField(record, 'state');
|
|
976
|
-
if (state !== 'loaded' || getStringField(record, 'name') !== inspection.name) throw
|
|
1021
|
+
if (state !== 'loaded' || getStringField(record, 'name') !== inspection.name) throw mismatch('Uploaded update set name/state did not match the loaded export');
|
|
977
1022
|
const members = [];
|
|
978
1023
|
for (let offset = 0; ; offset += 500) {
|
|
979
1024
|
const page = await this.list('sys_update_xml', new URLSearchParams({
|
|
@@ -981,20 +1026,52 @@ export class SDKClient {
|
|
|
981
1026
|
sysparm_offset: String(offset), sysparm_display_value: 'false', sysparm_fields: 'sys_id,name,action',
|
|
982
1027
|
}));
|
|
983
1028
|
members.push(...page);
|
|
984
|
-
if (members.length > inspection.count) throw
|
|
1029
|
+
if (members.length > inspection.count) throw mismatch('Uploaded update set contains unexpected extra members');
|
|
985
1030
|
if (page.length < 500) break;
|
|
986
1031
|
}
|
|
987
1032
|
const actual = new Map(members.map(member => [getStringField(member, 'sys_id'), member]));
|
|
988
1033
|
if (actual.size !== inspection.count || inspection.members.some(expected => {
|
|
989
1034
|
const member = actual.get(expected.sys_id);
|
|
990
1035
|
return !member || getStringField(member, 'name') !== expected.name || getStringField(member, 'action') !== expected.action;
|
|
991
|
-
})) throw
|
|
1036
|
+
})) throw mismatch('Uploaded update set members did not match the XML export');
|
|
992
1037
|
return { sys_id: importedID, state, count: members.length, link: `${this.baseURL}/sys_remote_update_set.do?sys_id=${importedID}` };
|
|
993
1038
|
} catch (error) {
|
|
994
|
-
|
|
1039
|
+
if (error.verificationMismatch) {
|
|
1040
|
+
throw new AppError(CodeAPI, `XML import could not be verified: ${error.message}. It may have partially loaded; inspect Retrieved Update Sets before retrying.`, 'Inspect Retrieved Update Sets before retrying.', 0, error);
|
|
1041
|
+
}
|
|
1042
|
+
// The upload may have landed even though a request threw. Re-read for the
|
|
1043
|
+
// exact identity before declaring failure; an agent told "failed" retries
|
|
1044
|
+
// a load that already happened.
|
|
1045
|
+
const landed = await this.#findImportedSet(params, inspection).catch(() => null);
|
|
1046
|
+
if (landed) return landed;
|
|
1047
|
+
throw new AppError(CodeAPI, `XML import could not be verified: ${describeTransportError(error)}. It may have partially loaded, and no matching retrieved update set is visible yet.`, 'Inspect Retrieved Update Sets before retrying.', 0, error);
|
|
995
1048
|
}
|
|
996
1049
|
}
|
|
997
1050
|
|
|
1051
|
+
/**
|
|
1052
|
+
* Find the retrieved update set this XML would have created, and report it as
|
|
1053
|
+
* a successful load. Returns null when nothing matching is readable, so the
|
|
1054
|
+
* caller can report the original failure.
|
|
1055
|
+
*/
|
|
1056
|
+
async #findImportedSet(params, inspection) {
|
|
1057
|
+
const records = await this.list('sys_remote_update_set', params);
|
|
1058
|
+
if (records.length !== 1) return null;
|
|
1059
|
+
const record = records[0];
|
|
1060
|
+
if (getStringField(record, 'name') !== inspection.name) return null;
|
|
1061
|
+
const sysID = getStringField(record, 'sys_id');
|
|
1062
|
+
const members = await this.list('sys_update_xml', new URLSearchParams({
|
|
1063
|
+
sysparm_query: `remote_update_set=${sysID}`, sysparm_fields: 'sys_id', sysparm_limit: String(inspection.count + 1),
|
|
1064
|
+
}));
|
|
1065
|
+
return {
|
|
1066
|
+
sys_id: sysID,
|
|
1067
|
+
state: getStringField(record, 'state'),
|
|
1068
|
+
count: members.length,
|
|
1069
|
+
link: `${this.baseURL}/sys_remote_update_set.do?sys_id=${sysID}`,
|
|
1070
|
+
recovered_after_error: true,
|
|
1071
|
+
members_match_inspection: members.length === inspection.count,
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
|
|
998
1075
|
/**
|
|
999
1076
|
* Preview a loaded retrieved update set through the CICD Update Set API and
|
|
1000
1077
|
* wait for its progress tracker. Does not commit and does not resolve
|