@jacebenson/jsn 5.4.0-dev.151.1 → 5.4.0-dev.153.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.4.0-dev.151.1",
3
+ "version": "5.4.0-dev.153.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": {
@@ -1,5 +1,6 @@
1
1
  import { parseArgs } from 'node:util';
2
2
  import process from 'node:process';
3
+ import { renderSubcommandHelp } from './help.js';
3
4
 
4
5
  const camel = (name) => name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
5
6
  const names = (x) => typeof x === 'string' ? [x] : (x || []);
@@ -331,18 +332,66 @@ export class LocalCLI {
331
332
  });
332
333
  }
333
334
 
335
+ /**
336
+ * Usage line for a command page, derived from the node's own declared
337
+ * command. Subcommand pages printed only the path (`Usage: jsn flows`,
338
+ * `Usage: jsn flows show`), which hid the positionals the command accepts and
339
+ * never mentioned options at all.
340
+ */
341
+ _usageLine(node, path, hasChildren) {
342
+ if (node.usageText) return node.usageText;
343
+ const declared = (node.definition.command || '').trim().split(/\s+/).slice(1)
344
+ .filter((token) => !(hasChildren && /^\[sub-?commands?\]$/i.test(token)));
345
+ const parts = [this.script, ...path, ...(hasChildren ? ['<command>'] : []), ...declared, '[options]'];
346
+ return `Usage: ${parts.join(' ')}`;
347
+ }
348
+
349
+ _commandRows(node) {
350
+ return node.children
351
+ .filter((child) => child.name !== this.completionCommand && !child.definition.hidden)
352
+ .map((child) => ({
353
+ label: child.definition.command || child.name,
354
+ description: child.definition.describe || '',
355
+ note: child.aliases.length ? `[aliases: ${child.aliases.join(', ')}]` : '',
356
+ }));
357
+ }
358
+
359
+ /**
360
+ * Option rows carry the alias, type and default a user needs to type the
361
+ * command. The old line dropped all three and printed long aliases with a
362
+ * single dash (`-fields`), which is not a flag.
363
+ */
364
+ _optionRows(node) {
365
+ const rows = [];
366
+ for (const spec of node.options.values()) {
367
+ const aliases = names(spec.alias).map((alias) => (alias.length === 1 ? `-${alias}` : `--${alias}`));
368
+ const type = isArrayOption(spec) ? 'array' : spec.type;
369
+ const meta = [];
370
+ if (names(spec.choices).length) meta.push(`${type || 'string'}: ${names(spec.choices).join(', ')}`);
371
+ else if (type && type !== 'boolean') meta.push(type);
372
+ if (spec.default !== undefined && spec.default !== false && spec.default !== '') meta.push(`default: ${spec.default}`);
373
+ rows.push({
374
+ label: [`--${spec.name}`, ...aliases].join(', '),
375
+ description: spec.describe || spec.description || '',
376
+ note: meta.map((part) => `[${part}]`).join(' '),
377
+ });
378
+ }
379
+ return rows;
380
+ }
381
+
334
382
  _help(node, path = []) {
335
383
  if (!path.length && this.rootHelpRenderer) {
336
384
  process.stdout.write(this.rootHelpRenderer() + "\n");
337
385
  return;
338
386
  }
339
- const lines = [node.usageText || `Usage: ${this.script} ${path.join(' ') || '<command>'}`];
340
- if (node.definition.describe) lines.push(`\n${node.definition.describe}`);
341
- const children = node.children.filter(n => n.name !== this.completionCommand && !n.definition.hidden);
342
- if (children.length) lines.push('\nCommands:\n' + children.map((n) => ` ${n.definition.command} ${n.definition.describe || ''}`).join('\n'));
343
- if (node.options.size) lines.push('\nOptions:\n' + [...node.options].map(([name, s]) => ` --${name}${s.alias ? `, -${names(s.alias).join(', -')}` : ''} ${s.describe || s.description || ''}`).join('\n'));
344
- if (node.epilogueText) lines.push(`\n${node.epilogueText}`);
345
- process.stdout.write(lines.join('\n') + '\n');
387
+ const commands = this._commandRows(node);
388
+ process.stdout.write(renderSubcommandHelp({
389
+ usage: this._usageLine(node, path, commands.length > 0),
390
+ description: node.definition.describe,
391
+ commands,
392
+ options: this._optionRows(node),
393
+ epilogue: node.epilogueText,
394
+ }));
346
395
  }
347
396
  async parse() {
348
397
  if (this.args.includes('--get-yargs-completions')) {
@@ -5,7 +5,7 @@ import { declareCapabilities } from '../capabilities.js';
5
5
  import { inspectFlow } from '../flow-inspection.js';
6
6
  import { publishFlows, publishFlowLifecycle, publishDoctor, flowStatus } from '../flow-publish.js';
7
7
  import { resolveRecord, unwrapSysId } from '../resolve-record.js';
8
- import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet } from '../flow-create.js';
8
+ import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet, readCatalogItemVariables } from '../flow-create.js';
9
9
  import { alignUpdateSetCapture } from '../context.js';
10
10
  import { EXCLUDED_TRIGGER_TYPES, SUPPORTED_TRIGGER_TYPES, readTriggerCatalog, readTriggerInputDefinitions } from '../flow-triggers.js';
11
11
  import { testFlow } from '../flow-test.js';
@@ -16,6 +16,8 @@ import { cancelled, pickDesignerRecord, guidedFlowCreate, guidedFlowEdit, guided
16
16
  const pickFlow = (argv, app, query = '') => pickDesignerRecord(argv, app, argv.action ? 'sys_hub_action_type_definition' : 'sys_hub_flow', argv.action ? 'action' : 'flow', query);
17
17
 
18
18
  const FLOW_COMMANDS = [
19
+ { name: 'schemas', description: 'Read live trigger catalog and input schemas' },
20
+ { name: 'catalog-variables [identifier]', description: 'List a catalog item\'s variables for a service_catalog trigger' },
19
21
  { name: 'list', description: 'List flows' },
20
22
  { name: 'executions', description: 'Show flow executions from sys_flow_context' },
21
23
  { name: 'show [identifier]', description: 'Show a flow: structure, inputs, steps and conditions' },
@@ -68,7 +70,7 @@ export function flowsCmd(wrap) {
68
70
  return yargs
69
71
  .command({
70
72
  command: 'schemas',
71
- describe: 'Read live trigger catalog and declared inputs; supported marks verified CLI creation families',
73
+ describe: 'Read live trigger catalog and input schemas',
72
74
  handler: wrap(async (_argv, app) => {
73
75
  app.requireInstance();
74
76
  const catalog = await readTriggerCatalog(app.sdk);
@@ -85,6 +87,30 @@ export function flowsCmd(wrap) {
85
87
  app.ok(data, { summary: 'Live Flow trigger schemas' });
86
88
  }),
87
89
  })
90
+ .command({
91
+ command: 'catalog-variables [identifier]',
92
+ describe: 'List a catalog item\'s variables for a service_catalog trigger input',
93
+ builder: (y) => y
94
+ .option('catalog-item', { type: 'string', describe: 'sc_cat_item sys_id used as the trigger\'s template_catalog_item' })
95
+ .option('scope', { type: 'string', describe: 'Transaction scope sys_id (default: the flow\'s own scope)' }),
96
+ handler: wrap(async (argv, app) => {
97
+ app.requireInstance();
98
+ const catalogItem = argv.catalogItem ?? argv['catalog-item'];
99
+ if (!String(catalogItem || '').trim()) throw errUsage('--catalog-item <sc_cat_item sys_id> is required; it is the trigger\'s template_catalog_item');
100
+ const identifier = await pickFlow(argv, app);
101
+ if (identifier === undefined) return;
102
+ const record = await resolveRecord(app.sdk, { table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow' });
103
+ const flowId = unwrapSysId(record);
104
+ // resolveRecord reads display values; sending `Global` as a
105
+ // transaction scope is not a scope id. Prefer the raw value.
106
+ const rawScope = record?.sys_scope && typeof record.sys_scope === 'object' ? record.sys_scope.value : record?.sys_scope;
107
+ const scope = argv.scope || rawScope || 'global';
108
+ const result = await readCatalogItemVariables(app.sdk, app.getEffectiveInstance(), flowId, catalogItem, { scope });
109
+ app.ok(result, {
110
+ summary: `${result.count} catalog variable(s) on ${catalogItem}; trigger catalog_variables input: ${result.catalog_variables_input || '(none)'}`,
111
+ });
112
+ }),
113
+ })
88
114
  .command({
89
115
  command: 'list',
90
116
  aliases: ['ls'],
@@ -316,11 +342,13 @@ export function flowsCmd(wrap) {
316
342
  })
317
343
  .command({
318
344
  command: 'create',
319
- describe: 'Create a draft flow from a JSON manifest or guided prompts. Use `jsn flows schemas` for instance-derived trigger and input schemas, and `jsn actions action-type-schema --id <actionTypeId> --scope <scopeId>` for provider action inputs. Manifest structure remains code-owned.',
345
+ describe: 'Create a draft flow from a JSON manifest or guided prompts',
320
346
  builder: (y) => y
321
347
  .option('data', { type: 'string', describe: 'Flow manifest as inline JSON' })
322
348
  .option('data-file', { type: 'string', describe: 'Read the flow manifest from a JSON file' })
323
- .option('scope', { type: 'string', describe: 'Transaction scope sys_id or global for the guided picker' }),
349
+ .option('scope', { type: 'string', describe: 'Transaction scope sys_id or global for the guided picker' })
350
+ .epilogue('Manifest structure is code-owned. Use `jsn flows schemas` for trigger and input schemas, and\n'
351
+ + '`jsn actions action-type-schema --id <actionTypeId> --scope <scopeId>` for provider action inputs.'),
324
352
  handler: wrap(async (argv, app) => {
325
353
  app.requireInstance();
326
354
  const dataFile = argv.dataFile ?? argv['data-file'];
@@ -345,12 +373,21 @@ export function flowsCmd(wrap) {
345
373
  .command({
346
374
  command: 'update [identifier]',
347
375
  aliases: ['edit'],
348
- describe: 'Save partial edits to a Draft, or to a published/active flow whose ProcessFlow definition reports security.can_write=true: record_create_or_update trigger table/condition and existing action inputs. Published flows are edited as their working definition; the published snapshot and runtime pointers must stay unchanged, and the command fails loudly if they do not. Flows without write access are refused before any lock or content write, naming the permission. Use --preview for before/after values without writes. Flow Logic, variables, catalog-trigger edits and stage placement require Flow Designer. Never publishes or executes. Use `jsn flows schemas` and `jsn actions action-type-schema --id <actionTypeId> --scope <scopeId>` for live schemas; omitted values are preserved.',
376
+ describe: 'Update a draft, or a published flow that reports write access',
349
377
  builder: (y) => y
350
378
  .option('data', { type: 'string', describe: 'Update manifest as inline JSON' })
351
379
  .option('data-file', { type: 'string', describe: 'Read the update manifest from a JSON file' })
352
380
  .option('preview', { type: 'boolean', default: false, describe: 'Validate and show exact before/after input values without saving or versioning' })
353
- .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation' }),
381
+ .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation' })
382
+ .epilogue('Editable: record_create_or_update trigger table/condition, existing action inputs, and stage\n'
383
+ + 'placement (add a stage, or move flow steps onto one with componentIndexes). A service_catalog\n'
384
+ + 'trigger is created with its template_catalog_item and catalog_variables inputs. A published flow\n'
385
+ + 'is edited as its working definition; the published snapshot and runtime pointers must stay\n'
386
+ + 'unchanged, and the command fails loudly if they do not. A flow without write access is refused\n'
387
+ + 'before any lock or content write, naming the permission. Flow Logic, flow variables, subflows and\n'
388
+ + 'error handling still need Flow Designer. Never publishes or executes; omitted values are preserved.\n'
389
+ + 'Live schemas: `jsn flows schemas` and `jsn actions action-type-schema --id <actionTypeId>\n'
390
+ + '--scope <scopeId>`.'),
354
391
  handler: wrap(async (argv, app) => {
355
392
  app.requireInstance();
356
393
  const dataFile = argv.dataFile ?? argv['data-file'];
@@ -387,9 +424,13 @@ export function flowsCmd(wrap) {
387
424
  })
388
425
  .command({
389
426
  command: 'unlock [identifier]',
390
- describe: 'Release this user\'s stale Flow Designer safe-edit session on a flow. Recovery for an orphaned lease left by a failed update: the provider only releases the calling user\'s own session, the before/after canUserEdit and currentEditor values are printed, and an unconfirmed release fails instead of reporting success. Does not edit content, publish, or touch another user\'s session.',
427
+ describe: 'Release this user\'s stale safe-edit lease after a failed update',
391
428
  builder: (y) => y
392
- .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation' }),
429
+ .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation' })
430
+ .epilogue('Recovery for an orphaned lease left by a failed update: the provider only releases the calling\n'
431
+ + 'user\'s own session, the before/after canUserEdit and currentEditor values are printed, and an\n'
432
+ + 'unconfirmed release fails instead of reporting success. Does not edit content, publish, or touch\n'
433
+ + 'another user\'s session.'),
393
434
  handler: wrap(async (argv, app) => {
394
435
  app.requireInstance();
395
436
  const identifier = await pickFlow(argv, app);
@@ -412,14 +453,16 @@ export function flowsCmd(wrap) {
412
453
  })
413
454
  .command({
414
455
  command: 'delete [identifier]',
415
- describe: 'Delete a flow (not yet implemented)',
456
+ describe: 'Delete a flow (not implemented: use the Flow Designer UI)',
416
457
  handler: wrap(async (argv, app) => {
417
458
  const identifier = await pickFlow(argv, app);
418
459
  if (identifier === undefined) return;
419
460
  throw errUsage('Flow deletion requires the Flow Designer GraphQL API - not yet implemented.\n'
420
461
  + 'Use the ServiceNow web UI to delete flows.');
421
462
  }),
422
- });
463
+ })
464
+ .epilogue('Run "jsn flows <command> --help" for details. In a terminal you can omit the target and pick\n'
465
+ + 'one; scripts use explicit identifiers and manifests.');
423
466
  },
424
467
  handler: wrap(async (_argv, app) => {
425
468
  const summary = 'Manage Flow Designer flows from the sys_hub_flow table. Flow structure comes from the ProcessFlow API, so V1, V2 and subflow definitions all render in full.';
@@ -159,6 +159,7 @@ export function validateFlowManifest(manifest) {
159
159
  if (manifest.subflows !== undefined || manifest.subFlows !== undefined) throw new Error('Subflows are unsupported in this creation slice');
160
160
  if (manifest.variables !== undefined || manifest.flowVariables !== undefined) throw new Error('Flow-variable lifecycle is unsupported in this creation slice');
161
161
  if (manifest.errorHandling !== undefined) throw new Error('Error handling is unsupported in this creation slice');
162
+ if (manifest.stages !== undefined) validateStages(manifest.stages);
162
163
  const trigger = manifest.trigger;
163
164
  if (!trigger || typeof trigger !== 'object' || Array.isArray(trigger)) throw new Error('Flow manifest requires a trigger object');
164
165
  for (const key of Object.keys(trigger)) if (!['type', 'table', 'condition', 'inputs'].includes(key)) throw new Error(`Flow manifest trigger field "${key}" is unsupported`);
@@ -195,6 +196,161 @@ export function buildFlowProperties(manifest) {
195
196
  };
196
197
  }
197
198
 
199
+ // Stage placement. Shapes come from a captured Flow Designer session that both
200
+ // created stages and moved steps onto them: the V1-style
201
+ // `PUT /processflow/flow/{id}/stages` body and the `stages {insert|update}`
202
+ // snFlowDesigner patch. A stage carries a UUID `stageId`, a display `label`, a
203
+ // machine `value`, an `order`, and `componentIndexes` — the flow-step orders
204
+ // placed on that stage. `componentIndexes` is why a placement update must run
205
+ // after the actions exist.
206
+ const STAGE_DURATION = '1970-01-01 00:00:00';
207
+ // ProcessFlow returns `states` as a list of {label, name}; the REST stage map
208
+ // (PUT /processflow/flow/{id}/stages) returns it keyed by name. Sending the
209
+ // keyed form is not what Flow Designer sends, so use the list on insert.
210
+ const STAGE_STATES = [
211
+ { label: 'Pending - has not started', name: 'pending' },
212
+ { label: 'In progress', name: 'in_progress' },
213
+ { label: 'Skipped', name: 'skipped' },
214
+ { label: 'Completed', name: 'complete' },
215
+ { label: 'Error', name: 'error' },
216
+ ];
217
+ const STAGE_KEYS = ['label', 'value', 'order', 'system', 'componentIndexes', 'stageId', 'duration', 'states'];
218
+
219
+ const asBool = (value) => value === true || value === 'true';
220
+
221
+ /**
222
+ * Stages as a list, whichever shape the definition uses.
223
+ *
224
+ * ProcessFlow readback carries `stages` as an object keyed by stageId; the REST
225
+ * stage map uses the same shape while a definition built in code may hold an
226
+ * array. Treating only the array form as data made a live flow look like it had
227
+ * no stages at all.
228
+ */
229
+ export function stageList(definition) {
230
+ const stages = definition?.stages;
231
+ if (Array.isArray(stages)) return stages;
232
+ if (stages && typeof stages === 'object') return Object.values(stages).filter(stage => stage && typeof stage === 'object');
233
+ return [];
234
+ }
235
+
236
+ function stageValueFromLabel(label) {
237
+ return String(label).trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
238
+ }
239
+
240
+ /**
241
+ * Validate a manifest `stages` array.
242
+ *
243
+ * `stageId` is only meaningful for updates: an entry without one inserts a new
244
+ * stage, an entry with one edits the stage it names.
245
+ */
246
+ export function validateStages(stages, { update = false } = {}) {
247
+ if (!Array.isArray(stages)) throw new Error('Flow stages must be an array');
248
+ for (const [index, stage] of stages.entries()) {
249
+ const where = `Stage ${index + 1}`;
250
+ if (!stage || typeof stage !== 'object' || Array.isArray(stage)) throw new Error(`${where} must be an object`);
251
+ for (const key of Object.keys(stage)) if (!STAGE_KEYS.includes(key)) throw new Error(`${where} field "${key}" is unsupported`);
252
+ if (stage.stageId !== undefined && !update) throw new Error(`${where} stageId is only accepted when updating an existing stage; omit it to insert`);
253
+ if (update && stage.stageId !== undefined && !/^[0-9a-fA-F-]{32,36}$/.test(String(stage.stageId))) throw new Error(`${where} stageId must be the stage UUID`);
254
+ if (stage.label !== undefined && !String(stage.label).trim()) throw new Error(`${where} label must not be empty`);
255
+ if (stage.value !== undefined && !String(stage.value).trim()) throw new Error(`${where} value must not be empty`);
256
+ if (stage.order !== undefined && (!Number.isInteger(stage.order) || stage.order < 0)) throw new Error(`${where} order must be a non-negative integer`);
257
+ if (stage.system !== undefined && typeof stage.system !== 'boolean') throw new Error(`${where} system must be a boolean`);
258
+ if (stage.componentIndexes !== undefined) {
259
+ if (!Array.isArray(stage.componentIndexes) || stage.componentIndexes.some(value => !Number.isInteger(value) || value < 1)) {
260
+ throw new Error(`${where} componentIndexes must be an array of flow-step orders (integers >= 1)`);
261
+ }
262
+ }
263
+ if (stage.duration !== undefined && typeof stage.duration !== 'string') throw new Error(`${where} duration must be a string`);
264
+ if (stage.states !== undefined && (!stage.states || typeof stage.states !== 'object' || Array.isArray(stage.states))) throw new Error(`${where} states must be an object`);
265
+ const inserts = stage.stageId === undefined;
266
+ if (inserts && !String(stage.label ?? '').trim()) throw new Error(`${where} requires a label`);
267
+ if (!inserts) {
268
+ const edited = ['label', 'value', 'order', 'componentIndexes'].filter(key => stage[key] !== undefined);
269
+ if (!edited.length) throw new Error(`${where} must change label, value, order or componentIndexes`);
270
+ }
271
+ }
272
+ return stages;
273
+ }
274
+
275
+ export function buildStageInserts(stages = [], { idFactory = () => randomUUID(), flowId } = {}) {
276
+ return stages
277
+ .map((stage, index) => ({ stage, index }))
278
+ .sort((a, b) => (a.stage.order ?? a.index) - (b.stage.order ?? b.index))
279
+ .map(({ stage, index }) => ({
280
+ stageId: idFactory(),
281
+ label: String(stage.label).trim(),
282
+ value: stage.value ?? stageValueFromLabel(stage.label),
283
+ type: 'standard',
284
+ duration: stage.duration ?? STAGE_DURATION,
285
+ ancestorArrPos: '0',
286
+ ...(flowId ? { flow: flowId } : {}),
287
+ alwaysShow: true,
288
+ order: stage.order ?? index,
289
+ system: stage.system ?? false,
290
+ componentIndexes: stage.componentIndexes ?? [],
291
+ states: stage.states ?? STAGE_STATES,
292
+ }));
293
+ }
294
+
295
+ export function buildStageUpdates(stages = []) {
296
+ return stages.map((stage) => {
297
+ const update = { stageId: stage.stageId };
298
+ if (stage.label !== undefined) update.label = String(stage.label).trim();
299
+ if (stage.value !== undefined) update.value = stage.value;
300
+ if (stage.order !== undefined) update.order = stage.order;
301
+ if (stage.componentIndexes !== undefined) update.componentIndexes = stage.componentIndexes;
302
+ return update;
303
+ });
304
+ }
305
+
306
+ /**
307
+ * `stages` is part of the same snFlowDesigner patch as actions, but placement
308
+ * has to follow the actions: `componentIndexes` name flow-step orders that must
309
+ * already exist. Creation therefore sends stages in a second patch.
310
+ */
311
+ export function buildFlowStageMutation({ flowId, inserts = [], updates = [] }) {
312
+ const parts = [];
313
+ if (inserts.length) parts.push(`insert: [${inserts.map(gqlInputObject).join(', ')}]`);
314
+ if (updates.length) parts.push(`update: [${updates.map(gqlInputObject).join(', ')}]`);
315
+ if (!parts.length) throw new Error('Flow stage patch requires at least one insert or update');
316
+ return `mutation { global { snFlowDesigner { flow(flowPatch: {flowId: ${gqlString(flowId)}, stages: {${parts.join(', ')}}}) { id stages { inserts { sysId } } } } } }`;
317
+ }
318
+
319
+ /**
320
+ * Read the catalog item's variables as a `service_catalog` flow sees them.
321
+ *
322
+ * A service_catalog trigger takes `template_catalog_item` (an sc_cat_item
323
+ * sys_id) plus `catalog_variables`, a comma-joined list of item_option_new
324
+ * sys_ids. This is the lookup Flow Designer runs when you pick the item, so the
325
+ * ids a manifest needs are the `id` values returned here.
326
+ */
327
+ export async function readCatalogItemVariables(sdk, instance, flowId, catalogItemId, { scope = 'global', includeMultiRowVariableSets = true, selectedVariables = '' } = {}) {
328
+ if (!String(catalogItemId || '').trim()) throw new Error('catalog-variables requires a catalog item sys_id');
329
+ const query = new URLSearchParams({ sysparm_transaction_scope: scope });
330
+ const response = await sdk.request(`${instance}${FLOW_ENDPOINT}/${encodeURIComponent(flowId)}/service_get_catalog_variables?${query}`, {
331
+ method: 'POST',
332
+ body: JSON.stringify({ flow_catalog_model: catalogItemId, includeMultiRowVariableSets, selectedVariables }),
333
+ });
334
+ const data = response?.result?.data;
335
+ if (!data || !Array.isArray(data.availableList)) throw new Error('Catalog variable lookup returned no availableList; check the flow and catalog item sys_ids and the transaction scope');
336
+ const variables = data.availableList.map(variable => ({
337
+ id: stringValue(variable.id),
338
+ name: stringValue(variable.name),
339
+ label: stringValue(variable.label),
340
+ type: stringValue(variable.type),
341
+ mandatory: asBool(variable.mandatory),
342
+ readonly: asBool(variable.readonly),
343
+ }));
344
+ return {
345
+ flow_id: flowId,
346
+ catalog_item: catalogItemId,
347
+ count: variables.length,
348
+ variables,
349
+ // Exactly what the trigger input expects, so it can be pasted into a manifest.
350
+ catalog_variables_input: variables.map(variable => variable.id).join(','),
351
+ };
352
+ }
353
+
198
354
  export function buildFlowPatchMutation({ flowId, trigger, actions }) {
199
355
  const triggerInsert = {
200
356
  flowSysId: trigger.flowSysId,
@@ -223,12 +379,17 @@ export function buildFlowPatchMutation({ flowId, trigger, actions }) {
223
379
  return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { inserts { sysId } updates } actions { inserts { sysId uiUniqueIdentifier } } } } } }`;
224
380
  }
225
381
 
226
- export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [] }) {
382
+ export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [], stageInserts = [], stageUpdates = [] }) {
227
383
  const updates = [];
228
384
  if (triggerUpdates.length) updates.push(`triggerInstances: {update: [${triggerUpdates.map(gqlInputObject).join(', ')}]}`);
229
385
  if (actionUpdates.length) updates.push(`actions: {update: [${actionUpdates.map(gqlInputObject).join(', ')}]}`);
386
+ const stageParts = [];
387
+ if (stageInserts.length) stageParts.push(`insert: [${stageInserts.map(gqlInputObject).join(', ')}]`);
388
+ if (stageUpdates.length) stageParts.push(`update: [${stageUpdates.map(gqlInputObject).join(', ')}]`);
389
+ if (stageParts.length) updates.push(`stages: {${stageParts.join(', ')}}`);
390
+ if (!updates.length) throw new Error('Flow update mutation requires at least one change');
230
391
  const patch = `flowPatch: {flowId: ${gqlString(flowId)}, ${updates.join(', ')}}`;
231
- return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { updates } actions { updates } } } } }`;
392
+ return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { updates } actions { updates } stages { inserts { sysId } } } } } }`;
232
393
  }
233
394
 
234
395
  export async function readProcessFlow(sdk, instance, flowId, scope) {
@@ -384,6 +545,31 @@ function actionTypeIdOf(action) {
384
545
  return idValue(action?.actionTypeSysId || action?.action_type_sys_id || action?.actionType?.sys_id || action?.actionType?.sysId);
385
546
  }
386
547
 
548
+ /**
549
+ * Confirm the stages this command asked for are the ones the flow now carries.
550
+ * Matching is by generated stageId: a label-only check could pass while the
551
+ * placement landed on a different stage.
552
+ */
553
+ function assertStagesPlaced(processflow, stageInserts, flowId) {
554
+ if (!stageInserts.length) return;
555
+ const saved = stageList(processflow);
556
+ if (!saved.length) throw new Error(`Flow ${flowId} stage read-back returned no stages after placing ${stageInserts.length}`);
557
+ for (const expected of stageInserts) {
558
+ const matches = saved.filter(stage => stringValue(stage.stageId || stage.stage_id) === expected.stageId);
559
+ if (matches.length !== 1) throw new Error(`Flow ${flowId} stage "${expected.label}" (${expected.stageId}) was not uniquely present in ProcessFlow read-back`);
560
+ const savedStage = matches[0];
561
+ if (expected.label !== undefined && stringValue(savedStage.label) !== expected.label) throw new Error(`Flow ${flowId} stage ${expected.stageId} label did not match the requested "${expected.label}"`);
562
+ if (expected.order !== undefined && String(savedStage.order) !== String(expected.order)) throw new Error(`Flow ${flowId} stage ${expected.stageId} order did not match the requested ${expected.order}`);
563
+ if (expected.componentIndexes !== undefined) {
564
+ const savedIndexes = (Array.isArray(savedStage.componentIndexes) ? savedStage.componentIndexes : []).map(String).sort();
565
+ const expectedIndexes = expected.componentIndexes.map(String).sort();
566
+ if (JSON.stringify(savedIndexes) !== JSON.stringify(expectedIndexes)) {
567
+ throw new Error(`Flow ${flowId} stage ${expected.stageId} placement did not match the requested componentIndexes`);
568
+ }
569
+ }
570
+ }
571
+ }
572
+
387
573
  function verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted }) {
388
574
  const returnedFlowId = stringValue(processflow.flowId || processflow.flow_id || processflow.sysId || processflow.sys_id);
389
575
  if (returnedFlowId && returnedFlowId !== flowId) throw new Error(`ProcessFlow read-back returned a different flow ID (${returnedFlowId})`);
@@ -549,8 +735,8 @@ async function resolveExistingAction(sdk, actions, requested, index) {
549
735
 
550
736
  export function validateFlowUpdateManifest(manifest) {
551
737
  if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('Flow update manifest must be a JSON object');
552
- const allowed = new Set(['scope', 'trigger', 'actions']);
553
- for (const key of Object.keys(manifest)) if (!allowed.has(key)) throw new Error(`Flow update field "${key}" is unsupported; only trigger and existing action inputs may be updated`);
738
+ const allowed = new Set(['scope', 'trigger', 'actions', 'stages']);
739
+ for (const key of Object.keys(manifest)) if (!allowed.has(key)) throw new Error(`Flow update field "${key}" is unsupported; only trigger, existing action inputs and stages may be updated`);
554
740
  if (manifest.scope !== undefined && !String(manifest.scope).trim()) throw new Error('Flow update scope must not be empty');
555
741
  if (manifest.trigger !== undefined) {
556
742
  if (!manifest.trigger || typeof manifest.trigger !== 'object' || Array.isArray(manifest.trigger)) throw new Error('Flow update trigger must be an object');
@@ -571,7 +757,8 @@ export function validateFlowUpdateManifest(manifest) {
571
757
  if (Object.keys(action.inputs).length === 0) throw new Error(`Update action ${index + 1} inputs must contain at least one changed value`);
572
758
  }
573
759
  }
574
- if (manifest.trigger === undefined && manifest.actions === undefined) throw new Error('Flow update manifest must specify trigger and/or actions');
760
+ if (manifest.trigger === undefined && manifest.actions === undefined && manifest.stages === undefined) throw new Error('Flow update manifest must specify trigger, actions and/or stages');
761
+ if (manifest.stages !== undefined) validateStages(manifest.stages, { update: true });
575
762
  return manifest;
576
763
  }
577
764
 
@@ -949,8 +1136,20 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
949
1136
  const inserted = insertedActions(patchResponse);
950
1137
  if (inserted.length !== actionInstances.length) throw new Error(`Flow action patch returned ${inserted.length} inserted action identities; expected ${actionInstances.length}`);
951
1138
 
1139
+ // Stages carry componentIndexes that name flow-step orders, so placement
1140
+ // runs after the actions exist — the same order Flow Designer uses.
1141
+ const stageInserts = buildStageInserts(manifest.stages || [], { idFactory, flowId });
1142
+ if (stageInserts.length) {
1143
+ const stageResponse = await mutationContext('stage_placement', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1144
+ method: 'POST',
1145
+ body: JSON.stringify({ query: buildFlowStageMutation({ flowId, inserts: stageInserts }), variables: {} }),
1146
+ }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1147
+ assertGraphQLSuccess(stageResponse, 'Flow stage placement');
1148
+ }
1149
+
952
1150
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
953
- verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted });
1151
+ verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted, stageInserts });
1152
+ assertStagesPlaced(processflow, stageInserts, flowId);
954
1153
  const { version } = await mutationContext('autosave_version', readUpdateSet, snapshots, () => createVerifiedFlowVersion(sdk, {
955
1154
  instance, flowId, scope, type: 'Autosave', annotation: 'JSN flow create',
956
1155
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
@@ -1013,6 +1212,8 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1013
1212
  const snapshots = [];
1014
1213
  const triggerUpdates = [];
1015
1214
  const actionUpdates = [];
1215
+ const stageInserts = buildStageInserts((manifest.stages || []).filter(stage => stage.stageId === undefined), { idFactory: options.idFactory || (() => randomUUID()), flowId });
1216
+ const stageUpdates = buildStageUpdates((manifest.stages || []).filter(stage => stage.stageId !== undefined));
1016
1217
  const changedActionInputs = new Map();
1017
1218
  const actionTargets = new Map();
1018
1219
  const changes = [];
@@ -1040,7 +1241,20 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1040
1241
  changedActionInputs.set(uiId, new Set(Object.keys(requested.inputs)));
1041
1242
  for (const [input, after] of Object.entries(requested.inputs)) changes.push({ component: 'action', order: requested.order, type: requested.type, input, before: inputRawValue(inputList(existing).find(field => field.name === input)), after });
1042
1243
  }
1043
- if (triggerUpdates.length === 0 && actionUpdates.length === 0) throw new Error(`Flow ${flowId} update has no supported changes`);
1244
+ const savedStages = stageList(beforeDefinition);
1245
+ const savedStageById = new Map(savedStages.map(stage => [stringValue(stage.stageId || stage.stage_id), stage]));
1246
+ for (const update of stageUpdates) {
1247
+ const before = savedStageById.get(update.stageId);
1248
+ if (!before) throw new Error(`Flow ${flowId} has no stage ${update.stageId}; omit stageId to insert a new stage`);
1249
+ for (const [field, after] of Object.entries(update)) {
1250
+ if (field === 'stageId') continue;
1251
+ changes.push({ component: 'stage', stage: stringValue(before.label), input: field, before: before[field], after });
1252
+ }
1253
+ }
1254
+ for (const insert of stageInserts) {
1255
+ changes.push({ component: 'stage', stage: insert.label, input: 'insert', before: null, after: { order: insert.order, componentIndexes: insert.componentIndexes } });
1256
+ }
1257
+ if (triggerUpdates.length === 0 && actionUpdates.length === 0 && stageInserts.length === 0 && stageUpdates.length === 0) throw new Error(`Flow ${flowId} update has no supported changes`);
1044
1258
  if (options.preview) return {
1045
1259
  preview: true,
1046
1260
  flow: { id: flowId, name: target.flowName, status: lifecycle.status, active: lifecycle.active },
@@ -1069,15 +1283,31 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1069
1283
  try {
1070
1284
  const patchResponse = await mutationContext('trigger_and_actions_update', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1071
1285
  method: 'POST',
1072
- body: JSON.stringify({ query: buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates }), variables: {} }),
1286
+ body: JSON.stringify({ query: buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates, stageInserts, stageUpdates }), variables: {} }),
1073
1287
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1074
1288
  assertGraphQLSuccess(patchResponse, 'Flow trigger/action update');
1075
1289
  completedStage = 'patch_acknowledged';
1076
1290
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
1077
1291
  // Only requested values may differ. Preserve array order and opaque fields.
1078
- for (const field of ['flowVariables', 'flowLogicInstances', 'subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs', 'stages']) {
1292
+ // `stages` is compared separately below: a stage edit may touch specific
1293
+ // fields, while every stage the manifest did not name must stay identical.
1294
+ for (const field of ['flowVariables', 'flowLogicInstances', 'subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs']) {
1079
1295
  if (!isDeepStrictEqual(beforeDefinition[field], processflow[field])) throw new Error(`Flow ${flowId} changed omitted ${field}; preservation failed`);
1080
1296
  }
1297
+ if (stageInserts.length || stageUpdates.length) {
1298
+ const requestedStageIds = new Set([...stageInserts.map(stage => stage.stageId), ...stageUpdates.map(stage => stage.stageId)]);
1299
+ const untouched = definition => stageList(definition)
1300
+ .filter(stage => !requestedStageIds.has(stringValue(stage.stageId || stage.stage_id)));
1301
+ if (!isDeepStrictEqual(untouched(beforeDefinition), untouched(processflow))) throw new Error(`Flow ${flowId} changed omitted stages; preservation failed`);
1302
+ assertStagesPlaced(processflow, [...stageInserts, ...stageUpdates.map(update => ({
1303
+ stageId: update.stageId,
1304
+ label: update.label ?? stringValue(savedStageById.get(update.stageId)?.label),
1305
+ order: update.order ?? savedStageById.get(update.stageId)?.order,
1306
+ componentIndexes: update.componentIndexes,
1307
+ }))].filter(stage => stage.label !== undefined), flowId);
1308
+ } else if (!isDeepStrictEqual(beforeDefinition.stages, processflow.stages)) {
1309
+ throw new Error(`Flow ${flowId} changed omitted stages; preservation failed`);
1310
+ }
1081
1311
  if (!triggerUpdate && !isDeepStrictEqual(beforeDefinition.triggerInstances, processflow.triggerInstances)) throw new Error(`Flow ${flowId} changed omitted triggerInstances`);
1082
1312
  const maskActions = definition => findExistingActions(definition).map(action => {
1083
1313
  const copy = clone(action);
package/src/help.js CHANGED
@@ -258,3 +258,99 @@ export function renderHelp(config, registry = null) {
258
258
  '',
259
259
  ].join('\n');
260
260
  }
261
+
262
+ // Subcommand pages (`jsn flows --help`) used to print one unbroken line per
263
+ // entry. A description written for a command's own page — `flows update` is
264
+ // ~700 characters — became an 801-column line that the terminal cut off, so the
265
+ // list advertised a command nobody could read and options lost their aliases,
266
+ // types and defaults. These helpers wrap the text to the terminal instead.
267
+
268
+ const HELP_WIDTH_FALLBACK = 100;
269
+
270
+ /**
271
+ * Columns available to help text. A piped run has no `columns`, and a very wide
272
+ * terminal should not stretch prose to 200 columns, so cap it.
273
+ */
274
+ export function helpWidth(stream = process.stdout) {
275
+ const columns = Number(stream?.columns);
276
+ if (!Number.isFinite(columns) || columns <= 0) return HELP_WIDTH_FALLBACK;
277
+ return Math.min(columns, HELP_WIDTH_FALLBACK);
278
+ }
279
+
280
+ /**
281
+ * Wrap `text` into lines no wider than `width`, indenting `firstIndent` spaces
282
+ * on the first line and `indent` on the rest. A word longer than the available
283
+ * width stays whole: a split alias or sys_id reads as a different token.
284
+ */
285
+ export function wrapText(text, { width, firstIndent = 0, indent = firstIndent } = {}) {
286
+ const words = String(text ?? '').split(/\s+/).filter(Boolean);
287
+ if (!words.length) return [];
288
+ const limit = Number.isFinite(width) && width > 0 ? width : HELP_WIDTH_FALLBACK;
289
+ const lines = [];
290
+ let line = '';
291
+ let prefix = ' '.repeat(firstIndent);
292
+ for (const word of words) {
293
+ const candidate = line ? `${line} ${word}` : word;
294
+ if (line && prefix.length + candidate.length > limit) {
295
+ lines.push(prefix + line);
296
+ line = word;
297
+ prefix = ' '.repeat(indent);
298
+ } else {
299
+ line = candidate;
300
+ }
301
+ }
302
+ lines.push(prefix + line);
303
+ return lines;
304
+ }
305
+
306
+ /**
307
+ * Render help rows as one padded label column plus a wrapped description.
308
+ *
309
+ * @param {Array<{label: string, description?: string, note?: string}>} rows
310
+ * `note` is appended verbatim (already bracketed) — aliases, option type and
311
+ * default — so the description itself stays plain prose.
312
+ * @param {{width?: number, indent?: number}} [opts]
313
+ */
314
+ export function renderRows(rows, { width = helpWidth(), indent = 2 } = {}) {
315
+ if (!rows.length) return '';
316
+ const labelWidth = Math.max(...rows.map(row => row.label.length));
317
+ const descriptionIndent = indent + labelWidth + 2;
318
+ const available = Math.max(20, width - descriptionIndent);
319
+ const lines = [];
320
+ for (const row of rows) {
321
+ const head = `${' '.repeat(indent)}${row.label.padEnd(labelWidth)}`.padEnd(descriptionIndent);
322
+ const wrapped = wrapText(row.description, { width: available });
323
+ // The note (aliases, type, default) is one token: splitting `[aliases: runs,
324
+ // contexts]` across lines leaves a bracket fragment that reads as prose.
325
+ if (row.note) {
326
+ const last = wrapped.at(-1);
327
+ if (last !== undefined && last.length + 1 + row.note.length <= available) wrapped[wrapped.length - 1] = `${last} ${row.note}`;
328
+ else wrapped.push(row.note);
329
+ }
330
+ if (!wrapped.length) {
331
+ lines.push(head.trimEnd());
332
+ continue;
333
+ }
334
+ lines.push(`${head}${wrapped[0]}`);
335
+ for (const line of wrapped.slice(1)) lines.push(`${' '.repeat(descriptionIndent)}${line}`);
336
+ }
337
+ return lines.join('\n');
338
+ }
339
+
340
+ /**
341
+ * Render one command page: usage, description, subcommands, options, epilogue.
342
+ * Sections are separated by a blank line so the list is skimmable in a
343
+ * terminal; nothing is emitted for an empty section. The epilogue is authored
344
+ * text and prints verbatim: it is where command examples live, and breaking
345
+ * `jsn records watch --table incident` at a flag boundary turns one
346
+ * copy-pasteable command into two wrong ones.
347
+ */
348
+ export function renderSubcommandHelp({ usage, description, commands = [], options = [], epilogue, width = helpWidth() }) {
349
+ const blocks = [usage];
350
+ if (description) blocks.push(description);
351
+ if (commands.length) blocks.push(`Commands:\n${renderRows(commands, { width })}`);
352
+ if (options.length) blocks.push(`Options:\n${renderRows(options, { width })}`);
353
+ if (epilogue) blocks.push(epilogue);
354
+ return `${blocks.join('\n\n')}\n`;
355
+ }
356
+