@jacebenson/jsn 5.5.1-dev.156.1 → 5.5.1-dev.158.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 +490 -25
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.1-dev.156.1",
3
+ "version": "5.5.1-dev.158.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": {
@@ -243,6 +243,7 @@ function stageValueFromLabel(label) {
243
243
  * `stageId` is only meaningful for updates: an entry without one inserts a new
244
244
  * stage, an entry with one edits the stage it names.
245
245
  */
246
+
246
247
  export function validateStages(stages, { update = false } = {}) {
247
248
  if (!Array.isArray(stages)) throw new Error('Flow stages must be an array');
248
249
  for (const [index, stage] of stages.entries()) {
@@ -379,17 +380,95 @@ export function buildFlowPatchMutation({ flowId, trigger, actions }) {
379
380
  return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { inserts { sysId } updates } actions { inserts { sysId uiUniqueIdentifier } } } } } }`;
380
381
  }
381
382
 
382
- export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [], stageInserts = [], stageUpdates = [] }) {
383
+
384
+ const FLOW_LOGIC_DEFINITIONS = {
385
+ 'if': {
386
+ id: 'af4e1945c3e232002841b63b12d3ae3e',
387
+ name: 'If',
388
+ type: 'IF',
389
+ description: 'Selectively apply one or more actions only when a list of conditions is met.',
390
+ compilationClass: 'com.glide.flow.compiler.logic_block.IfCompiler',
391
+ order: 1,
392
+ connectedTo: '',
393
+ attributes: 'allow_children=true,allow_siblings=true,icon_class=diamond-if-icon,line_type=q_if_curve,pills_draggable_outside_block=false,',
394
+ },
395
+ 'else if': {
396
+ id: '666e5545c3e232002841b63b12d3ae99',
397
+ name: 'Else If',
398
+ type: 'ELSEIF',
399
+ description: 'Selectively apply one or more actions only when a list of conditions is met.',
400
+ compilationClass: 'com.glide.flow.compiler.logic_block.ElseIfCompiler',
401
+ order: 2,
402
+ connectedTo: 'af4e1945c3e232002841b63b12d3ae3e,666e5545c3e232002841b63b12d3ae99',
403
+ attributes: 'allow_children=true,allow_siblings=true,icon_class=elseif-icon,line_type=q_if_curve,pills_draggable_outside_block=false,',
404
+ },
405
+ 'else': {
406
+ id: '1f781bf3c32232002841b63b12d3aee6',
407
+ name: 'Else',
408
+ type: 'ELSE',
409
+ description: 'Else statement',
410
+ compilationClass: 'com.glide.flow.compiler.logic_block.ElseCompiler',
411
+ order: 3,
412
+ connectedTo: '666e5545c3e232002841b63b12d3ae99,af4e1945c3e232002841b63b12d3ae3e',
413
+ attributes: 'allow_children=true,allow_siblings=true,disable_opening=true,icon_class=else-icon,line_type=q_if_curve,pills_draggable_outside_block=false,',
414
+ },
415
+ 'set flow variables': {
416
+ id: '4f787d1e0f9b0010ecf0cc52ff767ea0',
417
+ name: 'Set Flow Variables',
418
+ type: 'SETFLOWVARIABLES',
419
+ description: "Assign a value to one or more flow variables. Change or update a variable's value during a flow.",
420
+ compilationClass: 'com.glide.flow.compiler.logic_block.SetVariablesCompiler',
421
+ order: 14,
422
+ connectedTo: '',
423
+ attributes: 'allow_children=false,allow_siblings=true,',
424
+ },
425
+ 'end flow': {
426
+ id: 'd176605ea76103004f27b0d2187901c7',
427
+ name: 'End Flow',
428
+ type: 'END',
429
+ description: 'Use this flow logic to stop a flow within flow designer.',
430
+ compilationClass: 'com.glide.flow.compiler.logic_block.EndCompiler',
431
+ order: 10,
432
+ connectedTo: '',
433
+ attributes: 'allow_children=false,allow_siblings=false,disable_opening=true,',
434
+ }
435
+ };
436
+
437
+ export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [], actionInserts = [], actionDeletes = [], flowVariableInserts = [], flowLogicInserts = [], flowLogicUpdates = [], flowLogicDeletes = [], labelCacheUpdates = [], labelCacheInserts = [], stageInserts = [], stageUpdates = [] }) {
383
438
  const updates = [];
384
439
  if (triggerUpdates.length) updates.push(`triggerInstances: {update: [${triggerUpdates.map(gqlInputObject).join(', ')}]}`);
385
- if (actionUpdates.length) updates.push(`actions: {update: [${actionUpdates.map(gqlInputObject).join(', ')}]}`);
440
+ const actionParts = [];
441
+ if (actionInserts.length) actionParts.push(`insert: [${actionInserts.map(gqlInputObject).join(', ')}]`);
442
+ if (actionUpdates.length) actionParts.push(`update: [${actionUpdates.map(gqlInputObject).join(', ')}]`);
443
+ if (actionDeletes.length) actionParts.push(`delete: [${actionDeletes.map(id => gqlString(id)).join(', ')}]`);
444
+ if (actionParts.length) updates.push(`actions: {${actionParts.join(', ')}}`);
445
+ if (flowVariableInserts.length) updates.push(`flowVariables: {insert: [${flowVariableInserts.map(gqlInputObject).join(', ')}]}`);
446
+ const logicParts = [];
447
+ if (flowLogicInserts.length) logicParts.push(`insert: [${flowLogicInserts.map(gqlInputObject).join(', ')}]`);
448
+ if (flowLogicUpdates.length) logicParts.push(`update: [${flowLogicUpdates.map(gqlInputObject).join(', ')}]`);
449
+ if (flowLogicDeletes.length) logicParts.push(`delete: [${flowLogicDeletes.map(id => gqlString(id)).join(', ')}]`);
450
+ if (logicParts.length) updates.push(`flowLogics: {${logicParts.join(', ')}}`);
451
+ const labelParts = [];
452
+ if (labelCacheInserts.length) labelParts.push(`insert: [${labelCacheInserts.map(gqlInputObject).join(', ')}]`);
453
+ if (labelCacheUpdates.length) labelParts.push(`update: [${labelCacheUpdates.map(gqlInputObject).join(', ')}]`);
454
+ if (labelParts.length) updates.push(`labelCache: {${labelParts.join(', ')}}`);
386
455
  const stageParts = [];
387
- if (stageInserts.length) stageParts.push(`insert: [${stageInserts.map(gqlInputObject).join(', ')}]`);
456
+ if (stageInserts.length) stageParts.push(`insert: [${stageInserts.map(s => {
457
+ const copy = { ...s };
458
+ delete copy.system;
459
+ return gqlInputObject(copy);
460
+ }).join(', ')}]`);
388
461
  if (stageUpdates.length) stageParts.push(`update: [${stageUpdates.map(gqlInputObject).join(', ')}]`);
389
462
  if (stageParts.length) updates.push(`stages: {${stageParts.join(', ')}}`);
390
463
  if (!updates.length) throw new Error('Flow update mutation requires at least one change');
391
464
  const patch = `flowPatch: {flowId: ${gqlString(flowId)}, ${updates.join(', ')}}`;
392
- return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { updates } actions { updates } stages { inserts { sysId } } } } } }`;
465
+ const returnFields = ['triggerInstances { updates }'];
466
+ if (actionInserts.length) returnFields.push('actions { inserts { sysId uiUniqueIdentifier } updates }');
467
+ else returnFields.push('actions { updates }');
468
+ if (flowLogicInserts.length) returnFields.push('flowLogics { inserts { sysId uiUniqueIdentifier } }');
469
+ if (flowVariableInserts.length) returnFields.push('flowVariables { inserts { sysId uiUniqueIdentifier } }');
470
+ returnFields.push('stages { inserts { sysId } }');
471
+ return `mutation { global { snFlowDesigner { flow(${patch}) { ${returnFields.join(' ')} } } } }`;
393
472
  }
394
473
 
395
474
  export async function readProcessFlow(sdk, instance, flowId, scope) {
@@ -735,8 +814,8 @@ async function resolveExistingAction(sdk, actions, requested, index) {
735
814
 
736
815
  export function validateFlowUpdateManifest(manifest) {
737
816
  if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('Flow update manifest must be a JSON object');
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`);
817
+ const allowed = new Set(['scope', 'trigger', 'actions', 'stages', 'flowVariables', 'variables', 'flowLogics', 'logic', 'deleteSteps', 'delete', 'deleteOrders']);
818
+ 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`);
740
819
  if (manifest.scope !== undefined && !String(manifest.scope).trim()) throw new Error('Flow update scope must not be empty');
741
820
  if (manifest.trigger !== undefined) {
742
821
  if (!manifest.trigger || typeof manifest.trigger !== 'object' || Array.isArray(manifest.trigger)) throw new Error('Flow update trigger must be an object');
@@ -757,7 +836,7 @@ export function validateFlowUpdateManifest(manifest) {
757
836
  if (Object.keys(action.inputs).length === 0) throw new Error(`Update action ${index + 1} inputs must contain at least one changed value`);
758
837
  }
759
838
  }
760
- if (manifest.trigger === undefined && manifest.actions === undefined && manifest.stages === undefined) throw new Error('Flow update manifest must specify trigger, actions and/or stages');
839
+ if (manifest.trigger === undefined && manifest.actions === undefined && manifest.stages === 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');
761
840
  if (manifest.stages !== undefined) validateStages(manifest.stages, { update: true });
762
841
  return manifest;
763
842
  }
@@ -1177,6 +1256,96 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1177
1256
  }
1178
1257
  }
1179
1258
 
1259
+ // Flow Designer renders a canvas pill from the `label` of its label_cache entry;
1260
+ // the ProcessFlow read exposes that cache as `labelCacheAsJsonString` (a JSON
1261
+ // string), never as a `label_cache` array. Reading the wrong field is how a
1262
+ // write ends up with an entry that has a name and no label to draw.
1263
+ function normalizeUsedInstances(used) {
1264
+ const out = new Map();
1265
+ const add = (uiId, inputName) => {
1266
+ if (!uiId || !inputName) return;
1267
+ if (!out.has(uiId)) out.set(uiId, []);
1268
+ const names = out.get(uiId);
1269
+ if (!names.includes(inputName)) names.push(inputName);
1270
+ };
1271
+ if (Array.isArray(used)) {
1272
+ for (const entry of used) add(stringValue(entry?.uiUniqueIdentifier), stringValue(entry?.inputName));
1273
+ } else if (used && typeof used === 'object') {
1274
+ for (const [uiId, names] of Object.entries(used)) {
1275
+ for (const name of (Array.isArray(names) ? names : [names])) add(uiId, stringValue(name));
1276
+ }
1277
+ }
1278
+ const result = {};
1279
+ for (const [uiId, names] of out) result[uiId] = names;
1280
+ return result;
1281
+ }
1282
+
1283
+ export function readLabelCache(definition) {
1284
+ const raw = definition?.labelCacheAsJsonString ?? definition?.label_cache ?? definition?.labelCache;
1285
+ let entries = raw;
1286
+ if (typeof raw === 'string') {
1287
+ try { entries = raw.trim() ? JSON.parse(raw) : []; } catch { entries = []; }
1288
+ }
1289
+ if (!Array.isArray(entries)) return [];
1290
+ return entries
1291
+ .map(entry => ({
1292
+ name: stringValue(entry?.name),
1293
+ label: stringValue(entry?.label),
1294
+ type: stringValue(entry?.type),
1295
+ baseType: stringValue(entry?.base_type || entry?.baseType),
1296
+ usedInstances: normalizeUsedInstances(entry?.usedInstances),
1297
+ }))
1298
+ .filter(entry => entry.name);
1299
+ }
1300
+
1301
+ function describeKnownPills(cache) {
1302
+ const names = cache.map(entry => entry.name);
1303
+ if (!names.length) return 'this flow has no registered data pills';
1304
+ return `registered pills: ${names.slice(0, 8).join(', ')}${names.length > 8 ? ` (+${names.length - 8} more)` : ''}`;
1305
+ }
1306
+
1307
+ // A pill no entry covers still needs a label the canvas can draw. Resolve the
1308
+ // producing step and the field it names, then build the label Flow Designer
1309
+ // itself would: `Trigger - <trigger>➛<input>` or `<order> - <action>➛<input>`.
1310
+ // `pending` covers steps this same manifest is inserting: their identity and
1311
+ // input schema already exist here even though the flow does not carry them yet.
1312
+ export function resolvePillBinding(definition, pillName, flowId, cache, pending = []) {
1313
+ const fail = () => {
1314
+ throw new Error(`Flow ${flowId} has no label_cache entry for data pill {{${pillName}}}; ${describeKnownPills(cache)}. Use a pill this flow already registers, or resave the flow in Flow Designer first. No content write attempted.`);
1315
+ };
1316
+ const separator = pillName.indexOf('.');
1317
+ if (separator <= 0) return fail();
1318
+ const stepKey = pillName.slice(0, separator);
1319
+ const fieldName = pillName.slice(separator + 1).split('.')[0];
1320
+ const describe = (fields, name) => {
1321
+ const field = inputList({ inputs: fields }).find(entry => stringValue(entry?.name) === name);
1322
+ if (!field) return null;
1323
+ return {
1324
+ label: stringValue(field?.parameter?.label) || stringValue(field?.parameter?.name) || String(field?.name ?? ''),
1325
+ type: stringValue(field?.parameter?.type),
1326
+ };
1327
+ };
1328
+
1329
+ const candidates = [
1330
+ ...findArray(definition, 'triggerInstances').map(step => ({ ...step, trigger: true })),
1331
+ ...findExistingActions(definition).map(step => ({ ...step, trigger: false })),
1332
+ ...pending.map(step => ({ ...step, trigger: false })),
1333
+ ];
1334
+ for (const step of candidates) {
1335
+ const name = stringValue(step.name);
1336
+ const order = stringValue(step.order) || '1';
1337
+ const uiId = stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier);
1338
+ const matchesAlias = new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}_\\d+$`).test(stepKey);
1339
+ if (!matchesAlias && stepKey !== uiId) continue;
1340
+ // Inputs and outputs both become draggable pills; look at each before failing.
1341
+ const field = describe(step.inputs, fieldName) || describe(step.outputs, fieldName);
1342
+ if (!field) continue;
1343
+ const prefix = step.trigger ? `Trigger - ${name}` : `${order} - ${name}`;
1344
+ return { label: `${prefix}➛${field.label}`, type: field.type };
1345
+ }
1346
+ return fail();
1347
+ }
1348
+
1180
1349
  export async function updateFlowFromManifest(sdk, instance, identifier, inputManifest, options = {}) {
1181
1350
  const manifest = validateFlowUpdateManifest(inputManifest);
1182
1351
  const target = await resolveFlowForUpdate(sdk, identifier);
@@ -1212,6 +1381,13 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1212
1381
  const snapshots = [];
1213
1382
  const triggerUpdates = [];
1214
1383
  const actionUpdates = [];
1384
+ const actionInserts = [];
1385
+ const actionDeletes = [];
1386
+ const flowVariableInserts = [];
1387
+ const flowLogicInserts = [];
1388
+ const flowLogicUpdates = [];
1389
+ const flowLogicDeletes = [];
1390
+ const labelCacheUpdates = [];
1215
1391
  const stageInserts = buildStageInserts((manifest.stages || []).filter(stage => stage.stageId === undefined), { idFactory: options.idFactory || (() => randomUUID()), flowId });
1216
1392
  const stageUpdates = buildStageUpdates((manifest.stages || []).filter(stage => stage.stageId !== undefined));
1217
1393
  const changedActionInputs = new Map();
@@ -1231,16 +1407,72 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1231
1407
  }
1232
1408
  }
1233
1409
  const existingActions = findExistingActions(beforeDefinition);
1410
+ const existingOrders = new Set(existingActions.map(a => String(a.order)));
1411
+ const idFactory = options.idFactory || (() => randomUUID());
1412
+ const pillToInstances = new Map();
1413
+ const pendingSteps = [];
1414
+ const actionUiMap = new Map();
1415
+ for (const a of existingActions) {
1416
+ const ui = stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier);
1417
+ if (a.order && ui) actionUiMap.set(String(a.order), ui);
1418
+ }
1419
+ // One input value can carry several pills; register every reference, not just
1420
+ // the first, or the later ones never reach label_cache and stay blank.
1421
+ const collectPills = (value, uiUniqueIdentifier, inputName) => {
1422
+ for (const match of String(value).matchAll(/\{\{([^}]+)\}\}/g)) {
1423
+ const pillName = match[1].trim();
1424
+ if (!pillName) continue;
1425
+ if (!pillToInstances.has(pillName)) pillToInstances.set(pillName, []);
1426
+ const instances = pillToInstances.get(pillName);
1427
+ if (!instances.some(entry => entry.uiUniqueIdentifier === uiUniqueIdentifier && entry.inputName === inputName)) {
1428
+ instances.push({ uiUniqueIdentifier, inputName });
1429
+ }
1430
+ }
1431
+ };
1432
+
1234
1433
  for (const [index, requested] of (manifest.actions || []).entries()) {
1235
- const existing = await resolveExistingAction(sdk, existingActions, requested, index);
1236
- const update = buildActionUpdate(existing, requested, index);
1237
- actionUpdates.push(update);
1238
- const uiId = stringValue(existing.uiUniqueIdentifier || existing.ui_unique_identifier);
1239
- if (actionTargets.has(uiId)) throw new Error(`Duplicate action update for order ${requested.order}; combine input changes in one action entry`);
1240
- actionTargets.set(uiId, existing);
1241
- changedActionInputs.set(uiId, new Set(Object.keys(requested.inputs)));
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 });
1434
+ const isInsert = !existingOrders.has(String(requested.order));
1435
+ if (isInsert) {
1436
+ const resolved = await resolveActionType(sdk, requested.type);
1437
+ const actionDefinition = await readActionDefinition(sdk, instance, resolved.id, scope);
1438
+ const uiUniqueIdentifier = requested.uiUniqueIdentifier || idFactory();
1439
+ actionUiMap.set(String(requested.order), uiUniqueIdentifier);
1440
+ const insertInputs = buildTypedInputs(requested, actionDefinition.schema);
1441
+ // A later step in this same manifest may reference this one; its identity
1442
+ // and schema exist now even though the flow does not carry it yet.
1443
+ pendingSteps.push({ name: requested.type, order: String(requested.order), uiUniqueIdentifier, inputs: insertInputs });
1444
+ actionInserts.push({
1445
+ actionTypeSysId: resolved.id,
1446
+ flowSysId: flowId,
1447
+ generationSource: '',
1448
+ type: 'action',
1449
+ order: String(requested.order),
1450
+ parent: '',
1451
+ uiUniqueIdentifier,
1452
+ parentUiId: '',
1453
+ metadata: JSON.stringify(parseMaybeJson(actionDefinition.definition.metadata, {})),
1454
+ inputs: insertInputs,
1455
+ });
1456
+ changedActionInputs.set(uiUniqueIdentifier, new Set(Object.keys(requested.inputs || {})));
1457
+ for (const [input, after] of Object.entries(requested.inputs || {})) {
1458
+ changes.push({ component: 'action', order: requested.order, type: requested.type, input, before: null, after });
1459
+ collectPills(after, uiUniqueIdentifier, input);
1460
+ }
1461
+ } else {
1462
+ const existing = await resolveExistingAction(sdk, existingActions, requested, index);
1463
+ const update = buildActionUpdate(existing, requested, index);
1464
+ actionUpdates.push(update);
1465
+ const uiId = stringValue(existing.uiUniqueIdentifier || existing.ui_unique_identifier);
1466
+ if (actionTargets.has(uiId)) throw new Error(`Duplicate action update for order ${requested.order}; combine input changes in one action entry`);
1467
+ actionTargets.set(uiId, existing);
1468
+ changedActionInputs.set(uiId, new Set(Object.keys(requested.inputs)));
1469
+ for (const [input, after] of Object.entries(requested.inputs)) {
1470
+ changes.push({ component: 'action', order: requested.order, type: requested.type, input, before: inputRawValue(inputList(existing).find(field => field.name === input)), after });
1471
+ collectPills(after, uiId, input);
1472
+ }
1473
+ }
1243
1474
  }
1475
+
1244
1476
  const savedStages = stageList(beforeDefinition);
1245
1477
  const savedStageById = new Map(savedStages.map(stage => [stringValue(stage.stageId || stage.stage_id), stage]));
1246
1478
  for (const update of stageUpdates) {
@@ -1254,7 +1486,218 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1254
1486
  for (const insert of stageInserts) {
1255
1487
  changes.push({ component: 'stage', stage: insert.label, input: 'insert', before: null, after: { order: insert.order, componentIndexes: insert.componentIndexes } });
1256
1488
  }
1257
- if (triggerUpdates.length === 0 && actionUpdates.length === 0 && stageInserts.length === 0 && stageUpdates.length === 0) throw new Error(`Flow ${flowId} update has no supported changes`);
1489
+
1490
+ // Handle flowVariables insertion
1491
+ const requestedVariables = manifest.flowVariables || manifest.variables || [];
1492
+ const existingVars = beforeDefinition.flowVariables || [];
1493
+ for (const [varIdx, v] of requestedVariables.entries()) {
1494
+ const label = v.label || v.name;
1495
+ const name = (v.name || v.label).toLowerCase().replace(/[^a-z0-9_]/g, '');
1496
+ const rawType = (v.type || 'string').toLowerCase();
1497
+ const TYPE_MAP = {
1498
+ 'string': { type: 'string', label: 'String' },
1499
+ 'boolean': { type: 'boolean', label: 'True/False' },
1500
+ 'true/false': { type: 'boolean', label: 'True/False' },
1501
+ 'bool': { type: 'boolean', label: 'True/False' },
1502
+ 'integer': { type: 'integer', label: 'Integer' },
1503
+ 'int': { type: 'integer', label: 'Integer' },
1504
+ 'decimal': { type: 'decimal', label: 'Decimal' },
1505
+ 'float': { type: 'float', label: 'Floating Point Number' },
1506
+ 'date': { type: 'glide_date', label: 'Date' },
1507
+ 'glide_date': { type: 'glide_date', label: 'Date' },
1508
+ 'date/time': { type: 'glide_date_time', label: 'Date/Time' },
1509
+ 'datetime': { type: 'glide_date_time', label: 'Date/Time' },
1510
+ 'glide_date_time': { type: 'glide_date_time', label: 'Date/Time' },
1511
+ 'reference': { type: 'reference', label: 'Reference' },
1512
+ 'choice': { type: 'choice', label: 'Choice' },
1513
+ 'array.string': { type: 'array.string', label: 'Array.String' },
1514
+ 'array.reference': { type: 'array.reference', label: 'Array.Reference' },
1515
+ 'array.integer': { type: 'array.integer', label: 'Array.Integer' },
1516
+ 'array.boolean': { type: 'array.boolean', label: 'Array.True/False' },
1517
+ 'json': { type: 'json', label: 'JSON' },
1518
+ 'html': { type: 'html', label: 'HTML' }
1519
+ };
1520
+ const mapped = TYPE_MAP[rawType] || { type: rawType, label: v.type_label || (rawType.charAt(0).toUpperCase() + rawType.slice(1)) };
1521
+ const type = mapped.type;
1522
+ const type_label = v.type_label || mapped.label;
1523
+ const varOrder = v.order || (existingVars.length + varIdx + 1);
1524
+ const varUiId = v.uiUniqueIdentifier || idFactory();
1525
+ flowVariableInserts.push({
1526
+ label,
1527
+ name,
1528
+ type,
1529
+ type_label,
1530
+ order: varOrder,
1531
+ mandatory: Boolean(v.mandatory),
1532
+ readonly: Boolean(v.readonly),
1533
+ attributes: `sourceUiUniqueId=,sourceType=,sourceId=,uiUniqueId=${varUiId},`,
1534
+ uiDisplayType: type,
1535
+ uiDisplayTypeLabel: type_label
1536
+ });
1537
+ changes.push({ component: 'flowVariable', input: name, before: null, after: { label, type, order: varOrder } });
1538
+ }
1539
+
1540
+ // Handle flowLogics insertion and update
1541
+ const requestedLogics = manifest.flowLogics || manifest.logic || [];
1542
+ const logicTypeKey = t => String(t || '').toLowerCase().trim();
1543
+ const logicUiMap = new Map(); // order -> uiUniqueIdentifier
1544
+
1545
+ for (const [logicIdx, l] of requestedLogics.entries()) {
1546
+ const lType = logicTypeKey(l.type || l.name);
1547
+ const logicDef = FLOW_LOGIC_DEFINITIONS[lType] || {
1548
+ id: l.definitionId || l.id || '',
1549
+ name: l.name || l.type,
1550
+ type: (l.type || '').toUpperCase(),
1551
+ description: '',
1552
+ compilationClass: '',
1553
+ order: l.order || logicIdx + 1,
1554
+ connectedTo: l.connectedTo || '',
1555
+ attributes: 'allow_children=true,allow_siblings=true,'
1556
+ };
1557
+
1558
+ const uiUniqueIdentifier = l.uiUniqueIdentifier || idFactory();
1559
+ logicUiMap.set(String(l.order), uiUniqueIdentifier);
1560
+ const parentUiId = l.parentUiId || (l.parent ? (logicUiMap.get(String(l.parent)) || l.parent) : '');
1561
+ const connectedTo = l.connectedTo || (l.connectedToOrder ? (logicUiMap.get(String(l.connectedToOrder)) || l.connectedToOrder) : logicDef.connectedTo);
1562
+
1563
+ let resolvedCondition = String(l.condition || '').replace(/\{\{(?:step_)?(\d+)\.([^}]+)\}\}/g, (match, order, field) => {
1564
+ const ui = actionUiMap.get(String(order)) || logicUiMap.get(String(order));
1565
+ return ui ? '{{' + ui + '.' + field + '}}' : match;
1566
+ });
1567
+
1568
+ const inputs = [];
1569
+ collectPills(resolvedCondition, uiUniqueIdentifier, 'condition');
1570
+
1571
+ if (lType === 'if' || lType === 'else if') {
1572
+ inputs.push({
1573
+ name: 'condition_name',
1574
+ value: { schemaless: false, schemalessValue: '', value: l.condition_name || l.conditionName || l.label || '' }
1575
+ });
1576
+ inputs.push({
1577
+ name: 'condition',
1578
+ value: { schemaless: false, schemalessValue: '', value: resolvedCondition }
1579
+ });
1580
+ }
1581
+
1582
+ const flowVarsArray = [];
1583
+ if (lType === 'set flow variables' && l.values) {
1584
+ for (const [varName, varVal] of Object.entries(l.values)) {
1585
+ flowVarsArray.push({
1586
+ id: '',
1587
+ name: varName,
1588
+ children: [],
1589
+ displayValue: { value: '' },
1590
+ value: { schemaless: false, schemalessValue: '', value: String(varVal) }
1591
+ });
1592
+ }
1593
+ }
1594
+
1595
+ flowLogicInserts.push({
1596
+ order: String(l.order || logicIdx + 1),
1597
+ uiUniqueIdentifier,
1598
+ parent: parentUiId,
1599
+ parentUiId,
1600
+ connectedTo,
1601
+ metadata: '{"predicates":[]}',
1602
+ flowSysId: flowId,
1603
+ generationSource: '',
1604
+ definitionId: logicDef.id,
1605
+ type: 'flowlogic',
1606
+ inputs,
1607
+ outputsToAssign: [],
1608
+ ...(flowVarsArray.length ? { flowVariables: flowVarsArray } : {}),
1609
+ flowLogicDefinition: {
1610
+ id: logicDef.id,
1611
+ name: logicDef.name,
1612
+ description: logicDef.description,
1613
+ connectedTo: logicDef.connectedTo,
1614
+ quiescence: 'never',
1615
+ compilationClass: logicDef.compilationClass,
1616
+ order: logicDef.order,
1617
+ type: logicDef.type,
1618
+ visible: true,
1619
+ attributes: logicDef.attributes,
1620
+ userCanRead: true,
1621
+ category: '',
1622
+ inputs: [],
1623
+ variables: '[]'
1624
+ }
1625
+ });
1626
+
1627
+ changes.push({ component: 'flowLogic', order: l.order, type: logicDef.name, input: 'insert', before: null, after: { parent: parentUiId, connectedTo } });
1628
+ }
1629
+
1630
+ // Handle deletions by step order or uiUniqueIdentifier
1631
+ const rawDeletes = manifest.deleteSteps || manifest.delete || manifest.deleteOrders || [];
1632
+ const deleteTargets = new Set((Array.isArray(rawDeletes) ? rawDeletes : [rawDeletes]).map(String));
1633
+ if (deleteTargets.size > 0) {
1634
+ const existingLogics = beforeDefinition.flowLogicInstances || beforeDefinition.flowLogics || [];
1635
+ for (const a of existingActions) {
1636
+ const uiId = stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier);
1637
+ const targetId = stringValue(a.sysId || a.id || a.sys_id || uiId);
1638
+ if (deleteTargets.has(String(a.order)) || deleteTargets.has(uiId) || deleteTargets.has(targetId)) {
1639
+ actionDeletes.push(targetId);
1640
+ changes.push({ component: 'action', order: a.order, type: a.name, input: 'delete', before: targetId, after: null });
1641
+ }
1642
+ }
1643
+ for (const fl of existingLogics) {
1644
+ const uiId = stringValue(fl.uiUniqueIdentifier || fl.ui_unique_identifier);
1645
+ const targetId = stringValue(fl.sysId || fl.id || fl.sys_id || uiId);
1646
+ if (deleteTargets.has(String(fl.order)) || deleteTargets.has(uiId) || deleteTargets.has(targetId)) {
1647
+ flowLogicDeletes.push(targetId);
1648
+ changes.push({ component: 'flowLogic', order: fl.order, type: fl.name, input: 'delete', before: targetId, after: null });
1649
+ }
1650
+ }
1651
+ }
1652
+ // Register every referenced pill so the canvas can draw it. Runs after every
1653
+ // collection point (actions and logic blocks) so no reference is missed.
1654
+ // Existing entries keep their label/type; a pill this flow has never seen gets
1655
+ // a label resolved from its producing step.
1656
+ const labelCacheInserts = [];
1657
+ const existingLabelCache = readLabelCache(beforeDefinition);
1658
+ const labelCacheEntry = ({ name, label, type, baseType, usedInstances }) => {
1659
+ // The provider stores usedInstances as a map, but a map key is a UUID and an
1660
+ // unquoted UUID key is not valid GraphQL. Send the array form it accepts.
1661
+ const instances = Object.entries(usedInstances || {}).flatMap(([uiUniqueIdentifier, inputNames]) =>
1662
+ (Array.isArray(inputNames) ? inputNames : [inputNames]).map(inputName => ({ uiUniqueIdentifier, inputName })));
1663
+ const entry = { name, usedInstances: instances };
1664
+ if (label) entry.label = label;
1665
+ if (type) entry.type = type;
1666
+ if (baseType) entry.base_type = baseType;
1667
+ return entry;
1668
+ };
1669
+ const mergeUsedInstances = (existing, instances) => {
1670
+ const merged = { ...(existing || {}) };
1671
+ for (const { uiUniqueIdentifier, inputName } of instances) {
1672
+ if (!merged[uiUniqueIdentifier]) merged[uiUniqueIdentifier] = [];
1673
+ if (!merged[uiUniqueIdentifier].includes(inputName)) merged[uiUniqueIdentifier].push(inputName);
1674
+ }
1675
+ return merged;
1676
+ };
1677
+ for (const [pillName, instances] of pillToInstances.entries()) {
1678
+ const existing = existingLabelCache.find(entry => entry.name === pillName);
1679
+ const usedInstances = mergeUsedInstances(existing?.usedInstances, instances);
1680
+ // An entry with no caption draws nothing, so a missing label is repaired
1681
+ // rather than passed through; a missing type is filled in when resolvable.
1682
+ let binding = null;
1683
+ if (!existing?.label) {
1684
+ binding = resolvePillBinding(beforeDefinition, pillName, flowId, existingLabelCache, pendingSteps);
1685
+ } else if (!existing.type) {
1686
+ try { binding = resolvePillBinding(beforeDefinition, pillName, flowId, existingLabelCache, pendingSteps); } catch { binding = null; }
1687
+ }
1688
+ if (existing) {
1689
+ labelCacheUpdates.push(labelCacheEntry({
1690
+ ...existing,
1691
+ label: existing.label || binding.label,
1692
+ type: existing.type || binding.type,
1693
+ baseType: existing.baseType || binding.type,
1694
+ usedInstances,
1695
+ }));
1696
+ } else {
1697
+ labelCacheInserts.push(labelCacheEntry({ name: pillName, label: binding.label, type: binding.type, baseType: binding.type, usedInstances }));
1698
+ }
1699
+ }
1700
+ 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`);
1258
1701
  if (options.preview) return {
1259
1702
  preview: true,
1260
1703
  flow: { id: flowId, name: target.flowName, status: lifecycle.status, active: lifecycle.active },
@@ -1281,9 +1724,10 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1281
1724
  const outcome = await withFlowSafeEdit(sdk, instance, flowId, beforeDefinition.updated, async () => {
1282
1725
  let completedStage = 'validated';
1283
1726
  try {
1727
+ const patchQuery = buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates, actionInserts, actionDeletes, flowVariableInserts, flowLogicInserts, flowLogicUpdates, flowLogicDeletes, labelCacheUpdates, labelCacheInserts, stageInserts, stageUpdates });
1284
1728
  const patchResponse = await mutationContext('trigger_and_actions_update', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1285
1729
  method: 'POST',
1286
- body: JSON.stringify({ query: buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates, stageInserts, stageUpdates }), variables: {} }),
1730
+ body: JSON.stringify({ query: patchQuery, variables: {} }),
1287
1731
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1288
1732
  assertGraphQLSuccess(patchResponse, 'Flow trigger/action update');
1289
1733
  completedStage = 'patch_acknowledged';
@@ -1291,7 +1735,10 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1291
1735
  // Only requested values may differ. Preserve array order and opaque fields.
1292
1736
  // `stages` is compared separately below: a stage edit may touch specific
1293
1737
  // fields, while every stage the manifest did not name must stay identical.
1294
- for (const field of ['flowVariables', 'flowLogicInstances', 'subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs']) {
1738
+ const checkFields = ['subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs'];
1739
+ if (flowVariableInserts.length === 0) checkFields.push('flowVariables');
1740
+ if (flowLogicInserts.length === 0 && flowLogicUpdates.length === 0 && flowLogicDeletes.length === 0) checkFields.push('flowLogicInstances');
1741
+ for (const field of checkFields) {
1295
1742
  if (!isDeepStrictEqual(beforeDefinition[field], processflow[field])) throw new Error(`Flow ${flowId} changed omitted ${field}; preservation failed`);
1296
1743
  }
1297
1744
  if (stageInserts.length || stageUpdates.length) {
@@ -1309,13 +1756,31 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1309
1756
  throw new Error(`Flow ${flowId} changed omitted stages; preservation failed`);
1310
1757
  }
1311
1758
  if (!triggerUpdate && !isDeepStrictEqual(beforeDefinition.triggerInstances, processflow.triggerInstances)) throw new Error(`Flow ${flowId} changed omitted triggerInstances`);
1312
- const maskActions = definition => findExistingActions(definition).map(action => {
1313
- const copy = clone(action);
1314
- const changed = changedActionInputs.get(stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier));
1315
- for (const [index, input] of inputList(copy).entries()) if (changed?.has(input.name)) inputList(copy)[index] = maskInputValue(input);
1316
- return copy;
1317
- });
1318
- if (!isDeepStrictEqual(maskActions(beforeDefinition), maskActions(processflow))) throw new Error(`Flow ${flowId} changed omitted action fields; preservation failed`);
1759
+ const insertedUiIds = new Set(actionInserts.map(a => a.uiUniqueIdentifier));
1760
+ const deletedActionIds = new Set(actionDeletes);
1761
+ const maskActions = (definition, isAfter = false) => findExistingActions(definition)
1762
+ .filter(action => {
1763
+ const uiId = stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier);
1764
+ const sId = stringValue(action.sysId || action.id || action.sys_id);
1765
+ if (isAfter && insertedUiIds.has(uiId)) return false;
1766
+ if (!isAfter && (deletedActionIds.has(uiId) || deletedActionIds.has(sId))) return false;
1767
+ return true;
1768
+ })
1769
+ .map(action => {
1770
+ const copy = clone(action);
1771
+ const changed = changedActionInputs.get(stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier));
1772
+ for (const [index, input] of inputList(copy).entries()) if (changed?.has(input.name)) inputList(copy)[index] = maskInputValue(input);
1773
+ return copy;
1774
+ });
1775
+ if (!isDeepStrictEqual(maskActions(beforeDefinition), maskActions(processflow, true))) throw new Error(`Flow ${flowId} changed omitted action fields; preservation failed`);
1776
+ // A pill the provider accepted but did not store still renders blank, so
1777
+ // read the cache back instead of trusting the mutation acknowledgement.
1778
+ const readbackCache = readLabelCache(processflow);
1779
+ for (const entry of [...labelCacheInserts, ...labelCacheUpdates]) {
1780
+ const saved = readbackCache.find(candidate => candidate.name === entry.name);
1781
+ if (!saved) throw new Error(`Flow ${flowId} did not persist data pill ${entry.name} to label_cache; the reference would render blank`);
1782
+ if (!saved.label) throw new Error(`Flow ${flowId} persisted data pill ${entry.name} without a label; the reference would render blank`);
1783
+ }
1319
1784
  const readbackTrigger = findArray(processflow, 'triggerInstances')[0];
1320
1785
  if (triggerUpdate) {
1321
1786
  if (!readbackTrigger || findId(readbackTrigger, ['sysId', 'sys_id', 'id', 'triggerId']) !== triggerUpdate.id) throw new Error(`Flow ${flowId} trigger update was not readable after mutation`);