@uipath/maestro-builder-sdk 6.124.1 → 6.124.3

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.
@@ -107,12 +107,13 @@ export interface PreservedConnectorRows {
107
107
  * `elementIds` are the spellings of the element's own id a row may carry:
108
108
  * the one compile writes (the trigger's node id, else `<stage id>-<task or
109
109
  * rule id>`), and an older SDK's bare task or rule id, which compile repairs
110
- * (#1426).
110
+ * (#1426). `stageId` is the stage a task or rule sits in.
111
111
  */
112
112
  export declare function caseConnectorRowOwners(plan: Record<string, any>): Array<{
113
113
  key: string;
114
114
  bag: Record<string, any>;
115
115
  elementIds: string[];
116
+ stageId?: string;
116
117
  }>;
117
118
  /**
118
119
  * The saved own rows of a connector element, for each half compile would not
@@ -144,8 +145,11 @@ export declare function droppedConnectorOutputRows(result: Record<string, any>,
144
145
  * Write each element's saved own rows back over the ones compile built, half
145
146
  * by half, while they still describe the element. Runs after the ids are
146
147
  * restored, so an owner key finds its element by the plan's own ids, also
147
- * after a rename.
148
+ * after a rename, and after a move to another stage ({@link ownerEntries},
149
+ * {@link followMove}). `identities` is the payload's `identities` as saved,
150
+ * before `followRenames` moves a moved task's identity to its stage now: where
151
+ * each task and rule was saved, and a task's saved `elementId`.
148
152
  */
149
- export declare function applyConnectorRows(result: Record<string, any>, entries: readonly PreservedConnectorRows[] | undefined): void;
153
+ export declare function applyConnectorRows(result: Record<string, any>, entries: readonly PreservedConnectorRows[] | undefined, identities?: unknown): void;
150
154
  /** Problems with a payload's `connectorRows`, for `caseJsonPreservationErrors`. */
151
155
  export declare function connectorRowErrors(entries: unknown): string[];
@@ -61,7 +61,7 @@
61
61
  * variable) gets compile's row.
62
62
  */
63
63
  import { activityFieldValues, comparesContextRow, ConnectorKind, connectorKind, onlyLibraryValuesDiffer, subscriptionValues } from './connector-saved-context.js';
64
- import { caseSubscriptionOwners, withScopeExpression } from './subscription.js';
64
+ import { caseSubscriptionOwners, ownerEntries, withScopeExpression } from './subscription.js';
65
65
  /** Two input values that hold the same thing: both empty, or equal with key order not counting. */
66
66
  function sameInput(a, b) {
67
67
  return (isEmpty(a) && isEmpty(b)) || stable(a) === stable(b);
@@ -85,7 +85,7 @@ const isObject = (value) => !!value && typeof value === 'object' && !Array.isArr
85
85
  * `elementIds` are the spellings of the element's own id a row may carry:
86
86
  * the one compile writes (the trigger's node id, else `<stage id>-<task or
87
87
  * rule id>`), and an older SDK's bare task or rule id, which compile repairs
88
- * (#1426).
88
+ * (#1426). `stageId` is the stage a task or rule sits in.
89
89
  */
90
90
  export function caseConnectorRowOwners(plan) {
91
91
  const out = caseSubscriptionOwners(plan).map(({ key, bag }) => {
@@ -94,7 +94,7 @@ export function caseConnectorRowOwners(plan) {
94
94
  return { key, bag, elementIds: [rest.join(':')] };
95
95
  const [stageId, ...own] = rest;
96
96
  const ownId = own.join(':');
97
- return { key: kind === 'task' ? `task:${ownId}` : key, bag, elementIds: [`${stageId}-${ownId}`, ownId] };
97
+ return { key: kind === 'task' ? `task:${ownId}` : key, bag, elementIds: [`${stageId}-${ownId}`, ownId], stageId };
98
98
  });
99
99
  for (const node of Array.isArray(plan?.nodes) ? plan.nodes : []) {
100
100
  if (!String(node?.type ?? '').endsWith('Stage'))
@@ -102,7 +102,7 @@ export function caseConnectorRowOwners(plan) {
102
102
  for (const lane of Array.isArray(node.data?.tasks) ? node.data.tasks : [])
103
103
  for (const task of Array.isArray(lane) ? lane : [])
104
104
  if (task?.type === CONNECTOR_ACTIVITY_TYPE && isObject(task.data))
105
- out.push({ key: `task:${task.id}`, bag: task.data, elementIds: [`${node.id}-${task.id}`, String(task.id)] });
105
+ out.push({ key: `task:${task.id}`, bag: task.data, elementIds: [`${node.id}-${task.id}`, String(task.id)], stageId: String(node.id) });
106
106
  }
107
107
  return out;
108
108
  }
@@ -505,11 +505,12 @@ function inputsBack(built, set, kind) {
505
505
  export function droppedConnectorOutputRows(result, entries, finalVar = (row) => row.var) {
506
506
  if (!entries?.length)
507
507
  return [];
508
- const byOwner = new Map(entries.map((entry) => [entry.owner, entry]));
508
+ const owners = caseConnectorRowOwners(result);
509
+ const entryFor = ownerEntries(entries, owners.map(({ key }) => key));
509
510
  const caseVariables = caseVariableIds(result);
510
511
  const out = [];
511
- for (const { key, bag } of caseConnectorRowOwners(result)) {
512
- const entry = byOwner.get(key);
512
+ for (const { key, bag } of owners) {
513
+ const entry = entryFor(key);
513
514
  if (!entry?.outputs || !sameOperation(bag, entry) || !Array.isArray(bag.outputs))
514
515
  continue;
515
516
  // Each built own row as it will read once its queued renames run.
@@ -527,19 +528,27 @@ export function droppedConnectorOutputRows(result, entries, finalVar = (row) =>
527
528
  * Write each element's saved own rows back over the ones compile built, half
528
529
  * by half, while they still describe the element. Runs after the ids are
529
530
  * restored, so an owner key finds its element by the plan's own ids, also
530
- * after a rename.
531
+ * after a rename, and after a move to another stage ({@link ownerEntries},
532
+ * {@link followMove}). `identities` is the payload's `identities` as saved,
533
+ * before `followRenames` moves a moved task's identity to its stage now: where
534
+ * each task and rule was saved, and a task's saved `elementId`.
531
535
  */
532
- export function applyConnectorRows(result, entries) {
536
+ export function applyConnectorRows(result, entries, identities) {
533
537
  if (!entries?.length)
534
538
  return;
535
- const byOwner = new Map(entries.map((entry) => [entry.owner, entry]));
539
+ const owners = caseConnectorRowOwners(result);
540
+ const entryFor = ownerEntries(entries, owners.map(({ key }) => key));
536
541
  const caseVariables = caseVariableIds(result);
537
- for (const { key, bag } of caseConnectorRowOwners(result)) {
538
- const entry = byOwner.get(key);
542
+ const saved = savedPlaces(identities);
543
+ const finalElementIds = taskElementIds(result);
544
+ for (const { key, bag, elementIds, stageId } of owners) {
545
+ const entry = entryFor(key);
539
546
  if (!entry || !sameOperation(bag, entry))
540
547
  continue;
541
548
  if (entry.extracts)
542
549
  extractsBack(bag, entry.extracts);
550
+ const ownId = elementIds[1];
551
+ const move = stageId !== undefined && ownId ? movedElement(saved.get(ownId), stageId, finalElementIds.get(ownId) ?? elementIds[0]) : undefined;
543
552
  for (const field of ['inputs', 'outputs']) {
544
553
  const set = entry[field];
545
554
  if (!set)
@@ -548,6 +557,8 @@ export function applyConnectorRows(result, entries) {
548
557
  const back = field === 'inputs' ? inputsBack(built, set, connectorKind(bag)) : outputsBack(built, set, caseVariables);
549
558
  if (!back)
550
559
  continue;
560
+ if (move)
561
+ followMove(back, move);
551
562
  if (set.absent && back.length === 0)
552
563
  delete bag[field];
553
564
  else
@@ -555,6 +566,78 @@ export function applyConnectorRows(result, entries) {
555
566
  }
556
567
  }
557
568
  }
569
+ /**
570
+ * Each task's and rule's saved place, by its own id, from the payload's
571
+ * `identities`. A task's saved `elementId` is the one the identity carries (a
572
+ * task Studio Web copied keeps `Stage_old-tOld`), else `<stage id>-<task id>`,
573
+ * the value compile writes and the identity then omits. A rule's is always
574
+ * `<stage id>-<rule id>`.
575
+ */
576
+ function savedPlaces(identities) {
577
+ const out = new Map();
578
+ const stages = isObject(identities) && Array.isArray(identities.stages) ? identities.stages : [];
579
+ for (const stage of stages) {
580
+ if (!isObject(stage) || typeof stage.id !== 'string')
581
+ continue;
582
+ const stageId = stage.id;
583
+ const rules = (conditions) => {
584
+ for (const condition of Array.isArray(conditions) ? conditions : [])
585
+ for (const group of isObject(condition) && Array.isArray(condition.rules) ? condition.rules : [])
586
+ for (const rule of Array.isArray(group) ? group : [group])
587
+ if (isObject(rule) && typeof rule.id === 'string')
588
+ out.set(rule.id, { stageId, elementId: `${stageId}-${rule.id}` });
589
+ };
590
+ rules(stage.entryConditions);
591
+ rules(stage.exitConditions);
592
+ for (const lane of Array.isArray(stage.tasks) ? stage.tasks : [])
593
+ for (const task of Array.isArray(lane) ? lane : []) {
594
+ if (!isObject(task))
595
+ continue;
596
+ if (typeof task.id === 'string')
597
+ out.set(task.id, { stageId, elementId: typeof task.elementId === 'string' ? task.elementId : `${stageId}-${task.id}` });
598
+ rules(task.entryConditions);
599
+ }
600
+ }
601
+ return out;
602
+ }
603
+ /** Each task's `elementId` in the compiled plan, by task id, once the saved ones are back. */
604
+ function taskElementIds(plan) {
605
+ const out = new Map();
606
+ for (const node of Array.isArray(plan?.nodes) ? plan.nodes : []) {
607
+ if (!String(node?.type ?? '').endsWith('Stage'))
608
+ continue;
609
+ for (const lane of Array.isArray(node.data?.tasks) ? node.data.tasks : [])
610
+ for (const task of Array.isArray(lane) ? lane : [])
611
+ if (typeof task?.id === 'string' && typeof task.elementId === 'string')
612
+ out.set(task.id, task.elementId);
613
+ }
614
+ return out;
615
+ }
616
+ /**
617
+ * The rewrite a moved element's saved rows need: from the `elementId` it was
618
+ * saved with to the one it has now. Only for an element an edit moved (saved
619
+ * in another stage than it sits in now) whose `elementId` changed with the
620
+ * move. An element in the stage it was saved in keeps its rows as saved, also
621
+ * when they name a stage it never sat in: a task Studio Web copied keeps
622
+ * `Stage_old-tOld` on the task and its rows.
623
+ */
624
+ function movedElement(saved, stageId, now) {
625
+ return !saved || saved.stageId === stageId || saved.elementId === now ? undefined : { from: saved.elementId, to: now };
626
+ }
627
+ /**
628
+ * Point each saved row that named a moved element where it was saved at the
629
+ * element's `elementId` now: the converter keeps only the rows whose
630
+ * `elementId` is their task's. For instance, a wait task `tW` saved in
631
+ * `Stage_A` with an output row `elementId: "Stage_A-tW"` and moved to
632
+ * `Stage_B` writes that row `elementId: "Stage_B-tW"`, as the task's own. A
633
+ * row that names another element (one it was copied from, `root`) or the bare
634
+ * id an older SDK wrote (#1426) is left as it is.
635
+ */
636
+ function followMove(rows, { from, to }) {
637
+ for (const row of rows)
638
+ if (isObject(row) && row.elementId === from)
639
+ row.elementId = to;
640
+ }
558
641
  /** Problems with a payload's `connectorRows`, for `caseJsonPreservationErrors`. */
559
642
  export function connectorRowErrors(entries) {
560
643
  if (entries === undefined)
@@ -105,9 +105,10 @@ export declare function applyPreservation(result: Record<string, unknown>, prese
105
105
  * instead of reading as a delete plus an add. Stages left over on both sides
106
106
  * pair by the most task names shared, then the fewest not shared, then in order
107
107
  * when as many are left on each side; a task left over pairs with one in the
108
- * same stage whose input and output rows have the same names, and a task gone
109
- * from its stage that another stage now holds under the same name and rows
110
- * moved there.
108
+ * same stage whose input and output rows have the same names (in any order,
109
+ * and not counting an empty container compile writes and the file lacks), and
110
+ * a task gone from its stage that another stage now holds under the same name
111
+ * and rows moved there.
111
112
  *
112
113
  * `wanted` is the payload's side (identities read from the original plan),
113
114
  * `compiled` this compile's. Per stage, `missing` tasks are the payload's that
@@ -22,7 +22,7 @@ import { connectorActivityMetadata, connectorEventFilterTree, connectorEventMeta
22
22
  import { EQUALS_EXPR_DIALECT } from '../core/connector-checks.js';
23
23
  import { bindingLabelRefusal, connectionStubMessage } from '../core/binding-messages.js';
24
24
  import { resolveEventWhere } from '../core/lookups.js';
25
- import { CASE_FILTER_SPELLING, caseSubscriptionBody, caseSubscriptionOwners, resolveCaseSubscription } from './subscription.js';
25
+ import { CASE_FILTER_SPELLING, caseSubscriptionBody, caseSubscriptionOwners, ownerEntries, resolveCaseSubscription } from './subscription.js';
26
26
  import { dedupeConditionNames } from './rule-names.js';
27
27
  import { EXTERNAL_TASK_DESCRIPTOR_CONTRACT, externalDescriptorRefusal, externalExecution, externalServiceType, } from './external.js';
28
28
  import { CASE_FORMAT_PROFILE, CASE_SCHEMA_VERSIONS, caseVersionMismatch } from './format-profile.js';
@@ -561,11 +561,13 @@ export function applyPreservation(result, preservation, options = {}) {
561
561
  const errors = caseJsonPreservationErrors(preservation);
562
562
  if (errors.length)
563
563
  throw new CompileRefusal('PRESERVATION_COLLISION', `invalid Case JSON preservation payload: ${errors.join('; ')}`);
564
+ // Where each task was saved, before `followRenames` moves a moved task's identity to its stage now.
565
+ const savedIdentities = preservation.identities;
564
566
  preservation = followRenames(result, preservation);
565
567
  applyPreservedIdentities(result, preservation, options.warn);
566
568
  applySubscriptionFilters(result, preservation);
567
569
  // After the ids are restored: an unchanged connector element takes its saved own io rows.
568
- applyConnectorRows(result, preservation.connectorRows);
570
+ applyConnectorRows(result, preservation.connectorRows, savedIdentities);
569
571
  applySubscriptionBindings(result, preservation.subscriptionBindings);
570
572
  // Once every row has its saved name and the connector rows are back.
571
573
  restoreOutputInterleaving(result, preservation.identities);
@@ -1158,9 +1160,10 @@ function withoutLayoutNodes(layout, gone) {
1158
1160
  * instead of reading as a delete plus an add. Stages left over on both sides
1159
1161
  * pair by the most task names shared, then the fewest not shared, then in order
1160
1162
  * when as many are left on each side; a task left over pairs with one in the
1161
- * same stage whose input and output rows have the same names, and a task gone
1162
- * from its stage that another stage now holds under the same name and rows
1163
- * moved there.
1163
+ * same stage whose input and output rows have the same names (in any order,
1164
+ * and not counting an empty container compile writes and the file lacks), and
1165
+ * a task gone from its stage that another stage now holds under the same name
1166
+ * and rows moved there.
1164
1167
  *
1165
1168
  * `wanted` is the payload's side (identities read from the original plan),
1166
1169
  * `compiled` this compile's. Per stage, `missing` tasks are the payload's that
@@ -1211,7 +1214,29 @@ export function followRenames(result, preservation) {
1211
1214
  if (typeof row?.id === 'string' && !variableNames.has(row.id))
1212
1215
  variableNames.set(row.id, row.name);
1213
1216
  const rowName = (row) => row?.custom === true && typeof row.var === 'string' ? variableNames.get(row.var) ?? row.var : String(row?.name ?? '');
1214
- const rowNames = (inputs, outputs) => JSON.stringify([inputs, outputs].map((rows) => (Array.isArray(rows) ? rows : []).map(rowName)));
1217
+ // Which rows a task has, as the source can change them: by name, in any
1218
+ // order. Compile can write a task's rows in another order than the file
1219
+ // saved them (a connector's `Error` row right after `response`), which the
1220
+ // payload restores later (`restoreOutputRowOrder`), and it writes `body: {}`
1221
+ // for an activity container the file saved no row for. Neither is an edit,
1222
+ // so neither may part a renamed or moved task from its saved identity. For
1223
+ // instance, a connector task saved with inputs `pathParameters,
1224
+ // queryParameters` and outputs `response, Id, Error` pairs with the compiled
1225
+ // one whose inputs are `pathParameters, queryParameters, body: {}` and
1226
+ // outputs `response, Error, Id`.
1227
+ const listOf = (rows) => (Array.isArray(rows) ? rows : []);
1228
+ const sorted = (names) => JSON.stringify([...names].sort());
1229
+ const isEmptyRow = (row) => {
1230
+ const value = row?.body !== undefined ? row.body : row?.value;
1231
+ return value === undefined || value === null || value === ''
1232
+ || (typeof value === 'object' && Object.keys(value).length === 0);
1233
+ };
1234
+ const sameRows = (saved, task) => {
1235
+ const savedInputs = listOf(saved.inputs).map(rowName);
1236
+ const inputs = listOf(task.data?.inputs).filter((row) => savedInputs.includes(rowName(row)) || !isEmptyRow(row)).map(rowName);
1237
+ return sorted(savedInputs) === sorted(inputs)
1238
+ && sorted(listOf(saved.outputs).map(rowName)) === sorted(listOf(task.data?.outputs).map(rowName));
1239
+ };
1215
1240
  const nameOf = (task) => String(task.displayName ?? '');
1216
1241
  const stageSides = wanted.map((stage) => {
1217
1242
  const target = compiled.find((candidate) => labelOf(candidate) === (stageLabels.get(stage.label) ?? stage.label));
@@ -1230,8 +1255,7 @@ export function followRenames(result, preservation) {
1230
1255
  const moves = new Map();
1231
1256
  const claimed = new Set();
1232
1257
  for (const { stage, task } of missingTasks) {
1233
- const rows = rowNames(task.inputs, task.outputs);
1234
- const to = extraTasks.filter((extra) => nameOf(extra.task) === task.name && rowNames(extra.task.data?.inputs, extra.task.data?.outputs) === rows);
1258
+ const to = extraTasks.filter((extra) => nameOf(extra.task) === task.name && sameRows(task, extra.task));
1235
1259
  if (to.length !== 1 || missingTasks.filter((other) => other.task.name === task.name).length !== 1)
1236
1260
  continue;
1237
1261
  if (!moves.has(stage))
@@ -1254,11 +1278,11 @@ export function followRenames(result, preservation) {
1254
1278
  const missing = side.missing.filter((task) => !movedTo(side.stage.label, task.name));
1255
1279
  const extra = side.extra
1256
1280
  .filter((task) => !claimed.has(task))
1257
- .map((task) => ({ name: nameOf(task), rows: rowNames(task.data?.inputs, task.data?.outputs), task }));
1281
+ .map((task) => ({ name: nameOf(task), task }));
1258
1282
  // A deleted sibling can share a renamed task's rows, so the one whose content
1259
1283
  // the renamed task still has wins, then the old name closest to the new one,
1260
1284
  // then the earlier task.
1261
- const candidates = missing.flatMap((task, from) => extra.flatMap((candidate, to) => candidate.rows === rowNames(task.inputs, task.outputs)
1285
+ const candidates = missing.flatMap((task, from) => extra.flatMap((candidate, to) => sameRows(task, candidate.task)
1262
1286
  ? [{ from, to, same: Number(task.fingerprint !== undefined && task.fingerprint === taskFingerprint(candidate.task, boundRows)), score: nameAffinity(task.name, candidate.name) }]
1263
1287
  : []));
1264
1288
  candidates.sort((a, b) => b.same - a.same || b.score - a.score || a.from - b.from || a.to - b.to);
@@ -2235,9 +2259,10 @@ function applyPreservedIdentities(result, preservation, warn) {
2235
2259
  function applySubscriptionBindings(result, entries) {
2236
2260
  if (!entries?.length)
2237
2261
  return;
2238
- const byOwner = new Map(entries.map((entry) => [entry.owner, entry.bindings]));
2239
- for (const { key, bag } of caseSubscriptionOwners(result)) {
2240
- const saved = byOwner.get(key);
2262
+ const owners = caseSubscriptionOwners(result);
2263
+ const entryFor = ownerEntries(entries, owners.map(({ key }) => key));
2264
+ for (const { key, bag } of owners) {
2265
+ const saved = entryFor(key)?.bindings;
2241
2266
  if (!saved || !Array.isArray(bag.bindings) || bag.bindings.length !== 0)
2242
2267
  continue;
2243
2268
  const text = JSON.stringify({ ...bag, bindings: undefined });
@@ -2287,12 +2312,14 @@ function conditionAndRuleIds(plan) {
2287
2312
  * minted, as an SDK-written leaf would.
2288
2313
  */
2289
2314
  function applySubscriptionFilters(result, preservation) {
2290
- const entries = new Map((preservation.subscriptionFilters ?? []).map((entry) => [entry.owner, entry]));
2291
- if (entries.size === 0)
2315
+ const saved = preservation.subscriptionFilters ?? [];
2316
+ if (saved.length === 0)
2292
2317
  return;
2293
2318
  const written = WRITTEN_SUBSCRIPTIONS.get(result) ?? [];
2294
- for (const owner of caseSubscriptionOwners(result)) {
2295
- const entry = entries.get(owner.key);
2319
+ const owners = caseSubscriptionOwners(result);
2320
+ const entryFor = ownerEntries(saved, owners.map(({ key }) => key));
2321
+ for (const owner of owners) {
2322
+ const entry = entryFor(owner.key);
2296
2323
  const row = Array.isArray(owner.bag.inputs) ? owner.bag.inputs[0] : undefined;
2297
2324
  const sub = entry && written.find((candidate) => candidate.inputRow === row);
2298
2325
  if (!entry || !sub)
@@ -143,11 +143,31 @@ export interface CaseSubscriptionOwner {
143
143
  /** The bag: `serviceType`, `context`, `inputs`. */
144
144
  bag: Record<string, any>;
145
145
  }
146
+ /**
147
+ * An owner key without the stage it sits in: `task:<task id>`,
148
+ * `rule:<rule id>`, `trigger:<node id>`. A task or rule keeps its own id when
149
+ * an edit moves it to another stage; only the stage part of its key changes.
150
+ */
151
+ export declare function ownElementKey(owner: string): string;
152
+ /**
153
+ * A lookup of `preserveCaseJson` entries by the owner key compile finds an
154
+ * element under (`ownerKeys`, the keys of the plan compile built). The exact
155
+ * key first; else the one entry for the same element id in another stage,
156
+ * when no element of the plan holds that entry's own key: the element moved
157
+ * there, and keeps what was saved for it. For instance, a wait-for-connector
158
+ * task `tW` saved as `task:Stage_A:tW` and moved to `Stage_B` is looked up as
159
+ * `task:Stage_B:tW` and finds that entry.
160
+ */
161
+ export declare function ownerEntries<T extends {
162
+ owner: string;
163
+ }>(entries: readonly T[], ownerKeys: Iterable<string>): (key: string) => T | undefined;
146
164
  /**
147
165
  * Every connector event subscription in a plan, keyed by the ids of what owns
148
166
  * it: an event trigger, a wait-for-connector task, or a wait-for-connector rule
149
167
  * in a stage's or task's conditions. Decompile and compile both key
150
168
  * `preserveCaseJson` subscription entries this way, so an entry follows its
151
- * owner through preservation's id restore and through a rename.
169
+ * owner through preservation's id restore and through a rename. A move to
170
+ * another stage changes the key's stage part; {@link ownerEntries} finds the
171
+ * entry by the element's own id then.
152
172
  */
153
173
  export declare function caseSubscriptionOwners(plan: Record<string, any>): CaseSubscriptionOwner[];
@@ -237,12 +237,54 @@ export function withScopeExpression(body, owner, eventParameters) {
237
237
  }
238
238
  const literalsOf = (params) => Object.values(params).map(String);
239
239
  const SUBSCRIPTION_SERVICE_TYPES = new Set(['Intsvc.EventTrigger', 'Intsvc.WaitForEvent']);
240
+ /**
241
+ * An owner key without the stage it sits in: `task:<task id>`,
242
+ * `rule:<rule id>`, `trigger:<node id>`. A task or rule keeps its own id when
243
+ * an edit moves it to another stage; only the stage part of its key changes.
244
+ */
245
+ export function ownElementKey(owner) {
246
+ const parts = owner.split(':');
247
+ return parts[0] === 'trigger' ? owner : `${parts[0]}:${parts[parts.length - 1]}`;
248
+ }
249
+ /**
250
+ * A lookup of `preserveCaseJson` entries by the owner key compile finds an
251
+ * element under (`ownerKeys`, the keys of the plan compile built). The exact
252
+ * key first; else the one entry for the same element id in another stage,
253
+ * when no element of the plan holds that entry's own key: the element moved
254
+ * there, and keeps what was saved for it. For instance, a wait-for-connector
255
+ * task `tW` saved as `task:Stage_A:tW` and moved to `Stage_B` is looked up as
256
+ * `task:Stage_B:tW` and finds that entry.
257
+ */
258
+ export function ownerEntries(entries, ownerKeys) {
259
+ const exact = new Map(entries.map((entry) => [entry.owner, entry]));
260
+ const present = new Set(ownerKeys);
261
+ const moved = new Map();
262
+ for (const entry of entries) {
263
+ if (present.has(entry.owner))
264
+ continue;
265
+ const own = ownElementKey(entry.owner);
266
+ moved.set(own, moved.has(own) ? null : entry);
267
+ }
268
+ const movedTo = new Map();
269
+ for (const key of present)
270
+ if (!exact.has(key))
271
+ movedTo.set(ownElementKey(key), (movedTo.get(ownElementKey(key)) ?? 0) + 1);
272
+ return (key) => {
273
+ const hit = exact.get(key);
274
+ if (hit)
275
+ return hit;
276
+ const own = ownElementKey(key);
277
+ return movedTo.get(own) === 1 ? moved.get(own) ?? undefined : undefined;
278
+ };
279
+ }
240
280
  /**
241
281
  * Every connector event subscription in a plan, keyed by the ids of what owns
242
282
  * it: an event trigger, a wait-for-connector task, or a wait-for-connector rule
243
283
  * in a stage's or task's conditions. Decompile and compile both key
244
284
  * `preserveCaseJson` subscription entries this way, so an entry follows its
245
- * owner through preservation's id restore and through a rename.
285
+ * owner through preservation's id restore and through a rename. A move to
286
+ * another stage changes the key's stage part; {@link ownerEntries} finds the
287
+ * entry by the element's own id then.
246
288
  */
247
289
  export function caseSubscriptionOwners(plan) {
248
290
  const out = [];
package/dist/decompile.js CHANGED
@@ -31,6 +31,7 @@
31
31
  import { FLOW_SCHEMA_VERSIONS } from './format-profile.js';
32
32
  import { preserveSchemaVersion } from './schema-version.js';
33
33
  import { BUNDLED_DEFINITIONS, bundledVersions } from './flow-definitions.js';
34
+ import { definitionHasErrorPort } from './core/error-port.js';
34
35
  import { DEFAULT_TRIGGER_ID, Expr } from './core/expr.js';
35
36
  import { FLOW_NODE_TYPES, FLOW_TRIGGER_TYPES } from './flow-node-registry.js';
36
37
  import { SUBFLOW_START_LABEL } from './core/subflow-start.js';
@@ -295,6 +296,26 @@ function updatesPart(rows, imp, inputNames) {
295
296
  function optsArg(node, ctx) {
296
297
  return optsArgWith(node, ctx, []);
297
298
  }
299
+ /**
300
+ * `errorHandlingEnabled: true` for a node whose error handle is switched on
301
+ * with nothing wired to it: the canvas's state right after the toggle, or after
302
+ * the handler's only step was deleted. With an `error` edge `.onError(...)`
303
+ * sets the flag itself, so it is printed only without one; without it the
304
+ * recompile dropped the flag and the handle vanished from the canvas.
305
+ */
306
+ function unwiredErrorHandle(node, ctx) {
307
+ if (node.inputs?.errorHandlingEnabled !== true)
308
+ return [];
309
+ if (ctx.graph.outEdges(node.id).some((e) => e.sourcePort === 'error'))
310
+ return [];
311
+ // A node type with no error port (a `delay`, say) can still carry the flag, and
312
+ // `flow validate` accepts it; printing the option there would make the recompile
313
+ // refuse the source (ONERROR_NO_ERROR_PORT), so such a node keeps dropping it.
314
+ const def = runDefs.get(`${node.type}@${node.typeVersion}`) ?? BUNDLED_DEFINITIONS[`${node.type}@${node.typeVersion}`] ?? runDefs.get(node.type);
315
+ if (def !== undefined && !definitionHasErrorPort(def))
316
+ return [];
317
+ return ['errorHandlingEnabled: true'];
318
+ }
298
319
  /** `optsArg` plus construct-specific option clauses (loop/do-while recovery). */
299
320
  function optsArgWith(node, ctx, extra) {
300
321
  const parts = [...extra];
@@ -2280,6 +2301,7 @@ function region(cursor, stop, scope, ipdom, ctx, refInto) {
2280
2301
  if (unwrapPlain(inputs.breakEnabled) === true && !bodyBreaks(ctx.graph, bodyScope, node.id)) {
2281
2302
  extra.push('breakEnabled: true');
2282
2303
  }
2304
+ extra.push(...unwiredErrorHandle(node, ctx));
2283
2305
  const opts = optsArgWith(node, ctx, extra);
2284
2306
  if (node.type === T.doWhile) {
2285
2307
  const condRaw = unwrapSource(inputs.condition);
@@ -2314,7 +2336,7 @@ function region(cursor, stop, scope, ipdom, ctx, refInto) {
2314
2336
  continue;
2315
2337
  }
2316
2338
  if (node.type === T.subflow) {
2317
- segs.push(`.step(${tsLiteral(node.id)}, ${emitSubflow(node, ctx)}${optsArg(node, ctx)})`);
2339
+ segs.push(`.step(${tsLiteral(node.id)}, ${emitSubflow(node, ctx)}${optsArgWith(node, ctx, unwiredErrorHandle(node, ctx))})`);
2318
2340
  // A subflow step guards its body like any step: `core.subflow` declares
2319
2341
  // the `error` handle, and `.onError()` after the step authors it. Without
2320
2342
  // this the handler's edge had no spelling and a recompile dropped it.
@@ -2350,7 +2372,7 @@ function region(cursor, stop, scope, ipdom, ctx, refInto) {
2350
2372
  cursor = r === EXIT ? undefined : r;
2351
2373
  continue;
2352
2374
  }
2353
- segs.push(`.step(${tsLiteral(node.id)}, ${spec}${optsArg(node, ctx)})`);
2375
+ segs.push(`.step(${tsLiteral(node.id)}, ${spec}${optsArgWith(node, ctx, unwiredErrorHandle(node, ctx))})`);
2354
2376
  // An error handler on this step (source port `error` + `errorHandlingEnabled`).
2355
2377
  const succ = scopeSucc(ctx.graph, node.id, scope);
2356
2378
  const handler = errorHandlerSeg(node.id, succ, scope, ipdom, ctx);
@@ -12,15 +12,15 @@
12
12
  import { declareKeys } from './core/option-keys.js';
13
13
  /** The option keys of each builder method, by the kind of step it makes. */
14
14
  export const STEP_OPTION_KEYS = {
15
- action: { call: '.step()', keys: declareKeys({ version: true, updates: true, label: true, draft: true }) },
15
+ action: { call: '.step()', keys: declareKeys({ version: true, updates: true, label: true, draft: true, errorHandlingEnabled: true }) },
16
16
  branch: { call: '.branch()', keys: declareKeys({ version: true, updates: true, label: true, draft: true }) },
17
17
  switch: { call: '.switch()', keys: declareKeys({ version: true, updates: true, label: true }) },
18
18
  stepSwitch: { call: '.stepSwitch()', keys: declareKeys({ version: true, updates: true, label: true }) },
19
19
  loop: {
20
20
  call: '.loop()',
21
- keys: declareKeys({ version: true, updates: true, label: true, parallel: true, completionCondition: true, breakEnabled: true }),
21
+ keys: declareKeys({ version: true, updates: true, label: true, parallel: true, completionCondition: true, breakEnabled: true, errorHandlingEnabled: true }),
22
22
  },
23
- doWhile: { call: '.doWhile()', keys: declareKeys({ version: true, updates: true, label: true, limit: true, breakEnabled: true }) },
23
+ doWhile: { call: '.doWhile()', keys: declareKeys({ version: true, updates: true, label: true, limit: true, breakEnabled: true, errorHandlingEnabled: true }) },
24
24
  parallel: { call: '.parallel()', keys: declareKeys({ version: true, updates: true, label: true, fork: true }) },
25
25
  terminate: { call: '.terminate()', keys: declareKeys({ version: true, updates: true, label: true }) },
26
26
  return: { call: '.return()', keys: declareKeys({ version: true, updates: true, label: true, name: true }) },
@@ -330,6 +330,19 @@ export interface StepOptions extends NodeOptions {
330
330
  * for a Slack send saved with no connection.
331
331
  */
332
332
  draft?: boolean;
333
+ /**
334
+ * Show the step's error handle without wiring a handler: the node's
335
+ * `inputs.errorHandlingEnabled`, which the canvas's error-handling toggle
336
+ * sets. `.onError(...)` sets it on its own, so this is only for a handle left
337
+ * unwired. Decompile prints it for such a node, so a recompile keeps the
338
+ * handle. Nothing routes there: with no `error` edge a failure still fails
339
+ * the run. Refused on a node type with no error port (ONERROR_NO_ERROR_PORT).
340
+ *
341
+ * ```ts
342
+ * .step('fetch', script(fetchInvoice), { errorHandlingEnabled: true })
343
+ * ```
344
+ */
345
+ errorHandlingEnabled?: boolean;
333
346
  }
334
347
  /**
335
348
  * The options of `.branch()`: the {@link NodeOptions}, plus `draft` for a
@@ -447,6 +460,11 @@ export interface LoopOptions extends NodeOptions {
447
460
  * the body calls `b.break()`.
448
461
  */
449
462
  breakEnabled?: boolean;
463
+ /**
464
+ * Show the loop's error handle without wiring a handler — set automatically
465
+ * by `.onError(...)` after the loop (see {@link StepOptions.errorHandlingEnabled}).
466
+ */
467
+ errorHandlingEnabled?: boolean;
450
468
  }
451
469
  /**
452
470
  * Do-while options. `limit` caps iterations; the platform
@@ -457,6 +475,11 @@ export interface DoWhileOptions extends NodeOptions {
457
475
  limit?: number;
458
476
  /** Show the break handle without wiring one — set automatically by `b.break()`. */
459
477
  breakEnabled?: boolean;
478
+ /**
479
+ * Show the do-while's error handle without wiring a handler — set
480
+ * automatically by `.onError(...)` after it (see {@link StepOptions.errorHandlingEnabled}).
481
+ */
482
+ errorHandlingEnabled?: boolean;
460
483
  }
461
484
  export type Step = {
462
485
  kind: 'action';