@uipath/maestro-builder-sdk 6.82.3 → 6.82.4

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.
@@ -12,6 +12,14 @@ export interface ConnectorLiftVerdict {
12
12
  * `type` attribute and the response row's schema body do not either.
13
13
  */
14
14
  export declare function canonicalConnectorTask(el: Moddle): string;
15
+ /**
16
+ * The source that compiles one lifted call on its own: the decompile's preamble, a
17
+ * `.var()` stub for each variable it does not declare, then a start event, the call
18
+ * and an end event. Written through `builtChainSource`, as the decompile writes its
19
+ * own source, because the declarations and stubs can be more calls than one chain
20
+ * holds (#1663).
21
+ */
22
+ export declare function liftVerifySource(preamble: ConnectorLiftSummary['preamble'], stubs: readonly string[], id: string, call: string): string;
15
23
  /**
16
24
  * Whether each lifted connector task recompiles to the task the file carried, the
17
25
  * regenerated fields aside.
@@ -19,6 +19,7 @@
19
19
  import BpmnModdle from 'bpmn-moddle';
20
20
  import { createRequire } from 'node:module';
21
21
  import { buildSource } from './lift-verify.js';
22
+ import { builtChainSource } from '../core/builder-chain.js';
22
23
  import { serialize } from './serialize.js';
23
24
  const require = createRequire(import.meta.url);
24
25
  const uipathDescriptor = require('./uipath-moddle.v1.json');
@@ -154,6 +155,30 @@ function elementsById(root) {
154
155
  walk(r);
155
156
  return out;
156
157
  }
158
+ /**
159
+ * The source that compiles one lifted call on its own: the decompile's preamble, a
160
+ * `.var()` stub for each variable it does not declare, then a start event, the call
161
+ * and an end event. Written through `builtChainSource`, as the decompile writes its
162
+ * own source, because the declarations and stubs can be more calls than one chain
163
+ * holds (#1663).
164
+ */
165
+ export function liftVerifySource(preamble, stubs, id, call) {
166
+ return `${preamble.prefix}${builtChainSource({
167
+ target: 'export default',
168
+ head: preamble.head,
169
+ segments: [
170
+ ...preamble.calls,
171
+ ...stubs,
172
+ ' .startEvent("verify_start")',
173
+ ` ${call}`,
174
+ ' .endEvent("verify_end")',
175
+ ` .sequenceFlow("verify_start", ${JSON.stringify(id)})`,
176
+ ` .sequenceFlow(${JSON.stringify(id)}, "verify_end")`,
177
+ ],
178
+ binding: 'processBuilder',
179
+ indent: ' ',
180
+ })}\n`;
181
+ }
157
182
  /**
158
183
  * Whether each lifted connector task recompiles to the task the file carried, the
159
184
  * regenerated fields aside.
@@ -182,12 +207,11 @@ export async function verifyConnectorLifts(originalXml, summary, sdkEntry, libra
182
207
  // preamble does not write.
183
208
  const declares = (v) => {
184
209
  const q = JSON.stringify(v).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
185
- return new RegExp(`\\.var\\(${q}|\\{ id: ${q}, (?:name|type|direction)`).test(summary.preamble);
210
+ return new RegExp(`\\.var\\(${q}|\\{ id: ${q}, (?:name|type|direction)`).test(summary.preamble.calls.join('\n'));
186
211
  };
187
212
  const stubs = declaredVariableIds(original)
188
213
  .filter((v) => !declares(v))
189
- .map((v) => ` .var(${JSON.stringify(v)}, "object")`)
190
- .join('\n');
214
+ .map((v) => ` .var(${JSON.stringify(v)}, "object")`);
191
215
  for (const id of summary.lifted) {
192
216
  const call = summary.calls.get(id);
193
217
  const a = before.get(id);
@@ -195,8 +219,7 @@ export async function verifyConnectorLifts(originalXml, summary, sdkEntry, libra
195
219
  failed.set(id, call ? 'not in the original' : 'the lift recorded no call for it');
196
220
  continue;
197
221
  }
198
- const source = `${summary.preamble}\n${stubs ? `${stubs}\n` : ''} .startEvent("verify_start")\n ${call}\n .endEvent("verify_end")\n` +
199
- ` .sequenceFlow("verify_start", ${JSON.stringify(id)})\n .sequenceFlow(${JSON.stringify(id)}, "verify_end")\n .build();\n`;
222
+ const source = liftVerifySource(summary.preamble, stubs, id, call);
200
223
  let recompiled;
201
224
  try {
202
225
  recompiled = await serialize(await buildSource(source, sdkEntry), { library });
@@ -141,8 +141,19 @@ export interface ConnectorLiftSummary {
141
141
  * schemas, bindings and variables — so a verifier can compile one lifted call on its
142
142
  * own (`verifyConnectorLifts`) instead of the whole process, where one refused lift
143
143
  * would take every other down with it.
144
+ *
145
+ * In parts, not as text, so the verifier writes its source through
146
+ * `builtChainSource` like the decompile does: a process with many declarations is
147
+ * a chain too long for one expression (#1663).
144
148
  */
145
- preamble: string;
149
+ preamble: {
150
+ /** Everything before the builder: the collaboration note and the import line. */
151
+ prefix: string;
152
+ /** The factory call, `bpmn("id")`. */
153
+ head: string;
154
+ /** The declaration calls after it (`.name()`, `.var()`, …), one per entry, indented. */
155
+ calls: string[];
156
+ };
146
157
  /** Each lifted call's source line, by element id. */
147
158
  calls: Map<string, string>;
148
159
  }
@@ -61,6 +61,7 @@ import { BPMN_SCHEMA_VERSIONS } from './format-profile.js';
61
61
  import { preserveSchemaVersion } from '../schema-version.js';
62
62
  import { commentText } from '../core/comment-text.js';
63
63
  import { tsLiteral, tsText } from '../core/ts-literal.js';
64
+ import { builtChainSource, chainStatements } from '../core/builder-chain.js';
64
65
  import { defaultEntryPointId } from './entry-point-id.js';
65
66
  import { liftQuickHumanTask } from './human-task-form.js';
66
67
  const require = createRequire(import.meta.url);
@@ -1452,7 +1453,19 @@ function renderArmBody(plan, arm, depth, indent) {
1452
1453
  if (!lines.length)
1453
1454
  return undefined;
1454
1455
  const pad = indent.repeat(depth + 1);
1455
- return `(b) => b\n${pad}${lines.join(`\n${pad}`)}`;
1456
+ return callbackBody('b', lines, pad);
1457
+ }
1458
+ /**
1459
+ * A nested construct's body, `(x) => x` and its calls one per line — or, when they
1460
+ * are too many for one chain, a block of statements on `x` (#1663,
1461
+ * `core/builder-chain.ts`). Each entry of `lines` is one call; its first line gets
1462
+ * `pad`, the rest carry their own indent.
1463
+ */
1464
+ function callbackBody(param, lines, pad) {
1465
+ const statements = chainStatements(lines.map((l) => `${pad}${l}`), `${pad}${param}`, `${pad}${param}`);
1466
+ if (statements)
1467
+ return `(${param}) => {\n${statements.join('\n')}\n${pad}}`;
1468
+ return `(${param}) => ${param}\n${pad}${lines.join(`\n${pad}`)}`;
1456
1469
  }
1457
1470
  function renderHandler(plan, h, depth, indent) {
1458
1471
  const b = h.boundary;
@@ -1609,7 +1622,7 @@ function renderEventSubProcess(plan, sp, depth, indent) {
1609
1622
  emitVariablesInto(vars, sp, sp.id, capture !== undefined && captureDeclLooksDerived(sp, capture, start.id) ? new Set([capture]) : undefined);
1610
1623
  const bodyLines = [...vars.all, ...lines];
1611
1624
  const pad = indent.repeat(depth + 2);
1612
- const body = bodyLines.length ? `(h) => h\n${pad}${bodyLines.join(`\n${pad}`)}` : '(h) => h';
1625
+ const body = bodyLines.length ? callbackBody('h', bodyLines, pad) : '(h) => h';
1613
1626
  plan.summary.nets++;
1614
1627
  return `.eventSubProcess(${tsText(sp.id)}, ${optsText}, ${body})`;
1615
1628
  }
@@ -1968,9 +1981,13 @@ function emitElement(chain, el, depth, indent) {
1968
1981
  inner.add(".flowMode('explicit')");
1969
1982
  emitScope(inner, el, depth + 1, indent);
1970
1983
  emitVariablesInto(inner, el, el.id);
1971
- const body = inner.all.length
1972
- ? `(sp) => {\n${inner.all.map((l, i) => (i === 0 ? `${l.replace(/^(\s*)\./, '$1sp.')}` : l)).join('\n')};\n${indent.repeat(depth + 1)}}`
1973
- : '(sp) => {}';
1984
+ // Too many calls for one chain: statements on `sp`, as at the top level (#1663).
1985
+ const statements = chainStatements(inner.all, `${indent.repeat(depth + 2)}sp`, `${indent.repeat(depth + 2)}sp`);
1986
+ const body = statements
1987
+ ? `(sp) => {\n${statements.join('\n')}\n${indent.repeat(depth + 1)}}`
1988
+ : inner.all.length
1989
+ ? `(sp) => {\n${inner.all.map((l, i) => (i === 0 ? `${l.replace(/^(\s*)\./, '$1sp.')}` : l)).join('\n')};\n${indent.repeat(depth + 1)}}`
1990
+ : '(sp) => {}';
1974
1991
  // The mapping a sub-process carries maps its results back out to the
1975
1992
  // enclosing scope — distinct from the variables it DECLARES, which
1976
1993
  // `emitVariablesInto` has already written into the body above.
@@ -2395,15 +2412,29 @@ export async function decompile(xml, options = {}) {
2395
2412
  }
2396
2413
  const importFrom = options.importSpecifier ?? './bpmn-sdk.js';
2397
2414
  const imported = ['bpmn', ...[...schemaPlan.imports].sort()].join(', ');
2398
- const head = `import { ${imported} } from ${tsText(importFrom)};\n\nexport default bpmn(${tsText(process.id)})`;
2399
- const name = process.name !== undefined ? `\n${indent}.name(${tsText(process.name)})` : '';
2415
+ const imports = `import { ${imported} } from ${tsText(importFrom)};\n\n`;
2416
+ const nameCall = process.name !== undefined ? `${indent}.name(${tsText(process.name)})` : undefined;
2400
2417
  options.onConnectorLift?.({
2401
2418
  lifted: [...runLiftPlans.keys()],
2402
2419
  verbatim: runLiftSkipped,
2403
- preamble: `${host.note}${head}${name}\n${chain.all.slice(0, preambleLines).join('\n')}`,
2420
+ preamble: {
2421
+ prefix: `${host.note}${imports}`,
2422
+ head: `bpmn(${tsText(process.id)})`,
2423
+ calls: [...(nameCall !== undefined ? [nameCall] : []), ...chain.all.slice(0, preambleLines)],
2424
+ },
2404
2425
  calls: runLiftCalls,
2405
2426
  });
2406
- return `${host.note}${head}${name}\n${chain.all.join('\n')}\n${indent}.build();\n`;
2427
+ // One chain, or statements on `processBuilder` when it is too long to be one
2428
+ // expression (#1663, `core/builder-chain.ts`).
2429
+ const body = builtChainSource({
2430
+ target: 'export default',
2431
+ head: `bpmn(${tsText(process.id)})`,
2432
+ // An empty body keeps its blank line, as the single chain always wrote it.
2433
+ segments: [...(nameCall !== undefined ? [nameCall] : []), ...(chain.all.length ? chain.all : [''])],
2434
+ binding: 'processBuilder',
2435
+ indent,
2436
+ });
2437
+ return `${host.note}${imports}${body}\n`;
2407
2438
  }
2408
2439
  /**
2409
2440
  * Variable ids the serializer creates on its own from a node's output rows.
@@ -8,6 +8,7 @@ import { isOlderDocumentExtractionData } from './document-extraction-saved.js';
8
8
  import { isScriptOwnOutput, liftScript } from './decompile-script.js';
9
9
  import { isHttpRequestOwnOutput, liftHttpRequest } from './decompile-http-request.js';
10
10
  import { savedHttpRequestMetadata } from './http-request.js';
11
+ import { builtChainSource, chainStatements } from '../core/builder-chain.js';
11
12
  import { CASE_FORMAT_PROFILE, CASE_SCHEMA_VERSIONS } from './format-profile.js';
12
13
  import { EXTERNAL_TASK_CONTEXT, EXTERNAL_TASK_EVENT_CONTEXT, externalDescriptorRefusal, externalEventRefusal, externalServiceType, isExternalExecutionMode, libraryExecution } from './external.js';
13
14
  import { preserveSchemaVersion } from '../schema-version.js';
@@ -50,6 +51,24 @@ class Emit {
50
51
  toString() {
51
52
  return this.lines.join('\n');
52
53
  }
54
+ /**
55
+ * The lines as chain segments at `depth`: a line at exactly that indent that
56
+ * starts a call (`.`) or a comment (`/`) opens a segment, and every other line —
57
+ * deeper, or a closing `)` — continues the one before. Safe because nothing this
58
+ * decompiler writes breaks a line inside a literal (`tsLiteral` escapes them).
59
+ */
60
+ segments(depth) {
61
+ const pad = ' '.repeat(depth);
62
+ const out = [];
63
+ for (const line of this.lines) {
64
+ const opens = line.startsWith(pad) && (line[pad.length] === '.' || line[pad.length] === '/');
65
+ if (opens || out.length === 0)
66
+ out.push(line);
67
+ else
68
+ out[out.length - 1] += `\n${line}`;
69
+ }
70
+ return out;
71
+ }
53
72
  }
54
73
  function nodeType(node) {
55
74
  return String(node.type ?? '');
@@ -1438,10 +1457,12 @@ function slaSource(sla, index) {
1438
1457
  ['escalations', escalations.length ? `[${escalations.join(', ')}]` : undefined],
1439
1458
  ]);
1440
1459
  }
1441
- function emitStage(out, depth, stage, refs, library, selectNextStage) {
1460
+ function emitStage(stageOut, depth, stage, refs, library, selectNextStage) {
1442
1461
  const exception = stage.type.endsWith('ExceptionStage') || stage.data?.stageType === 'secondary';
1443
1462
  const data = stage.data ?? {};
1444
- out.line(depth, `.${exception ? 'exceptionStage' : 'stage'}(${tsLiteral(data.label ?? '')}, s => s`);
1463
+ const opener = `.${exception ? 'exceptionStage' : 'stage'}(${tsLiteral(data.label ?? '')}, `;
1464
+ // The stage's own calls, collected first so they can be written as one chain or as statements.
1465
+ const out = new Emit();
1445
1466
  const inner = depth + 1;
1446
1467
  if (data.description)
1447
1468
  out.line(inner, `.description(${tsLiteral(data.description)})`);
@@ -1454,7 +1475,22 @@ function emitStage(out, depth, stage, refs, library, selectNextStage) {
1454
1475
  (data.slaRules ?? []).forEach((sla, index) => out.line(inner, `.sla(${slaSource(sla, index)})`));
1455
1476
  for (const condition of data.exitConditions ?? [])
1456
1477
  emitExitWhen(out, inner, condition, refs, selectNextStage.get(condition));
1457
- out.line(depth, ')');
1478
+ // The stage's calls sit inside the case's chain, so a long stage is a block of
1479
+ // statements on `s` (#1663, `core/builder-chain.ts`).
1480
+ const calls = out.segments(inner);
1481
+ const statements = chainStatements(calls.map((c) => c.replace(/^/gm, ' ')), `${' '.repeat(inner)}s`, `${' '.repeat(inner)}s`);
1482
+ if (statements) {
1483
+ stageOut.line(depth, `${opener}s => {`);
1484
+ for (const statement of statements)
1485
+ stageOut.line(0, statement);
1486
+ stageOut.line(depth, '})');
1487
+ }
1488
+ else {
1489
+ stageOut.line(depth, `${opener}s => s`);
1490
+ for (const call of calls)
1491
+ stageOut.line(0, call);
1492
+ stageOut.line(depth, ')');
1493
+ }
1458
1494
  }
1459
1495
  /** `required` is an In-arg's own flag (`.input({ x: { type, required } })`); other lanes pass none. */
1460
1496
  function varSpec(entry, required) {
@@ -2536,7 +2572,7 @@ export function decompileWithDiagnostics(plan, options = {}) {
2536
2572
  });
2537
2573
  if (triggers.length)
2538
2574
  out.line(0, '');
2539
- out.line(0, `${preservation ? 'const caseDefinition =' : 'export default'} casePlan(${tsLiteral(slugId(plan))})`);
2575
+ const chain = new Emit();
2540
2576
  const depth = 1;
2541
2577
  // The declared grammar version first, mirroring the document's own key order
2542
2578
  // and emitted even when it equals this SDK's write version: preserving means
@@ -2547,43 +2583,51 @@ export function decompileWithDiagnostics(plan, options = {}) {
2547
2583
  // repair diagnostics that mark a source intentionally unbuildable.
2548
2584
  const schema = preserveSchemaVersion(CASE_SCHEMA_VERSIONS, plan.version);
2549
2585
  if (schema.call)
2550
- out.line(depth, schema.call);
2586
+ chain.line(depth, schema.call);
2551
2587
  if (schema.problem)
2552
- out.line(depth, `// TODO: ${commentText(schema.problem)}`);
2588
+ chain.line(depth, `// TODO: ${commentText(schema.problem)}`);
2553
2589
  if (plan.name !== undefined)
2554
- out.line(depth, `.name(${tsLiteral(plan.name)})`);
2590
+ chain.line(depth, `.name(${tsLiteral(plan.name)})`);
2555
2591
  if (plan.description !== undefined)
2556
- out.line(depth, `.description(${tsLiteral(plan.description)})`);
2592
+ chain.line(depth, `.description(${tsLiteral(plan.description)})`);
2557
2593
  if (metadata.caseIdentifier !== undefined) {
2558
2594
  const type = metadata.caseIdentifierType && metadata.caseIdentifierType !== 'constant'
2559
2595
  ? `, ${tsLiteral(metadata.caseIdentifierType)}`
2560
2596
  : '';
2561
- out.line(depth, `.identifier(${tsLiteral(metadata.caseIdentifier)}${type})`);
2597
+ chain.line(depth, `.identifier(${tsLiteral(metadata.caseIdentifier)}${type})`);
2562
2598
  }
2563
2599
  if (metadata.caseAppConfig !== undefined)
2564
- out.line(depth, `.caseApp(${caseAppSource(metadata.caseAppConfig)})`);
2600
+ chain.line(depth, `.caseApp(${caseAppSource(metadata.caseAppConfig)})`);
2565
2601
  // An absent flag is ON: the Case Designer's converter reads
2566
2602
  // `caseAppEnabled ?? true` (convertCaseInMemoryJsonToCanvasJson).
2567
2603
  else if (metadata.caseAppEnabled ?? true)
2568
- out.line(depth, '.caseApp()');
2604
+ chain.line(depth, '.caseApp()');
2569
2605
  if (metadata.caseAppConfig !== undefined && metadata.caseAppEnabled === false)
2570
- out.line(depth, '.caseApp(false)');
2606
+ chain.line(depth, '.caseApp(false)');
2571
2607
  if (metadata.allowAdhocOptionalStageTasks !== undefined) {
2572
2608
  if (typeof metadata.allowAdhocOptionalStageTasks !== 'boolean')
2573
2609
  throw new Error('allowAdhocOptionalStageTasks must be boolean.');
2574
- out.line(depth, metadata.allowAdhocOptionalStageTasks ? '.allowAdhocTasks()' : '.allowAdhocTasks(false)');
2610
+ chain.line(depth, metadata.allowAdhocOptionalStageTasks ? '.allowAdhocTasks()' : '.allowAdhocTasks(false)');
2575
2611
  }
2576
- emitVariables(out, depth, plan, triggerNameById, triggers.map(isTimerTrigger));
2577
- triggers.forEach((_trigger, index) => out.line(depth, `.trigger(trigger${index + 1})`));
2578
- (metadata.slaRules ?? []).forEach((sla, index) => out.line(depth, `.sla(${slaSource(sla, index)})`));
2612
+ emitVariables(chain, depth, plan, triggerNameById, triggers.map(isTimerTrigger));
2613
+ triggers.forEach((_trigger, index) => chain.line(depth, `.trigger(trigger${index + 1})`));
2614
+ (metadata.slaRules ?? []).forEach((sla, index) => chain.line(depth, `.sla(${slaSource(sla, index)})`));
2579
2615
  for (const event of metadata.businessEvents ?? [])
2580
- out.line(depth, businessEventSource(event));
2616
+ chain.line(depth, businessEventSource(event));
2581
2617
  for (const node of plan.nodes ?? [])
2582
2618
  if (isStage(node))
2583
- emitStage(out, depth, node, refs, options.library, selectNextStage);
2619
+ emitStage(chain, depth, node, refs, options.library, selectNextStage);
2584
2620
  for (const condition of metadata.caseExitRules ?? [])
2585
- emitCompleteWhen(out, depth, condition, refs);
2586
- out.line(depth, '.build();');
2621
+ emitCompleteWhen(chain, depth, condition, refs);
2622
+ // One chain, or statements on `caseBuilder` when it is too long to be one
2623
+ // expression (#1663, `core/builder-chain.ts`).
2624
+ out.line(0, builtChainSource({
2625
+ target: preservation ? 'const caseDefinition =' : 'export default',
2626
+ head: `casePlan(${tsLiteral(slugId(plan))})`,
2627
+ segments: chain.segments(depth),
2628
+ binding: 'caseBuilder',
2629
+ indent: ' '.repeat(depth),
2630
+ }));
2587
2631
  if (preservation) {
2588
2632
  out.line(0, '');
2589
2633
  out.line(0, `export default preserveCaseJson(caseDefinition, ${tsLiteral(preservation)});`);
@@ -0,0 +1,68 @@
1
+ /**
2
+ * How a decompiler writes a builder chain that is too long to be one expression.
3
+ * Why: builder-sdk#1663 (a chain of N calls is an expression N levels deep, and a
4
+ * small stack cannot walk it).
5
+ *
6
+ * A chain of more than {@link MAX_CHAIN_CALLS} calls is written as statements on a
7
+ * named builder. This compiles to the same output, because every builder method
8
+ * changes the builder in place and returns it:
9
+ *
10
+ * ```ts
11
+ * const flowBuilder = flow("x")
12
+ * .step("s1", …)
13
+ * …; // at most MAX_CHAIN_CALLS calls per statement
14
+ * flowBuilder
15
+ * .step("s51", …)
16
+ * …;
17
+ * export default flowBuilder.build();
18
+ * ```
19
+ *
20
+ * A chain of at most {@link MAX_CHAIN_CALLS} calls is written as one chain, so
21
+ * ordinary sources keep their shape. The same rule applies to a builder callback's
22
+ * body (`(b) => b.step(…)…` becomes `(b) => { b…; b…; }`): a callback's chain sits
23
+ * inside the outer one, so the two depths add up.
24
+ *
25
+ * Shared by the Flow, BPMN and Case decompilers; each one owns its own layout
26
+ * (indent, receiver names) and hands this module its list of call segments.
27
+ */
28
+ /**
29
+ * The most calls one emitted chain holds. Measured in QuickJS 0.32 (asyncify
30
+ * build, 512 KB stack, the Studio Web sandbox): a chain of 110 small calls
31
+ * transpiles, 125 does not. 50 leaves room for large arguments and for one nested
32
+ * callback chain of the same length (50 inside 50 measured fine).
33
+ */
34
+ export declare const MAX_CHAIN_CALLS = 50;
35
+ /** The number of calls in `segments`, comments not counted. */
36
+ export declare function chainCallCount(segments: readonly string[]): number;
37
+ /**
38
+ * `segments` as statements, or `undefined` when they fit in one chain.
39
+ *
40
+ * Each segment is one call (`.step(…)`, possibly over several lines) or one comment
41
+ * line, already indented the way the caller wants it. The result is a list of
42
+ * statement texts: the first starts with `first` (for instance
43
+ * `const flowBuilder = flow("x")`), the rest with `receiver`, each followed by its
44
+ * segments on their own lines and a `;` after the last call. A comment travels with
45
+ * the call after it; comments after the last call come back as their own entries,
46
+ * unchanged.
47
+ */
48
+ export declare function chainStatements(segments: readonly string[], first: string, receiver: string, max?: number): string[] | undefined;
49
+ /** What {@link builtChainSource} writes. */
50
+ export interface BuiltChain {
51
+ /** What receives the built value: `export default`, or `const caseDefinition =`. */
52
+ target: string;
53
+ /** The factory call that starts the chain: `flow("x")`. */
54
+ head: string;
55
+ /** The calls between the factory and `.build()`, each already indented by `indent`. */
56
+ segments: readonly string[];
57
+ /** The name the builder is bound to when the chain is split: `flowBuilder`. */
58
+ binding: string;
59
+ /** The chain's indent, before `.build()`. */
60
+ indent: string;
61
+ }
62
+ /**
63
+ * The top-level source that builds a decompiled artifact: one chain ending in
64
+ * `.build();` when it fits ({@link MAX_CHAIN_CALLS}), else statements on
65
+ * `binding` ending in `<target> <binding>.build();`. A short chain is written
66
+ * byte for byte as the decompilers always wrote it.
67
+ */
68
+ export declare function builtChainSource(chain: BuiltChain): string;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * How a decompiler writes a builder chain that is too long to be one expression.
3
+ * Why: builder-sdk#1663 (a chain of N calls is an expression N levels deep, and a
4
+ * small stack cannot walk it).
5
+ *
6
+ * A chain of more than {@link MAX_CHAIN_CALLS} calls is written as statements on a
7
+ * named builder. This compiles to the same output, because every builder method
8
+ * changes the builder in place and returns it:
9
+ *
10
+ * ```ts
11
+ * const flowBuilder = flow("x")
12
+ * .step("s1", …)
13
+ * …; // at most MAX_CHAIN_CALLS calls per statement
14
+ * flowBuilder
15
+ * .step("s51", …)
16
+ * …;
17
+ * export default flowBuilder.build();
18
+ * ```
19
+ *
20
+ * A chain of at most {@link MAX_CHAIN_CALLS} calls is written as one chain, so
21
+ * ordinary sources keep their shape. The same rule applies to a builder callback's
22
+ * body (`(b) => b.step(…)…` becomes `(b) => { b…; b…; }`): a callback's chain sits
23
+ * inside the outer one, so the two depths add up.
24
+ *
25
+ * Shared by the Flow, BPMN and Case decompilers; each one owns its own layout
26
+ * (indent, receiver names) and hands this module its list of call segments.
27
+ */
28
+ /**
29
+ * The most calls one emitted chain holds. Measured in QuickJS 0.32 (asyncify
30
+ * build, 512 KB stack, the Studio Web sandbox): a chain of 110 small calls
31
+ * transpiles, 125 does not. 50 leaves room for large arguments and for one nested
32
+ * callback chain of the same length (50 inside 50 measured fine).
33
+ */
34
+ export const MAX_CHAIN_CALLS = 50;
35
+ /** Whether a segment is a comment line (`// …` or `/* … *\/`), not a call. */
36
+ function isComment(segment) {
37
+ const text = segment.trimStart();
38
+ return text.startsWith('//') || text.startsWith('/*');
39
+ }
40
+ /** The number of calls in `segments`, comments not counted. */
41
+ export function chainCallCount(segments) {
42
+ return segments.filter((s) => !isComment(s)).length;
43
+ }
44
+ /**
45
+ * `segments` as statements, or `undefined` when they fit in one chain.
46
+ *
47
+ * Each segment is one call (`.step(…)`, possibly over several lines) or one comment
48
+ * line, already indented the way the caller wants it. The result is a list of
49
+ * statement texts: the first starts with `first` (for instance
50
+ * `const flowBuilder = flow("x")`), the rest with `receiver`, each followed by its
51
+ * segments on their own lines and a `;` after the last call. A comment travels with
52
+ * the call after it; comments after the last call come back as their own entries,
53
+ * unchanged.
54
+ */
55
+ export function chainStatements(segments, first, receiver, max = MAX_CHAIN_CALLS) {
56
+ if (chainCallCount(segments) <= max)
57
+ return undefined;
58
+ const statements = [];
59
+ let group = [];
60
+ let calls = 0;
61
+ for (const segment of segments) {
62
+ group.push(segment);
63
+ if (isComment(segment))
64
+ continue;
65
+ calls++;
66
+ if (calls === max) {
67
+ statements.push(statement(statements.length === 0 ? first : receiver, group));
68
+ group = [];
69
+ calls = 0;
70
+ }
71
+ }
72
+ // `group` is now the calls of a last, short statement (if any) and the comments
73
+ // after the last call; the `;` goes after the call, the comments after it.
74
+ let lastCall = group.length - 1;
75
+ while (lastCall >= 0 && isComment(group[lastCall]))
76
+ lastCall--;
77
+ if (lastCall >= 0)
78
+ statements.push(statement(receiver, group.slice(0, lastCall + 1)));
79
+ statements.push(...group.slice(lastCall + 1));
80
+ return statements;
81
+ }
82
+ function statement(head, group) {
83
+ return `${head}\n${group.join('\n')};`;
84
+ }
85
+ /**
86
+ * The top-level source that builds a decompiled artifact: one chain ending in
87
+ * `.build();` when it fits ({@link MAX_CHAIN_CALLS}), else statements on
88
+ * `binding` ending in `<target> <binding>.build();`. A short chain is written
89
+ * byte for byte as the decompilers always wrote it.
90
+ */
91
+ export function builtChainSource(chain) {
92
+ const { target, head, segments, binding, indent } = chain;
93
+ const statements = chainStatements(segments, `const ${binding} = ${head}`, binding);
94
+ if (!statements)
95
+ return [`${target} ${head}`, ...segments, `${indent}.build();`].join('\n');
96
+ return [...statements, `${target} ${binding}.build();`].join('\n');
97
+ }
@@ -93,3 +93,28 @@ export declare function buildConfiguration(entry: any, version: string, inputVal
93
93
  * @returns The essential configuration, with only Studio Web's essential keys.
94
94
  */
95
95
  export declare function buildEssentialConfiguration(entry: any, version: string, inputValues?: Record<string, unknown>, seed?: string, executionType?: string | null): Record<string, unknown>;
96
+ /** The operation identity a connector node's configuration envelope records. */
97
+ export interface ConfigurationIdentity {
98
+ /** `instanceParameters.objectName`: the object the operation addresses. */
99
+ objectName?: string;
100
+ /** `instanceParameters.activityType`: `Generic` when the object is the author's choice, `Curated` when the node type is it. */
101
+ activityType?: string;
102
+ }
103
+ /**
104
+ * Read back the operation identity that {@link buildConfiguration} writes into
105
+ * the `=jsonString:` envelope, so the reader cannot drift from the writer.
106
+ *
107
+ * It reads `essentialConfiguration.instanceParameters` (what compile and Studio
108
+ * Web write), and also the flat form a file saved before #976 carries, with
109
+ * `instanceParameters` at the top of the object. A key missing in
110
+ * `instanceParameters` falls back to the essential `objectName` beside it.
111
+ * Anything that is not such an envelope reads as `{}`.
112
+ *
113
+ * For instance a generic Jira "Retrieve Issue" saved as
114
+ * `=jsonString:{"essentialConfiguration":{"objectName":"curated_issue","instanceParameters":{"activityType":"Generic",…}}}`
115
+ * reads as `{ objectName: 'curated_issue', activityType: 'Generic' }`.
116
+ *
117
+ * @param configuration - A connector node's `inputs.detail.configuration`.
118
+ * @returns The object name and activity type, each only when it is a string.
119
+ */
120
+ export declare function readConfigurationIdentity(configuration: unknown): ConfigurationIdentity;
@@ -246,3 +246,42 @@ export function buildEssentialConfiguration(entry, version, inputValues, seed =
246
246
  };
247
247
  return envelope(composed).essentialConfiguration;
248
248
  }
249
+ /**
250
+ * Read back the operation identity that {@link buildConfiguration} writes into
251
+ * the `=jsonString:` envelope, so the reader cannot drift from the writer.
252
+ *
253
+ * It reads `essentialConfiguration.instanceParameters` (what compile and Studio
254
+ * Web write), and also the flat form a file saved before #976 carries, with
255
+ * `instanceParameters` at the top of the object. A key missing in
256
+ * `instanceParameters` falls back to the essential `objectName` beside it.
257
+ * Anything that is not such an envelope reads as `{}`.
258
+ *
259
+ * For instance a generic Jira "Retrieve Issue" saved as
260
+ * `=jsonString:{"essentialConfiguration":{"objectName":"curated_issue","instanceParameters":{"activityType":"Generic",…}}}`
261
+ * reads as `{ objectName: 'curated_issue', activityType: 'Generic' }`.
262
+ *
263
+ * @param configuration - A connector node's `inputs.detail.configuration`.
264
+ * @returns The object name and activity type, each only when it is a string.
265
+ */
266
+ export function readConfigurationIdentity(configuration) {
267
+ if (typeof configuration !== 'string' || !configuration.startsWith('=jsonString:'))
268
+ return {};
269
+ let parsed;
270
+ try {
271
+ parsed = JSON.parse(configuration.slice('=jsonString:'.length));
272
+ }
273
+ catch {
274
+ return {};
275
+ }
276
+ const record = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
277
+ const root = record(parsed);
278
+ const essential = record(root?.essentialConfiguration) ?? root;
279
+ const instance = record(essential?.instanceParameters);
280
+ const text = (...values) => values.find((v) => typeof v === 'string' && v !== '');
281
+ const objectName = text(instance?.objectName, essential?.objectName);
282
+ const activityType = text(instance?.activityType);
283
+ return {
284
+ ...(objectName !== undefined ? { objectName } : {}),
285
+ ...(activityType !== undefined ? { activityType } : {}),
286
+ };
287
+ }
package/dist/decompile.js CHANGED
@@ -51,6 +51,7 @@ import { contributionPort, forwardFanOut } from './core/definition-handles.js';
51
51
  import { STICKY_NOTE_TYPE } from './core/definitionless-node-types.js';
52
52
  import { eventFilterFromTreeLeaf } from './core/event-filters.js';
53
53
  import { referencedBindingNames } from './core/contribution-bindings.js';
54
+ import { builtChainSource, chainStatements } from './core/builder-chain.js';
54
55
  /**
55
56
  * The trigger id of the flow currently being decompiled, so a reference through a
56
57
  * RENAMED trigger is still recognized as `input('x')` rather than falling back to
@@ -344,6 +345,10 @@ class Emit {
344
345
  toString() {
345
346
  return this.lines.join('\n');
346
347
  }
348
+ /** The lines written so far, one per `line()` call: one chain call or comment each. */
349
+ get entries() {
350
+ return this.lines;
351
+ }
347
352
  }
348
353
  /**
349
354
  * Tracks which identifiers the emitted source uses, per module, so each import
@@ -1999,10 +2004,17 @@ function templateLineStarts(src) {
1999
2004
  function renderSegs(segs, pad) {
2000
2005
  return segs.map((s) => reindent(s, pad)).join('\n');
2001
2006
  }
2002
- /** An arm callback `(x) => x <chain>` (or just `(x) => x` for an empty arm). */
2007
+ /**
2008
+ * An arm callback `(x) => x <chain>` (or just `(x) => x` for an empty arm). An arm
2009
+ * too long for one chain is a block of statements on `x` instead (#1663): the
2010
+ * arm's chain sits inside the outer one, so its depth adds to the outer chain's.
2011
+ */
2003
2012
  function armCb(param, segs) {
2004
2013
  if (segs.length === 0)
2005
2014
  return `(${param}) => ${param}`;
2015
+ const statements = chainStatements(segs.map((s) => reindent(s, ' ')), param, param);
2016
+ if (statements)
2017
+ return `(${param}) => {\n${renderSegs(statements, ' ')}\n}`;
2006
2018
  return `(${param}) => ${param}\n${renderSegs(segs, ' ')}`;
2007
2019
  }
2008
2020
  /**
@@ -2971,7 +2983,15 @@ function emitChildFlowIn(name, child, trigger, ctx) {
2971
2983
  const childLayout = layoutSeg(child, child.nodes ?? [], child.edges ?? []);
2972
2984
  if (childLayout)
2973
2985
  parts.push(childLayout);
2974
- return `(\n${renderSegs(parts.map((p, i) => (i === 0 ? p : p)), ' ')}\n)`;
2986
+ // A child too long for one chain is built by statements inside an arrow that
2987
+ // returns it (#1663): `subflow()` takes the builder as an expression.
2988
+ const [childHead, ...childSegs] = parts;
2989
+ const statements = chainStatements(childSegs.map((p) => reindent(p, ' ')), 'childFlow', 'childFlow');
2990
+ if (statements) {
2991
+ const block = [`((childFlow) => {`, ...statements.map((p) => reindent(p, ' ')), ' return childFlow;', `})(${childHead})`];
2992
+ return `(\n${renderSegs(block, ' ')}\n)`;
2993
+ }
2994
+ return `(\n${renderSegs(parts, ' ')}\n)`;
2975
2995
  }
2976
2996
  // ─── Entry point ──────────────────────────────────────────────────────────────
2977
2997
  /** Slugify the flow name/id into a stable-but-cosmetic `flow(id)` argument. */
@@ -3116,7 +3136,7 @@ export function decompile(flow, options = {}) {
3116
3136
  (flow.nodes ?? []).find((n) => String(n.type ?? '').startsWith('core.trigger.'))?.id ??
3117
3137
  DEFAULT_TRIGGER_ID;
3118
3138
  const e = new Emit();
3119
- e.line(0, `export default ${imp.use('flow')}(${tsLiteral(slugId(flow))})`);
3139
+ const head = `${imp.use('flow')}(${tsLiteral(slugId(flow))})`;
3120
3140
  const d = 1;
3121
3141
  // The file-format version FIRST, mirroring the order the file itself carries
3122
3142
  // it (`id`, `version`, `name`) — and emitted even when it equals this SDK's
@@ -3223,16 +3243,23 @@ export function decompile(flow, options = {}) {
3223
3243
  throw new Error(`decompile: ${runDropped.length} edge(s) have no spelling in the decompiled source, so recompiling would drop them: `
3224
3244
  + `${runDropped.map(edgeName).join(', ')}.`);
3225
3245
  }
3226
- const header = e.toString();
3227
- const body = bodySegs.map((s) => reindent(s, ' ')).join('\n');
3228
- const eps = extraEps.map((s) => reindent(s, ' ')).join('\n');
3246
+ const body = bodySegs.map((s) => reindent(s, ' '));
3247
+ const eps = extraEps.map((s) => reindent(s, ' '));
3229
3248
  // Designer layout last, so the graph reads first and the coordinates do not
3230
3249
  // interleave with the steps they position.
3231
3250
  const notes = stickyNotesSeg(flow.nodes ?? [], flow);
3232
3251
  const sticky = notes ? reindent(notes, ' ') : '';
3233
3252
  const lay = layoutSeg(flow, (flow.nodes ?? []).filter((n) => !detachedIds.has(n.id)), (flow.edges ?? []).filter((edge) => !detachedIds.has(edge.sourceNodeId) && !detachedIds.has(edge.targetNodeId)));
3234
3253
  const layout = lay ? reindent(lay, ' ') : '';
3235
- const chain = [header, eps, body, sticky, layout, ' .build();'].filter((s) => s.length > 0).join('\n');
3254
+ // One chain, or statements on `flowBuilder` when it is too long to be one
3255
+ // expression (#1663, `core/builder-chain.ts`).
3256
+ const chain = builtChainSource({
3257
+ target: 'export default',
3258
+ head,
3259
+ segments: [...e.entries, ...eps, ...body, sticky, layout].filter((s) => s.length > 0),
3260
+ binding: 'flowBuilder',
3261
+ indent: ' ',
3262
+ });
3236
3263
  const carriedConsts = [...runCarried].map(([key, name]) => [name, JSON.stringify(runDefs.get(key), null, 2)]);
3237
3264
  const hoisted = [...carriedConsts, ...runRawManifests]
3238
3265
  .map(([name, json]) => `const ${name} = ${json};`)
@@ -1,6 +1,6 @@
1
1
  import { BindingRefusal, bindingMissingMessage, missingBindingLabels } from '../../../core/binding-messages.js';
2
2
  import { prepareCommand } from '../../../core/cli-spelling.js';
3
- import { buildConfiguration } from '../../../core/connector-configuration.js';
3
+ import { buildConfiguration, readConfigurationIdentity } from '../../../core/connector-configuration.js';
4
4
  import { CONNECTOR_INPUT_MISSING, FLOW_EXPR_DIALECT, buildConnectorInputs, replayInputsOf, transportHttpMethod } from '../../../core/connector-inputs.js';
5
5
  import { ConnectorResolveError } from '../../../core/connector-resolve-error.js';
6
6
  import { definitionHasErrorPort } from '../../../core/error-port.js';
@@ -219,18 +219,26 @@ function liftValue(v, ctx) {
219
219
  return v;
220
220
  return raw.startsWith('=js:') ? new Expr(raw.slice(4)) : raw;
221
221
  }
222
- /** Pull `objectName` out of a connector's `=jsonString:` configuration blob, if present. */
223
- function configurationObjectName(configuration) {
224
- if (typeof configuration !== 'string' || !configuration.startsWith('=jsonString:'))
225
- return undefined;
226
- try {
227
- const cfg = JSON.parse(configuration.slice('=jsonString:'.length));
228
- const name = cfg?.instanceParameters?.objectName ?? cfg?.objectName;
229
- return typeof name === 'string' ? name : undefined;
230
- }
231
- catch {
222
+ /**
223
+ * The object a connector node addresses, when it is the author's choice: a
224
+ * GENERIC operation (`get-record` on `curated_issue`) names only the verb in its
225
+ * node type, so `compile` needs the object back as the `object` option
226
+ * (CONNECTOR_OBJECT_REQUIRED without it, #1614). A CURATED operation's node type
227
+ * is its object, so it gets none. A node whose configuration records no
228
+ * activity type keeps the object it names: compile accepts an object that
229
+ * matches a curated entry, and refuses one that does not, by name.
230
+ *
231
+ * The configuration is read by `readConfigurationIdentity`, which lives beside
232
+ * the writer (`buildConfiguration`); the node's sibling `objectName` is the
233
+ * fallback, as compile writes both.
234
+ */
235
+ function liftedObject(detail) {
236
+ const identity = readConfigurationIdentity(detail.configuration);
237
+ if (identity.activityType === 'Curated')
232
238
  return undefined;
233
- }
239
+ if (identity.objectName !== undefined)
240
+ return identity.objectName;
241
+ return typeof detail.objectName === 'string' && detail.objectName !== '' ? detail.objectName : undefined;
234
242
  }
235
243
  function liftConnector(node, ctx) {
236
244
  const n = node;
@@ -269,7 +277,7 @@ function liftConnector(node, ctx) {
269
277
  }
270
278
  return {
271
279
  kind: 'connector', ...split, inputs, connection, folder,
272
- object: configurationObjectName(detail.configuration),
280
+ object: liftedObject(detail),
273
281
  missing,
274
282
  };
275
283
  }
@@ -312,14 +320,19 @@ function printConnector(l, ctx) {
312
320
  // serialize keeps it in memory) prints as `undefined`, as it did before the port.
313
321
  const value = (v) => (v === undefined ? 'undefined' : v instanceof Expr ? ctx.value(v) : ctx.json(v));
314
322
  const optional = (v) => (v === undefined ? undefined : ctx.string(v));
323
+ // One entry per `connector()` option, so an option added to ConnectorOpts
324
+ // fails to type-check here until the lift reads it back: a dropped option
325
+ // compiles to a different node, or not at all.
326
+ // `version` is the step's pin, which decompile prints for every node type.
327
+ const opts = {
328
+ connection: optional(l.connection),
329
+ folder: optional(l.folder),
330
+ object: optional(l.object),
331
+ };
315
332
  return {
316
333
  factory: 'connector',
317
334
  positional: [ctx.string(l.key), ctx.string(l.action), tsObject(l.inputs.map(([k, v]) => [k, value(v)])) || '{}'],
318
- options: [
319
- ['connection', optional(l.connection)],
320
- ['folder', optional(l.folder)],
321
- ['object', optional(l.object)],
322
- ],
335
+ options: Object.entries(opts),
323
336
  ...(l.missing.length > 0
324
337
  ? { comment: `TODO: bind ${l.missing.join(' and ')}; check refuses this node until it has both labels (BINDING_MISSING)` }
325
338
  : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uipath/maestro-builder-sdk",
3
- "version": "6.82.3",
3
+ "version": "6.82.4",
4
4
  "description": "Build UiPath Flow, Case, and BPMN artifacts by writing TypeScript.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://docs.uipath.com/maestro",
@@ -103,5 +103,5 @@
103
103
  "@types/node": "^22.7.0",
104
104
  "esbuild": "^0.28.1"
105
105
  },
106
- "gitref": "e0b86864208ddfdb8a4694661944938cfe588fe7"
106
+ "gitref": "de2f5b3d1b28484542a97405dc5a727dae7ac187"
107
107
  }