@jacebenson/jsn 5.2.0-dev.129.1 → 5.2.0-dev.131.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/README.md +72 -9
- package/package.json +1 -1
- package/skills/servicenow/SKILL.md +11 -1
- package/src/amb.js +370 -0
- package/src/app.js +8 -4
- package/src/cli.js +2 -0
- package/src/command-audience.js +1 -1
- package/src/commands/cases.js +218 -0
- package/src/commands/catalog/enrich.js +151 -56
- package/src/commands/catalog-order.js +99 -23
- package/src/commands/catalog.js +6 -5
- package/src/commands/records.js +110 -1
- package/src/errors.js +5 -0
- package/src/output.js +28 -1
- package/src/record-command-profiles.js +1 -1
- package/src/record-watch.js +206 -0
- package/src/sdk.js +35 -1
package/src/commands/catalog.js
CHANGED
|
@@ -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,
|
|
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,
|
|
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}
|
|
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
|
}
|
package/src/commands/records.js
CHANGED
|
@@ -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',
|
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
|
}
|
package/src/output.js
CHANGED
|
@@ -186,6 +186,33 @@ export class OutputWriter {
|
|
|
186
186
|
}
|
|
187
187
|
}
|
|
188
188
|
|
|
189
|
+
/**
|
|
190
|
+
* Write one item of an event stream (e.g. `records watch`).
|
|
191
|
+
*
|
|
192
|
+
* A stream cannot use the single-envelope `ok()`, so this method emits one
|
|
193
|
+
* compact JSON object per line — newline-delimited JSON, the shape agents
|
|
194
|
+
* and scripts can consume incrementally without buffering the whole run.
|
|
195
|
+
* Human formats print `opts.line` (domain-formatted by the command) and
|
|
196
|
+
* fall back to the JSON line when the command supplied none.
|
|
197
|
+
*
|
|
198
|
+
* `--get` stays meaningful: the path is resolved against each event, and
|
|
199
|
+
* a path that does not resolve emits `null` rather than aborting the
|
|
200
|
+
* stream mid-observation.
|
|
201
|
+
*/
|
|
202
|
+
writeEvent(data, opts = {}) {
|
|
203
|
+
const format = this.effectiveFormat();
|
|
204
|
+
if (format === FormatStyled || format === FormatMarkdown) {
|
|
205
|
+
this.writer.write(`${opts.line ?? JSON.stringify(data)}\n`);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (this.jqFilter) {
|
|
209
|
+
const value = resolvePath(data, this.jqFilter);
|
|
210
|
+
this.writer.write(`${JSON.stringify(value === undefined ? null : value)}\n`);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
this.writer.write(`${JSON.stringify(data)}\n`);
|
|
214
|
+
}
|
|
215
|
+
|
|
189
216
|
writeJSON(data, opts) {
|
|
190
217
|
const resp = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [] };
|
|
191
218
|
if (opts.notice) resp.notice = opts.notice;
|
|
@@ -385,7 +412,7 @@ export class OutputWriter {
|
|
|
385
412
|
let val = getDisplayValue(row[col]);
|
|
386
413
|
const width = colWidths[col] || 20;
|
|
387
414
|
|
|
388
|
-
if (j === 0 && instanceURL && table && row.sys_id) {
|
|
415
|
+
if (j === 0 && instanceURL && table && row.sys_id && isTTY(this.writer)) {
|
|
389
416
|
const url = getTableURL(instanceURL, table, row.sys_id);
|
|
390
417
|
val = hyperlink(val, url);
|
|
391
418
|
}
|
|
@@ -61,7 +61,7 @@ export default {
|
|
|
61
61
|
options: { singular: 'table', scopeValidation: true, showFields: ['name', 'label', 'super_class', 'create_access_controls', 'sys_scope', 'sys_created_on', 'sys_updated_on', 'sys_created_by', 'sys_updated_by', 'is_extendable'] } },
|
|
62
62
|
incidents: { table: 'incident', aliases: ['incident', 'inc'], columns: ['number', 'short_description', 'priority', 'state', 'assigned_to'], kind: 'ticket' },
|
|
63
63
|
changes: { table: 'change_request', aliases: ['change_request', 'chg'], columns: ['number', 'short_description', 'risk', 'state', 'assigned_to'], kind: 'ticket' },
|
|
64
|
-
requests: { table: 'sc_req_item', aliases: ['sc_req_item', 'req'], columns: ['number', 'short_description', 'stage', 'assigned_to'], kind: 'ticket' },
|
|
64
|
+
requests: { table: 'sc_req_item', aliases: ['sc_req_item', 'req'], columns: ['number', 'cat_item', 'short_description', 'stage', 'assigned_to'], kind: 'ticket' },
|
|
65
65
|
tasks: { table: 'sc_task', aliases: ['sc_task', 'task'], columns: ['number', 'short_description', 'state', 'assigned_to'], kind: 'ticket' },
|
|
66
66
|
uipolicies: { table: 'sys_ui_policy', aliases: ['uipolicy', 'up'], columns: ['short_description', 'table', 'sys_class_name', 'active'],
|
|
67
67
|
identifierField: 'short_description', options: { singular: 'UI policy', scopeValidation: true },
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// Record watching: bounded observation of one ServiceNow record over AMB.
|
|
2
|
+
//
|
|
3
|
+
// The AMB client (src/amb.js) owns the wire protocol. This module owns the
|
|
4
|
+
// observation session: what counts as an event, when to fetch the record to
|
|
5
|
+
// fill in detail the notification omitted, bounded duration, cancellation,
|
|
6
|
+
// reconnect backoff and — most importantly — honest gap reporting.
|
|
7
|
+
//
|
|
8
|
+
// A record-watcher subscription is best-effort delivery, not a durable
|
|
9
|
+
// stream. After a disconnect the platform does not replay what was missed,
|
|
10
|
+
// so this module reports a gap instead of pretending the event list is
|
|
11
|
+
// complete.
|
|
12
|
+
|
|
13
|
+
import { AppError, CodeUsage } from './errors.js';
|
|
14
|
+
import { normalizeRecordWatcherEvent, recordWatcherChannel } from './amb.js';
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_RECONNECT_DELAYS = [1000, 2000, 4000, 8000, 16000, 30000];
|
|
17
|
+
|
|
18
|
+
function defaultSleep(ms, signal) {
|
|
19
|
+
return new Promise((resolve) => {
|
|
20
|
+
if (signal?.aborted) return resolve();
|
|
21
|
+
const timer = setTimeout(done, ms);
|
|
22
|
+
function done() {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
signal?.removeEventListener('abort', done);
|
|
25
|
+
resolve();
|
|
26
|
+
}
|
|
27
|
+
if (signal) signal.addEventListener('abort', done, { once: true });
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Does the notification carry enough detail that a follow-up read is redundant? */
|
|
32
|
+
export function notificationHasDetail(event) {
|
|
33
|
+
return Boolean(event?.record) || (Array.isArray(event?.changes) && event.changes.length > 0);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Watch one record until a bound is reached, the caller cancels, or a fatal
|
|
38
|
+
* error occurs.
|
|
39
|
+
*
|
|
40
|
+
* @param {object} opts
|
|
41
|
+
* @param {{ start: Function, next: Function, stop: Function }} opts.client
|
|
42
|
+
* @param {string} opts.table
|
|
43
|
+
* @param {string} opts.sysID
|
|
44
|
+
* @param {string} [opts.query] — encoded query; defaults to `sys_id=<sysID>`
|
|
45
|
+
* @param {number} [opts.timeoutMs] — 0 means "until cancelled"
|
|
46
|
+
* @param {number} [opts.maxEvents] — 0 means unlimited
|
|
47
|
+
* @param {AbortSignal} [opts.signal]
|
|
48
|
+
* @param {'auto'|'always'|'never'} [opts.statePolicy]
|
|
49
|
+
* @param {() => Promise<object|null>} [opts.fetchState]
|
|
50
|
+
* @param {(event: object) => any} [opts.onEvent]
|
|
51
|
+
* @param {(status: object) => any} [opts.onStatus]
|
|
52
|
+
* @param {boolean} [opts.reconnect]
|
|
53
|
+
* @param {number[]} [opts.reconnectDelays]
|
|
54
|
+
* @param {() => number} [opts.now]
|
|
55
|
+
* @param {Function} [opts.sleep]
|
|
56
|
+
*/
|
|
57
|
+
export async function watchRecord({
|
|
58
|
+
client,
|
|
59
|
+
table,
|
|
60
|
+
sysID,
|
|
61
|
+
query,
|
|
62
|
+
timeoutMs = 0,
|
|
63
|
+
maxEvents = 0,
|
|
64
|
+
signal,
|
|
65
|
+
statePolicy = 'auto',
|
|
66
|
+
fetchState,
|
|
67
|
+
onEvent = () => {},
|
|
68
|
+
onStatus = () => {},
|
|
69
|
+
reconnect = true,
|
|
70
|
+
reconnectDelays = DEFAULT_RECONNECT_DELAYS,
|
|
71
|
+
now = () => Date.now(),
|
|
72
|
+
sleep = defaultSleep,
|
|
73
|
+
}) {
|
|
74
|
+
if (!client) throw new AppError(CodeUsage, 'Record watch needs an AMB client.');
|
|
75
|
+
if (!table) throw new AppError(CodeUsage, 'Record watch needs a table.');
|
|
76
|
+
if (!sysID) throw new AppError(CodeUsage, 'Record watch needs a record sys_id.');
|
|
77
|
+
if (!['auto', 'always', 'never'].includes(statePolicy)) {
|
|
78
|
+
throw new AppError(CodeUsage, `Unknown state policy: ${statePolicy}`);
|
|
79
|
+
}
|
|
80
|
+
if (timeoutMs < 0 || maxEvents < 0) throw new AppError(CodeUsage, 'Watch bounds cannot be negative.');
|
|
81
|
+
if (statePolicy !== 'never' && typeof fetchState !== 'function') {
|
|
82
|
+
throw new AppError(CodeUsage, 'State fetching is enabled but no record reader was supplied.');
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const channel = recordWatcherChannel(table, query || `sys_id=${sysID}`);
|
|
86
|
+
const startedAt = now();
|
|
87
|
+
const startedISO = new Date(startedAt).toISOString();
|
|
88
|
+
const deadline = timeoutMs > 0 ? startedAt + timeoutMs : Infinity;
|
|
89
|
+
|
|
90
|
+
let events = 0;
|
|
91
|
+
let gaps = 0;
|
|
92
|
+
let attempts = 0;
|
|
93
|
+
let lastEventAt = null;
|
|
94
|
+
let connected = false;
|
|
95
|
+
let reason = 'timeout';
|
|
96
|
+
|
|
97
|
+
const finish = async (why) => {
|
|
98
|
+
reason = why;
|
|
99
|
+
try { await client.stop([channel]); } catch { /* unsubscription is best effort */ }
|
|
100
|
+
onStatus({ type: 'unsubscribed', reason: why });
|
|
101
|
+
const endedAt = now();
|
|
102
|
+
return {
|
|
103
|
+
type: 'watch_summary',
|
|
104
|
+
table,
|
|
105
|
+
sys_id: sysID,
|
|
106
|
+
channel,
|
|
107
|
+
reason: why,
|
|
108
|
+
events,
|
|
109
|
+
gaps,
|
|
110
|
+
reconnects: Math.max(0, gaps),
|
|
111
|
+
complete: gaps === 0 && reason !== 'error',
|
|
112
|
+
started_at: startedISO,
|
|
113
|
+
ended_at: new Date(endedAt).toISOString(),
|
|
114
|
+
duration_ms: Math.max(0, endedAt - startedAt),
|
|
115
|
+
last_event_at: lastEventAt,
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
onStatus({ type: 'connecting', table, sys_id: sysID, channel });
|
|
120
|
+
|
|
121
|
+
try {
|
|
122
|
+
while (true) {
|
|
123
|
+
const remaining = deadline - now();
|
|
124
|
+
if (remaining <= 0) return await finish('timeout');
|
|
125
|
+
if (signal?.aborted) return await finish('cancelled');
|
|
126
|
+
|
|
127
|
+
if (!connected) {
|
|
128
|
+
const session = await client.start([channel]);
|
|
129
|
+
connected = true;
|
|
130
|
+
attempts = 0;
|
|
131
|
+
const resumed = gaps > 0;
|
|
132
|
+
onStatus({
|
|
133
|
+
type: resumed ? 'reconnected' : 'subscribed',
|
|
134
|
+
channel,
|
|
135
|
+
...(session?.sessionStatus ? { session_status: session.sessionStatus } : {}),
|
|
136
|
+
// State the limitation, do not imply the stream was continuous.
|
|
137
|
+
...(resumed ? { may_have_missed_events: true, gaps } : {}),
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
let messages;
|
|
142
|
+
try {
|
|
143
|
+
messages = await client.next({ timeoutMs: Math.min(remaining, 60000), signal });
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (signal?.aborted) return await finish('cancelled');
|
|
146
|
+
if (deadline - now() <= 0) return await finish('timeout');
|
|
147
|
+
if (error?.fatal === true || !reconnect) throw error;
|
|
148
|
+
|
|
149
|
+
// A dropped connection is a real gap in observation, not a retry note.
|
|
150
|
+
gaps += 1;
|
|
151
|
+
const gapStart = lastEventAt || startedISO;
|
|
152
|
+
const gapAt = new Date(now()).toISOString();
|
|
153
|
+
onStatus({
|
|
154
|
+
type: 'gap',
|
|
155
|
+
at: gapAt,
|
|
156
|
+
since: gapStart,
|
|
157
|
+
reason: error?.message || String(error),
|
|
158
|
+
code: error?.code || null,
|
|
159
|
+
});
|
|
160
|
+
connected = false;
|
|
161
|
+
const wait = reconnectDelays[Math.min(attempts, reconnectDelays.length - 1)];
|
|
162
|
+
attempts += 1;
|
|
163
|
+
const waitedUntil = now() + wait;
|
|
164
|
+
while (now() < waitedUntil && !signal?.aborted && now() < deadline) {
|
|
165
|
+
await sleep(Math.min(wait, Math.max(1, waitedUntil - now())), signal);
|
|
166
|
+
}
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
for (const message of messages) {
|
|
171
|
+
if (signal?.aborted) return await finish('cancelled');
|
|
172
|
+
const event = normalizeRecordWatcherEvent(message, { table, sysID }, new Date(now()).toISOString());
|
|
173
|
+
// The channel query scopes delivery to this record. The live payload
|
|
174
|
+
// does not carry a sys_id (jsn fills it from the subscription), so this
|
|
175
|
+
// guard only bites on an instance that does send one — for example a
|
|
176
|
+
// table-level channel returning a different record.
|
|
177
|
+
if (event.sys_id && sysID && event.sys_id !== sysID) continue;
|
|
178
|
+
|
|
179
|
+
const shouldFetch = statePolicy === 'always'
|
|
180
|
+
|| (statePolicy === 'auto' && !notificationHasDetail(event));
|
|
181
|
+
if (shouldFetch) {
|
|
182
|
+
try {
|
|
183
|
+
const record = await fetchState();
|
|
184
|
+
event.state = { source: 'fetched', fetched_at: new Date(now()).toISOString(), record };
|
|
185
|
+
} catch (error) {
|
|
186
|
+
// Never let a failed follow-up read masquerade as a failed or
|
|
187
|
+
// complete event; keep the notification and record the problem.
|
|
188
|
+
event.state = null;
|
|
189
|
+
event.state_error = {
|
|
190
|
+
code: error?.code || null,
|
|
191
|
+
message: error?.message || String(error),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
events += 1;
|
|
197
|
+
lastEventAt = event.received_at;
|
|
198
|
+
await onEvent(event);
|
|
199
|
+
if (maxEvents > 0 && events >= maxEvents) return await finish('max_events');
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
} catch (error) {
|
|
203
|
+
await finish('error');
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
}
|
package/src/sdk.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { batchRead } from './sdk-batch.js';
|
|
4
4
|
import { gunzipSync } from 'node:zlib';
|
|
5
|
-
import { AppError, CodeAPI, CodeAuth, errAuth, errAPI, errNetwork, errUsage } from './errors.js';
|
|
5
|
+
import { AppError, CodeAPI, CodeAuth, errAuth, errAuthHint, errAPI, errNetwork, errUsage } from './errors.js';
|
|
6
6
|
import { getStringField } from './helpers.js';
|
|
7
7
|
import { getAction, getStepTypes, createAction, updateAction, testAction } from './processflow-actions.js';
|
|
8
8
|
import { readSkippedBaseline, revertSkippedUpdate } from './skipped-update-provider.js';
|
|
@@ -974,6 +974,40 @@ export class SDKClient {
|
|
|
974
974
|
return variables;
|
|
975
975
|
}
|
|
976
976
|
|
|
977
|
+
/**
|
|
978
|
+
* Session material for channels that authorize like a browser (AMB).
|
|
979
|
+
*
|
|
980
|
+
* AMB does not accept bearer/basic headers on subscribe; it needs the
|
|
981
|
+
* cookies and X-UserToken of a UI session. gck credentials already carry
|
|
982
|
+
* them; basic/oauth profiles obtain them by warming the same session the
|
|
983
|
+
* SDK uses for UI calls. A bearer-token profile that cannot warm a session
|
|
984
|
+
* is an actionable error, never a silent fallback.
|
|
985
|
+
*/
|
|
986
|
+
async ambSession() {
|
|
987
|
+
if (!this.authProvider) throw errAuth('No authentication configured');
|
|
988
|
+
const creds = await this.authProvider.getCredentials();
|
|
989
|
+
if (!creds) throw errAuth('No valid credentials');
|
|
990
|
+
if (creds.auth_method === 'gck') {
|
|
991
|
+
if (!creds.cookies) {
|
|
992
|
+
throw errAuthHint('This gck credential has no session cookies, so AMB cannot open a channel.',
|
|
993
|
+
'Re-import the browser session: jsn auth login --browser');
|
|
994
|
+
}
|
|
995
|
+
return { cookies: creds.cookies, userToken: creds.access_token || '', authMethod: 'gck' };
|
|
996
|
+
}
|
|
997
|
+
if (creds.auth_method === 'basic' || creds.auth_method === 'token' || creds.auth_method === 'oauth') {
|
|
998
|
+
const cookies = await this._warmSession();
|
|
999
|
+
if (!cookies) {
|
|
1000
|
+
throw errAuthHint(
|
|
1001
|
+
`${creds.auth_method} credentials could not open a UI session, which AMB requires.`,
|
|
1002
|
+
'Record watching needs a browser session. Run "jsn auth login --browser" and use that profile, or ask an administrator whether AMB is enabled for this account.',
|
|
1003
|
+
);
|
|
1004
|
+
}
|
|
1005
|
+
return { cookies, userToken: this.sessionUserToken || '', authMethod: creds.auth_method };
|
|
1006
|
+
}
|
|
1007
|
+
throw errAuthHint(`Authentication method "${creds.auth_method}" cannot open an AMB session.`,
|
|
1008
|
+
'Use a browser-session (gck) profile: jsn auth login --browser');
|
|
1009
|
+
}
|
|
1010
|
+
|
|
977
1011
|
async _warmSession() {
|
|
978
1012
|
if (this.oauthCookies) return this.oauthCookies;
|
|
979
1013
|
if (!this._sessionPromise) {
|