@jacebenson/jsn 5.5.1-dev.164.1 → 5.5.1-dev.165.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 (2) hide show
  1. package/package.json +1 -1
  2. package/src/flow-create.js +433 -40
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.1-dev.164.1",
3
+ "version": "5.5.1-dev.165.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": {
@@ -28,7 +28,7 @@ const FLOW_RECORD_FIELDS = 'sys_id,name,sys_scope,scope,active,status,type,sys_u
28
28
 
29
29
  // Everything this partial-update contract still cannot do, whatever the
30
30
  // lifecycle state. Published edits reuse the same component rules.
31
- const DEFERRED_LIFECYCLE = ['publish/activation', 'Flow Logic', 'subflows', 'flow variables', 'error handling'];
31
+ const DEFERRED_LIFECYCLE = ['publish/activation', 'Flow Logic', 'subflows', 'flow variables'];
32
32
 
33
33
  function supportedLifecycle(published) {
34
34
  return published
@@ -158,7 +158,7 @@ export function validateFlowManifest(manifest) {
158
158
  if (manifest.logic !== undefined) throw new Error('Flow Logic is unsupported in this creation slice');
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
- if (manifest.errorHandling !== undefined) throw new Error('Error handling is unsupported in this creation slice');
161
+ if (manifest.errorHandling !== undefined) validateErrorHandling(manifest.errorHandling);
162
162
  if (manifest.stages !== undefined) validateStages(manifest.stages);
163
163
  if (manifest.stageTemplate !== undefined && !String(manifest.stageTemplate).trim()) throw new Error('Flow manifest stageTemplate must not be empty');
164
164
  if (manifest.stageSet !== undefined && !String(manifest.stageSet).trim()) throw new Error('Flow manifest stageSet must not be empty');
@@ -320,6 +320,20 @@ export async function resolveStageTemplate(sdk, templateIdentifier) {
320
320
  return finalStages;
321
321
  }
322
322
 
323
+ export function validateErrorHandling(eh) {
324
+ if (eh === null || typeof eh !== 'object' || Array.isArray(eh)) throw new Error('Flow errorHandling must be an object');
325
+ for (const key of Object.keys(eh)) if (key !== 'actions') throw new Error(`Unsupported errorHandling field ${key}`);
326
+ if (eh.actions !== undefined) {
327
+ if (!Array.isArray(eh.actions)) throw new Error('Flow errorHandling.actions must be an array');
328
+ for (const [index, action] of eh.actions.entries()) {
329
+ if (!action || typeof action !== 'object' || Array.isArray(action)) throw new Error(`Error action ${index + 1} must be an object`);
330
+ if (typeof action.type !== 'string' || !action.type.trim()) throw new Error(`Error action ${index + 1} requires type`);
331
+ for (const key of Object.keys(action)) if (!['type', 'inputs'].includes(key)) throw new Error(`Unsupported error action field ${key}; identities are allocated by the provider editor`);
332
+ if (action.inputs !== undefined && (!action.inputs || typeof action.inputs !== 'object' || Array.isArray(action.inputs))) throw new Error(`Error action ${index + 1} inputs must be an object`);
333
+ }
334
+ }
335
+ }
336
+
323
337
  export function validateStages(stages, { update = false } = {}) {
324
338
  if (!Array.isArray(stages)) throw new Error('Flow stages must be an array');
325
339
  for (const [index, stage] of stages.entries()) {
@@ -428,7 +442,7 @@ export async function readCatalogItemVariables(sdk, instance, flowId, catalogIte
428
442
  };
429
443
  }
430
444
 
431
- export function buildFlowPatchMutation({ flowId, trigger, actions }) {
445
+ export function buildFlowPatchMutation({ flowId, trigger, actions, flowLogicInserts = [], labelCacheInserts = [] }) {
432
446
  const triggerInsert = {
433
447
  flowSysId: trigger.flowSysId,
434
448
  name: trigger.name,
@@ -450,14 +464,35 @@ export function buildFlowPatchMutation({ flowId, trigger, actions }) {
450
464
  metadata: action.metadata,
451
465
  inputs: action.inputs,
452
466
  }));
453
- const patch = `flowPatch: {flowId: ${gqlString(flowId)}, triggerInstances: {insert: [${gqlInputObject(triggerInsert)}]}, actions: {insert: [${actionInsert.map(gqlInputObject).join(', ')}]}}`;
467
+ const extra = `${flowLogicInserts.length ? `, flowLogics: {insert: [${flowLogicInserts.map(gqlInputObject).join(', ')}]}` : ''}${labelCacheInserts.length ? `, labelCache: {insert: [${labelCacheInserts.map(gqlInputObject).join(', ')}]}` : ''}`;
468
+ const patch = `flowPatch: {flowId: ${gqlString(flowId)}, triggerInstances: {insert: [${gqlInputObject(triggerInsert)}]}, actions: {insert: [${actionInsert.map(gqlInputObject).join(', ')}]}${extra}}`;
454
469
  // `triggerInstances.updates` is a leaf [String] on this schema; only `inserts`
455
470
  // carries identities, and only for triggers does `inserts` lack a uiUniqueIdentifier.
456
- return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { inserts { sysId } updates } actions { inserts { sysId uiUniqueIdentifier } } } } } }`;
471
+ return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { inserts { sysId } updates } actions { inserts { sysId uiUniqueIdentifier } } ${flowLogicInserts.length ? 'flowLogics { inserts { sysId uiUniqueIdentifier } }' : ''} } } } }`;
457
472
  }
458
473
 
459
474
 
460
475
  const FLOW_LOGIC_DEFINITIONS = {
476
+ 'top level try': {
477
+ id: 'e9060aa2c3013010ace8b740ad40dd51',
478
+ name: 'Top Level Try',
479
+ type: 'TOP_LEVEL_TRY',
480
+ description: 'Begin a top level try block',
481
+ compilationClass: 'com.glide.flow.compiler.logic_block.TryCompiler',
482
+ order: 18,
483
+ connectedTo: '',
484
+ attributes: 'allow_siblings=true,draw_curve=true,line_type=q_curve,visible_in_picker=false,visible_in_ui=false,',
485
+ },
486
+ 'top level catch': {
487
+ id: '35d60003e6022010a5e40cdd1254dd23',
488
+ name: 'Top Level Catch',
489
+ type: 'TOP_LEVEL_CATCH',
490
+ description: 'Catch and handle an error',
491
+ compilationClass: 'com.glide.flow.compiler.logic_block.CatchCompiler',
492
+ order: 17,
493
+ connectedTo: '07223332de022010ec58424b73829721,e9060aa2c3013010ace8b740ad40dd51',
494
+ attributes: 'allow_siblings=true,draw_curve=true,line_type=q_curve,visible_in_picker=false,visible_in_ui=false,',
495
+ },
461
496
  'if': {
462
497
  id: 'af4e1945c3e232002841b63b12d3ae3e',
463
498
  name: 'If',
@@ -765,7 +800,7 @@ function verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigg
765
800
  if (savedInputs.length !== expected.inputs.length) throw new Error(`Created Action ${expected.uiUniqueIdentifier} input count did not match the installed schema`);
766
801
  for (const expectedInput of expected.inputs) {
767
802
  const actualInput = savedInputs.find(input => input.name === expectedInput.name);
768
- if (!actualInput || inputRawValue(actualInput) !== inputRawValue(expectedInput)) throw new Error(`Created Action ${expected.uiUniqueIdentifier} input ${expectedInput.name} did not match the requested value`);
803
+ if (!actualInput || !isDeepStrictEqual(inputRawValue(actualInput), inputRawValue(expectedInput))) throw new Error(`Created Action ${expected.uiUniqueIdentifier} input ${expectedInput.name} did not match the requested value`);
769
804
  }
770
805
  }
771
806
  }
@@ -890,7 +925,7 @@ async function resolveExistingAction(sdk, actions, requested, index) {
890
925
 
891
926
  export function validateFlowUpdateManifest(manifest) {
892
927
  if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('Flow update manifest must be a JSON object');
893
- const allowed = new Set(['scope', 'trigger', 'actions', 'stages', 'stageTemplate', 'stageSet', 'flowVariables', 'variables', 'flowLogics', 'logic', 'deleteSteps', 'delete', 'deleteOrders']);
928
+ const allowed = new Set(['scope', 'trigger', 'actions', 'stages', 'stageTemplate', 'stageSet', 'flowVariables', 'variables', 'flowLogics', 'logic', 'deleteSteps', 'delete', 'deleteOrders', 'errorHandling', 'errorHandler']);
894
929
  for (const key of Object.keys(manifest)) if (!allowed.has(key)) throw new Error(`Flow update field "${key}" is unsupported; editable: trigger, action inputs, action inserts, step deletes, flow variables, flow logic, stage placement`);
895
930
  if (manifest.scope !== undefined && !String(manifest.scope).trim()) throw new Error('Flow update scope must not be empty');
896
931
  if (manifest.trigger !== undefined) {
@@ -912,8 +947,14 @@ export function validateFlowUpdateManifest(manifest) {
912
947
  if (Object.keys(action.inputs).length === 0) throw new Error(`Update action ${index + 1} inputs must contain at least one changed value`);
913
948
  }
914
949
  }
915
- if (manifest.trigger === undefined && manifest.actions === undefined && manifest.stages === undefined && manifest.stageTemplate === undefined && manifest.stageSet === undefined && manifest.flowVariables === undefined && manifest.variables === undefined && manifest.flowLogics === undefined && manifest.logic === undefined && manifest.deleteSteps === undefined && manifest.delete === undefined && manifest.deleteOrders === undefined) throw new Error('Flow update manifest must specify trigger, actions and/or stages');
950
+ if (manifest.trigger === undefined && manifest.actions === undefined && manifest.stages === undefined && manifest.stageTemplate === undefined && manifest.stageSet === undefined && manifest.flowVariables === undefined && manifest.variables === undefined && manifest.flowLogics === undefined && manifest.logic === undefined && manifest.deleteSteps === undefined && manifest.delete === undefined && manifest.deleteOrders === undefined && manifest.errorHandling === undefined && manifest.errorHandler === undefined) throw new Error('Flow update manifest must specify trigger, actions and/or stages');
916
951
  if (manifest.stages !== undefined) validateStages(manifest.stages, { update: true });
952
+ if (manifest.errorHandling !== undefined && manifest.errorHandler !== undefined) throw new Error('Specify errorHandling or errorHandler, not both');
953
+ // Accepting the key without checking its shape would still insert the Try and
954
+ // Catch blocks while silently dropping a malformed action list.
955
+ for (const key of ['errorHandling', 'errorHandler']) {
956
+ if (manifest[key] !== undefined) validateErrorHandling(manifest[key]);
957
+ }
917
958
  for (const key of ['stageTemplate', 'stageSet']) {
918
959
  if (manifest[key] === undefined) continue;
919
960
  if (typeof manifest[key] !== 'string' || !manifest[key].trim()) throw new Error(`Flow update ${key} must be a non-empty string`);
@@ -1232,6 +1273,300 @@ async function findCaptureElsewhere(sdk, flowId, intendedSetId) {
1232
1273
  return { checked: true, available: true, query: `nameLIKE${id}`, update_sets: [...bySet.values()] };
1233
1274
  }
1234
1275
 
1276
+ // Verify requested step content independently of the mutation acknowledgement.
1277
+ function labelCacheEntry({ name, label, type, baseType, usedInstances }) {
1278
+ // The provider stores usedInstances as a map, but a map key is a UUID and an
1279
+ // unquoted UUID key is not valid GraphQL. Send the array form it accepts.
1280
+ const instances = Object.entries(usedInstances || {}).flatMap(([uiUniqueIdentifier, inputNames]) =>
1281
+ (Array.isArray(inputNames) ? inputNames : [inputNames]).map(inputName => ({ uiUniqueIdentifier, inputName })));
1282
+ const entry = { name, usedInstances: instances };
1283
+ if (label) entry.label = label;
1284
+ if (type) entry.type = type;
1285
+ if (baseType) entry.base_type = baseType;
1286
+ return entry;
1287
+ }
1288
+
1289
+ function assertInsertedIdentities(response, definition, expected, kind, flowId) {
1290
+ if (!expected.length) return;
1291
+ const field = kind === 'action' ? 'actions' : 'flowLogics';
1292
+ let inserted = [];
1293
+ walk(response, object => { if (object[field]?.inserts) inserted = object[field].inserts; });
1294
+ const saved = kind === 'action' ? findExistingActions(definition) : (definition.flowLogicInstances || definition.flowLogics || []);
1295
+ for (const step of expected) {
1296
+ const matches = inserted.filter(s => s.uiUniqueIdentifier === step.uiUniqueIdentifier);
1297
+ const actual = saved.filter(s => stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier) === step.uiUniqueIdentifier);
1298
+ const id = matches.length === 1 && findId(matches[0], ['sysId', 'sys_id', 'id']);
1299
+ if (!id || actual.length !== 1 || findId(actual[0], ['sysId', 'sys_id', 'id']) !== id) throw new Error(`Flow ${flowId} ${kind} ${step.uiUniqueIdentifier} persisted identity did not match the insert acknowledgement`);
1300
+ }
1301
+ }
1302
+
1303
+ // Compare the requested contract, allowing only additional provider fields.
1304
+ function requestedContentMatches(actual, expected) {
1305
+ if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((v, i) => requestedContentMatches(actual[i], v));
1306
+ if (expected && typeof expected === 'object') return actual !== null && typeof actual === 'object' && Object.entries(expected).every(([k, v]) => requestedContentMatches(actual[k], v));
1307
+ return isDeepStrictEqual(actual, expected);
1308
+ }
1309
+
1310
+ function validateFinalStepPlan(before, actionInserts, actionUpdates, actionDeletes, logicInserts, logicUpdates, logicDeletes) {
1311
+ const surviving = (steps, updates, deletes) => steps.filter(s => !deletes.includes(stringValue(s.sysId || s.id || s.sys_id || s.uiUniqueIdentifier))).map(s => ({ ...s, ...updates.find(u => u.uiUniqueIdentifier === stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier)) }));
1312
+ const steps = [...surviving(findExistingActions(before), actionUpdates, actionDeletes), ...surviving(before.flowLogicInstances || before.flowLogics || [], logicUpdates, logicDeletes), ...actionInserts, ...logicInserts];
1313
+ const orders = new Set(), identities = new Set();
1314
+ for (const s of steps) {
1315
+ const ui = stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier), order = String(s.order);
1316
+ if ((s.order !== undefined && orders.has(order)) || (ui && identities.has(ui))) throw new Error('Ambiguous final step orders or identities');
1317
+ if (s.order !== undefined) orders.add(order);
1318
+ if (ui) identities.add(ui);
1319
+ }
1320
+ }
1321
+
1322
+ function assertStepReadback(definition, expectedSteps, kind, flowId) {
1323
+ const saved = kind === 'action' ? findExistingActions(definition) : (definition.flowLogicInstances || definition.flowLogics || []);
1324
+ for (const expected of expectedSteps) {
1325
+ const matches = saved.filter(step => stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier) === expected.uiUniqueIdentifier);
1326
+ if (matches.length !== 1) throw new Error(`Flow ${flowId} ${kind} ${expected.uiUniqueIdentifier} was not uniquely persisted`);
1327
+ const actual = matches[0];
1328
+ if (!findId(actual, ['sysId', 'id', 'sys_id'])) throw new Error(`Flow ${flowId} ${kind} has no persisted identity`);
1329
+ for (const key of ['order', 'parent', 'parentUiId', 'connectedTo', 'definitionId', 'actionTypeSysId']) {
1330
+ if (expected[key] === undefined) continue;
1331
+ const value = key === 'actionTypeSysId' ? actionTypeIdOf(actual) : actual[key];
1332
+ if (String(value ?? '') !== String(expected[key])) throw new Error(`Flow ${flowId} ${kind} ${expected.uiUniqueIdentifier} ${key} did not match requested value`);
1333
+ }
1334
+ if (expected.inputs) {
1335
+ for (const input of expected.inputs) {
1336
+ const found = inputList(actual).filter(i => i.name === input.name);
1337
+ if (found.length !== 1 || !requestedContentMatches(found[0], input)) throw new Error(`Flow ${flowId} ${kind} ${expected.uiUniqueIdentifier} input ${input.name} did not match the requested value; preservation failed`);
1338
+ }
1339
+ }
1340
+ }
1341
+ }
1342
+
1343
+ function assertLogicPreserved(before, after, inserts, updates, deletes, flowId) {
1344
+ const ids = new Set(inserts.map(l => l.uiUniqueIdentifier));
1345
+ const mask = (definition, isAfter) => (definition.flowLogicInstances || definition.flowLogics || []).filter(l => {
1346
+ const ui = stringValue(l.uiUniqueIdentifier || l.ui_unique_identifier);
1347
+ return !(isAfter ? ids.has(ui) : deletes.includes(stringValue(l.sysId || l.id || l.sys_id || ui)));
1348
+ }).map(l => {
1349
+ const copy = clone(l);
1350
+ const update = updates.find(u => u.uiUniqueIdentifier === stringValue(l.uiUniqueIdentifier || l.ui_unique_identifier));
1351
+ if (update) for (const key of Object.keys(update)) if (!['uiUniqueIdentifier', 'type'].includes(key)) delete copy[key];
1352
+ return copy;
1353
+ });
1354
+ if (!isDeepStrictEqual(mask(before, false), mask(after, true))) throw new Error(`Flow ${flowId} changed omitted logic fields; preservation failed`);
1355
+ }
1356
+
1357
+ async function planErrorHandling({ sdk, instance, scope, flowId, beforeDefinition, existingActions, actionInserts, actionUpdates, flowLogicInserts, flowLogicUpdates, changes, idFactory, actionUiMap, pendingSteps, changedActionInputs, collectPills, errorHandlingInput, actionTargets = new Map() }) {
1358
+ const existingLogics = beforeDefinition.flowLogicInstances || beforeDefinition.flowLogics || [];
1359
+ const existingSteps = [...existingActions, ...existingLogics];
1360
+ if (existingSteps.some(s => !stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier) || !Number.isInteger(Number(s.order))) || new Set(existingSteps.map(s => String(s.order))).size !== existingSteps.length || new Set(existingSteps.map(s => stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier))).size !== existingSteps.length) throw new Error('Ambiguous existing step orders or identities');
1361
+ let topTry = existingLogics.find(fl => String(fl.definitionId) === 'e9060aa2c3013010ace8b740ad40dd51');
1362
+ let topCatch = existingLogics.find(fl => String(fl.definitionId) === '35d60003e6022010a5e40cdd1254dd23');
1363
+
1364
+ for (const id of ['e9060aa2c3013010ace8b740ad40dd51', '35d60003e6022010a5e40cdd1254dd23']) {
1365
+ if (existingLogics.filter(fl => String(fl.definitionId) === id).length > 1) throw new Error('Ambiguous existing error handling blocks');
1366
+ }
1367
+ if (Boolean(topTry) !== Boolean(topCatch)) throw new Error('Incomplete existing error handling pair; reconcile in Flow Designer before retrying');
1368
+ if (topTry && (!stringValue(topTry.uiUniqueIdentifier || topTry.ui_unique_identifier) || !stringValue(topCatch.uiUniqueIdentifier || topCatch.ui_unique_identifier) || !Number.isInteger(Number(topCatch.order)))) throw new Error('Malformed existing error handling identities');
1369
+ if (topCatch?.connectedTo && topCatch.connectedTo !== topTry.uiUniqueIdentifier) throw new Error('Existing Catch is connected to a different Try');
1370
+ // 1. Ensure Top Level Try (order 0)
1371
+ let tryUiId = topTry ? stringValue(topTry.uiUniqueIdentifier || topTry.ui_unique_identifier) : '';
1372
+ if (!topTry) {
1373
+ tryUiId = idFactory();
1374
+ const tryDef = FLOW_LOGIC_DEFINITIONS['top level try'];
1375
+ flowLogicInserts.push({
1376
+ order: '0',
1377
+ uiUniqueIdentifier: tryUiId,
1378
+ parent: '',
1379
+ parentUiId: '',
1380
+ connectedTo: '',
1381
+ metadata: '{"predicates":[]}',
1382
+ flowSysId: flowId,
1383
+ generationSource: '',
1384
+ definitionId: tryDef.id,
1385
+ type: 'flowlogic',
1386
+ inputs: [],
1387
+ outputsToAssign: [],
1388
+ flowLogicDefinition: {
1389
+ id: tryDef.id,
1390
+ name: tryDef.name,
1391
+ description: tryDef.description,
1392
+ connectedTo: '',
1393
+ quiescence: 'never',
1394
+ compilationClass: tryDef.compilationClass,
1395
+ order: tryDef.order,
1396
+ type: tryDef.type,
1397
+ visible: true,
1398
+ attributes: tryDef.attributes,
1399
+ userCanRead: true,
1400
+ category: '',
1401
+ inputs: [],
1402
+ variables: '[]'
1403
+ }
1404
+ });
1405
+ changes.push({ component: 'flowLogic', order: 0, type: 'Top Level Try', input: 'insert', before: null, after: { uiUniqueIdentifier: tryUiId } });
1406
+
1407
+ // Re-parent all existing unparented main body actions (order >= 1) to Top Level Try
1408
+ for (const a of existingActions) {
1409
+ if (!a.parent && !a.parentUiId && !actionUpdates.some(u => u.uiUniqueIdentifier === stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier) && u.parent !== undefined)) {
1410
+ const uiId = stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier);
1411
+ actionUpdates.push({
1412
+ uiUniqueIdentifier: uiId,
1413
+ type: 'action',
1414
+ parent: tryUiId,
1415
+ parentUiId: tryUiId
1416
+ });
1417
+ }
1418
+ }
1419
+ // Re-parent all newly inserted actions that lack parent to Top Level Try
1420
+ for (const a of actionInserts) {
1421
+ if (!a.parent) {
1422
+ a.parent = tryUiId;
1423
+ a.parentUiId = tryUiId;
1424
+ }
1425
+ }
1426
+ // Re-parent all unparented logic blocks
1427
+ for (const fl of existingLogics) {
1428
+ if (!fl.parent && String(fl.definitionId) !== '35d60003e6022010a5e40cdd1254dd23') {
1429
+ const uiId = stringValue(fl.uiUniqueIdentifier || fl.ui_unique_identifier);
1430
+ flowLogicUpdates.push({
1431
+ uiUniqueIdentifier: uiId,
1432
+ type: 'flowlogic',
1433
+ parent: tryUiId,
1434
+ parentUiId: tryUiId
1435
+ });
1436
+ }
1437
+ }
1438
+ for (const fl of flowLogicInserts) {
1439
+ if (!fl.parent && fl.definitionId !== 'e9060aa2c3013010ace8b740ad40dd51' && fl.definitionId !== '35d60003e6022010a5e40cdd1254dd23') {
1440
+ fl.parent = tryUiId;
1441
+ fl.parentUiId = tryUiId;
1442
+ }
1443
+ }
1444
+ }
1445
+
1446
+ // New main-body children belong to the Try even on a rerun. Explicit
1447
+ // requested parents are retained.
1448
+ for (const a of actionInserts) if (!a.parent && !a.parentUiId) { a.parent = tryUiId; a.parentUiId = tryUiId; }
1449
+
1450
+ // 2. Ensure Top Level Catch
1451
+ let catchUiId = topCatch ? stringValue(topCatch.uiUniqueIdentifier || topCatch.ui_unique_identifier) : '';
1452
+ // An existing Catch already owns its order; re-running the same manifest must
1453
+ // place error actions after it instead of guessing a fixed slot.
1454
+ let catchOrder = topCatch ? parseInt(topCatch.order, 10) : NaN;
1455
+ if (!topCatch) {
1456
+ catchUiId = idFactory();
1457
+ const catchDef = FLOW_LOGIC_DEFINITIONS['top level catch'];
1458
+ // Determine max order
1459
+ let maxOrder = 0;
1460
+ for (const a of existingActions) maxOrder = Math.max(maxOrder, parseInt(a.order, 10) || 0);
1461
+ for (const fl of existingLogics) maxOrder = Math.max(maxOrder, parseInt(fl.order, 10) || 0);
1462
+ for (const a of actionInserts) maxOrder = Math.max(maxOrder, parseInt(a.order, 10) || 0);
1463
+ for (const fl of flowLogicInserts) maxOrder = Math.max(maxOrder, parseInt(fl.order, 10) || 0);
1464
+ catchOrder = maxOrder + 1;
1465
+
1466
+ flowLogicInserts.push({
1467
+ order: String(catchOrder),
1468
+ uiUniqueIdentifier: catchUiId,
1469
+ parent: '',
1470
+ parentUiId: '',
1471
+ connectedTo: tryUiId,
1472
+ metadata: '{"predicates":[]}',
1473
+ flowSysId: flowId,
1474
+ generationSource: '',
1475
+ definitionId: catchDef.id,
1476
+ type: 'flowlogic',
1477
+ inputs: [
1478
+ { name: 'enabled', value: { schemaless: false, schemalessValue: '', value: 'true' } }
1479
+ ],
1480
+ outputsToAssign: [],
1481
+ flowLogicDefinition: {
1482
+ id: catchDef.id,
1483
+ name: catchDef.name,
1484
+ description: catchDef.description,
1485
+ connectedTo: catchDef.connectedTo,
1486
+ quiescence: 'never',
1487
+ compilationClass: catchDef.compilationClass,
1488
+ order: catchDef.order,
1489
+ type: catchDef.type,
1490
+ visible: true,
1491
+ attributes: catchDef.attributes,
1492
+ userCanRead: true,
1493
+ category: '',
1494
+ inputs: [],
1495
+ variables: '[]'
1496
+ }
1497
+ });
1498
+ changes.push({ component: 'flowLogic', order: catchOrder, type: 'Top Level Catch', input: 'insert', before: null, after: { uiUniqueIdentifier: catchUiId } });
1499
+ }
1500
+
1501
+ // Register Catch step in pendingSteps for data pill resolution
1502
+ pendingSteps.push({
1503
+ name: 'Error Handler',
1504
+ order: String(Number.isFinite(catchOrder) ? catchOrder : existingActions.length + 1),
1505
+ uiUniqueIdentifier: catchUiId,
1506
+ inputs: [
1507
+ { name: '__status__.message', parameter: { label: 'Error Status➛Message', type: 'string' } },
1508
+ { name: '__status__.code', parameter: { label: 'Error Status➛Code', type: 'integer' } }
1509
+ ]
1510
+ });
1511
+
1512
+ // 3. Process errorHandling actions
1513
+ const errorActions = Array.isArray(errorHandlingInput.actions) ? errorHandlingInput.actions : [];
1514
+ const errorPill = name => String(name)
1515
+ .replace(/\{\{error\.message\}\}/g, `{{${catchUiId}.__status__.message}}`)
1516
+ .replace(/\{\{error\.code\}\}/g, `{{${catchUiId}.__status__.code}}`);
1517
+ const children = existingActions.filter(a => a.parent === catchUiId || a.parentUiId === catchUiId).sort((a, b) => Number(a.order) - Number(b.order));
1518
+ if (existingLogics.some(l => l.parent === catchUiId || l.parentUiId === catchUiId)) throw new Error('Ambiguous Catch children include logic blocks');
1519
+ const childOrders = children.map(a => String(a.order));
1520
+ if (new Set(childOrders).size !== childOrders.length || children.some(a => !a.uiUniqueIdentifier || !Number.isInteger(Number(a.order)))) throw new Error('Ambiguous Catch child identities or orders');
1521
+ let errActionOrder = Math.max(catchOrder, ...existingActions.map(a => Number(a.order)), ...existingLogics.map(a => Number(a.order)), ...actionInserts.map(a => Number(a.order)), ...flowLogicInserts.map(a => Number(a.order))) + 1;
1522
+ for (const [eIdx, eAction] of errorActions.entries()) {
1523
+ const resolved = await resolveActionType(sdk, eAction.type);
1524
+ const actionDefinition = await readActionDefinition(sdk, instance, resolved.id, scope);
1525
+ const existingChild = children[eIdx];
1526
+ if (existingChild && actionTypeIdOf(existingChild) !== resolved.id) throw new Error(`Error action ${eIdx + 1} does not match existing Catch child type; ambiguous reconciliation`);
1527
+ const uiUniqueIdentifier = existingChild ? existingChild.uiUniqueIdentifier : idFactory();
1528
+ actionUiMap.set(`error_${eIdx + 1}`, uiUniqueIdentifier);
1529
+ // Resolve the friendly {{error.*}} tokens before the typed inputs are
1530
+ // built: the value that reaches the instance has to name the Catch
1531
+ // instance's own pill, otherwise the canvas stores an unresolved
1532
+ // reference and no labelCache entry can draw it.
1533
+ const errorInputs = Object.fromEntries(Object.entries(eAction.inputs || {})
1534
+ .map(([input, value]) => [input, typeof value === 'string' ? errorPill(value) : value]));
1535
+ if (existingChild) {
1536
+ const update = buildActionUpdate(existingChild, { ...eAction, inputs: errorInputs }, eIdx);
1537
+ actionUpdates.push(update);
1538
+ actionTargets.set(uiUniqueIdentifier, existingChild);
1539
+ changedActionInputs.set(uiUniqueIdentifier, new Set([...(changedActionInputs.get(uiUniqueIdentifier) || []), ...Object.keys(errorInputs)]));
1540
+ for (const [input, after] of Object.entries(errorInputs)) {
1541
+ changes.push({ component: 'errorAction', order: existingChild.order, type: eAction.type, input, before: inputRawValue(inputList(existingChild).find(i => i.name === input)), after });
1542
+ collectPills(after, uiUniqueIdentifier, input);
1543
+ }
1544
+ continue;
1545
+ }
1546
+ const insertInputs = buildTypedInputs({ ...eAction, inputs: errorInputs }, actionDefinition.schema);
1547
+ pendingSteps.push({ name: eAction.type, order: String(errActionOrder), uiUniqueIdentifier, inputs: insertInputs });
1548
+ actionInserts.push({
1549
+ actionTypeSysId: resolved.id,
1550
+ flowSysId: flowId,
1551
+ generationSource: '',
1552
+ type: 'action',
1553
+ order: String(errActionOrder),
1554
+ parent: catchUiId,
1555
+ uiUniqueIdentifier,
1556
+ parentUiId: catchUiId,
1557
+ metadata: JSON.stringify(parseMaybeJson(actionDefinition.definition.metadata, {})),
1558
+ inputs: insertInputs,
1559
+ });
1560
+ changedActionInputs.set(uiUniqueIdentifier, new Set(Object.keys(eAction.inputs || {})));
1561
+ for (const [input, after] of Object.entries(eAction.inputs || {})) {
1562
+ const resolvedVal = typeof after === 'string' ? errorPill(after) : after;
1563
+ changes.push({ component: 'errorAction', order: errActionOrder, type: eAction.type, input, before: null, after: resolvedVal });
1564
+ collectPills(resolvedVal, uiUniqueIdentifier, input);
1565
+ }
1566
+ errActionOrder++;
1567
+ }
1568
+ }
1569
+
1235
1570
  export async function createFlowFromManifest(sdk, instance, inputManifest, options = {}) {
1236
1571
  const manifest = validateFlowManifest(inputManifest);
1237
1572
  const scope = manifest.scope;
@@ -1245,6 +1580,44 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1245
1580
  throw new Error(`Flow creation refused before any content write: capture context could not be established. ${error.message}`, { cause: error });
1246
1581
  }
1247
1582
 
1583
+ const actionInstances = [];
1584
+ for (const [index, action] of manifest.actions.entries()) {
1585
+ const resolved = await resolveActionType(sdk, action.type);
1586
+ const actionDefinition = await readActionDefinition(sdk, instance, resolved.id, scope);
1587
+ actionInstances.push({
1588
+ actionTypeSysId: resolved.id,
1589
+ flowSysId: '',
1590
+ generationSource: '',
1591
+ type: 'action',
1592
+ order: String(index + 1),
1593
+ parent: '',
1594
+ uiUniqueIdentifier: idFactory(),
1595
+ parentUiId: '',
1596
+ metadata: JSON.stringify(parseMaybeJson(actionDefinition.definition.metadata, {})),
1597
+ inputs: buildTypedInputs(action, actionDefinition.schema),
1598
+ });
1599
+ }
1600
+
1601
+ const flowLogicInserts = [];
1602
+ const labelCacheInserts = [];
1603
+ const pendingSteps = [];
1604
+ const pills = [];
1605
+ if (manifest.errorHandling !== undefined) {
1606
+ await planErrorHandling({ sdk, instance, scope, flowId: '', beforeDefinition: {}, existingActions: [], actionInserts: actionInstances, actionUpdates: [], flowLogicInserts, flowLogicUpdates: [], changes: [], idFactory, actionUiMap: new Map(), pendingSteps, changedActionInputs: new Map(), collectPills: (value, uiUniqueIdentifier, inputName) => {
1607
+ for (const match of String(value).matchAll(/\{\{([^}]+)\}\}/g)) pills.push({ name: match[1], uiUniqueIdentifier, inputName });
1608
+ }, errorHandlingInput: manifest.errorHandling });
1609
+ for (const pill of pills) {
1610
+ const binding = resolvePillBinding({}, pill.name, '', [], pendingSteps);
1611
+ const previous = labelCacheInserts.find(e => e.name === pill.name);
1612
+ if (previous) {
1613
+ if (!previous.usedInstances.some(i => i.uiUniqueIdentifier === pill.uiUniqueIdentifier && i.inputName === pill.inputName)) previous.usedInstances.push({ uiUniqueIdentifier: pill.uiUniqueIdentifier, inputName: pill.inputName });
1614
+ }
1615
+ else labelCacheInserts.push(labelCacheEntry({ name: pill.name, label: binding.label, type: binding.type, baseType: binding.type, usedInstances: { [pill.uiUniqueIdentifier]: [pill.inputName] } }));
1616
+ }
1617
+ }
1618
+
1619
+ validateFinalStepPlan({}, actionInstances, [], [], flowLogicInserts, [], []);
1620
+
1248
1621
  let parentResponse;
1249
1622
  try {
1250
1623
  parentResponse = await mutationContext('parent_create', readUpdateSet, snapshots, () => sdk.request(`${instance}${FLOW_ENDPOINT}?param_only_properties=true&sysparm_transaction_scope=${encodeURIComponent(scope)}`, {
@@ -1270,27 +1643,12 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1270
1643
  const definition = await resolveTriggerDefinition(sdk, manifest.trigger.type);
1271
1644
  const trigger = await buildCreateTrigger(sdk, flowId, manifest, definition, options);
1272
1645
 
1273
- const actionInstances = [];
1274
- for (const [index, action] of manifest.actions.entries()) {
1275
- const resolved = await resolveActionType(sdk, action.type);
1276
- const actionDefinition = await readActionDefinition(sdk, instance, resolved.id, scope);
1277
- actionInstances.push({
1278
- actionTypeSysId: resolved.id,
1279
- flowSysId: flowId,
1280
- generationSource: '',
1281
- type: 'action',
1282
- order: String(index + 1),
1283
- parent: '',
1284
- uiUniqueIdentifier: idFactory(),
1285
- parentUiId: '',
1286
- metadata: JSON.stringify(parseMaybeJson(actionDefinition.definition.metadata, {})),
1287
- inputs: buildTypedInputs(action, actionDefinition.schema),
1288
- });
1289
- }
1646
+ for (const action of actionInstances) action.flowSysId = flowId;
1647
+ for (const logic of flowLogicInserts) logic.flowSysId = flowId;
1290
1648
 
1291
1649
  const patchResponse = await mutationContext('trigger_and_actions_patch', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1292
1650
  method: 'POST',
1293
- body: JSON.stringify({ query: buildFlowPatchMutation({ flowId, trigger, actions: actionInstances }), variables: {} }),
1651
+ body: JSON.stringify({ query: buildFlowPatchMutation({ flowId, trigger, actions: actionInstances, flowLogicInserts, labelCacheInserts }), variables: {} }),
1294
1652
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1295
1653
  assertGraphQLSuccess(patchResponse, 'Flow trigger/action patch');
1296
1654
  const insertedTrigger = insertedTriggers(patchResponse)[0];
@@ -1316,6 +1674,10 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1316
1674
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
1317
1675
  verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted, stageInserts });
1318
1676
  assertStagesPlaced(processflow, stageInserts, flowId);
1677
+ assertInsertedIdentities(patchResponse, processflow, flowLogicInserts, 'logic', flowId);
1678
+ assertStepReadback(processflow, actionInstances, 'action', flowId);
1679
+ assertStepReadback(processflow, flowLogicInserts, 'logic', flowId);
1680
+ for (const entry of labelCacheInserts) if (!readLabelCache(processflow).some(e => e.name === entry.name && e.label)) throw new Error(`Flow ${flowId} did not persist data pill ${entry.name}`);
1319
1681
  const { version } = await mutationContext('autosave_version', readUpdateSet, snapshots, () => createVerifiedFlowVersion(sdk, {
1320
1682
  instance, flowId, scope, type: 'Autosave', annotation: 'JSN flow create',
1321
1683
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
@@ -1333,7 +1695,7 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1333
1695
  ...(captureContext ? { capture_context: captureContext } : {}),
1334
1696
  update_set_capture: updateSetCapture,
1335
1697
  update_set_mutations: snapshots,
1336
- lifecycle: { published: false, supported: ['draft', 'autosave'], deferred: ['publish/activation', 'Flow Logic', 'subflows', 'flow variables', 'error handling'] },
1698
+ lifecycle: { published: false, supported: ['draft', 'autosave'], deferred: ['publish/activation', 'Flow Logic', 'subflows', 'flow variables'] },
1337
1699
  };
1338
1700
  } catch (error) {
1339
1701
  // Creation is two-stage: the parent POST leaves a real draft behind when the
@@ -1403,7 +1765,8 @@ export function resolvePillBinding(definition, pillName, flowId, cache, pending
1403
1765
  const separator = pillName.indexOf('.');
1404
1766
  if (separator <= 0) return fail();
1405
1767
  const stepKey = pillName.slice(0, separator);
1406
- const fieldName = pillName.slice(separator + 1).split('.')[0];
1768
+ const remainder = pillName.slice(separator + 1);
1769
+ const fieldName = remainder.startsWith('__status__.') ? remainder : remainder.split('.')[0];
1407
1770
  const describe = (fields, name) => {
1408
1771
  const field = inputList({ inputs: fields }).find(entry => stringValue(entry?.name) === name);
1409
1772
  if (!field) return null;
@@ -1417,6 +1780,16 @@ export function resolvePillBinding(definition, pillName, flowId, cache, pending
1417
1780
  ...findArray(definition, 'triggerInstances').map(step => ({ ...step, trigger: true })),
1418
1781
  ...findExistingActions(definition).map(step => ({ ...step, trigger: false })),
1419
1782
  ...pending.map(step => ({ ...step, trigger: false })),
1783
+ ...(findArray(definition, 'flowLogicInstances') || []).filter(fl => String(fl.definitionId) === '35d60003e6022010a5e40cdd1254dd23').map(fl => ({
1784
+ name: 'Error Handler',
1785
+ order: stringValue(fl.order),
1786
+ uiUniqueIdentifier: stringValue(fl.uiUniqueIdentifier || fl.ui_unique_identifier),
1787
+ trigger: false,
1788
+ inputs: [
1789
+ { name: '__status__.message', parameter: { label: 'Error Status➛Message', type: 'string' } },
1790
+ { name: '__status__.code', parameter: { label: 'Error Status➛Code', type: 'integer' } }
1791
+ ]
1792
+ }))
1420
1793
  ];
1421
1794
  for (const step of candidates) {
1422
1795
  const name = stringValue(step.name);
@@ -1750,23 +2123,31 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1750
2123
  }
1751
2124
  }
1752
2125
  }
2126
+ const errorHandlingInput = manifest.errorHandling ?? manifest.errorHandler;
2127
+ if (errorHandlingInput !== undefined) await planErrorHandling({ sdk, instance, scope, flowId, beforeDefinition, existingActions, actionInserts, actionUpdates, flowLogicInserts, flowLogicUpdates, changes, idFactory, actionUiMap, pendingSteps, changedActionInputs, collectPills, errorHandlingInput, actionTargets });
2128
+
2129
+ const mergedActionUpdates = new Map();
2130
+ for (const update of actionUpdates) {
2131
+ const prior = mergedActionUpdates.get(update.uiUniqueIdentifier);
2132
+ if (prior) {
2133
+ for (const key of ['parent', 'parentUiId']) if (prior[key] !== undefined && update[key] !== undefined && prior[key] !== update[key]) throw new Error(`Conflicting action ${key} requests`);
2134
+ const inputs = [...(prior.inputs || [])];
2135
+ for (const input of update.inputs || []) {
2136
+ const existing = inputs.find(i => i.name === input.name);
2137
+ if (existing && !isDeepStrictEqual(existing, input)) throw new Error(`Conflicting action input ${input.name} requests`);
2138
+ if (!existing) inputs.push(input);
2139
+ }
2140
+ Object.assign(prior, update, inputs.length ? { inputs } : {});
2141
+ } else mergedActionUpdates.set(update.uiUniqueIdentifier, { ...update });
2142
+ }
2143
+ actionUpdates.splice(0, actionUpdates.length, ...mergedActionUpdates.values());
2144
+
1753
2145
  // Register every referenced pill so the canvas can draw it. Runs after every
1754
2146
  // collection point (actions and logic blocks) so no reference is missed.
1755
2147
  // Existing entries keep their label/type; a pill this flow has never seen gets
1756
2148
  // a label resolved from its producing step.
1757
2149
  const labelCacheInserts = [];
1758
2150
  const existingLabelCache = readLabelCache(beforeDefinition);
1759
- const labelCacheEntry = ({ name, label, type, baseType, usedInstances }) => {
1760
- // The provider stores usedInstances as a map, but a map key is a UUID and an
1761
- // unquoted UUID key is not valid GraphQL. Send the array form it accepts.
1762
- const instances = Object.entries(usedInstances || {}).flatMap(([uiUniqueIdentifier, inputNames]) =>
1763
- (Array.isArray(inputNames) ? inputNames : [inputNames]).map(inputName => ({ uiUniqueIdentifier, inputName })));
1764
- const entry = { name, usedInstances: instances };
1765
- if (label) entry.label = label;
1766
- if (type) entry.type = type;
1767
- if (baseType) entry.base_type = baseType;
1768
- return entry;
1769
- };
1770
2151
  const mergeUsedInstances = (existing, instances) => {
1771
2152
  const merged = { ...(existing || {}) };
1772
2153
  for (const { uiUniqueIdentifier, inputName } of instances) {
@@ -1798,6 +2179,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1798
2179
  labelCacheInserts.push(labelCacheEntry({ name: pillName, label: binding.label, type: binding.type, baseType: binding.type, usedInstances }));
1799
2180
  }
1800
2181
  }
2182
+ validateFinalStepPlan(beforeDefinition, actionInserts, actionUpdates, actionDeletes, flowLogicInserts, flowLogicUpdates, flowLogicDeletes);
1801
2183
  if (triggerUpdates.length === 0 && actionUpdates.length === 0 && actionInserts.length === 0 && actionDeletes.length === 0 && flowVariableInserts.length === 0 && flowLogicInserts.length === 0 && flowLogicDeletes.length === 0 && stageInserts.length === 0 && stageUpdates.length === 0) throw new Error(`Flow ${flowId} update has no supported changes`);
1802
2184
  if (options.preview) return {
1803
2185
  preview: true,
@@ -1871,6 +2253,11 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1871
2253
  assertGraphQLSuccess(patchResponse, 'Flow trigger/action update');
1872
2254
  completedStage = 'patch_acknowledged';
1873
2255
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
2256
+ assertInsertedIdentities(patchResponse, processflow, actionInserts, 'action', flowId);
2257
+ assertInsertedIdentities(patchResponse, processflow, flowLogicInserts, 'logic', flowId);
2258
+ assertStepReadback(processflow, [...actionInserts, ...actionUpdates], 'action', flowId);
2259
+ assertStepReadback(processflow, [...flowLogicInserts, ...flowLogicUpdates], 'logic', flowId);
2260
+ assertLogicPreserved(beforeDefinition, processflow, flowLogicInserts, flowLogicUpdates, flowLogicDeletes, flowId);
1874
2261
  // Only requested values may differ. Preserve array order and opaque fields.
1875
2262
  // `stages` is compared separately below: a stage edit may touch specific
1876
2263
  // fields, while every stage the manifest did not name must stay identical.
@@ -1907,6 +2294,12 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1907
2294
  })
1908
2295
  .map(action => {
1909
2296
  const copy = clone(action);
2297
+ const move = actionUpdates.find(update => update.uiUniqueIdentifier === stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier) && update.parent !== undefined);
2298
+ if (move) {
2299
+ if (isAfter && (copy.parent !== move.parent || copy.parentUiId !== move.parentUiId)) throw new Error(`Flow ${flowId} action parent readback did not match requested target`);
2300
+ delete copy.parent;
2301
+ delete copy.parentUiId;
2302
+ }
1910
2303
  const changed = changedActionInputs.get(stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier));
1911
2304
  for (const [index, input] of inputList(copy).entries()) if (changed?.has(input.name)) inputList(copy)[index] = maskInputValue(input);
1912
2305
  return copy;
@@ -1970,7 +2363,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1970
2363
  const afterInput = inputList(readback).find(candidate => candidate.name === input.name);
1971
2364
  if (!afterInput) throw new Error(`Flow ${flowId} Action ${uiId} lost input ${input.name} during update`);
1972
2365
  if (!changed.has(input.name) && JSON.stringify(input) !== JSON.stringify(afterInput)) throw new Error(`Flow ${flowId} Action ${uiId} changed omitted input ${input.name}`);
1973
- if (changed.has(input.name) && inputRawValue(afterInput) !== inputRawValue(update.inputs.find(candidate => candidate.name === input.name))) throw new Error(`Flow ${flowId} Action ${uiId} input ${input.name} did not match the requested value`);
2366
+ if (changed.has(input.name) && !isDeepStrictEqual(inputRawValue(afterInput), inputRawValue(update.inputs.find(candidate => candidate.name === input.name)))) throw new Error(`Flow ${flowId} Action ${uiId} input ${input.name} did not match the requested value; preservation failed`);
1974
2367
  }
1975
2368
  }
1976
2369
  completedStage = 'definition_verified';