@jacebenson/jsn 5.2.0-dev.130.1 → 5.2.0-dev.132.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.2.0-dev.130.1",
3
+ "version": "5.2.0-dev.132.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -4,7 +4,7 @@ description: Use the jsn CLI for ServiceNow development, administration, and dat
4
4
  license: MIT
5
5
  metadata:
6
6
  author: jacebenson
7
- version: "4.3.13"
7
+ version: "4.3.14"
8
8
  repository: https://github.com/jacebenson/jsn
9
9
  ---
10
10
 
@@ -28,6 +28,16 @@ For development:
28
28
  5. Ask whether anything else belongs in the update set. If the user confirms
29
29
  it is finished, complete it with notes.
30
30
 
31
+ Tracking a record: when the user asks to track, watch or be told about changes
32
+ to an incident, task, change request or other record, use
33
+ `jsn records watch --table <table> --sys-id <id> --timeout <seconds> --json`.
34
+ It streams newline-delimited JSON (`record_change`, `gap`, `watch_summary`),
35
+ so run it for a bounded window and report what arrived; schedules and user
36
+ notifications belong to your runtime, not to the command. Use `--max-events 1`
37
+ for a single-change check. A `gap` or `"complete": false` means events were
38
+ missed — read the record's current state rather than assuming continuity.
39
+ Watching needs a browser session (`jsn auth login --browser`).
40
+
31
41
  For incoming update sets: import the XML, preview the set, and resolve preview
32
42
  errors with the human where needed. Once the preview is clear, commit the set
33
43
  and verify the results.
package/src/amb.js ADDED
@@ -0,0 +1,370 @@
1
+ // ServiceNow AMB (Asynchronous Message Bus) client.
2
+ //
3
+ // AMB is ServiceNow's real-time channel service. It is a Bayeux / CometD
4
+ // long-polling endpoint at `/amb`: you POST JSON message arrays to
5
+ // `/amb/handshake` (once) and `/amb/connect` (everything else), and the
6
+ // server holds the connect request until it has an event or its hold timer
7
+ // expires. It is NOT socket.io — the wire format is Bayeux, so no socket.io
8
+ // or WebSocket runtime dependency is needed here.
9
+ //
10
+ // Authorization is the part that surprises people: AMB authorizes like a
11
+ // browser session, not like a REST request. A bearer token or Basic header
12
+ // is not enough; the server wants the session cookies (glide_session_store,
13
+ // JSESSIONID, BAYEUX_BROWSER) plus X-UserToken that a logged-in UI session
14
+ // carries. `SDKClient.ambSession()` supplies that material from the active
15
+ // JSN credential; when it cannot, this module raises an actionable error
16
+ // instead of guessing.
17
+ //
18
+ // This module owns protocol framing, cookie/token handling and event
19
+ // normalization. Reconnect policy, gap reporting and duration bounds live in
20
+ // src/record-watch.js.
21
+
22
+ import { AppError, CodeAPI, CodeAuth, CodeNetwork, CodeUsage } from './errors.js';
23
+
24
+ const BAYEUX_VERSION = '1.0';
25
+ const DEFAULT_CONNECT_TIMEOUT = 60000;
26
+ const DEFAULT_REQUEST_TIMEOUT = 30000;
27
+
28
+ // AMB's subscribe step is tied to a browser session. These are the cookies
29
+ // that carry it, plus node affinity (BAYEUX_BROWSER) which subscribe needs
30
+ // when the instance sits behind a load balancer.
31
+ const SESSION_COOKIE = /^(glide_|JSESSIONID|BIGipServer|XSRF-TOKEN|BAYEUX_BROWSER)/i;
32
+
33
+ export class AmbError extends AppError {
34
+ constructor(code, message, hint = '', status = 0, cause = null) {
35
+ super(code, message, hint, status, cause);
36
+ // Auth/usage rejections cannot be fixed by reconnecting; transport and
37
+ // 5xx failures can. The watch loop reads this to decide.
38
+ this.fatal = code === CodeAuth || code === CodeUsage
39
+ || (code === CodeAPI && status > 0 && status < 500);
40
+ }
41
+ }
42
+
43
+ function ambAuthError(message, hint) {
44
+ return new AmbError(CodeAuth, message, hint);
45
+ }
46
+
47
+ /**
48
+ * The channel name for a record-watcher subscription.
49
+ *
50
+ * Encoding is ServiceNow's: standard base64 of the encoded query with `=`
51
+ * replaced by `-` (a channel segment cannot contain `=`). The action prefix
52
+ * defaults to `default`.
53
+ */
54
+ export function recordWatcherChannel(table, query, actionPrefix = 'default') {
55
+ if (typeof table !== 'string' || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(table)) {
56
+ throw new AmbError(CodeUsage, `Invalid table name for record watch: ${table}`);
57
+ }
58
+ if (typeof query !== 'string' || !query.trim()) {
59
+ throw new AmbError(CodeUsage, 'A record watcher needs a non-empty encoded query.');
60
+ }
61
+ const encoded = Buffer.from(query, 'utf8').toString('base64').replace(/=/g, '-');
62
+ return `/rw/${actionPrefix || 'default'}/${table}/${encoded}`;
63
+ }
64
+
65
+ const OPERATION_NAMES = {
66
+ insert: 'created', entry: 'created', add: 'created', created: 'created',
67
+ update: 'updated', change: 'updated', modify: 'updated', updated: 'updated',
68
+ delete: 'deleted', removed: 'deleted', deleted: 'deleted',
69
+ };
70
+
71
+ /** Normalize one raw change entry; the platform has used several shapes. */
72
+ function normalizeChange(change) {
73
+ if (Array.isArray(change)) {
74
+ const [field, previous, value] = change;
75
+ return { field: String(field ?? ''), previous_value: previous ?? null, value: value ?? null };
76
+ }
77
+ if (!change || typeof change !== 'object') return null;
78
+ const field = change.field ?? change.name ?? change.key;
79
+ if (!field) return null;
80
+ const value = change.value ?? change.new_value ?? change.newValue;
81
+ const previous = change.previous_value ?? change.old_value ?? change.oldValue;
82
+ const out = { field: String(field) };
83
+ if (value !== undefined) out.value = value;
84
+ if (change.display_value !== undefined) out.display_value = change.display_value;
85
+ if (previous !== undefined) out.previous_value = previous;
86
+ return out;
87
+ }
88
+
89
+ /**
90
+ * Turn a Bayeux event message on a record-watcher channel into the stable
91
+ * event shape JSN emits. Notification data is kept separate from any record
92
+ * state fetched later (see record-watch.js) — this object is only what the
93
+ * notification itself carried.
94
+ *
95
+ * @param {object} message — { channel, data, id }
96
+ * @param {{table?: string, sysID?: string}} expected — the watched record
97
+ * @param {string} [receivedAt] — ISO timestamp
98
+ */
99
+ export function normalizeRecordWatcherEvent(message, expected = {}, receivedAt = new Date().toISOString()) {
100
+ const channel = message?.channel || '';
101
+ let data = message?.data;
102
+ if (typeof data === 'string') {
103
+ try { data = JSON.parse(data); } catch { data = null; }
104
+ }
105
+ if (!data || typeof data !== 'object') data = {};
106
+ const record = data.record && typeof data.record === 'object' ? data.record : null;
107
+ const channelTable = channel.split('/')[3] || null;
108
+ const table = data.table || record?.table || expected.table || channelTable;
109
+ const sysID = data.sys_id || record?.sys_id || expected.sysID || null;
110
+ const rawOperation = String(data.operation || data.op || data.action || '').toLowerCase();
111
+ const operation = OPERATION_NAMES[rawOperation] || (rawOperation ? 'changed' : 'unknown');
112
+ const changes = Array.isArray(data.changes)
113
+ ? data.changes.map(normalizeChange).filter(Boolean)
114
+ : [];
115
+ const displayValue = data.display_value ?? data.displayValue
116
+ ?? record?.number ?? record?.display_value ?? null;
117
+
118
+ const event = {
119
+ type: 'record_change',
120
+ channel,
121
+ table,
122
+ sys_id: sysID,
123
+ operation,
124
+ received_at: receivedAt,
125
+ };
126
+ if (rawOperation) event.action = rawOperation;
127
+ if (displayValue != null) event.display_value = displayValue;
128
+ if (message?.id != null) event.event_id = message.id;
129
+ if (changes.length) event.changes = changes;
130
+ if (record) event.record = record;
131
+ return event;
132
+ }
133
+
134
+ /** Seed a cookie jar from a `a=1; b=2` header value. */
135
+ function seedCookies(jar, header) {
136
+ for (const part of String(header || '').split(';')) {
137
+ const pair = part.trim();
138
+ const eq = pair.indexOf('=');
139
+ if (eq <= 0) continue;
140
+ jar.set(pair.slice(0, eq), pair.slice(eq + 1));
141
+ }
142
+ }
143
+
144
+ function serializeCookies(jar) {
145
+ return [...jar].map(([name, value]) => `${name}=${value}`).join('; ');
146
+ }
147
+
148
+ /**
149
+ * Minimal Bayeux client for ServiceNow's /amb endpoint.
150
+ *
151
+ * `session()` returns `{ cookies, userToken }` and is called again on every
152
+ * reconnect so an expired session can be refreshed instead of replaying a
153
+ * dead cookie.
154
+ */
155
+ export class AmbClient {
156
+ constructor({
157
+ baseUrl,
158
+ session,
159
+ fetchImpl = globalThis.fetch,
160
+ path = '/amb',
161
+ connectTimeoutMs = DEFAULT_CONNECT_TIMEOUT,
162
+ requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT,
163
+ }) {
164
+ if (!baseUrl) throw new AmbError(CodeUsage, 'AMB needs an instance URL.');
165
+ if (typeof session !== 'function') throw new AmbError(CodeUsage, 'AMB needs a session provider.');
166
+ this.baseUrl = String(baseUrl).replace(/\/$/, '');
167
+ this.session = session;
168
+ this.fetchImpl = fetchImpl;
169
+ this.path = path.startsWith('/') ? path : `/${path}`;
170
+ this.connectTimeoutMs = connectTimeoutMs;
171
+ this.requestTimeoutMs = requestTimeoutMs;
172
+ this.clientId = null;
173
+ this.sessionStatus = null;
174
+ this.cookieJar = new Map();
175
+ this.userToken = '';
176
+ this.messageCounter = 0;
177
+ }
178
+
179
+ /** POST a Bayeux message array to /amb/handshake or /amb/connect. */
180
+ async _send(messages, { op, timeoutMs, signal }) {
181
+ const endpoint = op === 'handshake' ? 'handshake' : 'connect';
182
+ const url = `${this.baseUrl}${this.path}/${endpoint}`;
183
+ const headers = { Accept: 'application/json', 'Content-Type': 'application/json' };
184
+ const cookies = serializeCookies(this.cookieJar);
185
+ if (cookies) headers.Cookie = cookies;
186
+ if (this.userToken) headers['X-UserToken'] = this.userToken;
187
+
188
+ const controller = new AbortController();
189
+ let timedOut = false;
190
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
191
+ const forwardAbort = () => controller.abort();
192
+ if (signal) {
193
+ if (signal.aborted) controller.abort();
194
+ else signal.addEventListener('abort', forwardAbort, { once: true });
195
+ }
196
+ try {
197
+ const response = await this.fetchImpl(url, {
198
+ method: 'POST',
199
+ headers,
200
+ body: JSON.stringify(messages),
201
+ signal: controller.signal,
202
+ });
203
+ this._captureSession(response);
204
+ if (!response.ok) {
205
+ const detail = await response.text().catch(() => '');
206
+ const status = response.status;
207
+ if (status === 401) {
208
+ throw new AmbError(CodeAuth, 'AMB rejected the active session (HTTP 401).',
209
+ 'Run "jsn auth login --browser" (or reauthenticate the profile), then retry the watch.', 401);
210
+ }
211
+ if (status === 403) {
212
+ throw new AmbError(CodeAPI,
213
+ 'AMB access forbidden (HTTP 403).',
214
+ 'Record watching requires an interactive user session; check the role/ACL that governs AMB channels on this instance.',
215
+ 403);
216
+ }
217
+ if (status === 404) {
218
+ throw new AmbError(CodeAPI,
219
+ 'AMB endpoint not found (HTTP 404).',
220
+ 'This instance does not expose /amb, or the instance URL is wrong. Record watching is supported on ServiceNow instances with the AMB service enabled.',
221
+ 404);
222
+ }
223
+ const summary = detail.replace(/\s+/g, ' ').trim().slice(0, 200);
224
+ throw new AmbError(CodeAPI, `AMB ${op} failed (HTTP ${status})${summary ? `: ${summary}` : '.'}`,
225
+ status >= 500 ? 'The instance may be unavailable or the AMB service restarting; retry shortly.' : 'Check the AMB service on this instance.',
226
+ status);
227
+ }
228
+ const json = await response.json();
229
+ if (!Array.isArray(json)) {
230
+ throw new AmbError(CodeAPI, `AMB ${op} returned an unexpected response.`, 'Expected a Bayeux message array; the instance may be proxying /amb to something else.');
231
+ }
232
+ return json;
233
+ } catch (error) {
234
+ if (error instanceof AppError) throw error;
235
+ const abortedByCaller = signal?.aborted === true;
236
+ if (timedOut && !abortedByCaller) {
237
+ const timeout = new AmbError(CodeNetwork, `AMB ${op} timed out after ${timeoutMs}ms.`,
238
+ 'The instance did not answer the AMB request. Check connectivity, then retry.');
239
+ timeout.timedOut = true;
240
+ throw timeout;
241
+ }
242
+ if (abortedByCaller) {
243
+ const aborted = new AmbError(CodeNetwork, 'AMB request cancelled.');
244
+ aborted.cancelled = true;
245
+ throw aborted;
246
+ }
247
+ const network = new AmbError(CodeNetwork, `Network error talking to AMB: ${error.message || error}`,
248
+ 'Check your internet connection and instance URL.');
249
+ network.cause = error;
250
+ throw network;
251
+ } finally {
252
+ clearTimeout(timer);
253
+ if (signal) signal.removeEventListener('abort', forwardAbort);
254
+ }
255
+ }
256
+
257
+ /** Keep session cookies and X-UserToken from any AMB response. */
258
+ _captureSession(response) {
259
+ const setCookies = response.headers?.getSetCookie?.() || [];
260
+ const raw = setCookies.length
261
+ ? setCookies
262
+ : [response.headers?.get?.('set-cookie')].filter(Boolean);
263
+ for (const value of raw) {
264
+ const pair = value.split(';', 1)[0].trim();
265
+ const eq = pair.indexOf('=');
266
+ if (eq <= 0) continue;
267
+ const name = pair.slice(0, eq);
268
+ if (SESSION_COOKIE.test(name)) this.cookieJar.set(name, pair.slice(eq + 1));
269
+ }
270
+ const token = response.headers?.get?.('x-usertoken');
271
+ if (token) this.userToken = token;
272
+ }
273
+
274
+ _message(channel, fields = {}) {
275
+ if (!this.clientId) throw new AmbError(CodeUsage, 'AMB client has no clientId; handshake first.');
276
+ return { channel, clientId: this.clientId, id: String(++this.messageCounter), ...fields };
277
+ }
278
+
279
+ /**
280
+ * Refresh session material, handshake, and subscribe to every channel.
281
+ * Re-run this after a dropped connection: re-subscribing is what restores
282
+ * delivery, and the gap is reported by the caller.
283
+ */
284
+ async start(channels = []) {
285
+ const session = await this.session();
286
+ if (!session?.cookies) {
287
+ throw ambAuthError('AMB needs a browser session and the active profile has none.',
288
+ 'Log in with a UI session ("jsn auth login --browser") or use a profile that stores gck cookies. Bearer-token-only profiles cannot open AMB channels.');
289
+ }
290
+ this.cookieJar.clear();
291
+ seedCookies(this.cookieJar, session.cookies);
292
+ this.userToken = session.userToken || '';
293
+ this.clientId = null;
294
+
295
+ const [handshake] = await this._send([{
296
+ channel: '/meta/handshake',
297
+ version: BAYEUX_VERSION,
298
+ supportedConnectionTypes: ['long-polling'],
299
+ id: String(++this.messageCounter),
300
+ }], { op: 'handshake', timeoutMs: this.requestTimeoutMs });
301
+ if (!handshake?.successful || !handshake?.clientId) {
302
+ throw new AmbError(CodeAuth,
303
+ `AMB handshake was rejected${handshake?.error ? `: ${handshake.error}` : '.'}`,
304
+ 'The active session is not accepted by AMB. Reauthenticate with "jsn auth login --browser"; basic/OAuth-only logins often cannot open a UI session.');
305
+ }
306
+ this.clientId = handshake.clientId;
307
+ this.sessionStatus = handshake.ext?.['glide.session.status'] ?? null;
308
+
309
+ for (const channel of channels) {
310
+ const [reply] = await this._send([this._message('/meta/subscribe', { subscription: channel })],
311
+ { op: 'subscribe', timeoutMs: this.requestTimeoutMs });
312
+ if (!reply?.successful) {
313
+ throw new AmbError(CodeAPI,
314
+ `AMB subscribe failed for ${channel}${reply?.error ? `: ${reply.error}` : '.'}`,
315
+ 'The record watcher channel was refused. Check that the record is accessible to this user and that AMB record watchers are enabled on the instance.');
316
+ }
317
+ }
318
+ return { clientId: this.clientId, sessionStatus: this.sessionStatus, channels: [...channels] };
319
+ }
320
+
321
+ /**
322
+ * One long-poll: returns the non-meta Bayeux messages it received. A local
323
+ * timeout returns an empty array (the loop just polls again) unless the
324
+ * caller's signal aborted, which throws with `cancelled`.
325
+ */
326
+ async next({ timeoutMs = this.connectTimeoutMs, signal } = {}) {
327
+ let messages;
328
+ try {
329
+ messages = await this._send([this._message('/meta/connect', { connectionType: 'long-polling' })],
330
+ { op: 'connect', timeoutMs, signal });
331
+ } catch (error) {
332
+ if (error.timedOut) return [];
333
+ throw error;
334
+ }
335
+ const events = [];
336
+ for (const message of messages) {
337
+ if (!message || typeof message !== 'object') continue;
338
+ if (message.channel?.startsWith('/meta/')) {
339
+ // Server advised a fresh handshake (session moved nodes, restarted).
340
+ if (message.advice?.reconnect === 'handshake' || (message.error && !message.successful)) {
341
+ this.clientId = null;
342
+ throw new AmbError(CodeNetwork, `AMB connection lost${message.error ? `: ${message.error}` : '.'}`,
343
+ 'Reconnecting re-subscribes the record watcher; events sent while disconnected are not replayed.');
344
+ }
345
+ continue;
346
+ }
347
+ events.push(message);
348
+ }
349
+ return events;
350
+ }
351
+
352
+ /** Best-effort unsubscribe + disconnect. Never throws. */
353
+ async stop(channels = []) {
354
+ if (!this.clientId) return;
355
+ for (const channel of channels) {
356
+ try {
357
+ await this._send([this._message('/meta/unsubscribe', { subscription: channel })],
358
+ { op: 'unsubscribe', timeoutMs: 5000 });
359
+ } catch { /* best effort; the connect loop is already stopping */ }
360
+ }
361
+ try {
362
+ await this._send([this._message('/meta/disconnect', {})], { op: 'disconnect', timeoutMs: 5000 });
363
+ } catch { /* best effort */ }
364
+ this.clientId = null;
365
+ }
366
+ }
367
+
368
+ export function createAmbClient(options) {
369
+ return new AmbClient(options);
370
+ }
package/src/cli.js CHANGED
@@ -76,6 +76,7 @@ import { scrapiCmd } from './commands/scrapi.js';
76
76
  import { b4rulesCmd } from './commands/b4rules.js';
77
77
  import { atfCmd } from './commands/atf.js';
78
78
  import { scanCmd } from './commands/scan.js';
79
+ import { storeCmd } from './commands/store.js';
79
80
  import { approvalsCmd } from './commands/approvals.js';
80
81
  import { historyCmd } from './commands/history.js';
81
82
  import { perfCmd } from './commands/perf.js';
@@ -428,6 +429,7 @@ export function buildCLI() {
428
429
  // DEVELOPER
429
430
  .command(atfCmd(wrap))
430
431
  .command(scanCmd(wrap))
432
+ .command(storeCmd(wrap))
431
433
  .command(approvalsCmd(wrap))
432
434
  .command(skippedUpdatesCmd(wrap))
433
435
  .command(perfCmd(wrap))
@@ -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',