@jacebenson/jsn 5.5.1 → 5.5.2-dev.173.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 (51) hide show
  1. package/README.md +30 -2
  2. package/package.json +1 -1
  3. package/src/app.js +15 -2
  4. package/src/auth/mfa.js +85 -0
  5. package/src/cli-adapter.js +18 -4
  6. package/src/cli.js +26 -8
  7. package/src/commands/_generic.js +10 -2
  8. package/src/commands/_ticket.js +12 -4
  9. package/src/commands/approvals.js +1 -0
  10. package/src/commands/auth.js +15 -8
  11. package/src/commands/cases.js +1 -1
  12. package/src/commands/cmdb.js +1 -1
  13. package/src/commands/discover.js +1 -0
  14. package/src/commands/docs/client.js +17 -7
  15. package/src/commands/docs/community.js +4 -4
  16. package/src/commands/docs/db.js +26 -11
  17. package/src/commands/docs/docs.js +30 -13
  18. package/src/commands/docs/embed.js +2 -2
  19. package/src/commands/docs/index-worker.js +1 -1
  20. package/src/commands/docs/index.js +4 -3
  21. package/src/commands/docs/ingest.js +4 -4
  22. package/src/commands/docs/install.js +19 -17
  23. package/src/commands/docs/local.js +6 -4
  24. package/src/commands/docs/refresh.js +3 -3
  25. package/src/commands/docs/releases.js +27 -0
  26. package/src/commands/docs/search.js +3 -3
  27. package/src/commands/docs/serve.js +3 -3
  28. package/src/commands/docs/server.js +13 -10
  29. package/src/commands/docs/service-snapshot.js +3 -3
  30. package/src/commands/docs/snapshot.js +32 -11
  31. package/src/commands/docs/sync-service.js +8 -6
  32. package/src/commands/docs/sync.js +24 -15
  33. package/src/commands/flows.js +70 -5
  34. package/src/commands/knowledge.js +1 -0
  35. package/src/commands/records.js +12 -3
  36. package/src/commands/setup.js +20 -8
  37. package/src/commands/tickets.js +11 -3
  38. package/src/errors.js +23 -1
  39. package/src/flow-create.js +1237 -57
  40. package/src/flow-inspection.js +26 -2
  41. package/src/help.js +95 -21
  42. package/src/helpers.js +20 -1
  43. package/src/output.js +19 -5
  44. package/src/prompts.js +9 -0
  45. package/src/record-command-profiles.js +8 -4
  46. package/src/record-profiles.js +1 -0
  47. package/src/records-engine.js +2 -1
  48. package/src/sdk.js +157 -15
  49. package/src/setup-preferences.js +3 -3
  50. package/src/table-read-params.js +9 -0
  51. package/src/welcome.js +34 -36
@@ -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', 'subflows', 'flow variables'];
32
32
 
33
33
  function supportedLifecycle(published) {
34
34
  return published
@@ -155,11 +155,13 @@ export function validateFlowManifest(manifest) {
155
155
  if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('Flow manifest must be a JSON object');
156
156
  if (!String(manifest.name || '').trim()) throw new Error('Flow manifest requires name');
157
157
  if (!String(manifest.scope || '').trim()) throw new Error('Flow manifest requires scope');
158
- if (manifest.logic !== undefined) throw new Error('Flow Logic is unsupported in this creation slice');
158
+ validateLogicManifest(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
- 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
+ if (manifest.stageTemplate !== undefined && !String(manifest.stageTemplate).trim()) throw new Error('Flow manifest stageTemplate must not be empty');
164
+ if (manifest.stageSet !== undefined && !String(manifest.stageSet).trim()) throw new Error('Flow manifest stageSet must not be empty');
163
165
  const trigger = manifest.trigger;
164
166
  if (!trigger || typeof trigger !== 'object' || Array.isArray(trigger)) throw new Error('Flow manifest requires a trigger object');
165
167
  for (const key of Object.keys(trigger)) if (!['type', 'table', 'condition', 'inputs'].includes(key)) throw new Error(`Flow manifest trigger field "${key}" is unsupported`);
@@ -173,6 +175,8 @@ export function validateFlowManifest(manifest) {
173
175
  if (!Array.isArray(manifest.actions)) throw new Error('Flow manifest requires an actions array');
174
176
  for (const [index, action] of manifest.actions.entries()) {
175
177
  if (!action || typeof action !== 'object' || !String(action.type || '').trim()) throw new Error(`Action ${index + 1} requires type`);
178
+ for (const key of Object.keys(action)) if (!['type', 'inputs', 'order', 'parent', 'parentOrder', 'parentUiId'].includes(key)) throw new Error(`Unsupported action field ${key}`);
179
+ if (action.order !== undefined && (!Number.isInteger(action.order) || action.order < 1)) throw new Error('Action order must be a positive integer');
176
180
  if (action.inputs !== undefined && (!action.inputs || typeof action.inputs !== 'object' || Array.isArray(action.inputs))) throw new Error(`Action ${index + 1} inputs must be an object`);
177
181
  }
178
182
  return manifest;
@@ -243,6 +247,95 @@ function stageValueFromLabel(label) {
243
247
  * `stageId` is only meaningful for updates: an entry without one inserts a new
244
248
  * stage, an entry with one edits the stage it names.
245
249
  */
250
+
251
+ export async function resolveStageTemplate(sdk, templateIdentifier) {
252
+ const ident = String(templateIdentifier || "").trim();
253
+ if (!ident) throw new Error('Stage template identifier must not be empty');
254
+ // The identifier is embedded in an encoded query, so a separator character
255
+ // would silently change which records match.
256
+ if (/[\^=\n\r]/.test(ident)) throw new Error(`Stage template "${ident}" contains a query separator (^ or =); pass a plain name or sys_id`);
257
+ // 1. Check if ident matches a stage_set sys_id or name
258
+ let setId = "";
259
+ if (/^[0-9a-fA-F]{32}$/.test(ident)) {
260
+ setId = ident;
261
+ } else {
262
+ // Resolve by table first, then by stage set name. Provider failures must
263
+ // surface: a swallowed 401 would read as "template not found".
264
+ const tableMatches = await sdk.list("stage_set_table", new URLSearchParams({
265
+ sysparm_query: `table=${ident}^ORset.nameLIKE${ident}`,
266
+ sysparm_limit: "1"
267
+ }));
268
+ if (tableMatches.length && tableMatches[0].set) {
269
+ setId = typeof tableMatches[0].set === "object" ? tableMatches[0].set.value : tableMatches[0].set;
270
+ } else {
271
+ const setMatches = await sdk.list("stage_set", new URLSearchParams({
272
+ sysparm_query: `nameLIKE${ident}`,
273
+ sysparm_limit: "1"
274
+ }));
275
+ if (setMatches.length) setId = setMatches[0].sys_id;
276
+ }
277
+ }
278
+ if (!setId) throw new Error(`Stage template "${ident}" not found in stage_set or stage_set_table`);
279
+
280
+ // 2. Fetch stage_set_entry records for setId
281
+ const entries = await sdk.list("stage_set_entry", new URLSearchParams({
282
+ sysparm_query: `set=${setId}`,
283
+ sysparm_display_value: "all"
284
+ }));
285
+ if (!entries.length) throw new Error(`No stage entries found for stage template "${ident}" (${setId})`);
286
+
287
+ // Sort: Request Cancelled & Completed system stages, or order-based
288
+ const mapped = entries.map(e => {
289
+ const label = e.name?.display_value || e.name?.value || e.name || "";
290
+ const value = e.value?.display_value || e.value?.value || e.value || stageValueFromLabel(label);
291
+ const duration = e.ola?.value || e.ola?.display_value || STAGE_DURATION;
292
+ // `order` comes back display-formatted ("1,000"), so parseInt alone reads 1.
293
+ const rawOrder = String(e.order?.value ?? e.order ?? "0").replace(/[^0-9-]/g, "");
294
+ const orderNum = Number.isFinite(parseInt(rawOrder, 10)) ? parseInt(rawOrder, 10) : 0;
295
+ return {
296
+ label,
297
+ value,
298
+ duration,
299
+ rawOrder: orderNum,
300
+ system: (label === "Request Cancelled" || label === "Completed" || value === "complete" || value === "Request Cancelled")
301
+ };
302
+ });
303
+
304
+ // Flow Designer sorts Request Cancelled (order 0, system: true), Completed (order 1, system: true), then non-system stages by rawOrder
305
+ const systemStages = mapped.filter(s => s.system).sort((a, b) => {
306
+ if (a.value === "Request Cancelled" || a.label === "Request Cancelled") return -1;
307
+ if (b.value === "Request Cancelled" || b.label === "Request Cancelled") return 1;
308
+ return a.rawOrder - b.rawOrder;
309
+ });
310
+ const normalStages = mapped.filter(s => !s.system).sort((a, b) => a.rawOrder - b.rawOrder);
311
+
312
+ const finalStages = [...systemStages, ...normalStages].map((s, idx) => ({
313
+ label: s.label,
314
+ value: s.value,
315
+ duration: s.duration,
316
+ order: idx,
317
+ system: s.system,
318
+ alwaysShow: true,
319
+ componentIndexes: []
320
+ }));
321
+
322
+ return finalStages;
323
+ }
324
+
325
+ export function validateErrorHandling(eh) {
326
+ if (eh === null || typeof eh !== 'object' || Array.isArray(eh)) throw new Error('Flow errorHandling must be an object');
327
+ for (const key of Object.keys(eh)) if (key !== 'actions') throw new Error(`Unsupported errorHandling field ${key}`);
328
+ if (eh.actions !== undefined) {
329
+ if (!Array.isArray(eh.actions)) throw new Error('Flow errorHandling.actions must be an array');
330
+ for (const [index, action] of eh.actions.entries()) {
331
+ if (!action || typeof action !== 'object' || Array.isArray(action)) throw new Error(`Error action ${index + 1} must be an object`);
332
+ if (typeof action.type !== 'string' || !action.type.trim()) throw new Error(`Error action ${index + 1} requires type`);
333
+ 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`);
334
+ 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`);
335
+ }
336
+ }
337
+ }
338
+
246
339
  export function validateStages(stages, { update = false } = {}) {
247
340
  if (!Array.isArray(stages)) throw new Error('Flow stages must be an array');
248
341
  for (const [index, stage] of stages.entries()) {
@@ -351,7 +444,7 @@ export async function readCatalogItemVariables(sdk, instance, flowId, catalogIte
351
444
  };
352
445
  }
353
446
 
354
- export function buildFlowPatchMutation({ flowId, trigger, actions }) {
447
+ export function buildFlowPatchMutation({ flowId, trigger, actions, flowLogicInserts = [], labelCacheInserts = [] }) {
355
448
  const triggerInsert = {
356
449
  flowSysId: trigger.flowSysId,
357
450
  name: trigger.name,
@@ -373,23 +466,142 @@ export function buildFlowPatchMutation({ flowId, trigger, actions }) {
373
466
  metadata: action.metadata,
374
467
  inputs: action.inputs,
375
468
  }));
376
- const patch = `flowPatch: {flowId: ${gqlString(flowId)}, triggerInstances: {insert: [${gqlInputObject(triggerInsert)}]}, actions: {insert: [${actionInsert.map(gqlInputObject).join(', ')}]}}`;
469
+ const extra = `${flowLogicInserts.length ? `, flowLogics: {insert: [${flowLogicInserts.map(gqlInputObject).join(', ')}]}` : ''}${labelCacheInserts.length ? `, labelCache: {insert: [${labelCacheInserts.map(gqlInputObject).join(', ')}]}` : ''}`;
470
+ const patch = `flowPatch: {flowId: ${gqlString(flowId)}, triggerInstances: {insert: [${gqlInputObject(triggerInsert)}]}, actions: {insert: [${actionInsert.map(gqlInputObject).join(', ')}]}${extra}}`;
377
471
  // `triggerInstances.updates` is a leaf [String] on this schema; only `inserts`
378
472
  // carries identities, and only for triggers does `inserts` lack a uiUniqueIdentifier.
379
- return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { inserts { sysId } updates } actions { inserts { sysId uiUniqueIdentifier } } } } } }`;
380
- }
473
+ return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { inserts { sysId } updates } actions { inserts { sysId uiUniqueIdentifier } } ${flowLogicInserts.length ? 'flowLogics { inserts { sysId uiUniqueIdentifier } }' : ''} } } } }`;
474
+ }
475
+
476
+
477
+ const FLOW_LOGIC_DEFINITIONS = {
478
+ 'top level try': {
479
+ id: 'e9060aa2c3013010ace8b740ad40dd51',
480
+ name: 'Top Level Try',
481
+ type: 'TOP_LEVEL_TRY',
482
+ description: 'Begin a top level try block',
483
+ compilationClass: 'com.glide.flow.compiler.logic_block.TryCompiler',
484
+ order: 18,
485
+ connectedTo: '',
486
+ attributes: 'allow_siblings=true,draw_curve=true,line_type=q_curve,visible_in_picker=false,visible_in_ui=false,',
487
+ },
488
+ 'top level catch': {
489
+ id: '35d60003e6022010a5e40cdd1254dd23',
490
+ name: 'Top Level Catch',
491
+ type: 'TOP_LEVEL_CATCH',
492
+ description: 'Catch and handle an error',
493
+ compilationClass: 'com.glide.flow.compiler.logic_block.CatchCompiler',
494
+ order: 17,
495
+ connectedTo: '07223332de022010ec58424b73829721,e9060aa2c3013010ace8b740ad40dd51',
496
+ attributes: 'allow_siblings=true,draw_curve=true,line_type=q_curve,visible_in_picker=false,visible_in_ui=false,',
497
+ },
498
+ 'try': {
499
+ id: '07223332de022010ec58424b73829721',
500
+ name: 'Try',
501
+ type: 'TRY',
502
+ description: 'Allow a flow to continue running when an error occurs within a flow logic block. Run a sequence of actions in response to errors within the flow logic block',
503
+ compilationClass: 'com.glide.flow.compiler.logic_block.TryCompiler',
504
+ order: 15,
505
+ connectedTo: '',
506
+ attributes: 'allow_siblings=true,disable_opening=true,draw_curve=true,icon_class=try,line_type=cc_curve,visible_in_picker=true,',
507
+ },
508
+ 'catch': {
509
+ id: '35d60003e6022010a5e40cdd1254dd21',
510
+ name: 'Catch',
511
+ type: 'CATCH',
512
+ description: 'Catch and handle an error',
513
+ compilationClass: 'com.glide.flow.compiler.logic_block.CatchCompiler',
514
+ order: 16,
515
+ connectedTo: '07223332de022010ec58424b73829721',
516
+ attributes: 'allow_siblings=true,disable_opening=true,draw_curve=true,icon_class=catch,line_type=q_curve,visible_in_picker=false,',
517
+ },
518
+ 'if': {
519
+ id: 'af4e1945c3e232002841b63b12d3ae3e',
520
+ name: 'If',
521
+ type: 'IF',
522
+ description: 'Selectively apply one or more actions only when a list of conditions is met.',
523
+ compilationClass: 'com.glide.flow.compiler.logic_block.IfCompiler',
524
+ order: 1,
525
+ connectedTo: '',
526
+ attributes: 'allow_children=true,allow_siblings=true,icon_class=diamond-if-icon,line_type=q_if_curve,pills_draggable_outside_block=false,',
527
+ },
528
+ 'else if': {
529
+ id: '666e5545c3e232002841b63b12d3ae99',
530
+ name: 'Else If',
531
+ type: 'ELSEIF',
532
+ description: 'Selectively apply one or more actions only when a list of conditions is met.',
533
+ compilationClass: 'com.glide.flow.compiler.logic_block.ElseIfCompiler',
534
+ order: 2,
535
+ connectedTo: 'af4e1945c3e232002841b63b12d3ae3e,666e5545c3e232002841b63b12d3ae99',
536
+ attributes: 'allow_children=true,allow_siblings=true,icon_class=elseif-icon,line_type=q_if_curve,pills_draggable_outside_block=false,',
537
+ },
538
+ 'else': {
539
+ id: '1f781bf3c32232002841b63b12d3aee6',
540
+ name: 'Else',
541
+ type: 'ELSE',
542
+ description: 'Else statement',
543
+ compilationClass: 'com.glide.flow.compiler.logic_block.ElseCompiler',
544
+ order: 3,
545
+ connectedTo: '666e5545c3e232002841b63b12d3ae99,af4e1945c3e232002841b63b12d3ae3e',
546
+ attributes: 'allow_children=true,allow_siblings=true,disable_opening=true,icon_class=else-icon,line_type=q_if_curve,pills_draggable_outside_block=false,',
547
+ },
548
+ 'set flow variables': {
549
+ id: '4f787d1e0f9b0010ecf0cc52ff767ea0',
550
+ name: 'Set Flow Variables',
551
+ type: 'SETFLOWVARIABLES',
552
+ description: "Assign a value to one or more flow variables. Change or update a variable's value during a flow.",
553
+ compilationClass: 'com.glide.flow.compiler.logic_block.SetVariablesCompiler',
554
+ order: 14,
555
+ connectedTo: '',
556
+ attributes: 'allow_children=false,allow_siblings=true,',
557
+ },
558
+ 'end flow': {
559
+ id: 'd176605ea76103004f27b0d2187901c7',
560
+ name: 'End Flow',
561
+ type: 'END',
562
+ description: 'Use this flow logic to stop a flow within flow designer.',
563
+ compilationClass: 'com.glide.flow.compiler.logic_block.EndCompiler',
564
+ order: 10,
565
+ connectedTo: '',
566
+ attributes: 'allow_children=false,allow_siblings=false,disable_opening=true,',
567
+ }
568
+ };
381
569
 
382
- export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [], stageInserts = [], stageUpdates = [] }) {
570
+ export function buildFlowUpdateMutation({ flowId, triggerUpdates = [], actionUpdates = [], actionInserts = [], actionDeletes = [], flowVariableInserts = [], flowLogicInserts = [], flowLogicUpdates = [], flowLogicDeletes = [], labelCacheUpdates = [], labelCacheInserts = [], stageInserts = [], stageUpdates = [] }) {
383
571
  const updates = [];
384
572
  if (triggerUpdates.length) updates.push(`triggerInstances: {update: [${triggerUpdates.map(gqlInputObject).join(', ')}]}`);
385
- if (actionUpdates.length) updates.push(`actions: {update: [${actionUpdates.map(gqlInputObject).join(', ')}]}`);
573
+ const actionParts = [];
574
+ if (actionInserts.length) actionParts.push(`insert: [${actionInserts.map(gqlInputObject).join(', ')}]`);
575
+ if (actionUpdates.length) actionParts.push(`update: [${actionUpdates.map(gqlInputObject).join(', ')}]`);
576
+ if (actionDeletes.length) actionParts.push(`delete: [${actionDeletes.map(id => gqlString(id)).join(', ')}]`);
577
+ if (actionParts.length) updates.push(`actions: {${actionParts.join(', ')}}`);
578
+ if (flowVariableInserts.length) updates.push(`flowVariables: {insert: [${flowVariableInserts.map(gqlInputObject).join(', ')}]}`);
579
+ const logicParts = [];
580
+ if (flowLogicInserts.length) logicParts.push(`insert: [${flowLogicInserts.map(gqlInputObject).join(', ')}]`);
581
+ if (flowLogicUpdates.length) logicParts.push(`update: [${flowLogicUpdates.map(gqlInputObject).join(', ')}]`);
582
+ if (flowLogicDeletes.length) logicParts.push(`delete: [${flowLogicDeletes.map(id => gqlString(id)).join(', ')}]`);
583
+ if (logicParts.length) updates.push(`flowLogics: {${logicParts.join(', ')}}`);
584
+ const labelParts = [];
585
+ if (labelCacheInserts.length) labelParts.push(`insert: [${labelCacheInserts.map(gqlInputObject).join(', ')}]`);
586
+ if (labelCacheUpdates.length) labelParts.push(`update: [${labelCacheUpdates.map(gqlInputObject).join(', ')}]`);
587
+ if (labelParts.length) updates.push(`labelCache: {${labelParts.join(', ')}}`);
386
588
  const stageParts = [];
387
- if (stageInserts.length) stageParts.push(`insert: [${stageInserts.map(gqlInputObject).join(', ')}]`);
589
+ if (stageInserts.length) stageParts.push(`insert: [${stageInserts.map(s => {
590
+ const copy = { ...s };
591
+ delete copy.system;
592
+ return gqlInputObject(copy);
593
+ }).join(', ')}]`);
388
594
  if (stageUpdates.length) stageParts.push(`update: [${stageUpdates.map(gqlInputObject).join(', ')}]`);
389
595
  if (stageParts.length) updates.push(`stages: {${stageParts.join(', ')}}`);
390
596
  if (!updates.length) throw new Error('Flow update mutation requires at least one change');
391
597
  const patch = `flowPatch: {flowId: ${gqlString(flowId)}, ${updates.join(', ')}}`;
392
- return `mutation { global { snFlowDesigner { flow(${patch}) { triggerInstances { updates } actions { updates } stages { inserts { sysId } } } } } }`;
598
+ const returnFields = ['triggerInstances { updates }'];
599
+ if (actionInserts.length) returnFields.push('actions { inserts { sysId uiUniqueIdentifier } updates }');
600
+ else returnFields.push('actions { updates }');
601
+ if (flowLogicInserts.length) returnFields.push('flowLogics { inserts { sysId uiUniqueIdentifier } }');
602
+ if (flowVariableInserts.length) returnFields.push('flowVariables { inserts { sysId uiUniqueIdentifier } }');
603
+ returnFields.push('stages { inserts { sysId } }');
604
+ return `mutation { global { snFlowDesigner { flow(${patch}) { ${returnFields.join(' ')} } } } }`;
393
605
  }
394
606
 
395
607
  export async function readProcessFlow(sdk, instance, flowId, scope) {
@@ -610,7 +822,7 @@ function verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigg
610
822
  if (savedInputs.length !== expected.inputs.length) throw new Error(`Created Action ${expected.uiUniqueIdentifier} input count did not match the installed schema`);
611
823
  for (const expectedInput of expected.inputs) {
612
824
  const actualInput = savedInputs.find(input => input.name === expectedInput.name);
613
- if (!actualInput || inputRawValue(actualInput) !== inputRawValue(expectedInput)) throw new Error(`Created Action ${expected.uiUniqueIdentifier} input ${expectedInput.name} did not match the requested value`);
825
+ if (!actualInput || !isDeepStrictEqual(inputRawValue(actualInput), inputRawValue(expectedInput))) throw new Error(`Created Action ${expected.uiUniqueIdentifier} input ${expectedInput.name} did not match the requested value`);
614
826
  }
615
827
  }
616
828
  }
@@ -733,10 +945,37 @@ async function resolveExistingAction(sdk, actions, requested, index) {
733
945
  return matches[0];
734
946
  }
735
947
 
948
+ function validateLogicManifest(manifest) {
949
+ if (manifest.logic !== undefined && manifest.flowLogics !== undefined) throw new Error('Specify logic or flowLogics, not both');
950
+ const logics = manifest.logic ?? manifest.flowLogics;
951
+ if (logics === undefined) return;
952
+ if (!Array.isArray(logics)) throw new Error('Flow logic must be an array');
953
+ const orders = new Set();
954
+ for (const l of logics) {
955
+ if (!l || typeof l !== 'object' || Array.isArray(l)) throw new Error('Flow logic must be an object');
956
+ for (const key of Object.keys(l)) if (!['order', 'type', 'name', 'parent', 'parentOrder', 'parentUiId', 'connectedTo', 'connectedToOrder', 'condition', 'condition_name', 'conditionName', 'label', 'values'].includes(key)) throw new Error(`Unsupported logic field ${key}; caller identities are not accepted`);
957
+ if (!Number.isInteger(l.order) || l.order < 1 || orders.has(l.order)) throw new Error('Logic order must be a unique positive integer');
958
+ orders.add(l.order);
959
+ if (l.type !== undefined && l.name !== undefined && String(l.type).toLowerCase().trim() !== String(l.name).toLowerCase().trim()) throw new Error('Conflicting logic type/name aliases');
960
+ if (!FLOW_LOGIC_DEFINITIONS[String(l.type || l.name || '').toLowerCase().trim()]) throw new Error('Unsupported flow logic type');
961
+ const logicType = String(l.type || l.name).toLowerCase().trim();
962
+ const labels = ['condition_name', 'conditionName', 'label'].filter(k => l[k] !== undefined);
963
+ if (labels.some(k => typeof l[k] !== 'string') || new Set(labels.map(k => l[k])).size > 1) throw new Error('Conflicting or malformed condition label aliases');
964
+ if (![ 'if', 'else if' ].includes(logicType) && (l.condition !== undefined || labels.length)) throw new Error('Condition fields are supported only on If and Else If');
965
+ if (l.values !== undefined && logicType !== 'set flow variables') throw new Error('Assignment values are supported only on Set Flow Variables');
966
+ if (l.values && Object.values(l.values).some(v => typeof v !== 'string')) throw new Error('Assignment values must be strings (literal or supported pill reference)');
967
+ if ((manifest.errorHandling !== undefined || manifest.errorHandler !== undefined) && ['top level try', 'top level catch'].includes(logicType)) throw new Error('Explicit top-level error blocks conflict with errorHandling');
968
+ if (l.condition !== undefined && typeof l.condition !== 'string') throw new Error('Logic condition must be a string');
969
+ if (l.values !== undefined && (!l.values || typeof l.values !== 'object' || Array.isArray(l.values))) throw new Error('Logic values must be an object');
970
+ for (const key of ['parent', 'parentOrder', 'parentUiId', 'connectedTo', 'connectedToOrder']) if (l[key] !== undefined && !((typeof l[key] === 'string' && l[key].trim()) || (Number.isInteger(l[key]) && l[key] > 0))) throw new Error(`Malformed logic ${key}`);
971
+ }
972
+ }
973
+
736
974
  export function validateFlowUpdateManifest(manifest) {
737
975
  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`);
976
+ const allowed = new Set(['scope', 'trigger', 'actions', 'stages', 'stageTemplate', 'stageSet', 'flowVariables', 'variables', 'flowLogics', 'logic', 'deleteSteps', 'delete', 'deleteOrders', 'errorHandling', 'errorHandler']);
977
+ 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`);
978
+ validateLogicManifest(manifest);
740
979
  if (manifest.scope !== undefined && !String(manifest.scope).trim()) throw new Error('Flow update scope must not be empty');
741
980
  if (manifest.trigger !== undefined) {
742
981
  if (!manifest.trigger || typeof manifest.trigger !== 'object' || Array.isArray(manifest.trigger)) throw new Error('Flow update trigger must be an object');
@@ -751,14 +990,28 @@ export function validateFlowUpdateManifest(manifest) {
751
990
  if (!Array.isArray(manifest.actions)) throw new Error('Flow update actions must be an array');
752
991
  for (const [index, action] of manifest.actions.entries()) {
753
992
  if (!action || typeof action !== 'object' || Array.isArray(action)) throw new Error(`Update action ${index + 1} must be an object`);
754
- for (const key of Object.keys(action)) if (!['order', 'type', 'inputs'].includes(key)) throw new Error(`Update action ${index + 1} field "${key}" is unsupported; caller-supplied identities are not accepted`);
993
+ for (const key of Object.keys(action)) if (!['order', 'type', 'inputs', 'parent', 'parentOrder', 'parentUiId'].includes(key)) throw new Error(`Update action ${index + 1} field "${key}" is unsupported; caller-supplied identities are not accepted`);
994
+ for (const key of ['parent', 'parentOrder', 'parentUiId']) if (action[key] !== undefined && !((typeof action[key] === 'string' && action[key].trim()) || (Number.isInteger(action[key]) && action[key] > 0))) throw new Error(`Malformed action ${key}`);
755
995
  if (!Number.isInteger(action.order) || action.order < 1 || !String(action.type || '').trim()) throw new Error(`Update action ${index + 1} requires a positive integer order and type`);
756
996
  if (!action.inputs || typeof action.inputs !== 'object' || Array.isArray(action.inputs)) throw new Error(`Update action ${index + 1} inputs must be an object`);
757
997
  if (Object.keys(action.inputs).length === 0) throw new Error(`Update action ${index + 1} inputs must contain at least one changed value`);
758
998
  }
759
999
  }
760
- if (manifest.trigger === undefined && manifest.actions === undefined && manifest.stages === undefined) throw new Error('Flow update manifest must specify trigger, actions and/or stages');
1000
+ 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');
761
1001
  if (manifest.stages !== undefined) validateStages(manifest.stages, { update: true });
1002
+ if (manifest.errorHandling !== undefined && manifest.errorHandler !== undefined) throw new Error('Specify errorHandling or errorHandler, not both');
1003
+ // Accepting the key without checking its shape would still insert the Try and
1004
+ // Catch blocks while silently dropping a malformed action list.
1005
+ for (const key of ['errorHandling', 'errorHandler']) {
1006
+ if (manifest[key] !== undefined) validateErrorHandling(manifest[key]);
1007
+ }
1008
+ for (const key of ['stageTemplate', 'stageSet']) {
1009
+ if (manifest[key] === undefined) continue;
1010
+ if (typeof manifest[key] !== 'string' || !manifest[key].trim()) throw new Error(`Flow update ${key} must be a non-empty string`);
1011
+ }
1012
+ if (manifest.stages !== undefined && (manifest.stageTemplate !== undefined || manifest.stageSet !== undefined)) {
1013
+ throw new Error('Flow update takes stages or a stage template, not both; rename the stage entries to change them');
1014
+ }
762
1015
  return manifest;
763
1016
  }
764
1017
 
@@ -1070,6 +1323,580 @@ async function findCaptureElsewhere(sdk, flowId, intendedSetId) {
1070
1323
  return { checked: true, available: true, query: `nameLIKE${id}`, update_sets: [...bySet.values()] };
1071
1324
  }
1072
1325
 
1326
+ // Verify requested step content independently of the mutation acknowledgement.
1327
+ function labelCacheEntry({ name, label, type, baseType, usedInstances }) {
1328
+ // The provider stores usedInstances as a map, but a map key is a UUID and an
1329
+ // unquoted UUID key is not valid GraphQL. Send the array form it accepts.
1330
+ const instances = Object.entries(usedInstances || {}).flatMap(([uiUniqueIdentifier, inputNames]) =>
1331
+ (Array.isArray(inputNames) ? inputNames : [inputNames]).map(inputName => ({ uiUniqueIdentifier, inputName })));
1332
+ const entry = { name, usedInstances: instances };
1333
+ if (label) entry.label = label;
1334
+ if (type) entry.type = type;
1335
+ if (baseType) entry.base_type = baseType;
1336
+ return entry;
1337
+ }
1338
+
1339
+ function assertInsertedIdentities(response, definition, expected, kind, flowId) {
1340
+ if (!expected.length) return;
1341
+ const field = kind === 'action' ? 'actions' : 'flowLogics';
1342
+ let inserted = [];
1343
+ walk(response, object => { if (object[field]?.inserts) inserted = object[field].inserts; });
1344
+ const saved = kind === 'action' ? findExistingActions(definition) : (definition.flowLogicInstances || definition.flowLogics || []);
1345
+ for (const step of expected) {
1346
+ const matches = inserted.filter(s => s.uiUniqueIdentifier === step.uiUniqueIdentifier);
1347
+ const actual = saved.filter(s => stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier) === step.uiUniqueIdentifier);
1348
+ const id = matches.length === 1 && findId(matches[0], ['sysId', 'sys_id', 'id']);
1349
+ 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`);
1350
+ }
1351
+ }
1352
+
1353
+ // Compare the requested contract, allowing only additional provider fields.
1354
+ function requestedContentMatches(actual, expected) {
1355
+ if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((v, i) => requestedContentMatches(actual[i], v));
1356
+ if (expected && typeof expected === 'object') return actual !== null && typeof actual === 'object' && Object.entries(expected).every(([k, v]) => requestedContentMatches(actual[k], v));
1357
+ return isDeepStrictEqual(actual, expected);
1358
+ }
1359
+
1360
+ function validateFinalStepPlan(before, actionInserts, actionUpdates, actionDeletes, logicInserts, logicUpdates, logicDeletes) {
1361
+ 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)) }));
1362
+ const steps = [...surviving(findExistingActions(before), actionUpdates, actionDeletes), ...surviving(before.flowLogicInstances || before.flowLogics || [], logicUpdates, logicDeletes), ...actionInserts, ...logicInserts];
1363
+ const orders = new Set(), identities = new Set();
1364
+ for (const s of steps) {
1365
+ const ui = stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier), order = String(s.order);
1366
+ if ((s.order !== undefined && orders.has(order)) || (ui && identities.has(ui))) throw new Error('Ambiguous final step orders or identities');
1367
+ if (s.order !== undefined) orders.add(order);
1368
+ if (ui) identities.add(ui);
1369
+ }
1370
+ const byUi = new Map(steps.map(s => [stringValue(s.uiUniqueIdentifier || s.ui_unique_identifier), s]));
1371
+ const paired = new Set();
1372
+ const parentOf = s => stringValue(s.parentUiId || s.parent);
1373
+ for (const step of steps) {
1374
+ if (step.parent && step.parentUiId && step.parent !== step.parentUiId) throw new Error('Conflicting final parent aliases');
1375
+ const seen = new Set([stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier)]);
1376
+ let parent = parentOf(step);
1377
+ while (parent && byUi.has(parent)) {
1378
+ if (seen.has(parent)) throw new Error('Cyclic final parent links');
1379
+ seen.add(parent); parent = parentOf(byUi.get(parent));
1380
+ }
1381
+ const catchType = { '35d60003e6022010a5e40cdd1254dd21': '07223332de022010ec58424b73829721', '35d60003e6022010a5e40cdd1254dd23': 'e9060aa2c3013010ace8b740ad40dd51' }[step.definitionId];
1382
+ if (!catchType) continue;
1383
+ const target = byUi.get(stringValue(step.connectedTo));
1384
+ if (!target || target.definitionId !== catchType) throw new Error('Catch must connect to a compatible Try');
1385
+ if (paired.has(step.connectedTo)) throw new Error('Ambiguous Catch pair: Try already paired');
1386
+ paired.add(step.connectedTo);
1387
+ if (parentOf(target) !== parentOf(step)) throw new Error('Catch and Try must be siblings with compatible parents');
1388
+ }
1389
+ }
1390
+
1391
+ function assertStepReadback(definition, expectedSteps, kind, flowId) {
1392
+ const saved = kind === 'action' ? findExistingActions(definition) : (definition.flowLogicInstances || definition.flowLogics || []);
1393
+ for (const expected of expectedSteps) {
1394
+ const matches = saved.filter(step => stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier) === expected.uiUniqueIdentifier);
1395
+ if (matches.length !== 1) throw new Error(`Flow ${flowId} ${kind} ${expected.uiUniqueIdentifier} was not uniquely persisted`);
1396
+ const actual = matches[0];
1397
+ if (!findId(actual, ['sysId', 'id', 'sys_id'])) throw new Error(`Flow ${flowId} ${kind} has no persisted identity`);
1398
+ for (const key of ['order', 'parent', 'parentUiId', 'connectedTo', 'definitionId', 'actionTypeSysId']) {
1399
+ if (expected[key] === undefined) continue;
1400
+ const value = key === 'actionTypeSysId' ? actionTypeIdOf(actual) : actual[key];
1401
+ if (String(value ?? '') !== String(expected[key])) throw new Error(`Flow ${flowId} ${kind} ${expected.uiUniqueIdentifier} ${key} did not match requested value`);
1402
+ }
1403
+ if (expected.flowVariables && !requestedContentMatches(actual.flowVariables, expected.flowVariables)) throw new Error(`Flow ${flowId} ${kind} assignments did not match requested content`);
1404
+ if (expected.inputs) {
1405
+ for (const input of expected.inputs) {
1406
+ const found = inputList(actual).filter(i => i.name === input.name);
1407
+ 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`);
1408
+ }
1409
+ }
1410
+ }
1411
+ }
1412
+
1413
+ function assertLogicPreserved(before, after, inserts, updates, deletes, flowId) {
1414
+ const ids = new Set(inserts.map(l => l.uiUniqueIdentifier));
1415
+ const mask = (definition, isAfter) => (definition.flowLogicInstances || definition.flowLogics || []).filter(l => {
1416
+ const ui = stringValue(l.uiUniqueIdentifier || l.ui_unique_identifier);
1417
+ return !(isAfter ? ids.has(ui) : deletes.includes(stringValue(l.sysId || l.id || l.sys_id || ui)));
1418
+ }).map(l => {
1419
+ const copy = clone(l);
1420
+ const update = updates.find(u => u.uiUniqueIdentifier === stringValue(l.uiUniqueIdentifier || l.ui_unique_identifier));
1421
+ if (update) for (const key of Object.keys(update)) if (!['uiUniqueIdentifier', 'type'].includes(key)) delete copy[key];
1422
+ return copy;
1423
+ });
1424
+ if (!isDeepStrictEqual(mask(before, false), mask(after, true))) throw new Error(`Flow ${flowId} changed omitted logic fields; preservation failed`);
1425
+ }
1426
+
1427
+ async function planErrorHandling({ sdk, instance, scope, flowId, beforeDefinition, existingActions, actionInserts, actionUpdates, flowLogicInserts, flowLogicUpdates, changes, idFactory, actionUiMap, pendingSteps, changedActionInputs, collectPills, errorHandlingInput, actionTargets = new Map() }) {
1428
+ const existingLogics = beforeDefinition.flowLogicInstances || beforeDefinition.flowLogics || [];
1429
+ const existingSteps = [...existingActions, ...existingLogics];
1430
+ 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');
1431
+ let topTry = existingLogics.find(fl => String(fl.definitionId) === 'e9060aa2c3013010ace8b740ad40dd51');
1432
+ let topCatch = existingLogics.find(fl => String(fl.definitionId) === '35d60003e6022010a5e40cdd1254dd23');
1433
+
1434
+ for (const id of ['e9060aa2c3013010ace8b740ad40dd51', '35d60003e6022010a5e40cdd1254dd23']) {
1435
+ if (existingLogics.filter(fl => String(fl.definitionId) === id).length > 1) throw new Error('Ambiguous existing error handling blocks');
1436
+ }
1437
+ if (Boolean(topTry) !== Boolean(topCatch)) throw new Error('Incomplete existing error handling pair; reconcile in Flow Designer before retrying');
1438
+ 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');
1439
+ if (topCatch?.connectedTo && topCatch.connectedTo !== topTry.uiUniqueIdentifier) throw new Error('Existing Catch is connected to a different Try');
1440
+ // 1. Ensure Top Level Try (order 0)
1441
+ let tryUiId = topTry ? stringValue(topTry.uiUniqueIdentifier || topTry.ui_unique_identifier) : '';
1442
+ if (!topTry) {
1443
+ tryUiId = idFactory();
1444
+ const tryDef = FLOW_LOGIC_DEFINITIONS['top level try'];
1445
+ flowLogicInserts.push({
1446
+ order: '0',
1447
+ uiUniqueIdentifier: tryUiId,
1448
+ parent: '',
1449
+ parentUiId: '',
1450
+ connectedTo: '',
1451
+ metadata: '{"predicates":[]}',
1452
+ flowSysId: flowId,
1453
+ generationSource: '',
1454
+ definitionId: tryDef.id,
1455
+ type: 'flowlogic',
1456
+ inputs: [],
1457
+ outputsToAssign: [],
1458
+ flowLogicDefinition: {
1459
+ id: tryDef.id,
1460
+ name: tryDef.name,
1461
+ description: tryDef.description,
1462
+ connectedTo: '',
1463
+ quiescence: 'never',
1464
+ compilationClass: tryDef.compilationClass,
1465
+ order: tryDef.order,
1466
+ type: tryDef.type,
1467
+ visible: true,
1468
+ attributes: tryDef.attributes,
1469
+ userCanRead: true,
1470
+ category: '',
1471
+ inputs: [],
1472
+ variables: '[]'
1473
+ }
1474
+ });
1475
+ changes.push({ component: 'flowLogic', order: 0, type: 'Top Level Try', input: 'insert', before: null, after: { uiUniqueIdentifier: tryUiId } });
1476
+
1477
+ // Re-parent all existing unparented main body actions (order >= 1) to Top Level Try
1478
+ for (const a of existingActions) {
1479
+ if (!a.parent && !a.parentUiId && !actionUpdates.some(u => u.uiUniqueIdentifier === stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier) && u.parent !== undefined)) {
1480
+ const uiId = stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier);
1481
+ actionUpdates.push({
1482
+ uiUniqueIdentifier: uiId,
1483
+ type: 'action',
1484
+ parent: tryUiId,
1485
+ parentUiId: tryUiId
1486
+ });
1487
+ }
1488
+ }
1489
+ // Re-parent all newly inserted actions that lack parent to Top Level Try
1490
+ for (const a of actionInserts) {
1491
+ if (!a.parent) {
1492
+ a.parent = tryUiId;
1493
+ a.parentUiId = tryUiId;
1494
+ }
1495
+ }
1496
+ // Re-parent all unparented logic blocks
1497
+ for (const fl of existingLogics) {
1498
+ if (!fl.parent && String(fl.definitionId) !== '35d60003e6022010a5e40cdd1254dd23') {
1499
+ const uiId = stringValue(fl.uiUniqueIdentifier || fl.ui_unique_identifier);
1500
+ flowLogicUpdates.push({
1501
+ uiUniqueIdentifier: uiId,
1502
+ type: 'flowlogic',
1503
+ parent: tryUiId,
1504
+ parentUiId: tryUiId
1505
+ });
1506
+ }
1507
+ }
1508
+ for (const fl of flowLogicInserts) {
1509
+ if (!fl.parent && fl.definitionId !== 'e9060aa2c3013010ace8b740ad40dd51' && fl.definitionId !== '35d60003e6022010a5e40cdd1254dd23') {
1510
+ fl.parent = tryUiId;
1511
+ fl.parentUiId = tryUiId;
1512
+ }
1513
+ }
1514
+ }
1515
+
1516
+ // New main-body children belong to the Try even on a rerun. Explicit
1517
+ // requested parents are retained.
1518
+ for (const a of actionInserts) if (!a.parent && !a.parentUiId) { a.parent = tryUiId; a.parentUiId = tryUiId; }
1519
+
1520
+ // 2. Ensure Top Level Catch
1521
+ let catchUiId = topCatch ? stringValue(topCatch.uiUniqueIdentifier || topCatch.ui_unique_identifier) : '';
1522
+ // An existing Catch already owns its order; re-running the same manifest must
1523
+ // place error actions after it instead of guessing a fixed slot.
1524
+ let catchOrder = topCatch ? parseInt(topCatch.order, 10) : NaN;
1525
+ if (!topCatch) {
1526
+ catchUiId = idFactory();
1527
+ const catchDef = FLOW_LOGIC_DEFINITIONS['top level catch'];
1528
+ // Determine max order
1529
+ let maxOrder = 0;
1530
+ for (const a of existingActions) maxOrder = Math.max(maxOrder, parseInt(a.order, 10) || 0);
1531
+ for (const fl of existingLogics) maxOrder = Math.max(maxOrder, parseInt(fl.order, 10) || 0);
1532
+ for (const a of actionInserts) maxOrder = Math.max(maxOrder, parseInt(a.order, 10) || 0);
1533
+ for (const fl of flowLogicInserts) maxOrder = Math.max(maxOrder, parseInt(fl.order, 10) || 0);
1534
+ catchOrder = maxOrder + 1;
1535
+
1536
+ flowLogicInserts.push({
1537
+ order: String(catchOrder),
1538
+ uiUniqueIdentifier: catchUiId,
1539
+ parent: '',
1540
+ parentUiId: '',
1541
+ connectedTo: tryUiId,
1542
+ metadata: '{"predicates":[]}',
1543
+ flowSysId: flowId,
1544
+ generationSource: '',
1545
+ definitionId: catchDef.id,
1546
+ type: 'flowlogic',
1547
+ inputs: [
1548
+ { name: 'enabled', value: { schemaless: false, schemalessValue: '', value: 'true' } }
1549
+ ],
1550
+ outputsToAssign: [],
1551
+ flowLogicDefinition: {
1552
+ id: catchDef.id,
1553
+ name: catchDef.name,
1554
+ description: catchDef.description,
1555
+ connectedTo: catchDef.connectedTo,
1556
+ quiescence: 'never',
1557
+ compilationClass: catchDef.compilationClass,
1558
+ order: catchDef.order,
1559
+ type: catchDef.type,
1560
+ visible: true,
1561
+ attributes: catchDef.attributes,
1562
+ userCanRead: true,
1563
+ category: '',
1564
+ inputs: [],
1565
+ variables: '[]'
1566
+ }
1567
+ });
1568
+ changes.push({ component: 'flowLogic', order: catchOrder, type: 'Top Level Catch', input: 'insert', before: null, after: { uiUniqueIdentifier: catchUiId } });
1569
+ }
1570
+
1571
+ // Register Catch step in pendingSteps for data pill resolution
1572
+ pendingSteps.push({
1573
+ name: 'Error Handler',
1574
+ order: String(Number.isFinite(catchOrder) ? catchOrder : existingActions.length + 1),
1575
+ uiUniqueIdentifier: catchUiId,
1576
+ inputs: [
1577
+ { name: '__status__.message', parameter: { label: 'Error Status➛Message', type: 'string' } },
1578
+ { name: '__status__.code', parameter: { label: 'Error Status➛Code', type: 'integer' } }
1579
+ ]
1580
+ });
1581
+
1582
+ // 3. Process errorHandling actions
1583
+ const errorActions = Array.isArray(errorHandlingInput.actions) ? errorHandlingInput.actions : [];
1584
+ const errorPill = name => String(name)
1585
+ .replace(/\{\{error\.message\}\}/g, `{{${catchUiId}.__status__.message}}`)
1586
+ .replace(/\{\{error\.code\}\}/g, `{{${catchUiId}.__status__.code}}`);
1587
+ const children = existingActions.filter(a => a.parent === catchUiId || a.parentUiId === catchUiId).sort((a, b) => Number(a.order) - Number(b.order));
1588
+ if (existingLogics.some(l => l.parent === catchUiId || l.parentUiId === catchUiId)) throw new Error('Ambiguous Catch children include logic blocks');
1589
+ const childOrders = children.map(a => String(a.order));
1590
+ 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');
1591
+ 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;
1592
+ for (const [eIdx, eAction] of errorActions.entries()) {
1593
+ const resolved = await resolveActionType(sdk, eAction.type);
1594
+ const actionDefinition = await readActionDefinition(sdk, instance, resolved.id, scope);
1595
+ const existingChild = children[eIdx];
1596
+ if (existingChild && actionTypeIdOf(existingChild) !== resolved.id) throw new Error(`Error action ${eIdx + 1} does not match existing Catch child type; ambiguous reconciliation`);
1597
+ const uiUniqueIdentifier = existingChild ? existingChild.uiUniqueIdentifier : idFactory();
1598
+ actionUiMap.set(`error_${eIdx + 1}`, uiUniqueIdentifier);
1599
+ // Resolve the friendly {{error.*}} tokens before the typed inputs are
1600
+ // built: the value that reaches the instance has to name the Catch
1601
+ // instance's own pill, otherwise the canvas stores an unresolved
1602
+ // reference and no labelCache entry can draw it.
1603
+ const errorInputs = Object.fromEntries(Object.entries(eAction.inputs || {})
1604
+ .map(([input, value]) => [input, typeof value === 'string' ? errorPill(value) : value]));
1605
+ if (existingChild) {
1606
+ const update = buildActionUpdate(existingChild, { ...eAction, inputs: errorInputs }, eIdx);
1607
+ actionUpdates.push(update);
1608
+ actionTargets.set(uiUniqueIdentifier, existingChild);
1609
+ changedActionInputs.set(uiUniqueIdentifier, new Set([...(changedActionInputs.get(uiUniqueIdentifier) || []), ...Object.keys(errorInputs)]));
1610
+ for (const [input, after] of Object.entries(errorInputs)) {
1611
+ changes.push({ component: 'errorAction', order: existingChild.order, type: eAction.type, input, before: inputRawValue(inputList(existingChild).find(i => i.name === input)), after });
1612
+ collectPills(after, uiUniqueIdentifier, input);
1613
+ }
1614
+ continue;
1615
+ }
1616
+ const insertInputs = buildTypedInputs({ ...eAction, inputs: errorInputs }, actionDefinition.schema);
1617
+ pendingSteps.push({ name: eAction.type, order: String(errActionOrder), uiUniqueIdentifier, inputs: insertInputs });
1618
+ actionInserts.push({
1619
+ actionTypeSysId: resolved.id,
1620
+ flowSysId: flowId,
1621
+ generationSource: '',
1622
+ type: 'action',
1623
+ order: String(errActionOrder),
1624
+ parent: catchUiId,
1625
+ uiUniqueIdentifier,
1626
+ parentUiId: catchUiId,
1627
+ metadata: JSON.stringify(parseMaybeJson(actionDefinition.definition.metadata, {})),
1628
+ inputs: insertInputs,
1629
+ });
1630
+ changedActionInputs.set(uiUniqueIdentifier, new Set(Object.keys(eAction.inputs || {})));
1631
+ for (const [input, after] of Object.entries(eAction.inputs || {})) {
1632
+ const resolvedVal = typeof after === 'string' ? errorPill(after) : after;
1633
+ changes.push({ component: 'errorAction', order: errActionOrder, type: eAction.type, input, before: null, after: resolvedVal });
1634
+ collectPills(resolvedVal, uiUniqueIdentifier, input);
1635
+ }
1636
+ errActionOrder++;
1637
+ }
1638
+ }
1639
+
1640
+ async function planManifestSteps({ manifest, beforeDefinition, existingActions, existingOrders, actionUiMap, logicUiMap, pendingSteps, idFactory, sdk, instance, scope, flowId, actionInserts, actionUpdates, flowLogicInserts, actionTargets, changedActionInputs, changes, collectPills }) {
1641
+ const existingLogics = beforeDefinition.flowLogicInstances || beforeDefinition.flowLogics || [];
1642
+ const registry = new Map();
1643
+ const byUi = new Map();
1644
+ const register = (step, kind) => {
1645
+ const ui = stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier);
1646
+ const order = String(step.order);
1647
+ if (registry.has(order) && kind === 'action') throw new Error(`Ambiguous step order ${order}: multiple Action instances`);
1648
+ if (!ui || byUi.has(ui) || registry.has(order)) throw new Error(`Ambiguous step identity or order ${order}`);
1649
+ const entry = { ...step, uiUniqueIdentifier: ui, kind };
1650
+ registry.set(order, entry); byUi.set(ui, entry);
1651
+ (kind === 'action' ? actionUiMap : logicUiMap).set(order, ui);
1652
+ return entry;
1653
+ };
1654
+ const rawDeletes = manifest.deleteSteps || manifest.delete || manifest.deleteOrders || [];
1655
+ const deleteTargets = new Set((Array.isArray(rawDeletes) ? rawDeletes : [rawDeletes]).map(String));
1656
+ const isDeleted = step => {
1657
+ const ui = stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier);
1658
+ const id = stringValue(step.sysId || step.id || step.sys_id || ui);
1659
+ return [String(step.order), ui, id].some(value => deleteTargets.has(value));
1660
+ };
1661
+ const deletedUis = new Set();
1662
+ for (const step of [...existingActions, ...existingLogics]) {
1663
+ if (!isDeleted(step)) continue;
1664
+ deletedUis.add(stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier));
1665
+ actionUiMap.delete(String(step.order));
1666
+ logicUiMap.delete(String(step.order));
1667
+ }
1668
+ existingActions = existingActions.filter(step => !isDeleted(step));
1669
+ existingOrders = new Set(existingActions.map(step => String(step.order)));
1670
+ for (const step of existingActions) register(step, 'action');
1671
+ for (const step of existingLogics.filter(step => !isDeleted(step))) register(step, 'logic');
1672
+ const logicSpecs = manifest.flowLogics || manifest.logic || [];
1673
+ for (const l of logicSpecs) {
1674
+ const type = String(l.type || l.name).toLowerCase().trim();
1675
+ register({ ...l, definitionId: FLOW_LOGIC_DEFINITIONS[type].id, uiUniqueIdentifier: idFactory() }, 'logic');
1676
+ }
1677
+ const actionPlans = new Map();
1678
+ for (const [index, a] of (manifest.actions || []).entries()) {
1679
+ if (actionPlans.has(String(a.order))) throw new Error(`Duplicate action update for order ${a.order}`);
1680
+ if (existingOrders.has(String(a.order))) { actionPlans.set(String(a.order), { existing: true }); continue; }
1681
+ const resolved = await resolveActionType(sdk, a.type);
1682
+ const actionDefinition = await readActionDefinition(sdk, instance, resolved.id, scope);
1683
+ const uiUniqueIdentifier = idFactory();
1684
+ const entry = register({ ...a, uiUniqueIdentifier }, 'action');
1685
+ // Schemas exist before any value is resolved, including forward references.
1686
+ pendingSteps.push({ ...entry, name: a.type, inputs: buildTypedInputs(a, actionDefinition.schema) });
1687
+ actionPlans.set(String(a.order), { resolved, actionDefinition, uiUniqueIdentifier, index });
1688
+ }
1689
+ const resolveLink = (values, label, owner) => {
1690
+ const supplied = values.filter(v => v !== undefined);
1691
+ if (!supplied.length) return '';
1692
+ const targets = supplied.map(v => {
1693
+ const target = registry.get(String(v)) || byUi.get(String(v));
1694
+ if (!target || target.kind !== 'logic' || target.uiUniqueIdentifier === owner) throw new Error(`Absent, wrong-type or self ${label} target ${v}`);
1695
+ return target;
1696
+ });
1697
+ if (new Set(targets.map(t => t.uiUniqueIdentifier)).size !== 1) throw new Error(`Conflicting ${label} aliases`);
1698
+ const target = targets[0];
1699
+ if (label === 'Catch' && !['07223332de022010ec58424b73829721', 'e9060aa2c3013010ace8b740ad40dd51'].includes(target.definitionId)) throw new Error('Catch target must be a Try block');
1700
+ if (label === 'parent' && !Object.values(FLOW_LOGIC_DEFINITIONS).some(d => d.id === target.definitionId && /^(TRY|TOP_LEVEL_TRY|CATCH|TOP_LEVEL_CATCH|IF|ELSE|ELSEIF)$/.test(d.type))) throw new Error('Parent target cannot contain children');
1701
+ return target.uiUniqueIdentifier;
1702
+ };
1703
+ for (const l of logicSpecs) {
1704
+ const entry = registry.get(String(l.order));
1705
+ entry.resolvedParent = resolveLink([l.parent, l.parentOrder, l.parentUiId], 'parent', entry.uiUniqueIdentifier);
1706
+ }
1707
+ for (const entry of registry.values()) {
1708
+ const seen = new Set([entry.uiUniqueIdentifier]);
1709
+ let parent = entry.resolvedParent || entry.parentUiId || entry.parent;
1710
+ while (parent && byUi.has(String(parent))) {
1711
+ if (seen.has(parent)) throw new Error('Cyclic parent links');
1712
+ seen.add(parent); const next = byUi.get(parent); parent = next.resolvedParent || next.parentUiId || next.parent;
1713
+ }
1714
+ }
1715
+
1716
+ // Handle flowLogics insertion and update
1717
+ const requestedLogics = manifest.flowLogics || manifest.logic || [];
1718
+ const logicTypeKey = t => String(t || '').toLowerCase().trim();
1719
+ // A manifest names steps by order ({{step_4.__status__.message}} or
1720
+ // {{4.message}}). Resolve that only once the owning map entry exists, but do
1721
+ // it before any value is packaged: a token that survives into the payload
1722
+ // stores an unresolvable reference the canvas renders blank.
1723
+ const resolveStepPill = value => {
1724
+ for (const match of String(value).matchAll(/\{\{([^}]+)\}\}/g)) {
1725
+ if ([...deletedUis].some(ui => match[1].startsWith(`${ui}.`))) throw new Error(`Absent deleted step reference ${match[0]}`);
1726
+ }
1727
+ return String(value).replace(/\{\{(?:step_)?(\d+)\.([^}]+)\}\}/g, (match, order, field) => {
1728
+ const ui = actionUiMap.get(String(order)) || logicUiMap.get(String(order));
1729
+ if (!ui) throw new Error(`Absent step reference ${match}`);
1730
+ return `{{${ui}.${field}}}`;
1731
+ });
1732
+ };
1733
+ const resolveStepValue = value => {
1734
+ if (typeof value === 'string') return resolveStepPill(value);
1735
+ if (Array.isArray(value)) return value.map(resolveStepValue);
1736
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolveStepValue(v)]));
1737
+ return value;
1738
+ };
1739
+ const resolveStepInputs = inputs => resolveStepValue(inputs || {});
1740
+
1741
+ for (const [logicIdx, l] of requestedLogics.entries()) {
1742
+ const lType = logicTypeKey(l.type || l.name);
1743
+ const logicDef = FLOW_LOGIC_DEFINITIONS[lType] || {
1744
+ id: l.definitionId || l.id || '',
1745
+ name: l.name || l.type,
1746
+ type: (l.type || '').toUpperCase(),
1747
+ description: '',
1748
+ compilationClass: '',
1749
+ order: l.order || logicIdx + 1,
1750
+ connectedTo: l.connectedTo || '',
1751
+ attributes: 'allow_children=true,allow_siblings=true,'
1752
+ };
1753
+
1754
+ const uiUniqueIdentifier = logicUiMap.get(String(l.order));
1755
+ const parentUiId = resolveLink([l.parent, l.parentOrder, l.parentUiId], 'parent', uiUniqueIdentifier);
1756
+ const connectedTo = resolveLink([l.connectedTo, l.connectedToOrder], /catch$/.test(lType) ? 'Catch' : 'connection', uiUniqueIdentifier);
1757
+ // A Catch only works when it points at one specific Try instance. Falling
1758
+ // back to the definition id writes a link the instance cannot resolve, so
1759
+ // demand the pairing instead of guessing it.
1760
+ if ((lType === 'catch' || lType === 'top level catch') && l.connectedTo === undefined && l.connectedToOrder === undefined) {
1761
+ throw new Error(`Flow logic at order ${l.order} is a Catch block; set connectedToOrder to the Try block's order so the pair stays linked`);
1762
+ }
1763
+
1764
+ let resolvedCondition = resolveStepPill(l.condition || '');
1765
+
1766
+ const inputs = [];
1767
+ collectPills(resolvedCondition, uiUniqueIdentifier, 'condition');
1768
+
1769
+ if (lType === 'if' || lType === 'else if') {
1770
+ inputs.push({
1771
+ name: 'condition_name',
1772
+ value: { schemaless: false, schemalessValue: '', value: l.condition_name || l.conditionName || l.label || '' }
1773
+ });
1774
+ inputs.push({
1775
+ name: 'condition',
1776
+ value: { schemaless: false, schemalessValue: '', value: resolvedCondition }
1777
+ });
1778
+ } else if (lType === 'catch' || lType === 'top level catch') {
1779
+ inputs.push({
1780
+ name: 'enabled',
1781
+ value: { schemaless: false, schemalessValue: '', value: 'true' }
1782
+ });
1783
+ }
1784
+
1785
+ const flowVarsArray = [];
1786
+ if (lType === 'set flow variables' && l.values) {
1787
+ for (const [varName, varVal] of Object.entries(l.values)) {
1788
+ const resolvedValue = resolveStepValue(varVal);
1789
+ collectPills(resolvedValue, uiUniqueIdentifier, varName);
1790
+ flowVarsArray.push({
1791
+ id: '',
1792
+ name: varName,
1793
+ children: [],
1794
+ displayValue: { value: '' },
1795
+ value: { schemaless: false, schemalessValue: '', value: resolvedValue }
1796
+ });
1797
+ }
1798
+ }
1799
+
1800
+ flowLogicInserts.push({
1801
+ order: String(l.order || logicIdx + 1),
1802
+ uiUniqueIdentifier,
1803
+ parent: parentUiId,
1804
+ parentUiId,
1805
+ connectedTo,
1806
+ metadata: '{"predicates":[]}',
1807
+ flowSysId: flowId,
1808
+ generationSource: '',
1809
+ definitionId: logicDef.id,
1810
+ type: 'flowlogic',
1811
+ inputs,
1812
+ outputsToAssign: [],
1813
+ ...(flowVarsArray.length ? { flowVariables: flowVarsArray } : {}),
1814
+ flowLogicDefinition: {
1815
+ id: logicDef.id,
1816
+ name: logicDef.name,
1817
+ description: logicDef.description,
1818
+ connectedTo: logicDef.connectedTo,
1819
+ quiescence: 'never',
1820
+ compilationClass: logicDef.compilationClass,
1821
+ order: logicDef.order,
1822
+ type: logicDef.type,
1823
+ visible: true,
1824
+ attributes: logicDef.attributes,
1825
+ userCanRead: true,
1826
+ category: '',
1827
+ inputs: [],
1828
+ variables: '[]'
1829
+ }
1830
+ });
1831
+
1832
+ if (lType === 'catch' || lType === 'top level catch') {
1833
+ pendingSteps.push({
1834
+ name: 'Catch',
1835
+ order: String(l.order || logicIdx + 1),
1836
+ uiUniqueIdentifier,
1837
+ inputs: [
1838
+ { name: '__status__.message', parameter: { label: 'Error Status➛Message', type: 'string' } },
1839
+ { name: '__status__.code', parameter: { label: 'Error Status➛Code', type: 'integer' } }
1840
+ ]
1841
+ });
1842
+ }
1843
+
1844
+ changes.push({ component: 'flowLogic', order: l.order, type: logicDef.name, input: 'insert', before: null, after: { parent: parentUiId, connectedTo } });
1845
+ }
1846
+
1847
+ for (const [index, requested] of (manifest.actions || []).entries()) {
1848
+ const isInsert = !existingOrders.has(String(requested.order));
1849
+ if (isInsert) {
1850
+ const { resolved, actionDefinition, uiUniqueIdentifier } = actionPlans.get(String(requested.order));
1851
+ actionUiMap.set(String(requested.order), uiUniqueIdentifier);
1852
+ // Resolve before packaging: the instance must receive the producing step's
1853
+ // own pill name, not the order-based token from the manifest.
1854
+ const insertInputs = buildTypedInputs({ ...requested, inputs: resolveStepInputs(requested.inputs) }, actionDefinition.schema);
1855
+ // A later step in this same manifest may reference this one; its identity
1856
+ // and schema exist now even though the flow does not carry it yet.
1857
+ Object.assign(pendingSteps.find(s => s.uiUniqueIdentifier === uiUniqueIdentifier), { inputs: insertInputs });
1858
+ const actParent = resolveLink([requested.parentUiId, requested.parentOrder, requested.parent], 'parent', uiUniqueIdentifier);
1859
+ actionInserts.push({
1860
+ actionTypeSysId: resolved.id,
1861
+ flowSysId: flowId,
1862
+ generationSource: '',
1863
+ type: 'action',
1864
+ order: String(requested.order),
1865
+ parent: actParent,
1866
+ uiUniqueIdentifier,
1867
+ parentUiId: actParent,
1868
+ metadata: JSON.stringify(parseMaybeJson(actionDefinition.definition.metadata, {})),
1869
+ inputs: insertInputs,
1870
+ });
1871
+ changedActionInputs.set(uiUniqueIdentifier, new Set(Object.keys(requested.inputs || {})));
1872
+ for (const [input, after] of Object.entries(requested.inputs || {})) {
1873
+ const resolvedAfter = typeof after === 'string' ? resolveStepPill(after) : after;
1874
+ changes.push({ component: 'action', order: requested.order, type: requested.type, input, before: null, after: resolvedAfter });
1875
+ collectPills(resolvedAfter, uiUniqueIdentifier, input);
1876
+ }
1877
+ } else {
1878
+ const existing = await resolveExistingAction(sdk, existingActions, requested, index);
1879
+ const resolvedRequest = { ...requested, inputs: resolveStepInputs(requested.inputs) };
1880
+ const update = buildActionUpdate(existing, resolvedRequest, index);
1881
+ if (['parent', 'parentOrder', 'parentUiId'].some(k => requested[k] !== undefined)) {
1882
+ const parent = resolveLink([requested.parentUiId, requested.parentOrder, requested.parent], 'parent', existing.uiUniqueIdentifier);
1883
+ update.parent = parent; update.parentUiId = parent;
1884
+ }
1885
+ actionUpdates.push(update);
1886
+ const uiId = stringValue(existing.uiUniqueIdentifier || existing.ui_unique_identifier);
1887
+ if (actionTargets.has(uiId)) throw new Error(`Duplicate action update for order ${requested.order}; combine input changes in one action entry`);
1888
+ actionTargets.set(uiId, existing);
1889
+ changedActionInputs.set(uiId, new Set(Object.keys(requested.inputs)));
1890
+ for (const [input, after] of Object.entries(requested.inputs)) {
1891
+ const resolvedAfter = typeof after === 'string' ? resolveStepPill(after) : after;
1892
+ changes.push({ component: 'action', order: requested.order, type: requested.type, input, before: inputRawValue(inputList(existing).find(field => field.name === input)), after: resolvedAfter });
1893
+ collectPills(resolvedAfter, uiId, input);
1894
+ }
1895
+ }
1896
+ }
1897
+
1898
+ }
1899
+
1073
1900
  export async function createFlowFromManifest(sdk, instance, inputManifest, options = {}) {
1074
1901
  const manifest = validateFlowManifest(inputManifest);
1075
1902
  const scope = manifest.scope;
@@ -1083,6 +1910,27 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1083
1910
  throw new Error(`Flow creation refused before any content write: capture context could not be established. ${error.message}`, { cause: error });
1084
1911
  }
1085
1912
 
1913
+ const actionInstances = [];
1914
+ const flowLogicInserts = [];
1915
+ const labelCacheInserts = [];
1916
+ const pendingSteps = [];
1917
+ const pills = [];
1918
+ const collectPills = (value, uiUniqueIdentifier, inputName) => {
1919
+ for (const match of String(value).matchAll(/\{\{([^}]+)\}\}/g)) pills.push({ name: match[1], uiUniqueIdentifier, inputName });
1920
+ };
1921
+ const orderedManifest = { ...manifest, actions: manifest.actions.map((a, index) => ({ ...a, order: a.order ?? index + 1, inputs: a.inputs || {} })) };
1922
+ await planManifestSteps({ manifest: orderedManifest, beforeDefinition: {}, existingActions: [], existingOrders: new Set(), actionUiMap: new Map(), logicUiMap: new Map(), pendingSteps, idFactory, sdk, instance, scope, flowId: '', actionInserts: actionInstances, actionUpdates: [], flowLogicInserts, actionTargets: new Map(), changedActionInputs: new Map(), changes: [], collectPills });
1923
+ if (manifest.errorHandling !== undefined) await planErrorHandling({ sdk, instance, scope, flowId: '', beforeDefinition: {}, existingActions: [], actionInserts: actionInstances, actionUpdates: [], flowLogicInserts, flowLogicUpdates: [], changes: [], idFactory, actionUiMap: new Map(), pendingSteps, changedActionInputs: new Map(), collectPills, errorHandlingInput: manifest.errorHandling });
1924
+ for (const pill of pills) {
1925
+ const binding = resolvePillBinding({}, pill.name, '', [], pendingSteps);
1926
+ const previous = labelCacheInserts.find(e => e.name === pill.name);
1927
+ if (previous) {
1928
+ if (!previous.usedInstances.some(i => i.uiUniqueIdentifier === pill.uiUniqueIdentifier && i.inputName === pill.inputName)) previous.usedInstances.push({ uiUniqueIdentifier: pill.uiUniqueIdentifier, inputName: pill.inputName });
1929
+ } else labelCacheInserts.push(labelCacheEntry({ name: pill.name, label: binding.label, type: binding.type, baseType: binding.type, usedInstances: { [pill.uiUniqueIdentifier]: [pill.inputName] } }));
1930
+ }
1931
+
1932
+ validateFinalStepPlan({}, actionInstances, [], [], flowLogicInserts, [], []);
1933
+
1086
1934
  let parentResponse;
1087
1935
  try {
1088
1936
  parentResponse = await mutationContext('parent_create', readUpdateSet, snapshots, () => sdk.request(`${instance}${FLOW_ENDPOINT}?param_only_properties=true&sysparm_transaction_scope=${encodeURIComponent(scope)}`, {
@@ -1108,27 +1956,12 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1108
1956
  const definition = await resolveTriggerDefinition(sdk, manifest.trigger.type);
1109
1957
  const trigger = await buildCreateTrigger(sdk, flowId, manifest, definition, options);
1110
1958
 
1111
- const actionInstances = [];
1112
- for (const [index, action] of manifest.actions.entries()) {
1113
- const resolved = await resolveActionType(sdk, action.type);
1114
- const actionDefinition = await readActionDefinition(sdk, instance, resolved.id, scope);
1115
- actionInstances.push({
1116
- actionTypeSysId: resolved.id,
1117
- flowSysId: flowId,
1118
- generationSource: '',
1119
- type: 'action',
1120
- order: String(index + 1),
1121
- parent: '',
1122
- uiUniqueIdentifier: idFactory(),
1123
- parentUiId: '',
1124
- metadata: JSON.stringify(parseMaybeJson(actionDefinition.definition.metadata, {})),
1125
- inputs: buildTypedInputs(action, actionDefinition.schema),
1126
- });
1127
- }
1959
+ for (const action of actionInstances) action.flowSysId = flowId;
1960
+ for (const logic of flowLogicInserts) logic.flowSysId = flowId;
1128
1961
 
1129
1962
  const patchResponse = await mutationContext('trigger_and_actions_patch', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1130
1963
  method: 'POST',
1131
- body: JSON.stringify({ query: buildFlowPatchMutation({ flowId, trigger, actions: actionInstances }), variables: {} }),
1964
+ body: JSON.stringify({ query: buildFlowPatchMutation({ flowId, trigger, actions: actionInstances, flowLogicInserts, labelCacheInserts }), variables: {} }),
1132
1965
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1133
1966
  assertGraphQLSuccess(patchResponse, 'Flow trigger/action patch');
1134
1967
  const insertedTrigger = insertedTriggers(patchResponse)[0];
@@ -1138,7 +1971,11 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1138
1971
 
1139
1972
  // Stages carry componentIndexes that name flow-step orders, so placement
1140
1973
  // runs after the actions exist — the same order Flow Designer uses.
1141
- const stageInserts = buildStageInserts(manifest.stages || [], { idFactory, flowId });
1974
+ let manifestStages = manifest.stages || [];
1975
+ if ((manifest.stageTemplate || manifest.stageSet) && manifestStages.length === 0) {
1976
+ manifestStages = await resolveStageTemplate(sdk, manifest.stageTemplate || manifest.stageSet);
1977
+ }
1978
+ const stageInserts = buildStageInserts(manifestStages, { idFactory, flowId });
1142
1979
  if (stageInserts.length) {
1143
1980
  const stageResponse = await mutationContext('stage_placement', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1144
1981
  method: 'POST',
@@ -1150,6 +1987,10 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1150
1987
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
1151
1988
  verifyCreatedFlowReadback({ flowId, processflow, trigger, insertedTrigger, manifest, actionInstances, inserted, stageInserts });
1152
1989
  assertStagesPlaced(processflow, stageInserts, flowId);
1990
+ assertInsertedIdentities(patchResponse, processflow, flowLogicInserts, 'logic', flowId);
1991
+ assertStepReadback(processflow, actionInstances, 'action', flowId);
1992
+ assertStepReadback(processflow, flowLogicInserts, 'logic', flowId);
1993
+ 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}`);
1153
1994
  const { version } = await mutationContext('autosave_version', readUpdateSet, snapshots, () => createVerifiedFlowVersion(sdk, {
1154
1995
  instance, flowId, scope, type: 'Autosave', annotation: 'JSN flow create',
1155
1996
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
@@ -1167,7 +2008,7 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1167
2008
  ...(captureContext ? { capture_context: captureContext } : {}),
1168
2009
  update_set_capture: updateSetCapture,
1169
2010
  update_set_mutations: snapshots,
1170
- lifecycle: { published: false, supported: ['draft', 'autosave'], deferred: ['publish/activation', 'Flow Logic', 'subflows', 'flow variables', 'error handling'] },
2011
+ lifecycle: { published: false, supported: ['draft', 'autosave'], deferred: ['publish/activation', 'subflows', 'flow variables'] },
1171
2012
  };
1172
2013
  } catch (error) {
1173
2014
  // Creation is two-stage: the parent POST leaves a real draft behind when the
@@ -1177,6 +2018,107 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
1177
2018
  }
1178
2019
  }
1179
2020
 
2021
+ // Flow Designer renders a canvas pill from the `label` of its label_cache entry;
2022
+ // the ProcessFlow read exposes that cache as `labelCacheAsJsonString` (a JSON
2023
+ // string), never as a `label_cache` array. Reading the wrong field is how a
2024
+ // write ends up with an entry that has a name and no label to draw.
2025
+ function normalizeUsedInstances(used) {
2026
+ const out = new Map();
2027
+ const add = (uiId, inputName) => {
2028
+ if (!uiId || !inputName) return;
2029
+ if (!out.has(uiId)) out.set(uiId, []);
2030
+ const names = out.get(uiId);
2031
+ if (!names.includes(inputName)) names.push(inputName);
2032
+ };
2033
+ if (Array.isArray(used)) {
2034
+ for (const entry of used) add(stringValue(entry?.uiUniqueIdentifier), stringValue(entry?.inputName));
2035
+ } else if (used && typeof used === 'object') {
2036
+ for (const [uiId, names] of Object.entries(used)) {
2037
+ for (const name of (Array.isArray(names) ? names : [names])) add(uiId, stringValue(name));
2038
+ }
2039
+ }
2040
+ const result = {};
2041
+ for (const [uiId, names] of out) result[uiId] = names;
2042
+ return result;
2043
+ }
2044
+
2045
+ export function readLabelCache(definition) {
2046
+ const raw = definition?.labelCacheAsJsonString ?? definition?.label_cache ?? definition?.labelCache;
2047
+ let entries = raw;
2048
+ if (typeof raw === 'string') {
2049
+ try { entries = raw.trim() ? JSON.parse(raw) : []; } catch { entries = []; }
2050
+ }
2051
+ if (!Array.isArray(entries)) return [];
2052
+ return entries
2053
+ .map(entry => ({
2054
+ name: stringValue(entry?.name),
2055
+ label: stringValue(entry?.label),
2056
+ type: stringValue(entry?.type),
2057
+ baseType: stringValue(entry?.base_type || entry?.baseType),
2058
+ usedInstances: normalizeUsedInstances(entry?.usedInstances),
2059
+ }))
2060
+ .filter(entry => entry.name);
2061
+ }
2062
+
2063
+ function describeKnownPills(cache) {
2064
+ const names = cache.map(entry => entry.name);
2065
+ if (!names.length) return 'this flow has no registered data pills';
2066
+ return `registered pills: ${names.slice(0, 8).join(', ')}${names.length > 8 ? ` (+${names.length - 8} more)` : ''}`;
2067
+ }
2068
+
2069
+ // A pill no entry covers still needs a label the canvas can draw. Resolve the
2070
+ // producing step and the field it names, then build the label Flow Designer
2071
+ // itself would: `Trigger - <trigger>➛<input>` or `<order> - <action>➛<input>`.
2072
+ // `pending` covers steps this same manifest is inserting: their identity and
2073
+ // input schema already exist here even though the flow does not carry them yet.
2074
+ export function resolvePillBinding(definition, pillName, flowId, cache, pending = []) {
2075
+ const fail = () => {
2076
+ 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.`);
2077
+ };
2078
+ const separator = pillName.indexOf('.');
2079
+ if (separator <= 0) return fail();
2080
+ const stepKey = pillName.slice(0, separator);
2081
+ const remainder = pillName.slice(separator + 1);
2082
+ const fieldName = remainder.startsWith('__status__.') ? remainder : remainder.split('.')[0];
2083
+ const describe = (fields, name) => {
2084
+ const field = inputList({ inputs: fields }).find(entry => stringValue(entry?.name) === name);
2085
+ if (!field) return null;
2086
+ return {
2087
+ label: stringValue(field?.parameter?.label) || stringValue(field?.parameter?.name) || String(field?.name ?? ''),
2088
+ type: stringValue(field?.parameter?.type),
2089
+ };
2090
+ };
2091
+
2092
+ const candidates = [
2093
+ ...findArray(definition, 'triggerInstances').map(step => ({ ...step, trigger: true })),
2094
+ ...findExistingActions(definition).map(step => ({ ...step, trigger: false })),
2095
+ ...pending.map(step => ({ ...step, trigger: false })),
2096
+ ...(findArray(definition, 'flowLogicInstances') || []).filter(fl => String(fl.definitionId) === '35d60003e6022010a5e40cdd1254dd23' || String(fl.definitionId) === '35d60003e6022010a5e40cdd1254dd21').map(fl => ({
2097
+ name: String(fl.definitionId) === '35d60003e6022010a5e40cdd1254dd23' ? 'Error Handler' : 'Catch',
2098
+ order: stringValue(fl.order),
2099
+ uiUniqueIdentifier: stringValue(fl.uiUniqueIdentifier || fl.ui_unique_identifier),
2100
+ trigger: false,
2101
+ inputs: [
2102
+ { name: '__status__.message', parameter: { label: 'Error Status➛Message', type: 'string' } },
2103
+ { name: '__status__.code', parameter: { label: 'Error Status➛Code', type: 'integer' } }
2104
+ ]
2105
+ }))
2106
+ ];
2107
+ for (const step of candidates) {
2108
+ const name = stringValue(step.name);
2109
+ const order = stringValue(step.order) || '1';
2110
+ const uiId = stringValue(step.uiUniqueIdentifier || step.ui_unique_identifier);
2111
+ const matchesAlias = new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}_\\d+$`).test(stepKey);
2112
+ if (!matchesAlias && stepKey !== uiId) continue;
2113
+ // Inputs and outputs both become draggable pills; look at each before failing.
2114
+ const field = describe(step.inputs, fieldName) || describe(step.outputs, fieldName);
2115
+ if (!field) continue;
2116
+ const prefix = step.trigger ? `Trigger - ${name}` : `${order} - ${name}`;
2117
+ return { label: `${prefix}➛${field.label}`, type: field.type };
2118
+ }
2119
+ return fail();
2120
+ }
2121
+
1180
2122
  export async function updateFlowFromManifest(sdk, instance, identifier, inputManifest, options = {}) {
1181
2123
  const manifest = validateFlowUpdateManifest(inputManifest);
1182
2124
  const target = await resolveFlowForUpdate(sdk, identifier);
@@ -1212,7 +2154,19 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1212
2154
  const snapshots = [];
1213
2155
  const triggerUpdates = [];
1214
2156
  const actionUpdates = [];
1215
- const stageInserts = buildStageInserts((manifest.stages || []).filter(stage => stage.stageId === undefined), { idFactory: options.idFactory || (() => randomUUID()), flowId });
2157
+ const actionInserts = [];
2158
+ const actionDeletes = [];
2159
+ const flowVariableInserts = [];
2160
+ const flowLogicInserts = [];
2161
+ const flowLogicUpdates = [];
2162
+ const flowLogicDeletes = [];
2163
+ const labelCacheUpdates = [];
2164
+ let manifestStages = manifest.stages || [];
2165
+ if ((manifest.stageTemplate || manifest.stageSet) && manifestStages.length === 0) {
2166
+ const templateStages = await resolveStageTemplate(sdk, manifest.stageTemplate || manifest.stageSet);
2167
+ manifestStages = templateStages;
2168
+ }
2169
+ const stageInserts = buildStageInserts(manifestStages.filter(stage => stage.stageId === undefined), { idFactory: options.idFactory || (() => randomUUID()), flowId });
1216
2170
  const stageUpdates = buildStageUpdates((manifest.stages || []).filter(stage => stage.stageId !== undefined));
1217
2171
  const changedActionInputs = new Map();
1218
2172
  const actionTargets = new Map();
@@ -1231,18 +2185,43 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1231
2185
  }
1232
2186
  }
1233
2187
  const existingActions = findExistingActions(beforeDefinition);
1234
- 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 });
2188
+ const existingOrders = new Set(existingActions.map(a => String(a.order)));
2189
+ const idFactory = options.idFactory || (() => randomUUID());
2190
+ const pillToInstances = new Map();
2191
+ const pendingSteps = [];
2192
+ const actionUiMap = new Map();
2193
+ const logicUiMap = new Map(); // order -> uiUniqueIdentifier
2194
+ for (const a of existingActions) {
2195
+ const ui = stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier);
2196
+ if (a.order && ui) actionUiMap.set(String(a.order), ui);
1243
2197
  }
2198
+ // One input value can carry several pills; register every reference, not just
2199
+ // the first, or the later ones never reach label_cache and stay blank.
2200
+ const collectPills = (value, uiUniqueIdentifier, inputName) => {
2201
+ for (const match of String(value).matchAll(/\{\{([^}]+)\}\}/g)) {
2202
+ const pillName = match[1].trim();
2203
+ if (!pillName) continue;
2204
+ if (!pillToInstances.has(pillName)) pillToInstances.set(pillName, []);
2205
+ const instances = pillToInstances.get(pillName);
2206
+ if (!instances.some(entry => entry.uiUniqueIdentifier === uiUniqueIdentifier && entry.inputName === inputName)) {
2207
+ instances.push({ uiUniqueIdentifier, inputName });
2208
+ }
2209
+ }
2210
+ };
2211
+
2212
+ await planManifestSteps({ manifest, beforeDefinition, existingActions, existingOrders, actionUiMap, logicUiMap, pendingSteps, idFactory, sdk, instance, scope, flowId, actionInserts, actionUpdates, flowLogicInserts, actionTargets, changedActionInputs, changes, collectPills });
2213
+
1244
2214
  const savedStages = stageList(beforeDefinition);
1245
2215
  const savedStageById = new Map(savedStages.map(stage => [stringValue(stage.stageId || stage.stage_id), stage]));
2216
+ // The provider replaces a flow's whole stage list when the patch inserts
2217
+ // stages, so an insert-only manifest silently drops the stages already there.
2218
+ // Refuse before any write rather than let the preservation check fail after.
2219
+ const namedStageIds = new Set(stageUpdates.map(update => update.stageId));
2220
+ const unlistedStages = savedStages.filter(stage => !namedStageIds.has(stringValue(stage.stageId || stage.stage_id)));
2221
+ if (stageInserts.length && unlistedStages.length) {
2222
+ const names = unlistedStages.map(stage => stringValue(stage.label)).filter(Boolean).join(', ');
2223
+ throw new Error(`Flow ${flowId} already has ${unlistedStages.length} stage(s) (${names}); inserting stages replaces the flow's stage list. Name every existing stage with its stageId in the manifest so it is kept. No content write attempted.`);
2224
+ }
1246
2225
  for (const update of stageUpdates) {
1247
2226
  const before = savedStageById.get(update.stageId);
1248
2227
  if (!before) throw new Error(`Flow ${flowId} has no stage ${update.stageId}; omit stageId to insert a new stage`);
@@ -1254,7 +2233,137 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1254
2233
  for (const insert of stageInserts) {
1255
2234
  changes.push({ component: 'stage', stage: insert.label, input: 'insert', before: null, after: { order: insert.order, componentIndexes: insert.componentIndexes } });
1256
2235
  }
1257
- if (triggerUpdates.length === 0 && actionUpdates.length === 0 && stageInserts.length === 0 && stageUpdates.length === 0) throw new Error(`Flow ${flowId} update has no supported changes`);
2236
+
2237
+ // Handle flowVariables insertion
2238
+ const requestedVariables = manifest.flowVariables || manifest.variables || [];
2239
+ const existingVars = beforeDefinition.flowVariables || [];
2240
+ for (const [varIdx, v] of requestedVariables.entries()) {
2241
+ const label = v.label || v.name;
2242
+ const name = (v.name || v.label).toLowerCase().replace(/[^a-z0-9_]/g, '');
2243
+ const rawType = (v.type || 'string').toLowerCase();
2244
+ const TYPE_MAP = {
2245
+ 'string': { type: 'string', label: 'String' },
2246
+ 'boolean': { type: 'boolean', label: 'True/False' },
2247
+ 'true/false': { type: 'boolean', label: 'True/False' },
2248
+ 'bool': { type: 'boolean', label: 'True/False' },
2249
+ 'integer': { type: 'integer', label: 'Integer' },
2250
+ 'int': { type: 'integer', label: 'Integer' },
2251
+ 'decimal': { type: 'decimal', label: 'Decimal' },
2252
+ 'float': { type: 'float', label: 'Floating Point Number' },
2253
+ 'date': { type: 'glide_date', label: 'Date' },
2254
+ 'glide_date': { type: 'glide_date', label: 'Date' },
2255
+ 'date/time': { type: 'glide_date_time', label: 'Date/Time' },
2256
+ 'datetime': { type: 'glide_date_time', label: 'Date/Time' },
2257
+ 'glide_date_time': { type: 'glide_date_time', label: 'Date/Time' },
2258
+ 'reference': { type: 'reference', label: 'Reference' },
2259
+ 'choice': { type: 'choice', label: 'Choice' },
2260
+ 'array.string': { type: 'array.string', label: 'Array.String' },
2261
+ 'array.reference': { type: 'array.reference', label: 'Array.Reference' },
2262
+ 'array.integer': { type: 'array.integer', label: 'Array.Integer' },
2263
+ 'array.boolean': { type: 'array.boolean', label: 'Array.True/False' },
2264
+ 'json': { type: 'json', label: 'JSON' },
2265
+ 'html': { type: 'html', label: 'HTML' }
2266
+ };
2267
+ const mapped = TYPE_MAP[rawType] || { type: rawType, label: v.type_label || (rawType.charAt(0).toUpperCase() + rawType.slice(1)) };
2268
+ const type = mapped.type;
2269
+ const type_label = v.type_label || mapped.label;
2270
+ const varOrder = v.order || (existingVars.length + varIdx + 1);
2271
+ const varUiId = v.uiUniqueIdentifier || idFactory();
2272
+ flowVariableInserts.push({
2273
+ label,
2274
+ name,
2275
+ type,
2276
+ type_label,
2277
+ order: varOrder,
2278
+ mandatory: Boolean(v.mandatory),
2279
+ readonly: Boolean(v.readonly),
2280
+ attributes: `sourceUiUniqueId=,sourceType=,sourceId=,uiUniqueId=${varUiId},`,
2281
+ uiDisplayType: type,
2282
+ uiDisplayTypeLabel: type_label
2283
+ });
2284
+ changes.push({ component: 'flowVariable', input: name, before: null, after: { label, type, order: varOrder } });
2285
+ }
2286
+
2287
+ // Handle deletions by step order or uiUniqueIdentifier
2288
+ const rawDeletes = manifest.deleteSteps || manifest.delete || manifest.deleteOrders || [];
2289
+ const deleteTargets = new Set((Array.isArray(rawDeletes) ? rawDeletes : [rawDeletes]).map(String));
2290
+ if (deleteTargets.size > 0) {
2291
+ const existingLogics = beforeDefinition.flowLogicInstances || beforeDefinition.flowLogics || [];
2292
+ for (const a of existingActions) {
2293
+ const uiId = stringValue(a.uiUniqueIdentifier || a.ui_unique_identifier);
2294
+ const targetId = stringValue(a.sysId || a.id || a.sys_id || uiId);
2295
+ if (deleteTargets.has(String(a.order)) || deleteTargets.has(uiId) || deleteTargets.has(targetId)) {
2296
+ actionDeletes.push(targetId);
2297
+ changes.push({ component: 'action', order: a.order, type: a.name, input: 'delete', before: targetId, after: null });
2298
+ }
2299
+ }
2300
+ for (const fl of existingLogics) {
2301
+ const uiId = stringValue(fl.uiUniqueIdentifier || fl.ui_unique_identifier);
2302
+ const targetId = stringValue(fl.sysId || fl.id || fl.sys_id || uiId);
2303
+ if (deleteTargets.has(String(fl.order)) || deleteTargets.has(uiId) || deleteTargets.has(targetId)) {
2304
+ flowLogicDeletes.push(targetId);
2305
+ changes.push({ component: 'flowLogic', order: fl.order, type: fl.name, input: 'delete', before: targetId, after: null });
2306
+ }
2307
+ }
2308
+ }
2309
+ const errorHandlingInput = manifest.errorHandling ?? manifest.errorHandler;
2310
+ if (errorHandlingInput !== undefined) await planErrorHandling({ sdk, instance, scope, flowId, beforeDefinition, existingActions, actionInserts, actionUpdates, flowLogicInserts, flowLogicUpdates, changes, idFactory, actionUiMap, pendingSteps, changedActionInputs, collectPills, errorHandlingInput, actionTargets });
2311
+
2312
+ const mergedActionUpdates = new Map();
2313
+ for (const update of actionUpdates) {
2314
+ const prior = mergedActionUpdates.get(update.uiUniqueIdentifier);
2315
+ if (prior) {
2316
+ for (const key of ['parent', 'parentUiId']) if (prior[key] !== undefined && update[key] !== undefined && prior[key] !== update[key]) throw new Error(`Conflicting action ${key} requests`);
2317
+ const inputs = [...(prior.inputs || [])];
2318
+ for (const input of update.inputs || []) {
2319
+ const existing = inputs.find(i => i.name === input.name);
2320
+ if (existing && !isDeepStrictEqual(existing, input)) throw new Error(`Conflicting action input ${input.name} requests`);
2321
+ if (!existing) inputs.push(input);
2322
+ }
2323
+ Object.assign(prior, update, inputs.length ? { inputs } : {});
2324
+ } else mergedActionUpdates.set(update.uiUniqueIdentifier, { ...update });
2325
+ }
2326
+ actionUpdates.splice(0, actionUpdates.length, ...mergedActionUpdates.values());
2327
+
2328
+ // Register every referenced pill so the canvas can draw it. Runs after every
2329
+ // collection point (actions and logic blocks) so no reference is missed.
2330
+ // Existing entries keep their label/type; a pill this flow has never seen gets
2331
+ // a label resolved from its producing step.
2332
+ const labelCacheInserts = [];
2333
+ const existingLabelCache = readLabelCache(beforeDefinition);
2334
+ const mergeUsedInstances = (existing, instances) => {
2335
+ const merged = { ...(existing || {}) };
2336
+ for (const { uiUniqueIdentifier, inputName } of instances) {
2337
+ if (!merged[uiUniqueIdentifier]) merged[uiUniqueIdentifier] = [];
2338
+ if (!merged[uiUniqueIdentifier].includes(inputName)) merged[uiUniqueIdentifier].push(inputName);
2339
+ }
2340
+ return merged;
2341
+ };
2342
+ for (const [pillName, instances] of pillToInstances.entries()) {
2343
+ const existing = existingLabelCache.find(entry => entry.name === pillName);
2344
+ const usedInstances = mergeUsedInstances(existing?.usedInstances, instances);
2345
+ // An entry with no caption draws nothing, so a missing label is repaired
2346
+ // rather than passed through; a missing type is filled in when resolvable.
2347
+ let binding = null;
2348
+ if (!existing?.label) {
2349
+ binding = resolvePillBinding(beforeDefinition, pillName, flowId, existingLabelCache, pendingSteps);
2350
+ } else if (!existing.type) {
2351
+ try { binding = resolvePillBinding(beforeDefinition, pillName, flowId, existingLabelCache, pendingSteps); } catch { binding = null; }
2352
+ }
2353
+ if (existing) {
2354
+ labelCacheUpdates.push(labelCacheEntry({
2355
+ ...existing,
2356
+ label: existing.label || binding.label,
2357
+ type: existing.type || binding.type,
2358
+ baseType: existing.baseType || binding.type,
2359
+ usedInstances,
2360
+ }));
2361
+ } else {
2362
+ labelCacheInserts.push(labelCacheEntry({ name: pillName, label: binding.label, type: binding.type, baseType: binding.type, usedInstances }));
2363
+ }
2364
+ }
2365
+ validateFinalStepPlan(beforeDefinition, actionInserts, actionUpdates, actionDeletes, flowLogicInserts, flowLogicUpdates, flowLogicDeletes);
2366
+ 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
2367
  if (options.preview) return {
1259
2368
  preview: true,
1260
2369
  flow: { id: flowId, name: target.flowName, status: lifecycle.status, active: lifecycle.active },
@@ -1281,17 +2390,64 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1281
2390
  const outcome = await withFlowSafeEdit(sdk, instance, flowId, beforeDefinition.updated, async () => {
1282
2391
  let completedStage = 'validated';
1283
2392
  try {
2393
+ if (stageInserts.length > 0) {
2394
+ const stagesPayload = {};
2395
+ for (const s of stageInserts) {
2396
+ stagesPayload[s.stageId] = {
2397
+ stageId: s.stageId,
2398
+ duration: s.duration || STAGE_DURATION,
2399
+ componentIndexes: s.componentIndexes || [],
2400
+ label: s.label,
2401
+ value: s.value,
2402
+ type: s.type || 'standard',
2403
+ order: s.order,
2404
+ alwaysShow: s.alwaysShow ?? true,
2405
+ states: {
2406
+ pending: 'Pending - has not started',
2407
+ in_progress: 'In progress',
2408
+ skipped: 'Skipped',
2409
+ complete: 'Completed',
2410
+ error: 'Error'
2411
+ },
2412
+ system: Boolean(s._system ?? s.system)
2413
+ };
2414
+ }
2415
+ const stageRegRes = await sdk.request(`${instance}${FLOW_ENDPOINT}/${encodeURIComponent(flowId)}/stages?sysparm_transaction_scope=${encodeURIComponent(scope)}`, {
2416
+ method: 'PUT',
2417
+ body: JSON.stringify(stagesPayload)
2418
+ });
2419
+ const returnedStages = stageRegRes?.result?.data || {};
2420
+ // The PUT writes stage rows before the patch runs, so a silent omission
2421
+ // here would leave the flow holding stages nothing points at.
2422
+ const unconfirmed = [];
2423
+ for (const s of stageInserts) {
2424
+ if (returnedStages[s.stageId]?.id) s.id = returnedStages[s.stageId].id;
2425
+ else unconfirmed.push(s.label || s.stageId);
2426
+ }
2427
+ if (unconfirmed.length) {
2428
+ throw new Error(`Flow ${flowId} stage registration did not confirm ${unconfirmed.join(', ')}; those stages may already be attached to the flow. Inspect it before retrying`);
2429
+ }
2430
+ }
2431
+ const patchQuery = buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates, actionInserts, actionDeletes, flowVariableInserts, flowLogicInserts, flowLogicUpdates, flowLogicDeletes, labelCacheUpdates, labelCacheInserts, stageInserts, stageUpdates });
1284
2432
  const patchResponse = await mutationContext('trigger_and_actions_update', readUpdateSet, snapshots, () => sdk.request(`${instance}${GRAPHQL_ENDPOINT}`, {
1285
2433
  method: 'POST',
1286
- body: JSON.stringify({ query: buildFlowUpdateMutation({ flowId, triggerUpdates, actionUpdates, stageInserts, stageUpdates }), variables: {} }),
2434
+ body: JSON.stringify({ query: patchQuery, variables: {} }),
1287
2435
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
1288
2436
  assertGraphQLSuccess(patchResponse, 'Flow trigger/action update');
1289
2437
  completedStage = 'patch_acknowledged';
1290
2438
  const processflow = await readProcessFlow(sdk, instance, flowId, scope);
2439
+ assertInsertedIdentities(patchResponse, processflow, actionInserts, 'action', flowId);
2440
+ assertInsertedIdentities(patchResponse, processflow, flowLogicInserts, 'logic', flowId);
2441
+ assertStepReadback(processflow, [...actionInserts, ...actionUpdates], 'action', flowId);
2442
+ assertStepReadback(processflow, [...flowLogicInserts, ...flowLogicUpdates], 'logic', flowId);
2443
+ assertLogicPreserved(beforeDefinition, processflow, flowLogicInserts, flowLogicUpdates, flowLogicDeletes, flowId);
1291
2444
  // Only requested values may differ. Preserve array order and opaque fields.
1292
2445
  // `stages` is compared separately below: a stage edit may touch specific
1293
2446
  // fields, while every stage the manifest did not name must stay identical.
1294
- for (const field of ['flowVariables', 'flowLogicInstances', 'subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs']) {
2447
+ const checkFields = ['subFlowInstances', 'flowInputs', 'flowOutputs', 'inputs', 'outputs'];
2448
+ if (flowVariableInserts.length === 0) checkFields.push('flowVariables');
2449
+ if (flowLogicInserts.length === 0 && flowLogicUpdates.length === 0 && flowLogicDeletes.length === 0) checkFields.push('flowLogicInstances');
2450
+ for (const field of checkFields) {
1295
2451
  if (!isDeepStrictEqual(beforeDefinition[field], processflow[field])) throw new Error(`Flow ${flowId} changed omitted ${field}; preservation failed`);
1296
2452
  }
1297
2453
  if (stageInserts.length || stageUpdates.length) {
@@ -1309,13 +2465,37 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1309
2465
  throw new Error(`Flow ${flowId} changed omitted stages; preservation failed`);
1310
2466
  }
1311
2467
  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`);
2468
+ const insertedUiIds = new Set(actionInserts.map(a => a.uiUniqueIdentifier));
2469
+ const deletedActionIds = new Set(actionDeletes);
2470
+ const maskActions = (definition, isAfter = false) => findExistingActions(definition)
2471
+ .filter(action => {
2472
+ const uiId = stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier);
2473
+ const sId = stringValue(action.sysId || action.id || action.sys_id);
2474
+ if (isAfter && insertedUiIds.has(uiId)) return false;
2475
+ if (!isAfter && (deletedActionIds.has(uiId) || deletedActionIds.has(sId))) return false;
2476
+ return true;
2477
+ })
2478
+ .map(action => {
2479
+ const copy = clone(action);
2480
+ const move = actionUpdates.find(update => update.uiUniqueIdentifier === stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier) && update.parent !== undefined);
2481
+ if (move) {
2482
+ if (isAfter && (copy.parent !== move.parent || copy.parentUiId !== move.parentUiId)) throw new Error(`Flow ${flowId} action parent readback did not match requested target`);
2483
+ delete copy.parent;
2484
+ delete copy.parentUiId;
2485
+ }
2486
+ const changed = changedActionInputs.get(stringValue(action.uiUniqueIdentifier || action.ui_unique_identifier));
2487
+ for (const [index, input] of inputList(copy).entries()) if (changed?.has(input.name)) inputList(copy)[index] = maskInputValue(input);
2488
+ return copy;
2489
+ });
2490
+ if (!isDeepStrictEqual(maskActions(beforeDefinition), maskActions(processflow, true))) throw new Error(`Flow ${flowId} changed omitted action fields; preservation failed`);
2491
+ // A pill the provider accepted but did not store still renders blank, so
2492
+ // read the cache back instead of trusting the mutation acknowledgement.
2493
+ const readbackCache = readLabelCache(processflow);
2494
+ for (const entry of [...labelCacheInserts, ...labelCacheUpdates]) {
2495
+ const saved = readbackCache.find(candidate => candidate.name === entry.name);
2496
+ if (!saved) throw new Error(`Flow ${flowId} did not persist data pill ${entry.name} to label_cache; the reference would render blank`);
2497
+ if (!saved.label) throw new Error(`Flow ${flowId} persisted data pill ${entry.name} without a label; the reference would render blank`);
2498
+ }
1319
2499
  const readbackTrigger = findArray(processflow, 'triggerInstances')[0];
1320
2500
  if (triggerUpdate) {
1321
2501
  if (!readbackTrigger || findId(readbackTrigger, ['sysId', 'sys_id', 'id', 'triggerId']) !== triggerUpdate.id) throw new Error(`Flow ${flowId} trigger update was not readable after mutation`);
@@ -1366,7 +2546,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1366
2546
  const afterInput = inputList(readback).find(candidate => candidate.name === input.name);
1367
2547
  if (!afterInput) throw new Error(`Flow ${flowId} Action ${uiId} lost input ${input.name} during update`);
1368
2548
  if (!changed.has(input.name) && JSON.stringify(input) !== JSON.stringify(afterInput)) throw new Error(`Flow ${flowId} Action ${uiId} changed omitted input ${input.name}`);
1369
- 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`);
2549
+ 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`);
1370
2550
  }
1371
2551
  }
1372
2552
  completedStage = 'definition_verified';