@jacebenson/jsn 5.1.1 → 5.2.0-dev.130.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.
@@ -1,24 +1,122 @@
1
- // Catalog item enrichment — pure async data-shaping for `catalogitems show`.
1
+ // Catalog item enrichment — one place that reads a catalog item and shapes it
2
+ // for output. `catalogitems show` owns the user-facing view (and the
3
+ // describe/inputs aliases); `catalogitems order` reuses the same request-side
4
+ // read, so both agree on what a question is.
2
5
  //
3
- // Given an sdk handle, an instance URL and an item sys_id, return the
4
- // enriched item: core fields resolved to display values, flow name resolved
5
- // through the sys_hub_flow fallback chain, workflow/delivery-plan fallback,
6
- // and variables grouped by variable set. No yargs, no output formatting —
7
- // callers own the envelope and rendering.
6
+ // Two calls, one answer:
7
+ // 1. the Table API (sc_cat_item + item_option_new) — the definition, always
8
+ // readable, and the fallback when the catalog API cannot answer;
9
+ // 2. /api/sn_sc/servicecatalog/items/{id} — what this account can actually
10
+ // request, with the variables a submission must answer.
11
+ // The catalog API wins when it answers; the definition list keeps the command
12
+ // useful when it does not (a producer whose server script throws, an item that
13
+ // is not in the catalog).
8
14
 
9
15
  import { getStringField } from '../../helpers.js';
10
16
 
17
+ export const CATALOG_API = '/api/sn_sc/servicecatalog/items';
18
+
19
+ // Layout entries draw the form; they are not values a caller can send.
20
+ // Codes are item_option_new.type on a live instance (11 label, 14 macro,
21
+ // 17 macro with label, 19/20/24 containers, 23 html, 32 rich text label).
22
+ const LAYOUT_CODES = new Set([11, 14, 17, 19, 20, 23, 24, 32]);
23
+ const LAYOUT_TYPES = new Set([
24
+ 'container_start', 'container_end', 'container_split',
25
+ 'label', 'rich_text_label', 'html', 'break', 'formatter',
26
+ 'macro', 'macro_with_abel', 'ui_macro',
27
+ ]);
28
+ // "Requested for" (type 31) is mandatory in the API payload but is not a value
29
+ // the caller builds: the instance fills it from the session and --requested-for
30
+ // overrides it. It is reported separately so it never blocks an order.
31
+ export const REQUESTED_FOR = 31;
32
+ // item_option_new.type code → the same friendly word the catalog API uses, so
33
+ // the definition fallback and the API payload render identically. Codes taken
34
+ // from this instance's type choices; unknown codes fall back to null.
35
+ const TYPE_NAMES = {
36
+ 1: 'yes_no', 2: 'multi_line_text', 3: 'multiple_choice', 4: 'numeric_scale',
37
+ 5: 'select_box', 6: 'single_line_text', 7: 'check_box', 8: 'reference',
38
+ 9: 'date', 10: 'date_time', 11: 'label', 14: 'macro', 16: 'wide_single_line_text',
39
+ 17: 'macro_with_abel', 18: 'lookup_select_box', 19: 'container_start',
40
+ 20: 'container_end', 21: 'list_collector', 23: 'html', 24: 'container_split',
41
+ 25: 'masked', 26: 'email', 28: 'ip', 29: 'duration', 31: 'requested_for',
42
+ 32: 'rich_text_label', 33: 'attachment', 40: 'table_name',
43
+ };
44
+
45
+ /** Raw value of a field: list rows come back as {value, display_value}. */
46
+ function rawValue(row, field) {
47
+ const v = row?.[field];
48
+ return v && typeof v === 'object' ? v.value : v;
49
+ }
50
+
51
+ export const isInstanceSupplied = v => v?.friendly_type === 'requested_for' || Number(v?.type) === REQUESTED_FOR;
52
+ const object = v => v && typeof v === 'object' && !Array.isArray(v);
53
+
54
+ /** Read the item from the catalog API. Throws when the instance refuses. */
55
+ export async function readCatalogApiItem(sdk, sysID) {
56
+ const response = await sdk.request(`${sdk.baseURL}${CATALOG_API}/${sysID}`, { method: 'GET' });
57
+ if (!object(response?.result) || response.result.sys_id !== sysID) {
58
+ const error = new Error('Catalog API returned no readable item with the requested identity.');
59
+ error.code = 'api_error';
60
+ throw error;
61
+ }
62
+ return response.result;
63
+ }
64
+
65
+ /**
66
+ * Flatten a catalog API `variables` tree into the questions a caller can
67
+ * answer. Containers are walked for their children; every other layout entry
68
+ * is dropped. A name is reported once — the API can repeat a variable inside a
69
+ * container.
70
+ */
71
+ export function shapeVariables(list, out = [], seen = new Set()) {
72
+ if (!Array.isArray(list)) return out;
73
+ for (const entry of list) {
74
+ if (!object(entry)) continue;
75
+ const friendly = typeof entry.friendly_type === 'string' ? entry.friendly_type : '';
76
+ const name = typeof entry.name === 'string' ? entry.name : '';
77
+ if (name && !LAYOUT_TYPES.has(friendly) && !seen.has(name)) {
78
+ seen.add(name);
79
+ out.push({
80
+ name,
81
+ label: entry.label || entry.question_text || name,
82
+ type: entry.type ?? null,
83
+ friendly_type: friendly || null,
84
+ mandatory: entry.mandatory === true || entry.mandatory === 'true',
85
+ instance_supplied: isInstanceSupplied(entry),
86
+ });
87
+ }
88
+ if (Array.isArray(entry.children)) shapeVariables(entry.children, out, seen);
89
+ }
90
+ return out;
91
+ }
92
+
93
+ /** Shape one item_option_new row into the same question shape. */
94
+ function questionFromRow(row) {
95
+ const code = Number(rawValue(row, 'type'));
96
+ const name = getStringField(row, 'name');
97
+ if (!name || LAYOUT_CODES.has(code)) return null;
98
+ return {
99
+ name,
100
+ label: getStringField(row, 'question_text') || name,
101
+ type: Number.isFinite(code) ? code : null,
102
+ friendly_type: TYPE_NAMES[code] ?? null,
103
+ mandatory: String(rawValue(row, 'mandatory')) === 'true',
104
+ instance_supplied: code === REQUESTED_FOR,
105
+ };
106
+ }
107
+
108
+ /** Required / instance-supplied names for a question list. */
109
+ export function requestDetails(variables) {
110
+ return {
111
+ required: variables.filter(v => v.mandatory && !v.instance_supplied).map(v => v.name),
112
+ instanceSupplied: variables.filter(v => v.instance_supplied).map(v => v.name),
113
+ };
114
+ }
115
+
11
116
  /**
12
117
  * Fetch a catalog item and assemble the full show envelope.
13
118
  *
14
- * @param {object} deps
15
- * @param {object} deps.sdk - SDK handle (list/get).
16
- * @param {string} deps.instanceUrl - Effective instance URL (for the item link).
17
- * @param {string} deps.sysID - sc_cat_item sys_id.
18
- * @returns {Promise<{data: object, standalone: Array, setVars: Array, totalVars: number}>}
19
- * data is the envelope payload (no _formatted — the caller attaches it);
20
- * standalone/setVars/totalVars are the raw groupings needed by
21
- * buildCatalogFormatted.
119
+ * @returns {Promise<{data: object, variables: Array, totalVars: number, source: string}>}
22
120
  */
23
121
  export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
24
122
  // Use list + display_value=all so reference fields (category, flow) resolve
@@ -32,30 +130,27 @@ export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
32
130
  if (!item) throw new Error(`Not found: ${sysID}`);
33
131
 
34
132
  const vp = new URLSearchParams();
35
- vp.set('sysparm_query', `cat_item=${sysID}^active=true`);
133
+ vp.set('sysparm_query', `cat_item=${sysID}^active=true^ORDERBYorder`);
36
134
  vp.set('sysparm_limit', '100');
37
135
  vp.set('sysparm_display_value', 'all');
38
136
  vp.set('sysparm_fields', 'sys_id,name,question_text,type,order,mandatory,variable_set');
39
- const variables = await sdk.list('item_option_new', vp);
40
-
41
- const standalone = [];
42
- const setVars = new Map();
43
- for (const v of variables) {
44
- const vs = getStringField(v, 'variable_set');
45
- const entry = {
46
- name: getStringField(v, 'name'),
47
- question_text: getStringField(v, 'question_text'),
48
- type: getStringField(v, 'type'),
49
- mandatory: getStringField(v, 'mandatory'),
50
- };
51
- if (vs) {
52
- if (!setVars.has(vs)) setVars.set(vs, { name: vs, variables: [] });
53
- setVars.get(vs).variables.push(entry);
54
- } else {
55
- standalone.push(entry);
137
+ const rows = await sdk.list('item_option_new', vp);
138
+
139
+ let apiItem = null;
140
+ let apiError = '';
141
+ if (typeof sdk.request === 'function' && typeof sdk.baseURL === 'string') {
142
+ try {
143
+ apiItem = await readCatalogApiItem(sdk, sysID);
144
+ } catch (error) {
145
+ apiError = error?.message || 'catalog API read failed';
56
146
  }
57
147
  }
58
- const totalVars = standalone.length + Array.from(setVars.values()).reduce((a, s) => a + s.variables.length, 0);
148
+
149
+ const fromApi = Array.isArray(apiItem?.variables);
150
+ const variables = fromApi
151
+ ? shapeVariables(apiItem.variables)
152
+ : rows.map(questionFromRow).filter(Boolean);
153
+ const source = fromApi ? 'catalog_api' : 'item_option_new';
59
154
 
60
155
  // Resolve flow name
61
156
  let flowName = '', flowCmd = '';
@@ -69,6 +164,7 @@ export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
69
164
  }
70
165
  const wfName = getStringField(item, 'workflow') || '';
71
166
  const planName = getStringField(item, 'delivery_plan') || getStringField(item, 'execution_plan') || '';
167
+ const details = requestDetails(variables);
72
168
 
73
169
  const data = {
74
170
  name: getStringField(item, 'name'),
@@ -79,24 +175,22 @@ export async function enrichCatalogItem({ sdk, instanceUrl, sysID }) {
79
175
  flow: flowName || undefined,
80
176
  flow_cmd: flowCmd || undefined,
81
177
  workflow: wfName || undefined,
82
-
83
178
  execution_plan: planName || undefined,
84
- variables: totalVars > 0 ? {
85
- count: totalVars,
86
- standalone: standalone.map(v => ({ label: v.question_text || v.name, type: v.type, mandatory: String(v.mandatory) === 'true' })),
87
- sets: Array.from(setVars.values()).map(s => ({ name: s.name, variables: s.variables.map(v => ({ label: v.question_text || v.name, type: v.type, mandatory: String(v.mandatory) === 'true' })) })),
88
- } : undefined,
179
+ variables,
180
+ variables_source: source,
181
+ variables_reported: fromApi,
182
+ required_variables: details.required,
183
+ instance_supplied_variables: details.instanceSupplied,
184
+ ...(apiError ? { variables_api_error: apiError } : {}),
89
185
  };
90
186
 
91
- return { data, standalone, setVars: Array.from(setVars.values()), totalVars };
187
+ return { data, variables, totalVars: variables.length, source };
92
188
  }
93
189
 
94
190
  /**
95
- * Styled-mode rendering of an enriched catalog item. Kept verbatim from the
96
- * original catalog.js — the output layer is being reworked elsewhere, so this
97
- * stays byte-identical for now.
191
+ * Styled-mode rendering of an enriched catalog item.
98
192
  */
99
- export function buildCatalogFormatted(data, standalone, setVars, totalVars) {
193
+ export function buildCatalogFormatted(data, variables = data.variables || [], source = data.variables_source) {
100
194
  const lines = [];
101
195
  lines.push(`${data.name} (sc_cat_item)`);
102
196
  lines.push('');
@@ -118,19 +212,20 @@ export function buildCatalogFormatted(data, standalone, setVars, totalVars) {
118
212
  lines.push(` ${data.workflow}`);
119
213
  lines.push('');
120
214
  }
121
- if (totalVars > 0) {
122
- lines.push('─ Catalog Variables ─');
123
- for (const v of standalone) {
124
- const label = v.question_text || v.name;
125
- lines.push(` ${label}: ${v.type}${String(v.mandatory) === 'true' ? ' (mandatory)' : ''}`);
126
- }
127
- for (const s of setVars) {
128
- lines.push(` [${s.name}]`);
129
- for (const v of s.variables) {
130
- const label = v.question_text || v.name;
131
- lines.push(` ${label}: ${v.type}${String(v.mandatory) === 'true' ? ' (mandatory)' : ''}`);
132
- }
215
+ if (variables.length) {
216
+ lines.push(`─ Catalog Questions (${source === 'catalog_api' ? 'catalog API' : 'item_option_new'}) ─`);
217
+ for (const v of variables) {
218
+ const type = v.friendly_type || (v.type === null ? '?' : String(v.type));
219
+ const flags = [v.mandatory ? 'required' : '', v.instance_supplied ? 'instance-supplied' : ''].filter(Boolean);
220
+ lines.push(` ${v.name} ${v.label} [${type}]${flags.length ? ` (${flags.join(', ')})` : ''}`);
133
221
  }
222
+ if (data.required_variables?.length) lines.push(` required: ${data.required_variables.join(', ')}`);
223
+ if (data.instance_supplied_variables?.length) lines.push(` instance-supplied: ${data.instance_supplied_variables.join(', ')}`);
224
+ lines.push('');
225
+ }
226
+ if (data.variables_api_error) {
227
+ lines.push('─ Catalog API ─');
228
+ lines.push(` unavailable: ${data.variables_api_error}`);
134
229
  lines.push('');
135
230
  }
136
231
  return lines.join('\n');
@@ -1,8 +1,11 @@
1
1
  import { parseDataArg, confirmDelete, quoteShellArg } from '../helpers.js';
2
2
  import { errAPI, errUsage } from '../errors.js';
3
+ import { CATALOG_API, readCatalogApiItem, shapeVariables } from './catalog/enrich.js';
3
4
 
4
5
  const ID = /^[a-f0-9]{32}$/i;
5
- const API = '/api/sn_sc/servicecatalog/items';
6
+ const API = CATALOG_API;
7
+ const RITM = '/api/now/table/sc_req_item';
8
+ const MAX_REQUESTED_ITEMS = 10;
6
9
  const object = v => v && typeof v === 'object' && !Array.isArray(v);
7
10
 
8
11
  function emit(app, argv, data, summary, breadcrumbs = []) {
@@ -10,17 +13,67 @@ function emit(app, argv, data, summary, breadcrumbs = []) {
10
13
  app.ok(data, { summary, breadcrumbs: breadcrumbs.map(h => ({ ...h, cmd: h.cmd + connection })) });
11
14
  }
12
15
  function requireId(id) { if (!ID.test(id || '')) throw errUsage('Use the full catalog item sys_id; find it with catalogitems search.'); }
13
- async function describe(app, id) {
14
- requireId(id);
15
- const response = await app.sdk.request(`${app.sdk.baseURL}${API}/${id}`, { method: 'GET' });
16
- if (!object(response?.result) || response.result.sys_id !== id) throw errAPI(200, 'Catalog API returned no readable item with the requested identity.');
17
- return response.result;
16
+
17
+ /**
18
+ * Item definition plus flattened question definitions.
19
+ *
20
+ * This is the request side of the catalog, not a second view command: the
21
+ * questions and the order come from the same payload, so `order` can never
22
+ * disagree with what `catalogitems show` printed. Items the catalog API cannot
23
+ * serve (record producers whose server scripts throw, non-catalog records)
24
+ * fail here rather than submitting against guessed definitions.
25
+ */
26
+ async function inspect(app, id) {
27
+ const item = await readCatalogApiItem(app.sdk, id);
28
+ const variables = shapeVariables(item.variables);
29
+ return { item, variables, variablesReported: Array.isArray(item.variables) };
30
+ }
31
+
32
+ function isAnswered(value) {
33
+ if (value === undefined || value === null) return false;
34
+ if (typeof value === 'string') return value.trim() !== '';
35
+ if (Array.isArray(value)) return value.length > 0;
36
+ return true;
37
+ }
38
+
39
+ /**
40
+ * Compare supplied variables against the item's own question definitions.
41
+ * The server remains the authority; this only refuses an obviously incomplete
42
+ * submission before a confirmation prompt or a POST.
43
+ */
44
+ function reviewVariables(variables, supplied) {
45
+ const required = variables.filter(v => v.mandatory && !v.instance_supplied);
46
+ return {
47
+ requiredVariables: required.map(v => v.name),
48
+ missing: required.filter(v => !isAnswered(supplied[v.name])).map(v => v.name),
49
+ unknown: variables.length ? Object.keys(supplied).filter(name => !variables.some(v => v.name === name)) : [],
50
+ };
18
51
  }
52
+
19
53
  function itemHints(id) {
20
- return [{ action: 'describe', cmd: `jsn catalogitems describe ${id}`, description: 'Inspect catalog inputs and pricing' },
54
+ return [{ action: 'show', cmd: `jsn catalogitems show ${id}`, description: 'Read the item, its questions and required answers' },
21
55
  { action: 'preview', cmd: `jsn catalogitems order ${id} --dry-run --variables-file variables.json`, description: 'Preview an order without submitting' }];
22
56
  }
23
57
 
58
+ /**
59
+ * Read the requested item(s) a submitted order produced. Failure here is
60
+ * reported, never retried, and never turns a placed order into an error.
61
+ */
62
+ async function findRequestedItems(app, requestId) {
63
+ const params = new URLSearchParams({ sysparm_query: `request=${requestId}`, sysparm_fields: 'sys_id,number,cat_item', sysparm_limit: String(MAX_REQUESTED_ITEMS) });
64
+ try {
65
+ const response = await app.sdk.request(`${app.sdk.baseURL}${RITM}?${params}`, { method: 'GET' });
66
+ if (!Array.isArray(response?.result)) return { items: [], readable: false, error: 'unsupported response' };
67
+ return {
68
+ items: response.result.filter(r => object(r) && ID.test(r.sys_id || ''))
69
+ .map(r => ({ sys_id: r.sys_id, number: typeof r.number === 'string' ? r.number : null })),
70
+ readable: true,
71
+ };
72
+ } catch (error) {
73
+ return { items: [], readable: false, error: error?.status ? `HTTP ${error.status}` : 'read failed' };
74
+ }
75
+ }
76
+
24
77
  export function catalogOrderCommands(wrap) {
25
78
  return [
26
79
  { command: 'search <text>', describe: 'Find requestable items through the Service Catalog API',
@@ -35,20 +88,14 @@ export function catalogOrderCommands(wrap) {
35
88
  possibly_truncated: response.result.length === argv.limit }, `${response.result.length} catalog item(s)`,
36
89
  response.result.flatMap(i => itemHints(i.sys_id).slice(0, 1)));
37
90
  }) },
38
- { command: 'describe <id>', aliases: ['inputs'], describe: 'Read requestable item details, pricing and variable definitions',
39
- builder: y => y.positional('id', { type: 'string' }),
40
- handler: wrap(async (argv, app) => {
41
- const item = await describe(app, argv.id);
42
- emit(app, argv, item, item.name || item.short_description || argv.id, itemHints(argv.id));
43
- }) },
44
91
  { command: 'order <id>', describe: 'Submit a catalog order with explicit confirmation',
45
92
  builder: y => y.positional('id', { type: 'string' })
46
93
  .option('variables', { type: 'string', describe: 'JSON object of catalog variable names/values' })
47
94
  .option('variables-file', { type: 'string', describe: 'Read the variables object from a JSON file' })
48
95
  .option('quantity', { type: 'number', default: 1, describe: 'Positive integer quantity (max 1000)' })
49
96
  .option('requested-for', { type: 'string', describe: 'User sys_id; instance delegation rules still apply' })
50
- .option('dry-run', { type: 'boolean', default: false, describe: 'Read item details and preview variable names; no order is submitted' })
51
- .epilogue('Use describe to inspect variables first. Server-side rules validate the order; a preview does not prove submission will succeed. Existing create/list/show commands manage definitions. Orders require a write-enabled profile, including dry runs. No application/update-set selection is needed.'),
97
+ .option('dry-run', { type: 'boolean', default: false, describe: 'Read item details and preview variables; no order is submitted' })
98
+ .epilogue('Use describe to inspect variables and their types first. Requested for is supplied by the instance unless you pass --requested-for, so it is reported separately and never blocks an order. A preview only reads; submitting needs a write-enabled profile and an explicit confirmation (or --force). Server-side rules still validate the order, so a preview does not prove submission will succeed. Existing create/list/show commands manage definitions. Orders need no application/update-set selection.'),
52
99
  handler: wrap(async (argv, app) => {
53
100
  requireId(argv.id);
54
101
  if (!Number.isInteger(argv.quantity) || argv.quantity < 1 || argv.quantity > 1000) throw errUsage('--quantity must be an integer from 1 to 1000.');
@@ -59,12 +106,26 @@ export function catalogOrderCommands(wrap) {
59
106
  const variables = argv.variables !== undefined || file !== undefined
60
107
  ? parseDataArg({ data: argv.variables, 'data-file': file }) : {};
61
108
  if (!object(variables)) throw errUsage('Catalog variables must be a JSON object.');
62
- const item = await describe(app, argv.id);
109
+
110
+ const { item, variables: definitions, variablesReported } = await inspect(app, argv.id);
63
111
  if (item.sys_class_name && item.sys_class_name !== 'sc_cat_item') throw errUsage('order supports standard catalog items; record producers and order guides need their own submission workflows.');
64
112
  if (item.active === false || item.active === 'false' || item.can_order === false) throw errUsage('This item is not currently orderable.');
65
- const plan = { item_id: argv.id, name: item.name || item.short_description, quantity: argv.quantity,
66
- requested_for: requestedFor || null, variable_names: Object.keys(variables) };
113
+
114
+ // Only refuse on local evidence: an unreadable variable list is not
115
+ // proof that an item has no mandatory inputs.
116
+ const review = variablesReported ? reviewVariables(definitions, variables) : null;
117
+ if (review?.missing.length) {
118
+ throw errUsage(`Missing required catalog variable(s): ${review.missing.join(', ')}. Inspect them with: jsn catalogitems describe ${argv.id}`);
119
+ }
120
+
121
+ const plan = {
122
+ item_id: argv.id, name: item.name || item.short_description, quantity: argv.quantity,
123
+ requested_for: requestedFor || null, variable_names: Object.keys(variables),
124
+ required_variables: review ? review.requiredVariables : [],
125
+ ...(review?.unknown.length ? { unknown_variable_names: review.unknown } : {}),
126
+ };
67
127
  if (argv.dryRun ?? argv['dry-run']) return emit(app, argv, { ...plan, submitted: false, server_validation: 'not performed' }, 'Catalog order preview; nothing submitted', itemHints(argv.id));
128
+
68
129
  const rerun = ['catalogitems', 'order', argv.id, '--quantity', String(argv.quantity),
69
130
  ...(requestedFor ? ['--requested-for', requestedFor] : []),
70
131
  ...(file ? ['--variables-file', file] : Object.keys(variables).length ? ['--variables-file', '<variables.json>'] : [])];
@@ -83,11 +144,26 @@ export function catalogOrderCommands(wrap) {
83
144
  throw errAPI(error.status || 0, 'Catalog submission did not return a confirmed order. Inspect your requests before retrying; the order may have been placed.');
84
145
  }
85
146
  const result = response?.result;
86
- const requestId = result?.request_id || result?.sys_id, number = result?.request_number || result?.number;
87
- if (!object(result) || result.error || !ID.test(requestId || '') || typeof number !== 'string' || !number.trim()) throw errAPI(200, 'Catalog response did not confirm an order identity. Inspect your requests before retrying; do not resubmit automatically.');
88
- emit(app, argv, { item_id: argv.id, quantity: argv.quantity, request_id: requestId, request_number: number, submitted: true },
89
- `Ordered: ${number}`, [{ action: 'request', cmd: `jsn records get --table sc_request --sys-id ${requestId}`, description: 'Read the request header' },
90
- { action: 'items', cmd: `jsn requests list --query ${quoteShellArg(`request=${requestId}`)}`, description: 'Track the requested items' }]);
147
+ if (!object(result) || result.error || result.errMsg) throw errAPI(200, 'Catalog response did not confirm an order identity. Inspect your requests before retrying; do not resubmit automatically.');
148
+ // order_now answers with the request header (REQ); the requested item
149
+ // (RITM) identity is only knowable by reading the request's items.
150
+ const requestId = result.request_id || (result.table === 'sc_request' ? result.sys_id : undefined);
151
+ const requestNumber = result.request_number || (result.table === 'sc_request' ? result.number : undefined);
152
+ if (!ID.test(requestId || '') || typeof requestNumber !== 'string' || !requestNumber.trim()) throw errAPI(200, 'Catalog response did not confirm an order identity. Inspect your requests before retrying; do not resubmit automatically.');
153
+
154
+ const requested = await findRequestedItems(app, requestId);
155
+ emit(app, argv, {
156
+ item_id: argv.id, quantity: argv.quantity, request_id: requestId, request_number: requestNumber,
157
+ requested_items: requested.items,
158
+ requested_items_readable: requested.readable,
159
+ ...(requested.error ? { requested_items_error: requested.error } : {}),
160
+ ...(review?.unknown.length ? { unknown_variable_names: review.unknown } : {}),
161
+ submitted: true,
162
+ }, `Ordered: ${requestNumber}`, [
163
+ { action: 'request', cmd: `jsn records get --table sc_request --sys-id ${requestId}`, description: 'Read the request header' },
164
+ ...requested.items.filter(i => i.number).map(i => ({ action: 'item', cmd: `jsn requests show ${i.number}`, description: 'Read the requested item' })),
165
+ { action: 'items', cmd: `jsn requests list --query ${quoteShellArg(`request=${requestId}`)}`, description: 'Track the request\'s items' },
166
+ ]);
91
167
  }) },
92
168
  ];
93
169
  }
@@ -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, standalone, setVars, totalVars } = await enrichCatalogItem({
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, standalone, setVars, totalVars),
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} variable(s)`,
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
  }
@@ -0,0 +1,79 @@
1
+ // `tables behavior` — extends the existing tables command surface with a
2
+ // read-only configuration inventory. See docs/DECISIONS.md.
3
+
4
+ import { discoverTableBehavior, formatTableBehavior } from '../table-behavior.js';
5
+ import { errUsage } from '../errors.js';
6
+ import { FormatAuto, FormatStyled } from '../output.js';
7
+
8
+ function decodeCursorTokens(tokens = []) {
9
+ const cursors = {};
10
+ for (const token of tokens) {
11
+ let parsed;
12
+ try {
13
+ parsed = JSON.parse(Buffer.from(String(token), 'base64url').toString('utf8'));
14
+ } catch {
15
+ throw errUsage('Invalid cursor token.');
16
+ }
17
+ if (!parsed || typeof parsed.c !== 'string') throw errUsage('Invalid cursor token.');
18
+ cursors[parsed.c] = token;
19
+ }
20
+ return cursors;
21
+ }
22
+
23
+ export function withTableBehavior(command, wrap) {
24
+ const originalBuilder = command.builder;
25
+ command.builder = (yargs) => originalBuilder(yargs).command({
26
+ command: 'behavior <table>',
27
+ aliases: ['behaviour'],
28
+ describe: 'Read-only inventory of tables behavior: rules, scripts, actions, policies, dictionary, notifications, ACLs, styles, views and flow triggers (inherited included)',
29
+ builder: (y) => y
30
+ .positional('table', { type: 'string', describe: 'Table name (e.g. incident)' })
31
+ .option('category', {
32
+ alias: ['categories'], type: 'string', array: true,
33
+ describe: 'Limit categories (comma-separated or repeatable): business_rules, client_scripts, ui_actions, ui_policies, data_policies, dictionary_entries (dictionary), dictionary_overrides, notifications, access_controls (acls), styles, view_rules, flows',
34
+ })
35
+ .option('direct-only', { type: 'boolean', default: false, describe: 'Only configuration associated with this exact table; no ancestors or global actions' })
36
+ .option('include-inactive', { type: 'boolean', default: false, describe: 'Include inactive configuration (active-only by default)' })
37
+ .option('name', { type: 'string', describe: 'Filter artifact names with a LIKE match (no encoded-query characters)' })
38
+ .option('limit', { alias: 'l', type: 'number', default: 200, describe: 'Maximum items per category (1-500)' })
39
+ .option('max-bytes', { type: 'number', default: 524288, describe: 'Response size budget in bytes (4096-1048576); oversized pages are omitted whole' })
40
+ .option('cursor', { type: 'string', array: true, describe: 'Continuation token from a category next_cursor; repeatable' })
41
+ .epilogue([
42
+ 'Read-only: this inventories configuration with GET requests and never executes scripts, flows, notifications or evaluates conditions.',
43
+ 'Client requirements (client scripts, UI actions, UI policies, styles) are reported separately from server enforcement (business rules, data policies, ACLs, notifications, flow record triggers).',
44
+ 'Empty categories describe accessible configuration only; unavailable/unsupported categories are reported separately.',
45
+ 'Flow template and other non-record trigger types are explicitly unsupported; no text joins are guessed.',
46
+ 'Known artifacts stay directly retrievable: jsn records get --table <source_table> --sys-id <reference.sys_id> --json',
47
+ ].join('\n')),
48
+ handler: wrap(async (argv, app) => {
49
+ app.requireInstance();
50
+ const data = await discoverTableBehavior(app.sdk, argv.table, {
51
+ categories: argv.category,
52
+ directOnly: argv.directOnly === true,
53
+ includeInactive: argv.includeInactive === true,
54
+ name: argv.name,
55
+ limit: argv.limit,
56
+ maxBytes: argv.maxBytes,
57
+ cursors: decodeCursorTokens(argv.cursor),
58
+ });
59
+ const breadcrumbs = [
60
+ ...data.categories
61
+ .flatMap(section => section.items.slice(0, 1).map(item => ({
62
+ action: 'show',
63
+ cmd: `jsn records get --table ${item.reference.source_table} --sys-id ${item.reference.sys_id} --json`,
64
+ description: `Retrieve ${item.reference.kind} record for ${item.name}`,
65
+ }))),
66
+ { action: 'list', cmd: `jsn tables show ${data.table}`, description: `Show table ${data.table}` },
67
+ ];
68
+ const human = [FormatAuto, FormatStyled].includes(app.output.getFormat());
69
+ app.ok(human ? { ...data, _formatted: formatTableBehavior(data) } : data, {
70
+ summary: `Table behavior: ${data.table} \u2014 ${data.totals.returned} item(s), ${data.totals.direct} direct, ${data.totals.inherited} inherited`,
71
+ breadcrumbs,
72
+ });
73
+ }),
74
+ });
75
+ if (Array.isArray(command.discovery?.benefits)) {
76
+ command.discovery.benefits.push('Table behavior inventory: jsn tables behavior <table> [--direct-only] [--include-inactive]');
77
+ }
78
+ return command;
79
+ }
package/src/output.js CHANGED
@@ -385,7 +385,7 @@ export class OutputWriter {
385
385
  let val = getDisplayValue(row[col]);
386
386
  const width = colWidths[col] || 20;
387
387
 
388
- if (j === 0 && instanceURL && table && row.sys_id) {
388
+ if (j === 0 && instanceURL && table && row.sys_id && isTTY(this.writer)) {
389
389
  const url = getTableURL(instanceURL, table, row.sys_id);
390
390
  val = hyperlink(val, url);
391
391
  }
@@ -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 },