@jacebenson/jsn 5.5.7 → 5.5.8-dev.220.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.
Files changed (66) hide show
  1. package/README.md +16 -1
  2. package/package.json +5 -6
  3. package/skills/servicenow/SKILL.md +9 -1
  4. package/src/app.js +4 -79
  5. package/src/auth/credential-store.js +33 -8
  6. package/src/auth/windows-credential-store.js +85 -0
  7. package/src/auth/windows-credential-store.ps1 +163 -0
  8. package/src/bounded-reads.js +13 -0
  9. package/src/capabilities.js +8 -3
  10. package/src/cli-adapter.js +26 -3
  11. package/src/cli.js +13 -14
  12. package/src/command-families.js +68 -0
  13. package/src/commands/_generic.js +1 -0
  14. package/src/commands/_ticket.js +1 -1
  15. package/src/commands/actions.js +9 -4
  16. package/src/commands/approvals.js +1 -1
  17. package/src/commands/atf.js +1 -1
  18. package/src/commands/attachments.js +1 -1
  19. package/src/commands/auth.js +21 -2
  20. package/src/commands/codesearch.js +11 -2
  21. package/src/commands/compare.js +22 -0
  22. package/src/commands/customizations.js +3 -4
  23. package/src/commands/decisiontables.js +4 -0
  24. package/src/commands/docs/docs.js +5 -5
  25. package/src/commands/domains.js +1 -1
  26. package/src/commands/eval.js +11 -5
  27. package/src/commands/flows.js +24 -7
  28. package/src/commands/groupmembers.js +1 -1
  29. package/src/commands/grouproles.js +1 -1
  30. package/src/commands/groups.js +1 -1
  31. package/src/commands/midservers.js +4 -11
  32. package/src/commands/perf.js +2 -3
  33. package/src/commands/plugins.js +9 -0
  34. package/src/commands/records.js +12 -2
  35. package/src/commands/scopes.js +1 -1
  36. package/src/commands/scrapi.js +2 -2
  37. package/src/commands/setup.js +4 -34
  38. package/src/commands/skipped-updates.js +2 -3
  39. package/src/commands/store.js +4 -1
  40. package/src/commands/subscriptions.js +47 -0
  41. package/src/commands/tickets.js +1 -1
  42. package/src/commands/users.js +1 -1
  43. package/src/commands/workflows.js +3 -5
  44. package/src/config.js +1 -0
  45. package/src/context.js +8 -56
  46. package/src/docs-links.js +28 -0
  47. package/src/flow-create.js +9 -0
  48. package/src/help.js +4 -0
  49. package/src/helpers.js +17 -24
  50. package/src/instance-inventory.js +184 -0
  51. package/src/intended-context.js +68 -0
  52. package/src/mutation-context.js +69 -46
  53. package/src/output.js +1 -1
  54. package/src/paginated-search.js +146 -178
  55. package/src/picker-ui.js +20 -0
  56. package/src/prompt-engine.js +176 -0
  57. package/src/prompts.js +293 -43
  58. package/src/records/inspect.js +30 -16
  59. package/src/records-engine.js +2 -2
  60. package/src/schedule-cache.js +96 -0
  61. package/src/schedules/itom-2026-04-09.json +121 -0
  62. package/src/schedules/public-inventory.json +6224 -0
  63. package/src/sdk-batch.js +2 -1
  64. package/src/sdk.js +42 -16
  65. package/src/setup-preferences.js +2 -2
  66. package/src/subscriptions.js +176 -0
package/src/prompts.js CHANGED
@@ -1,35 +1,87 @@
1
- export class PromptCancelled extends Error {
2
- constructor() {
3
- super('Cancelled.');
4
- this.name = 'PromptCancelled';
5
- }
1
+ /**
2
+ * JSN's interactive prompt surface, implemented on the local engine
3
+ * (src/prompt-engine.js) instead of @inquirer/prompts.
4
+ *
5
+ * Callers use `prompt(config, { input, output, signal })`. Escape cancels
6
+ * ordinary prompts with PromptCancelled; record pickers live in
7
+ * paginated-search.js and resolve undefined instead.
8
+ */
9
+
10
+ import { pickerRows, pickerFooter } from './picker-ui.js';
11
+ import { runPrompt, normalizeChoices, PromptCancelled, escapeResult } from './prompt-engine.js';
12
+ export { PromptCancelled };
13
+
14
+ const ESC_HINT = ' (Esc to cancel)';
15
+
16
+ function withHint(config) {
17
+ const message = String(config.message ?? '');
18
+ return message.includes(ESC_HINT) ? message : `${message}${ESC_HINT}`;
6
19
  }
7
20
 
8
- /** Add Escape cancellation to an Inquirer prompt without changing its answers. */
9
- export function cancellablePrompt(prompt) {
10
- return async (config, context = {}) => {
11
- const input = context.input || process.stdin;
12
- const controller = new AbortController();
13
- const onKey = (_value, key) => {
14
- if (key?.name === 'escape') controller.abort(new PromptCancelled());
15
- };
16
- input.on('keypress', onKey);
17
- try {
18
- return await prompt({ ...config, message: `${config.message} (Esc to cancel)` }, {
19
- ...context,
20
- signal: context.signal ? AbortSignal.any([context.signal, controller.signal]) : controller.signal,
21
- });
22
- } catch (error) {
23
- if (controller.signal.aborted) throw controller.signal.reason;
24
- throw error;
25
- } finally {
26
- input.removeListener('keypress', onKey);
27
- }
28
- };
21
+ function applyValidate(validate, value) {
22
+ if (typeof validate !== 'function') return null;
23
+ const result = validate(value);
24
+ return result instanceof Promise ? result : result;
29
25
  }
30
26
 
31
- export const input = lazyPrompt('input');
32
- export const password = lazyPrompt('password');
27
+ async function validateAnswer(validate, value) {
28
+ const result = await applyValidate(validate, value);
29
+ if (result === true || result === undefined || result === '') return null;
30
+ return typeof result === 'string' ? result : result === false ? 'Invalid value.' : null;
31
+ }
32
+
33
+ function textPrompt({ secret = false, defaultValue = null } = {}) {
34
+ return async (config = {}, context = {}) => runPrompt({ ...config, message: withHint(config) }, context, {
35
+ init: () => ({ buffer: '', error: '' }),
36
+ async key(state, key, api) {
37
+ if (key.name === 'return' || key.name === 'enter') {
38
+ const value = state.buffer.length ? state.buffer : (config.default ?? defaultValue ?? '');
39
+ const message = await validateAnswer(config.validate, value);
40
+ if (message) { state.error = message; api.redraw(); return; }
41
+ return { done: value };
42
+ }
43
+ if (key.name === 'backspace') {
44
+ state.buffer = state.buffer.slice(0, -1);
45
+ state.error = '';
46
+ api.redraw();
47
+ return;
48
+ }
49
+ if (key.name === 'space') {
50
+ state.buffer += ' ';
51
+ state.error = '';
52
+ api.redraw();
53
+ return;
54
+ }
55
+ if (key.text) {
56
+ state.buffer += key.text;
57
+ state.error = '';
58
+ api.redraw();
59
+ return;
60
+ }
61
+ if (key.name === 'c' && key.ctrl) return { cancel: true };
62
+ api.redraw();
63
+ },
64
+ render(state) {
65
+ const label = withHint(config);
66
+ const suffix = config.default !== undefined && !secret ? ` (${config.default})` : '';
67
+ // Secrets are never echoed: the placeholder has a fixed width, so
68
+ // nothing about the typed value (characters or length) reaches stdout.
69
+ const shown = secret ? (state.buffer.length ? '******' : '') : state.buffer;
70
+ const error = state.error ? `\n ${state.error}` : '';
71
+ return `${label}${suffix}\n> ${shown}${error}`;
72
+ },
73
+ // Settled line keeps the prompt's own message (and hint) and never the
74
+ // secret value; Inquirer's `✔ message answer` shape.
75
+ final(cfg, value) {
76
+ const answer = secret || value === undefined || value === '' ? '' : ` ${value}`;
77
+ return `✔ ${withHint(cfg)}${answer}`;
78
+ },
79
+ });
80
+ }
81
+
82
+ export const input = textPrompt();
83
+
84
+ export const password = textPrompt({ secret: true });
33
85
 
34
86
  // Use the shared Escape contract and a masked prompt; codes stay ephemeral.
35
87
  export async function mfaCode(config = {}, context = {}) {
@@ -39,20 +91,218 @@ export async function mfaCode(config = {}, context = {}) {
39
91
  || 'Enter the 6-digit code from your authenticator app.',
40
92
  }, context);
41
93
  }
42
- export const select = lazyPrompt('select');
43
- export const search = lazyPrompt('search');
44
- export const confirm = lazyPrompt('confirm');
45
- export const checkbox = lazyPrompt('checkbox');
46
-
47
- // The editor prompt hands the keyboard to $EDITOR, so Escape belongs to that
48
- // editor. It lives here so every command imports prompts from one module;
49
- // cancelling an editor still uses Inquirer's Ctrl+C abort.
50
- export const editor = async (...args) => (await import('@inquirer/prompts')).editor(...args);
51
-
52
- // Load Inquirer only when a prompt is actually shown.
53
- function lazyPrompt(name) {
54
- return async (...args) => {
55
- const prompts = await import('@inquirer/prompts');
56
- return cancellablePrompt(prompts[name])(...args);
94
+
95
+ export async function confirm(config = {}, context = {}) {
96
+ const fallback = config.default === undefined ? true : Boolean(config.default);
97
+ return runPrompt({ ...config, message: withHint(config) }, context, {
98
+ init: () => ({ value: '', error: '' }),
99
+ key(state, key, api) {
100
+ if (key.name === 'return' || key.name === 'enter') {
101
+ const answer = /^y/i.test(state.value) ? true : /^n/i.test(state.value) ? false : fallback;
102
+ return { done: answer };
103
+ }
104
+ if (key.name === 'backspace') state.value = state.value.slice(0, -1);
105
+ else if (key.text) state.value += key.text;
106
+ api.redraw();
107
+ },
108
+ render(state) {
109
+ const hint = fallback ? '[Y/n]' : '[y/N]';
110
+ return `${withHint(config)} ${hint} ${state.value}`;
111
+ },
112
+ final: (cfg, value) => `✔ ${withHint(cfg)} ${value ? 'Yes' : 'No'}`,
113
+ });
114
+ }
115
+
116
+ export async function select(config = {}, context = {}) {
117
+ return localPicker(config, context);
118
+ }
119
+
120
+ async function localPicker(config, context, multiple = false) {
121
+ const choices = normalizeChoices(config.choices || []);
122
+ const state = {
123
+ term: '', choices, active: firstEnabled(choices), error: '',
124
+ picked: new Set(choices.filter(choice => choice.checked && !choice.disabled)),
57
125
  };
126
+ const defaultIndex = choices.findIndex(choice => !choice.disabled && choice.value === config.default);
127
+ if (defaultIndex >= 0) state.active = defaultIndex;
128
+ return runPrompt(config, context, {
129
+ ...(config.escapeValue ? { escapeValue: config.escapeValue } : {}),
130
+ init: () => state,
131
+ async key(_state, key, api) {
132
+ const visible = state.choices;
133
+ const choice = visible[state.active];
134
+ if (key.name === 'return' || key.name === 'enter') {
135
+ if (!multiple) {
136
+ if (choice && !choice.disabled) return { done: choice.value };
137
+ return;
138
+ }
139
+ const values = choices.filter(choice => state.picked.has(choice)).map(choice => choice.value);
140
+ state.error = config.required && !values.length ? 'Select at least one option.' : await validateAnswer(config.validate, values);
141
+ if (state.error) { api.redraw(); return; }
142
+ return { done: values };
143
+ }
144
+ if (multiple && key.name === 'space') {
145
+ if (choice && !choice.disabled) {
146
+ if (state.picked.has(choice)) state.picked.delete(choice);
147
+ else state.picked.add(choice);
148
+ state.error = '';
149
+ }
150
+ } else if (multiple && key.ctrl && key.name === 'a') {
151
+ visible.forEach(choice => { if (!choice.disabled) state.picked.add(choice); });
152
+ } else if (key.name === 'up' || key.name === 'down') {
153
+ state.active = move(visible, state.active, key.name === 'up' ? -1 : 1);
154
+ } else {
155
+ const previous = state.term;
156
+ if (key.name === 'backspace') state.term = Array.from(state.term).slice(0, -1).join('');
157
+ else if (key.text) state.term += key.text;
158
+ if (previous !== state.term) {
159
+ state.choices = state.term ? choices.filter(choice => !choice.separator && choice.name.toLocaleLowerCase().includes(state.term.toLocaleLowerCase())) : choices;
160
+ state.active = firstEnabled(state.choices);
161
+ }
162
+ }
163
+ api.redraw();
164
+ },
165
+ render() {
166
+ return [config.message ?? '', `Search: ${state.term}`, ...pickerRows(state.choices, state.active, multiple ? { picked: state.picked } : {}),
167
+ ...(!state.choices.length ? [' No matches'] : []), ...(state.error ? [` ${state.error}`] : []), ...pickerFooter({ checkbox: multiple })];
168
+ },
169
+ final: (_cfg, value) => value === undefined ? null : `✔ ${config.message ?? ''} ${multiple ? choices.filter(choice => value.includes(choice.value)).map(choice => choice.name).join(', ') : choices.find(choice => choice.value === value)?.name ?? value ?? ''}`,
170
+ });
171
+ }
172
+
173
+ export async function search(config = {}, context = {}) {
174
+ let request;
175
+ const state = { term: '', choices: [], active: 0, loading: false, token: 0, error: '' };
176
+ async function load(api) {
177
+ request?.abort();
178
+ request = new AbortController();
179
+ const signal = context.signal ? AbortSignal.any([request.signal, context.signal]) : request.signal;
180
+ const token = ++state.token;
181
+ state.loading = true;
182
+ state.error = '';
183
+ state.active = 0;
184
+ api.redraw();
185
+ try {
186
+ const items = await config.source?.(state.term, { signal });
187
+ if (token !== state.token) return;
188
+ state.choices = normalizeChoices(items || []);
189
+ } catch (error) {
190
+ if (token !== state.token) return;
191
+ state.choices = [];
192
+ state.error = error?.message || String(error);
193
+ }
194
+ if (token !== state.token) return;
195
+ state.loading = false;
196
+ state.active = firstEnabled(state.choices);
197
+ api.redraw();
198
+ }
199
+ try {
200
+ return await runPrompt({ ...config, message: withHint(config) }, context, {
201
+ init: () => state,
202
+ onReady: api => { void load(api); },
203
+ key(_state, key, api) {
204
+ if (key.name === 'return' || key.name === 'enter') {
205
+ const choice = state.choices[state.active];
206
+ if (!state.loading && choice && !choice.disabled) return { done: choice.value };
207
+ return;
208
+ }
209
+ if (key.name === 'up' || key.name === 'down') {
210
+ state.active = move(state.choices, state.active, key.name === 'up' ? -1 : 1);
211
+ api.redraw();
212
+ return;
213
+ }
214
+ const previous = state.term;
215
+ if (key.name === 'backspace') state.term = state.term.slice(0, -1);
216
+ else if (key.text) state.term += key.text;
217
+ if (state.term !== previous) void load(api);
218
+ },
219
+ render() {
220
+ const lines = [config.message ?? '', `Search: ${state.term}${state.loading ? ' ...' : ''}`];
221
+ if (state.error) lines.push(` ${state.error}`);
222
+ else if (!state.choices.length) lines.push(state.loading ? ' Loading...' : ' No matches');
223
+ else lines.push(...pickerRows(state.choices, state.active));
224
+ lines.push(...pickerFooter());
225
+ return lines;
226
+ },
227
+ });
228
+ } finally {
229
+ state.token += 1;
230
+ request?.abort();
231
+ }
232
+ }
233
+
234
+ export async function checkbox(config = {}, context = {}) {
235
+ return localPicker(config, context, true);
58
236
  }
237
+
238
+ function firstEnabled(choices) {
239
+ const index = choices.findIndex(choice => !choice.disabled);
240
+ return index < 0 ? 0 : index;
241
+ }
242
+
243
+ function move(choices, active, delta) {
244
+ let next = active + delta;
245
+ while (next >= 0 && next < choices.length && choices[next].disabled) next += delta;
246
+ if (next < 0 || next >= choices.length) return active;
247
+ return next;
248
+ }
249
+
250
+ /**
251
+ * Enter launches $EDITOR by default. Escape cancels before launch; once the
252
+ * editor owns the keyboard, its own controls apply.
253
+ */
254
+ export async function editor(config = {}, context = {}) {
255
+ if (config.waitForUserInput !== false) {
256
+ await runPrompt(config, context, {
257
+ init: () => ({}),
258
+ key(_state, key) {
259
+ if (key.name === 'return' || key.name === 'enter') return { done: true };
260
+ },
261
+ render: () => [withHint(config), 'Press Enter to launch your preferred editor.'],
262
+ });
263
+ } else {
264
+ (context.output || process.stdout).write(`${withHint(config)}\n`);
265
+ }
266
+ const fs = await import('node:fs');
267
+ const os = await import('node:os');
268
+ const path = await import('node:path');
269
+ const { spawn } = await import('node:child_process');
270
+
271
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'jsn-editor-'));
272
+ const file = path.join(directory, 'draft.txt');
273
+ try {
274
+ fs.writeFileSync(file, config.default ?? '', 'utf8');
275
+ const [command, ...args] = editorCommand();
276
+ await new Promise((resolve, reject) => {
277
+ const child = spawn(command, [...args, file], {
278
+ stdio: 'inherit',
279
+ signal: context.signal,
280
+ env: process.env,
281
+ });
282
+ child.on('error', reject);
283
+ child.on('exit', (code, signal) => {
284
+ if (code === 0) resolve();
285
+ else reject(new Error(`Editor exited with ${signal ? `signal ${signal}` : `code ${code}`}`));
286
+ });
287
+ });
288
+ return fs.readFileSync(file, 'utf8');
289
+ } finally {
290
+ fs.rmSync(directory, { recursive: true, force: true });
291
+ }
292
+ }
293
+
294
+ function editorCommand() {
295
+ const spec = process.env.VISUAL || process.env.EDITOR || 'vi';
296
+ return spec.trim().split(/\s+/);
297
+ }
298
+
299
+ /**
300
+ * Kept for callers/tests that wrapped an Inquirer prompt with the Escape
301
+ * contract. The engine owns Escape now, so this is a pass-through that
302
+ * preserves the previous signature.
303
+ */
304
+ export function cancellablePrompt(prompt) {
305
+ return async (config, context = {}) => prompt(config, context);
306
+ }
307
+
308
+ export { escapeResult };
@@ -1,5 +1,7 @@
1
1
  import { isHexString, getStringField, assertSafeExactMatch } from '../helpers.js';
2
2
  import { discoverFlowContextFields, normalizeFlowContext } from '../flow-context.js';
3
+ import { tableReadParams } from '../table-read-params.js';
4
+ import { boundedReads } from '../bounded-reads.js';
3
5
 
4
6
  export async function resolveIdentifier(app, table, identifier) {
5
7
  // If it looks like a sys_id (32 hex chars), use it directly
@@ -86,24 +88,36 @@ async function resolveHistoryDisplayValues(app, table, history) {
86
88
  }
87
89
  }
88
90
 
89
- // Batch lookup choice labels
91
+ // Preserve each exact field/value query and its one-row limit. Batching
92
+ // changes HTTP envelopes, not the number or authorization of server reads.
90
93
  const choiceLabelMap = new Map();
91
- if (choiceLookups.size > 0) {
92
- for (const key of choiceLookups) {
93
- const [field, val] = key.split('|');
94
- const params = new URLSearchParams();
95
- params.set('sysparm_query', `name=${table}^element=${field}^value=${val}^language=en`);
96
- params.set('sysparm_limit', '1');
97
- params.set('sysparm_fields', 'value,label');
98
- params.set('sysparm_display_value', 'all');
99
- try {
100
- const choices = await app.sdk.list('sys_choice', params);
101
- if (choices.length > 0) {
102
- const label = choices[0].label?.display_value || choices[0].label;
103
- if (label) choiceLabelMap.set(key, label);
104
- }
105
- } catch { /* non-fatal */ }
94
+ const lookups = [...choiceLookups].map(key => {
95
+ const [field, val] = key.split('|');
96
+ return { key, params: new URLSearchParams({
97
+ sysparm_query: `name=${table}^element=${field}^value=${val}^language=en`,
98
+ sysparm_limit: '1', sysparm_fields: 'value,label', sysparm_display_value: 'all',
99
+ }) };
100
+ });
101
+ let choicesByLookup;
102
+ if (lookups.length > 1 && typeof app.sdk.batch === 'function') {
103
+ try {
104
+ const batch = await app.sdk.batch(lookups.map(({ params }, index) => ({
105
+ id: String(index), url: `/api/now/table/sys_choice?${tableReadParams(params, app.sdk)}`,
106
+ })));
107
+ choicesByLookup = batch.results.map(item => item.ok && Array.isArray(item.data?.result) ? item.data.result : []);
108
+ } catch {
109
+ // Existing policy: labels are optional. Never retry an ACL denial,
110
+ // malformed response or uncertain batch failure as individual reads.
111
+ choicesByLookup = lookups.map(() => []);
106
112
  }
113
+ } else {
114
+ choicesByLookup = await boundedReads(lookups, async ({ params }) => {
115
+ try { return await app.sdk.list('sys_choice', params); } catch { return []; }
116
+ });
117
+ }
118
+ for (const [index, choices] of choicesByLookup.entries()) {
119
+ const label = choices[0]?.label?.display_value || choices[0]?.label;
120
+ if (label) choiceLabelMap.set(lookups[index].key, label);
107
121
  }
108
122
 
109
123
  // Apply resolutions to history entries
@@ -20,10 +20,10 @@ export function recordListParams({ limit, offset, query, fields, displayValue: r
20
20
  return params;
21
21
  }
22
22
 
23
- export function listRecords(sdk, { table, params, displayValues, ...options }) {
23
+ export function listRecords(sdk, { table, params, displayValues, responseMetadata, ...options }) {
24
24
  const query = tableReadParams(params || recordListParams(options), sdk);
25
25
  if (displayValues !== undefined) query.set('sysparm_display_value', displayValue(displayValues));
26
- return sdk.list(table, query);
26
+ return responseMetadata ? sdk.list(table, query, { responseMetadata }) : sdk.list(table, query);
27
27
  }
28
28
 
29
29
  export function getRecord(sdk, options) {
@@ -0,0 +1,96 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { cacheDir } from './config.js';
5
+ import { AppError } from './errors.js';
6
+
7
+ const MAX = 4 * 1024 * 1024;
8
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex');
9
+ const fail = message => { throw new AppError('invalid_catalog', message); };
10
+ const file = () => path.join(cacheDir(), 'subscription-schedules-v1.json');
11
+ const hash = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
12
+ export function validateCatalog(catalog) {
13
+ const checkDepth = (value, depth = 0) => {
14
+ if (depth > 32) fail('Catalog nesting exceeds schema limit.');
15
+ if (value && typeof value === 'object') for (const child of Object.values(value)) checkDepth(child, depth + 1);
16
+ };
17
+ checkDepth(catalog);
18
+ if (catalog?.schema_version !== 1 || !hash(catalog.revision) || !Array.isArray(catalog.schedules) || !catalog.schedules.length) fail('Invalid catalog schema.');
19
+ const ids = new Set();
20
+ for (const r of catalog.schedules) {
21
+ if (!r || typeof r.id !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(r.id) || ids.has(r.id) || typeof r.product !== 'string' || !r.product.trim()) fail('Invalid or duplicate schedule ID/product.');
22
+ ids.add(r.id);
23
+ for (const key of ['title', 'source_version', 'effective_date', 'applicability', 'measurement', 'normalization_status']) {
24
+ if (r[key] !== undefined && r[key] !== null && typeof r[key] !== 'string') fail(`Invalid record ${key}.`);
25
+ }
26
+ for (const key of ['source_sections', 'skus', 'unknowns', 'exceptions', 'limitations']) {
27
+ if (r[key] !== undefined && (!Array.isArray(r[key]) || r[key].some(v => typeof v !== 'string'))) fail(`Invalid record ${key}.`);
28
+ }
29
+ if (r.definitions !== undefined && (!r.definitions || typeof r.definitions !== 'object')) fail('Invalid definitions.');
30
+ if (Array.isArray(r.definitions) && r.definitions.some(d => !d || typeof d.term !== 'string' || typeof d.definition !== 'string' || !Array.isArray(d.source_sections) || d.source_sections.some(v => typeof v !== 'string'))) fail('Invalid definition provenance.');
31
+ if (r.meter !== undefined && (!r.meter || typeof r.meter !== 'object' || Array.isArray(r.meter))) fail('Invalid meter.');
32
+ if (r.meter?.rules !== undefined && (!Array.isArray(r.meter.rules) || r.meter.rules.some(v => !v || typeof v !== 'object' || Array.isArray(v)))) fail('Invalid meter rules.');
33
+ for (const key of ['packages', 'entitlements', 'section_coverage', 'capability_lists']) {
34
+ if (r[key] !== undefined && (!r[key] || typeof r[key] !== 'object')) fail(`Invalid record ${key}.`);
35
+ }
36
+ let source;
37
+ try { source = new URL(r.source_url); } catch { fail('Missing source provenance.'); }
38
+ if (source.protocol !== 'https:' || source.hostname !== 'www.servicenow.com' || source.username || source.password || !source.pathname.endsWith('.pdf') || !Number.isFinite(Date.parse(r.retrieved_at || r.fetched_at))) fail('Unsafe or missing source provenance.');
39
+ if (r.id !== 'itom-2026-04-09' && (!Array.isArray(r.source_sections) || !r.source_sections.length || !Array.isArray(r.skus) || !['normalized', 'partial'].includes(r.normalization_status))) fail('Invalid normalized record schema.');
40
+ }
41
+ return catalog;
42
+ }
43
+ function safeURL(value, origin) {
44
+ let u;
45
+ try { u = new URL(value); } catch { fail('Invalid catalog URL.'); }
46
+ if (u.username || u.password || u.hash || (u.protocol !== 'https:' && !(u.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(u.hostname))) || (origin && u.origin !== origin)) fail('Catalog URL must use HTTPS and the approved manifest origin (explicit loopback HTTP is allowed).');
47
+ return u;
48
+ }
49
+ async function download(url, cap) {
50
+ const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(10000), credentials: 'omit' });
51
+ if (!response.ok) fail(`Catalog HTTP ${response.status}.`);
52
+ if (Number(response.headers.get('content-length')) > cap) fail('Catalog exceeds size cap.');
53
+ const chunks = []; let size = 0;
54
+ for await (const chunk of response.body) {
55
+ size += chunk.length;
56
+ if (size > cap) { fail('Catalog exceeds size cap.'); }
57
+ chunks.push(chunk);
58
+ }
59
+ return Buffer.concat(chunks);
60
+ }
61
+ export async function refreshSchedules(manifestURL) {
62
+ if (!manifestURL) fail('Specify --manifest-url or configure JSN_DOCS_URL / global docs.url.');
63
+ const url = safeURL(manifestURL);
64
+ const manifest = JSON.parse(await download(url, 16384));
65
+ if (manifest.schema_version !== 1 || !hash(manifest.revision) || !hash(manifest.sha256) || !Number.isSafeInteger(manifest.bytes) || manifest.bytes < 1 || manifest.bytes > MAX || !Number.isFinite(Date.parse(manifest.published_at))) fail('Invalid manifest schema or size.');
66
+ const artifactURL = safeURL(manifest.catalog_url, url.origin);
67
+ const bytes = await download(artifactURL, MAX);
68
+ if (bytes.length !== manifest.bytes || digest(bytes) !== manifest.sha256) fail('Catalog byte length or SHA256 mismatch.');
69
+ const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
70
+ const catalog = validateCatalog(JSON.parse(text));
71
+ if (catalog.revision !== manifest.revision) fail('Catalog revision mismatch.');
72
+ const entry = { manifest, manifest_url: url.href, retrieved_at: new Date().toISOString(), artifact: text };
73
+ const serialized = JSON.stringify(entry);
74
+ if (Buffer.byteLength(serialized) > MAX * 2) fail('Serialized cache exceeds size cap.');
75
+ fs.mkdirSync(path.dirname(file()), { recursive: true, mode: 0o700 });
76
+ const temp = `${file()}.${randomUUID()}.tmp`;
77
+ try { fs.writeFileSync(temp, serialized, { mode: 0o600, flag: 'wx' }); fs.renameSync(temp, file()); }
78
+ finally { fs.rmSync(temp, { force: true }); }
79
+ return cachedSchedules().provenance;
80
+ }
81
+ export function cachedSchedules() {
82
+ try {
83
+ if (fs.statSync(file()).size > MAX * 2) return null;
84
+ const entry = JSON.parse(fs.readFileSync(file(), 'utf8'));
85
+ const m = entry.manifest;
86
+ if (m?.schema_version !== 1 || !hash(m.revision) || !hash(m.sha256) || !Number.isSafeInteger(m.bytes) || m.bytes < 1 || m.bytes > MAX || !Number.isFinite(Date.parse(m.published_at))) return null;
87
+ const approved = safeURL(entry.manifest_url);
88
+ safeURL(m.catalog_url, approved.origin);
89
+ if (typeof entry.artifact !== 'string') return null;
90
+ const bytes = Buffer.from(entry.artifact);
91
+ if (bytes.length > MAX || bytes.length !== entry.manifest.bytes || digest(bytes) !== entry.manifest.sha256) return null;
92
+ const catalog = validateCatalog(JSON.parse(bytes));
93
+ if (catalog.revision !== entry.manifest.revision || !Number.isFinite(Date.parse(entry.retrieved_at))) return null;
94
+ return { schedules: catalog.schedules, provenance: { source: 'validated-cache', revision: catalog.revision, sha256: entry.manifest.sha256, retrieved_at: entry.retrieved_at, manifest_url: entry.manifest_url, stale: Date.now() - Date.parse(entry.retrieved_at) > 86400000, freshness: 'last-good snapshot; no network freshness check' } };
95
+ } catch { return null; }
96
+ }
@@ -0,0 +1,121 @@
1
+ {
2
+ "id": "itom-2026-04-09",
3
+ "product": "ITOM",
4
+ "effective_for_skus_introduced": "2026-04-09",
5
+ "source_url": "https://www.servicenow.com/content/dam/servicenow-assets/public/en-us/doc-type/legal/it-operations-management-itom-servicenow-subscription-unit-overview.pdf",
6
+ "source_version": "Effective for SKUs introduced on April 9, 2026; sections 1.1 and 1.2",
7
+ "fetched_at": "2026-11-19T07:47:54.276651+00:00",
8
+ "retrieval": "Independent web_extract PDF text retrieval; direct download returned 403. Binary hash unavailable.",
9
+ "categories": [
10
+ {
11
+ "id": "server",
12
+ "resources_per_su": 1,
13
+ "classes": [
14
+ "cmdb_ci_server",
15
+ "cmdb_ci_vm_instance",
16
+ "cmdb_ci_ucs_rack_unit",
17
+ "cmdb_ci_ucs_blade",
18
+ "cmdb_ci_mainframe_hardware"
19
+ ]
20
+ },
21
+ {
22
+ "id": "paas",
23
+ "resources_per_su": 3,
24
+ "classes": [
25
+ "cmdb_ci_cloud_appserver",
26
+ "cmdb_ci_could_database",
27
+ "cmdb_ci_dynamodb_table",
28
+ "cmdb_ci_cloud_directory",
29
+ "cmdb_ci_cloud_gateway",
30
+ "cmdb_ci_cloud_messaging_service",
31
+ "cmdb_ci_cloud_webserver"
32
+ ]
33
+ },
34
+ {
35
+ "id": "container",
36
+ "resources_per_su": 10,
37
+ "classes": [
38
+ "cmdb_ci_oslv_container"
39
+ ]
40
+ },
41
+ {
42
+ "id": "image",
43
+ "resources_per_su": 3,
44
+ "classes": [
45
+ "cmdb_ci_oslv_image",
46
+ "cmdb_ci_oslv_local_image",
47
+ "cmdb_ci_openshift_images"
48
+ ]
49
+ },
50
+ {
51
+ "id": "end_user_device",
52
+ "resources_per_su": 4,
53
+ "classes": [
54
+ "cmdb_ci_computer"
55
+ ]
56
+ },
57
+ {
58
+ "id": "faas",
59
+ "resources_per_su": 20,
60
+ "classes": [
61
+ "cmdb_ci_cloud_function"
62
+ ]
63
+ },
64
+ {
65
+ "id": "gpu",
66
+ "resources_per_su": 1,
67
+ "classes": [
68
+ "cmdb_ci_gpu"
69
+ ]
70
+ },
71
+ {
72
+ "id": "api",
73
+ "resources_per_su": 1,
74
+ "classes": [
75
+ "cmdb_ci_api"
76
+ ]
77
+ },
78
+ {
79
+ "id": "ai_agent",
80
+ "resources_per_su": 3,
81
+ "classes": [
82
+ "cmdb_ci_function_ai"
83
+ ]
84
+ },
85
+ {
86
+ "id": "service_instance",
87
+ "resources_per_su": 1,
88
+ "classes": [
89
+ "cmdb_ci_service_auto"
90
+ ]
91
+ },
92
+ {
93
+ "id": "unresolved_object",
94
+ "resources_per_su": 4,
95
+ "classes": []
96
+ }
97
+ ],
98
+ "definitions": {
99
+ "provenance": "Paraphrases of section 1.1, not independent eligibility rules. All CI resource types must be represented in the listed classes or descendants and managed by an ITOM application.",
100
+ "server": "Physical or virtual server.",
101
+ "paas": "Cloud-based platform service.",
102
+ "container": "Operating system-level virtualization.",
103
+ "image": "Operating system-level virtualization image.",
104
+ "end_user_device": "Physical or virtual computing device not defined as another Managed IT Resource Type, with an ITOM component such as Agent Client Collector installed.",
105
+ "faas": "Serverless compute function-as-a-service instance.",
106
+ "gpu": "Graphics Processing Unit.",
107
+ "api": "Application programming interface.",
108
+ "ai_agent": "Service for machine learning, data processing and AI-driven tasks.",
109
+ "service_instance": "Interconnected applications and IT resources configured to offer a digital service.",
110
+ "unresolved_object": "IT resource receiving an ITOM event, performance metric or log, not represented as a CMDB CI; recorded in em_unique_nodes with type=unknown. Counting this source is unsupported in this slice."
111
+ },
112
+ "unresolved_mapping": "cmdb_ci_could_database is literal source text; no corrected mapping is assumed.",
113
+ "limitations": [
114
+ "CMDB populations are not managed or billable counts, nor a ceiling.",
115
+ "Managed-by-ITOM eligibility and product scope are unverified.",
116
+ "End-user devices require an installed ITOM component and exclusion of other resource types.",
117
+ "Container/image relationship exclusions are not evaluated.",
118
+ "Rounding and contract applicability are unknown.",
119
+ "Observed 90-day usage and purchased entitlements are not implemented."
120
+ ]
121
+ }