@uipath/maestro-builder-sdk 6.94.6 → 6.95.0

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.
@@ -21,6 +21,11 @@
21
21
  * resolves for a package consumer; the library default in `decompile.ts` stays
22
22
  * repo-relative for in-tree callers, mirroring the Flow and Case arms.
23
23
  *
24
+ * The first line of the written source is the stamp (decompile-stamp.ts):
25
+ * `// @decompiled-from <file> sha256:<hex> style=… connectors=…[ keep-flow-ids][ keep-unused-bindings]`.
26
+ * `bpmn merge X.bpmn.ts --original X.bpmn` reads it, refuses an original whose bytes
27
+ * changed since, and derives its baseline with the options it records.
28
+ *
24
29
  * Diagram layout is not read or emitted — the SDK emits semantic-only XML. For a
25
30
  * brownfield edit, `bpmn-merge` puts the original diagram back and draws only what the
26
31
  * edit added (merge-placement.ts); `uip maestro bpmn format`, which lays the whole
@@ -37,9 +42,8 @@ import { readFileSync } from 'node:fs';
37
42
  import { basename, resolve } from 'node:path';
38
43
  import { defaultSourceOut, writeSource } from '../workdir.js';
39
44
  import { flagValue, runWhenInvokedDirectly } from '../cli-run.js';
40
- import { decompile } from './decompile.js';
41
- import { sameGraph } from './lift-verify.js';
42
- import { verifyConnectorLifts } from './connector-lift-verify.js';
45
+ import { decompilePipeline } from './decompile-pipeline.js';
46
+ import { sourceDigest, stampSource } from './decompile-stamp.js';
43
47
  import { openCliLibrary } from '../core/cli-library.js';
44
48
  import { BPMN_IMPORT } from '../package-name.js';
45
49
  import { fileURLToPath } from 'node:url';
@@ -88,63 +92,30 @@ export async function run(argv) {
88
92
  console.error('decompile: missing <Name.bpmn>');
89
93
  return 2;
90
94
  }
91
- const xml = readFileSync(input, 'utf8');
95
+ const bytes = readFileSync(input);
96
+ const xml = bytes.toString('utf8');
92
97
  const importSpecifier = flagValue(argv, '--import') ?? BPMN_IMPORT;
93
- let pruned = [];
94
- // The connector lift: name each connector task through the library, then keep only
95
- // the lifts that verify. One decompile to plan, one verify, and — only when a lift
96
- // was refused — one more decompile with those tasks pinned verbatim. The pinned set
97
- // then rides into the nested-style passes below, so the flat and nested sources the
98
- // nested verify compares make the same connector decisions.
98
+ // The connector lift (`--connectors lift`, the default when a library opens) and
99
+ // the nested lift, each verified before it is written: decompile-pipeline.ts, which
100
+ // `bpmn merge` also runs to derive its baseline from an original.
99
101
  const library = connectors === 'lift' ? openCliLibrary(argv) : undefined;
100
102
  const sdkEntry = fileURLToPath(new URL('./bpmn-sdk.js', import.meta.url));
101
- let connectorSummary;
102
- let verbatimConnectors = new Set();
103
- const base0 = {
104
- importSpecifier,
105
- keepUnusedBindings,
106
- onPrune: (ids) => (pruned = ids),
107
- ...(library ? { library, connectors: 'lift' } : {}),
108
- onConnectorLift: (s) => (connectorSummary = s),
109
- };
110
- let source = await decompile(xml, { ...base0, verbatimConnectors });
111
- if (library && connectorSummary && connectorSummary.lifted.length > 0) {
112
- const verdict = await verifyConnectorLifts(xml, connectorSummary, sdkEntry, library);
113
- if (verdict.failed.size > 0) {
114
- verbatimConnectors = new Set(verdict.failed.keys());
115
- source = await decompile(xml, { ...base0, verbatimConnectors });
116
- // The summary from the second pass says "did not verify"; carry the measured reason.
117
- if (connectorSummary) {
118
- connectorSummary.verbatim = connectorSummary.verbatim.map((v) => ({ id: v.id, reason: verdict.failed.get(v.id) ?? v.reason }));
119
- }
120
- }
121
- }
122
- let lifted;
123
- let fallback;
124
- if (style === 'nested') {
125
- // Two rungs: the top level in sequence mode, then without it. Built against THIS
126
- // package's own entry, whatever specifier the written file carries — the check is
127
- // about the graph, not about module resolution. The flow ids the lift renamed are
128
- // the one sanctioned difference.
129
- for (const sequenceMode of [true, false]) {
130
- let summary;
131
- const nested = await decompile(xml, {
132
- ...base0, verbatimConnectors, style: 'nested', relabelFlows: !keepFlowIds, sequenceMode, onLift: (s) => (summary = s),
133
- });
134
- const renamed = new Map((summary?.renamedFlows ?? []).map((r) => [r.from, r.to]));
135
- const verdict = await sameGraph(source, nested, sdkEntry, renamed);
136
- if (verdict.same) {
137
- source = nested;
138
- lifted = summary;
139
- fallback = undefined;
140
- break;
141
- }
142
- fallback = verdict.reason ?? 'the graphs differ';
143
- }
144
- }
103
+ const { source, pruned, connectors: connectorSummary, lifted, fallback } = await decompilePipeline(xml, {
104
+ importSpecifier, style, keepFlowIds, keepUnusedBindings, sdkEntry, ...(library ? { library } : {}),
105
+ });
145
106
  const base = basename(input).replace(/\.bpmn$/, '');
146
107
  const out = flagValue(argv, '-o') ?? defaultSourceOut(`${base}.bpmn.ts`);
147
- writeSource(out, source);
108
+ // The stamp says which original this came from, and how, so `bpmn merge X.bpmn.ts
109
+ // --original X.bpmn` can refuse an original that changed since and derive its
110
+ // baseline with the same options (decompile-stamp.ts).
111
+ writeSource(out, stampSource(source, {
112
+ file: basename(input),
113
+ sha256: sourceDigest(source),
114
+ style,
115
+ connectors: library ? 'lift' : 'verbatim',
116
+ keepFlowIds,
117
+ keepUnusedBindings,
118
+ }));
148
119
  console.log(`decompile: wrote ${out}`);
149
120
  if (pruned.length) {
150
121
  // Never silent: these are declarations the source had and the output does not.
@@ -0,0 +1,51 @@
1
+ /**
2
+ * decompile-pipeline — what `bpmn decompile` does to a `.bpmn`, as one call.
3
+ *
4
+ * The plain decompile is `decompile()`. The CLI runs more than that: it lifts the
5
+ * connector tasks the library can name and keeps only the lifts that verify, and with
6
+ * `style: 'nested'` it lifts the regions the builder's nesting constructs lower to,
7
+ * writing the nested source only when it builds the same graph as the flat one
8
+ * (lift-verify.ts). `bpmn merge` runs the same steps to derive its baseline from the
9
+ * original when it is given the edited SOURCE (merge-source.ts), so the two must not
10
+ * drift: both call this.
11
+ *
12
+ * Nothing here prints. The caller reports what came back.
13
+ */
14
+ import type { Library } from '../core/library.js';
15
+ import { type ConnectorLiftSummary, type LiftSummary } from './decompile.js';
16
+ /** How to decompile: the options `bpmn decompile` takes, resolved. */
17
+ export interface DecompilePipelineOptions {
18
+ /** The module specifier of the emitted `import { bpmn }` line. */
19
+ importSpecifier: string;
20
+ /** `explicit` writes one call per element and flow; `nested` lifts what it can prove. */
21
+ style: 'explicit' | 'nested';
22
+ /** Confine the nested lift to regions whose flow ids already match, instead of pinning them. */
23
+ keepFlowIds?: boolean;
24
+ /** Echo bindings nothing references instead of dropping them. */
25
+ keepUnusedBindings?: boolean;
26
+ /** The connector library; given, connector tasks it can name are lifted to `.connector()`. */
27
+ library?: Library;
28
+ /** Absolute path of the `bpmn-sdk.js` the verifications build against. */
29
+ sdkEntry: string;
30
+ }
31
+ /** What the pipeline produced, and what it did to get there. */
32
+ export interface DecompilePipelineResult {
33
+ /** The `.bpmn.ts` source. */
34
+ source: string;
35
+ /** Binding ids dropped because nothing references them. */
36
+ pruned: string[];
37
+ /** The connector lift, when a library was in play. */
38
+ connectors?: ConnectorLiftSummary;
39
+ /** The nested lift, when `style: 'nested'` verified. */
40
+ lifted?: LiftSummary;
41
+ /** Why `style: 'nested'` fell back to the flat source. */
42
+ fallback?: string;
43
+ }
44
+ /**
45
+ * Decompile `xml` the way `bpmn decompile` does.
46
+ *
47
+ * @param xml - The `.bpmn` text.
48
+ * @param opts - The resolved decompile options.
49
+ * @returns The source, and what the lifts did.
50
+ */
51
+ export declare function decompilePipeline(xml: string, opts: DecompilePipelineOptions): Promise<DecompilePipelineResult>;
@@ -0,0 +1,78 @@
1
+ import { decompile } from './decompile.js';
2
+ import { sameGraph } from './lift-verify.js';
3
+ import { verifyConnectorLifts } from './connector-lift-verify.js';
4
+ /**
5
+ * Decompile `xml` the way `bpmn decompile` does.
6
+ *
7
+ * @param xml - The `.bpmn` text.
8
+ * @param opts - The resolved decompile options.
9
+ * @returns The source, and what the lifts did.
10
+ */
11
+ export async function decompilePipeline(xml, opts) {
12
+ const { library, sdkEntry } = opts;
13
+ let pruned = [];
14
+ // The connector lift: name each connector task through the library, then keep only
15
+ // the lifts that verify. One decompile to plan, one verify, and — only when a lift
16
+ // was refused — one more decompile with those tasks pinned verbatim. The pinned set
17
+ // then rides into the nested-style passes below, so the flat and nested sources the
18
+ // nested verify compares make the same connector decisions.
19
+ let connectors;
20
+ let verbatimConnectors = new Set();
21
+ const base0 = {
22
+ importSpecifier: opts.importSpecifier,
23
+ keepUnusedBindings: opts.keepUnusedBindings === true,
24
+ onPrune: (ids) => (pruned = ids),
25
+ ...(library ? { library, connectors: 'lift' } : {}),
26
+ onConnectorLift: (s) => (connectors = s),
27
+ };
28
+ let source = await decompile(xml, { ...base0, verbatimConnectors });
29
+ // `connectors` is assigned by the callback above; read it through a getter so the
30
+ // narrowing TypeScript did at the declaration does not survive the call.
31
+ const summary0 = () => connectors;
32
+ const planned = summary0();
33
+ if (library && planned && planned.lifted.length > 0) {
34
+ const verdict = await verifyConnectorLifts(xml, planned, sdkEntry, library);
35
+ if (verdict.failed.size > 0) {
36
+ verbatimConnectors = new Set(verdict.failed.keys());
37
+ source = await decompile(xml, { ...base0, verbatimConnectors });
38
+ // The summary from the second pass says "did not verify"; carry the measured reason.
39
+ const second = summary0();
40
+ if (second) {
41
+ second.verbatim = second.verbatim.map((v) => ({ id: v.id, reason: verdict.failed.get(v.id) ?? v.reason }));
42
+ }
43
+ }
44
+ }
45
+ let lifted;
46
+ let fallback;
47
+ if (opts.style === 'nested') {
48
+ // Two rungs: the top level in sequence mode, then without it. Built against THIS
49
+ // package's own entry, whatever specifier the written file carries — the check is
50
+ // about the graph, not about module resolution. The flow ids the lift renamed are
51
+ // the one sanctioned difference.
52
+ for (const sequenceMode of [true, false]) {
53
+ let summary;
54
+ const nested = await decompile(xml, {
55
+ ...base0, verbatimConnectors, style: 'nested', relabelFlows: opts.keepFlowIds !== true, sequenceMode, onLift: (s) => (summary = s),
56
+ });
57
+ const liftSummary = () => summary;
58
+ const renamed = new Map((liftSummary()?.renamedFlows ?? []).map((r) => [r.from, r.to]));
59
+ const verdict = await sameGraph(source, nested, sdkEntry, renamed);
60
+ if (verdict.same) {
61
+ source = nested;
62
+ lifted = liftSummary();
63
+ fallback = undefined;
64
+ break;
65
+ }
66
+ fallback = verdict.reason ?? 'the graphs differ';
67
+ }
68
+ }
69
+ const result = { source, pruned };
70
+ const finalSummary = summary0();
71
+ if (finalSummary)
72
+ result.connectors = finalSummary;
73
+ if (lifted)
74
+ result.lifted = lifted;
75
+ if (fallback)
76
+ result.fallback = fallback;
77
+ return result;
78
+ }
@@ -0,0 +1,48 @@
1
+ /** What `bpmn decompile` records about the decompile, and `bpmn merge` reads back. */
2
+ export interface DecompileStamp {
3
+ /** The original's base name. */
4
+ file: string;
5
+ /** {@link sourceDigest} of the source decompile made of the original, lowercase hex. */
6
+ sha256: string;
7
+ /** The style decompile was asked for. */
8
+ style: 'explicit' | 'nested';
9
+ /** `lift` when a library was open and the connector lift ran; else `verbatim`. */
10
+ connectors: 'lift' | 'verbatim';
11
+ /** Decompile was given `--keep-flow-ids`. */
12
+ keepFlowIds: boolean;
13
+ /** Decompile was given `--keep-unused-bindings`. */
14
+ keepUnusedBindings: boolean;
15
+ }
16
+ /** The marker that starts the stamp line. */
17
+ export declare const STAMP_MARKER = "// @decompiled-from ";
18
+ /**
19
+ * The digest the stamp records: SHA-256, lowercase hex, of a source as decompile makes
20
+ * it (no stamp line), with the SDK import specifier replaced by a fixed one, so
21
+ * `--import` and the absolute entry merge decompiles against give the same digest.
22
+ *
23
+ * @param source - The decompiled source, before {@link stampSource}.
24
+ */
25
+ export declare function sourceDigest(source: string): string;
26
+ /** The stamp line, without a line terminator. */
27
+ export declare function formatStamp(stamp: DecompileStamp): string;
28
+ /** `source` with the stamp line in front of it. */
29
+ export declare function stampSource(source: string, stamp: DecompileStamp): string;
30
+ /**
31
+ * Read the stamp from a `.bpmn.ts` source: the first line that starts with
32
+ * {@link STAMP_MARKER}.
33
+ *
34
+ * @returns The stamp; `undefined` when the source has no stamp line; or `{ error }`
35
+ * naming what is wrong with a stamp line that does not parse.
36
+ */
37
+ export declare function readStamp(source: string): DecompileStamp | {
38
+ error: string;
39
+ } | undefined;
40
+ /**
41
+ * `source` with its stamp line pointed at a new original: the `file` and `sha256`
42
+ * replaced, the options kept. `bpmn merge` calls this after it writes over the original,
43
+ * so the same source merges again in the next round: the merged original is what the
44
+ * source, as it now stands, would decompile from.
45
+ *
46
+ * @returns The restamped source, or `undefined` when `source` has no readable stamp.
47
+ */
48
+ export declare function restampSource(source: string, file: string, sha256: string): string | undefined;
@@ -0,0 +1,128 @@
1
+ /**
2
+ * decompile-stamp — the line `bpmn decompile` writes at the top of a `.bpmn.ts` to say
3
+ * which original it came from and how, and the reader `bpmn merge` uses to check it.
4
+ *
5
+ * The format is one `//` comment line:
6
+ *
7
+ * // @decompiled-from <file name> sha256:<64 hex> style=<explicit|nested> connectors=<lift|verbatim>[ keep-flow-ids][ keep-unused-bindings]
8
+ *
9
+ * - `<file name>` is the original's base name, for the messages only; a renamed or
10
+ * copied original with the same bytes still matches.
11
+ * - `sha256:` is the SHA-256 of the SOURCE decompile wrote for the original, without
12
+ * the stamp line and with its SDK import specifier normalized ({@link sourceDigest}),
13
+ * not of the original's bytes. Merge decompiles `--original` again with the recorded
14
+ * options and compares: what it needs is that the baseline it derives is the source
15
+ * the author started from, and this checks exactly that. So a change decompile does
16
+ * not read — line endings, the `bpmndi` layout `bpmn format` rewrites, attribute order
17
+ * — merges, since merge keeps it from the original; and a change in what decompile
18
+ * makes of the same bytes, a connector library that lifts differently, is refused.
19
+ * - `style` is the style decompile was asked for. The nested lift is deterministic and
20
+ * verified, so asking again gives the same source, fallback to flat included.
21
+ * - `connectors` is what the connector lift DID: `lift` when a library was open and the
22
+ * lift ran, `verbatim` when it was turned off or no library opened.
23
+ * - `keep-flow-ids` and `keep-unused-bindings` are present when decompile was given them.
24
+ *
25
+ * `--import` is not recorded: it changes the module specifier the source imports, not
26
+ * what the source builds, and the digest reads the import line with the specifier
27
+ * normalized.
28
+ *
29
+ * Why (UiPath/builder-sdk#1889): the source form of merge (`merge X.bpmn.ts --original
30
+ * X.bpmn`) derives its baseline by decompiling `--original` again. That is the source
31
+ * the author started from only while `--original` is the file the source was decompiled
32
+ * from, with the same options. If `X.bpmn` changed in between, its changes are in the
33
+ * derived baseline and not in the source, so the merge reads them as the author's
34
+ * deletions and reverts them. The stamp lets merge check the first and reproduce the
35
+ * second, and merge refuses a source without one.
36
+ *
37
+ * Nothing here prints; the CLIs do.
38
+ */
39
+ import { createHash } from 'node:crypto';
40
+ import { commentText } from '../core/comment-text.js';
41
+ /** The marker that starts the stamp line. */
42
+ export const STAMP_MARKER = '// @decompiled-from ';
43
+ /** The SDK import line of a decompiled source; `buildSource` (lift-verify.ts) rewrites the same line. */
44
+ const IMPORT_RE = /^(import\s*\{[^}]*\}\s*from\s*)["'][^"']+["'];/m;
45
+ /**
46
+ * The digest the stamp records: SHA-256, lowercase hex, of a source as decompile makes
47
+ * it (no stamp line), with the SDK import specifier replaced by a fixed one, so
48
+ * `--import` and the absolute entry merge decompiles against give the same digest.
49
+ *
50
+ * @param source - The decompiled source, before {@link stampSource}.
51
+ */
52
+ export function sourceDigest(source) {
53
+ return createHash('sha256').update(source.replace(IMPORT_RE, '$1"@";')).digest('hex');
54
+ }
55
+ /** The stamp line, without a line terminator. */
56
+ export function formatStamp(stamp) {
57
+ return (`${STAMP_MARKER}${commentText(stamp.file)} sha256:${stamp.sha256} style=${stamp.style} connectors=${stamp.connectors}` +
58
+ (stamp.keepFlowIds ? ' keep-flow-ids' : '') +
59
+ (stamp.keepUnusedBindings ? ' keep-unused-bindings' : ''));
60
+ }
61
+ /** `source` with the stamp line in front of it. */
62
+ export function stampSource(source, stamp) {
63
+ return `${formatStamp(stamp)}\n${source}`;
64
+ }
65
+ const STAMP_RE = /^\/\/ @decompiled-from (.*) sha256:([0-9a-f]{64})((?: \S+)*)\s*$/;
66
+ /**
67
+ * Read the stamp from a `.bpmn.ts` source: the first line that starts with
68
+ * {@link STAMP_MARKER}.
69
+ *
70
+ * @returns The stamp; `undefined` when the source has no stamp line; or `{ error }`
71
+ * naming what is wrong with a stamp line that does not parse.
72
+ */
73
+ export function readStamp(source) {
74
+ const line = source.split(/\r?\n/).find((l) => l.startsWith(STAMP_MARKER));
75
+ if (line === undefined)
76
+ return undefined;
77
+ const match = STAMP_RE.exec(line);
78
+ if (!match)
79
+ return { error: `the line does not read as \`${STAMP_MARKER}<file> sha256:<64 hex> <options>\`: ${line}` };
80
+ const stamp = {
81
+ file: match[1] ?? '',
82
+ sha256: match[2] ?? '',
83
+ style: 'explicit',
84
+ connectors: 'verbatim',
85
+ keepFlowIds: false,
86
+ keepUnusedBindings: false,
87
+ };
88
+ const seen = new Set();
89
+ for (const token of (match[3] ?? '').trim().split(' ').filter(Boolean)) {
90
+ const [key, value] = token.split('=', 2);
91
+ if (seen.has(key))
92
+ return { error: `\`${key}\` appears twice: ${line}` };
93
+ seen.add(key);
94
+ if (key === 'style' && (value === 'explicit' || value === 'nested'))
95
+ stamp.style = value;
96
+ else if (key === 'connectors' && (value === 'lift' || value === 'verbatim'))
97
+ stamp.connectors = value;
98
+ else if (key === 'keep-flow-ids' && value === undefined)
99
+ stamp.keepFlowIds = true;
100
+ else if (key === 'keep-unused-bindings' && value === undefined)
101
+ stamp.keepUnusedBindings = true;
102
+ else
103
+ return { error: `unknown option \`${token}\`: ${line}` };
104
+ }
105
+ for (const required of ['style', 'connectors']) {
106
+ if (!seen.has(required))
107
+ return { error: `\`${required}=\` is missing: ${line}` };
108
+ }
109
+ return stamp;
110
+ }
111
+ /**
112
+ * `source` with its stamp line pointed at a new original: the `file` and `sha256`
113
+ * replaced, the options kept. `bpmn merge` calls this after it writes over the original,
114
+ * so the same source merges again in the next round: the merged original is what the
115
+ * source, as it now stands, would decompile from.
116
+ *
117
+ * @returns The restamped source, or `undefined` when `source` has no readable stamp.
118
+ */
119
+ export function restampSource(source, file, sha256) {
120
+ const stamp = readStamp(source);
121
+ if (stamp === undefined || 'error' in stamp)
122
+ return undefined;
123
+ const lines = source.split('\n');
124
+ const at = lines.findIndex((l) => l.startsWith(STAMP_MARKER));
125
+ const cr = lines[at]?.endsWith('\r') ? '\r' : '';
126
+ lines[at] = `${formatStamp({ ...stamp, file, sha256 })}${cr}`;
127
+ return lines.join('\n');
128
+ }
@@ -77,12 +77,15 @@ export async function buildSource(source, sdkEntry) {
77
77
  // two per verify and up to four per `decompile --style nested`.
78
78
  //
79
79
  // Safe to delete once the import has resolved: the module is fully evaluated, the SDK
80
- // specifier was rewritten to an absolute path OUTSIDE this directory, and the file
80
+ // specifier was rewritten to an absolute file URL OUTSIDE this directory, and the file
81
81
  // name is `mkdtemp` plus a random suffix, so nothing re-resolves it.
82
82
  try {
83
83
  writeFileSync(join(dir, 'package.json'), '{"type":"module"}\n');
84
84
  const file = join(dir, `Lift-${Math.random().toString(36).slice(2)}.bpmn.ts`);
85
- const rewritten = source.replace(/^(import\s*\{[^}]*\}\s*from\s*)["'][^"']+["'];/m, `$1${JSON.stringify(sdkEntry)};`);
85
+ // A file URL, not the raw path: an ESM specifier is a URL, so a `#` in the install
86
+ // path would start a fragment and a Windows drive prefix would read as a scheme.
87
+ const specifier = pathToFileURL(sdkEntry).href;
88
+ const rewritten = source.replace(/^(import\s*\{[^}]*\}\s*from\s*)["'][^"']+["'];/m, `$1${JSON.stringify(specifier)};`);
86
89
  writeFileSync(file, rewritten);
87
90
  const mod = await import(pathToFileURL(file).href);
88
91
  if (!mod.default || !Array.isArray(mod.default.nodes))
@@ -1,3 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { type CliExitCode } from '../cli-run.js';
3
- export declare function run(argv: string[]): CliExitCode;
3
+ /**
4
+ * `run(argv)` is the tool contract the family-first `flow-sdk` CLI loads: the
5
+ * original first, then the edited document or source.
6
+ */
7
+ export declare function run(argv: string[]): Promise<CliExitCode>;
@@ -4,41 +4,290 @@
4
4
  *
5
5
  * Usage:
6
6
  * bpmn-merge <original.bpmn> <edited.bpmn> [-o merged.bpmn] [--baseline <baseline.bpmn>]
7
+ * bpmn-merge <original.bpmn> <edited.bpmn.ts> [-o <original.bpmn>] [--baseline <baseline.bpmn>]
8
+ * [--style nested|explicit] [--connectors lift|verbatim] [--keep-flow-ids] [--keep-unused-bindings]
9
+ * [--library <dir>] [--connectors-local <dir>] [--bindings <file>] [--resources <file>]
7
10
  *
8
11
  * `edited.bpmn` is compile(decompile(original)) after your edits. `--baseline` is
9
12
  * compile(decompile(original)) BEFORE any edit — supplying it enables the delta merge, so
10
13
  * every element you did not touch is emitted from the original byte for byte. Omit it for
11
14
  * a two-way merge (take the edited process, keep the original diagram). See merge.ts.
15
+ *
16
+ * An edited SOURCE (`.bpmn.ts`) needs neither file (UiPath/builder-sdk#1871): merge
17
+ * compiles it as `compile` would, derives the baseline by decompiling the original and
18
+ * compiling that, in memory, and writes only the merged result — over the original
19
+ * unless `-o` says otherwise. The library, bindings and resources are `compile`'s, and
20
+ * both compiles use them. See merge-source.ts.
21
+ *
22
+ * The source must carry the stamp `bpmn decompile` writes on its first line
23
+ * (decompile-stamp.ts). Merge refuses, writing nothing, when there is no stamp, and when
24
+ * the source it decompiles from the original now does not have the digest the stamp
25
+ * records — the derived baseline would then hold the original's later changes, and the
26
+ * merge would revert them. A change decompile does not read (line endings, the layout
27
+ * `bpmn format` rewrites) leaves the digest alone and merges. It derives the
28
+ * baseline with the decompile options the stamp records; a decompile flag given here
29
+ * that disagrees with the stamp is refused, one that agrees is accepted. With
30
+ * `--baseline` the stamp is not checked: the baseline is the caller's.
31
+ *
32
+ * After it writes over the original, merge decompiles the merged file the same way and
33
+ * rewrites the source's stamp with that digest, options kept, so the next
34
+ * edit-and-merge round on the same source passes the check; under `--baseline` too,
35
+ * when the source has a readable stamp. With `-o` elsewhere the original and the
36
+ * stamp stay as they were.
12
37
  */
13
- import { reportResult } from '../cli-result.js';
38
+ import { reportCompileRefusal, reportDiagnostics, reportResult } from '../cli-result.js';
14
39
  import { readFileSync, writeFileSync } from 'node:fs';
15
40
  import { basename, resolve } from 'node:path';
41
+ import { fileURLToPath } from 'node:url';
16
42
  import { mergeBpmn } from './merge.js';
43
+ import { decompiledDigest, deriveBaseline } from './merge-source.js';
44
+ import { readStamp, sourceDigest, restampSource, STAMP_MARKER } from './decompile-stamp.js';
45
+ import { loadBuiltBpmn } from './load.js';
46
+ import { serialize } from './serialize.js';
47
+ import { Bindings } from '../core/bindings.js';
48
+ import { openCliLibrary } from '../core/cli-library.js';
49
+ import { readCliResources } from '../registry/prepare/resources.js';
50
+ import { ensureTypeScriptRuntime } from '../node-runtime.js';
51
+ import { defaultBindingsFile, defaultResourcesFile } from '../workdir.js';
17
52
  import { flagValue, runWhenInvokedDirectly } from '../cli-run.js';
18
- export function run(argv) {
53
+ const USAGE = 'usage: bpmn-merge <original.bpmn> <edited.bpmn | edited.bpmn.ts> [-o merged.bpmn] [--baseline <baseline.bpmn>]\n' +
54
+ ' an edited .bpmn.ts is compiled here, the baseline derived from the original, and the\n' +
55
+ ' merge written over the original unless -o is given. The source must carry the stamp\n' +
56
+ ' `bpmn decompile` writes, and the original must be unchanged since; the decompile options\n' +
57
+ ' come from the stamp. It also takes\n' +
58
+ ' [--style nested|explicit] [--connectors lift|verbatim] [--keep-flow-ids] [--keep-unused-bindings]\n' +
59
+ ' (each refused when it disagrees with the stamp)\n' +
60
+ ' [--library <dir>] [--connectors-local <dir>] [--bindings <file>] [--resources <file>]';
61
+ /** Flags that take a value, so the value is not read as a positional. */
62
+ const VALUE_FLAGS = new Set([
63
+ '-o', '--baseline', '--style', '--connectors', '--library', '--connectors-local', '--bindings', '--resources',
64
+ ]);
65
+ const BARE_FLAGS = new Set(['--keep-flow-ids', '--keep-unused-bindings']);
66
+ /** The decompile options a stamp records, as `deriveBaseline` and `decompiledDigest` take them. */
67
+ function stampedDecompile(stamp, library) {
68
+ return {
69
+ sdkEntry: fileURLToPath(new URL('./bpmn-sdk.js', import.meta.url)),
70
+ style: stamp.style,
71
+ keepFlowIds: stamp.keepFlowIds,
72
+ keepUnusedBindings: stamp.keepUnusedBindings,
73
+ ...(stamp.connectors === 'lift' && library ? { liftLibrary: library } : {}),
74
+ };
75
+ }
76
+ /** Refuse the merge with a coded diagnostic; nothing has been written. */
77
+ function refuseMerge(code, message) {
78
+ console.error(`bpmn-merge: ${message}`);
79
+ reportDiagnostics([{ level: 'error', code, message }]);
80
+ return 1;
81
+ }
82
+ /** The way on from a refused source merge. */
83
+ function redoAdvice(originalPath) {
84
+ return (`Decompile ${basename(originalPath)} again (\`bpmn decompile\`) and reapply the edit to the new source, ` +
85
+ 'or merge with --baseline <file>, the compile of the unedited decompile.');
86
+ }
87
+ /**
88
+ * Check the decompile flags, then — unless `--baseline` was given — read the source's
89
+ * stamp, refuse a missing or unreadable one and a flag that disagrees with it. Returns
90
+ * the stamp (`undefined` under `--baseline`), or the exit code. Whether the original
91
+ * still decompiles to the stamped digest is checked once the baseline is derived
92
+ * (`compileSides`).
93
+ */
94
+ function decompileOptions(argv, editedPath, originalPath, hasBaseline) {
95
+ const style = flagValue(argv, '--style');
96
+ if (style !== undefined && style !== 'explicit' && style !== 'nested') {
97
+ console.error(`bpmn-merge: --style must be explicit or nested, not "${style}"`);
98
+ return 2;
99
+ }
100
+ const connectors = flagValue(argv, '--connectors');
101
+ if (connectors !== undefined && connectors !== 'lift' && connectors !== 'verbatim') {
102
+ console.error(`bpmn-merge: --connectors must be lift or verbatim, not "${connectors}"`);
103
+ return 2;
104
+ }
105
+ if (hasBaseline)
106
+ return undefined;
107
+ const edited = basename(editedPath);
108
+ const original = basename(originalPath);
109
+ const redo = redoAdvice(originalPath);
110
+ const stamp = readStamp(readFileSync(editedPath, 'utf8'));
111
+ if (stamp === undefined) {
112
+ return refuseMerge('MERGE_SOURCE_NOT_STAMPED', `${edited} has no \`${STAMP_MARKER.trim()}\` line, so merge cannot tell whether ${original} is still the file ` +
113
+ `it was decompiled from, or how it was decompiled. Nothing was written. ${redo}`);
114
+ }
115
+ if ('error' in stamp) {
116
+ return refuseMerge('MERGE_SOURCE_STAMP_UNREADABLE', `${edited}'s decompile stamp is unreadable — ${stamp.error}. Nothing was written. ${redo}`);
117
+ }
118
+ const given = [
119
+ ['--style', style, stamp.style],
120
+ ['--connectors', connectors, stamp.connectors],
121
+ ['--keep-flow-ids', argv.includes('--keep-flow-ids') || undefined, stamp.keepFlowIds],
122
+ ['--keep-unused-bindings', argv.includes('--keep-unused-bindings') || undefined, stamp.keepUnusedBindings],
123
+ ];
124
+ for (const [flag, value, recorded] of given) {
125
+ if (value === undefined || value === recorded)
126
+ continue;
127
+ const said = typeof value === 'string' ? `${flag} ${value}` : flag;
128
+ const records = typeof recorded === 'string' ? `${flag.slice(2)}=${recorded}` : `no ${flag.slice(2)}`;
129
+ return refuseMerge('MERGE_OPTION_CONFLICT', `${said} disagrees with ${edited}'s decompile stamp, which records ${records}. ` +
130
+ 'Merge derives the baseline with the options the stamp records; drop the flag. Nothing was written.');
131
+ }
132
+ return stamp;
133
+ }
134
+ /**
135
+ * Compile the edited source and, unless `--baseline` was given, derive the baseline
136
+ * from the original — both in memory, with the decompile options the source's stamp
137
+ * records — and refuse when the source derived from the original does not have the
138
+ * stamped digest. A refused compile is reported as `compile` reports it, and its exit
139
+ * code returned instead.
140
+ */
141
+ async function compileSides(argv, editedPath, originalPath, original, explicitBaseline, decompiled) {
142
+ // Loading authored TypeScript, and the nested decompile's verification, both import
143
+ // `.ts`; this re-executes under --experimental-strip-types where Node needs the flag.
144
+ ensureTypeScriptRuntime();
145
+ // `compile`'s context, shared by both compiles so they differ only by the edit.
146
+ const library = openCliLibrary(argv);
147
+ const resources = readCliResources(argv, defaultResourcesFile());
148
+ const opts = {
149
+ bindings: new Bindings(flagValue(argv, '--bindings') ?? defaultBindingsFile()),
150
+ ...(library ? { library } : {}),
151
+ ...(resources ? { resources } : {}),
152
+ };
153
+ // Two catches, as `compile` has them, so a broken source fails here exactly as it
154
+ // fails there. While the source loads, only a builder refusal is printed by its code;
155
+ // a syntax error or a missing import propagates with its own code and the JSON
156
+ // `error` field, not as a COMPILE_FAILED refusal.
157
+ let built;
158
+ try {
159
+ built = await loadBuiltBpmn(resolve(editedPath));
160
+ }
161
+ catch (error) {
162
+ return reportCompileRefusal(error, { uncoded: 'propagate' });
163
+ }
164
+ let edited;
165
+ try {
166
+ edited = await serialize(built, opts);
167
+ }
168
+ catch (error) {
169
+ // What `compile` would refuse, printed as `compile` prints it.
170
+ return reportCompileRefusal(error);
171
+ }
172
+ // No stamp options means `--baseline` was given: the baseline is the caller's.
173
+ if (decompiled === undefined)
174
+ return { edited, baseline: explicitBaseline };
175
+ const derive = { serialize: opts, ...stampedDecompile(decompiled, library) };
176
+ let derived;
177
+ try {
178
+ derived = await deriveBaseline(original, derive);
179
+ }
180
+ catch (error) {
181
+ console.error(`bpmn-merge: could not derive the baseline from ${basename(editedPath)}'s original (decompile, then compile, in memory). ` +
182
+ 'Compile the unedited decompile yourself and pass it as --baseline <file>.');
183
+ return reportCompileRefusal(error);
184
+ }
185
+ // The baseline is the source the author started from only if decompiling the original
186
+ // now gives the source decompile wrote then. Compared by digest, not by the original's
187
+ // bytes, so what decompile does not read (line endings, `bpmn format`'s layout) passes.
188
+ const actual = sourceDigest(derived.decompile.source);
189
+ if (actual !== decompiled.sha256) {
190
+ const edited = basename(editedPath);
191
+ const name = basename(originalPath);
192
+ const lift = decompiled.connectors === 'lift' ? ', or the connector library it lifted with,' : '';
193
+ return refuseMerge('MERGE_ORIGINAL_CHANGED', `${name}${lift} changed since ${edited} was decompiled from ${decompiled.file === name ? 'it' : decompiled.file}: ` +
194
+ `decompiling it now gives a different source (sha256 ${decompiled.sha256} recorded, ${actual} now). ` +
195
+ `Merging would read those changes as the edit's deletions and revert them, so nothing was written. ${redoAdvice(originalPath)}`);
196
+ }
197
+ return {
198
+ edited,
199
+ baseline: derived.xml,
200
+ derived: {
201
+ style: derived.decompile.lifted ? 'nested' : 'explicit',
202
+ lifted: derived.decompile.connectors?.lifted.length ?? 0,
203
+ },
204
+ derive,
205
+ };
206
+ }
207
+ /**
208
+ * `run(argv)` is the tool contract the family-first `flow-sdk` CLI loads: the
209
+ * original first, then the edited document or source.
210
+ */
211
+ export async function run(argv) {
19
212
  if (argv.length === 0 || argv[0] === '-h' || argv[0] === '--help') {
20
- console.error('usage: bpmn-merge <original.bpmn> <edited.bpmn> [-o merged.bpmn] [--baseline <baseline.bpmn>]');
213
+ console.error(USAGE);
21
214
  return 2;
22
215
  }
23
- const flags = new Set(['-o', '--baseline']);
24
- const positionals = argv.filter((a, i) => !flags.has(a) && !flags.has(argv[i - 1]) && !a.startsWith('-'));
216
+ const positionals = argv.filter((a, i) => !BARE_FLAGS.has(a) && !VALUE_FLAGS.has(a) && !VALUE_FLAGS.has(argv[i - 1] ?? '') && !a.startsWith('-'));
25
217
  const [originalPath, editedPath] = positionals;
26
218
  if (!originalPath || !editedPath) {
27
- console.error('bpmn-merge: need <original.bpmn> and <edited.bpmn>');
219
+ console.error('bpmn-merge: need <original.bpmn> and <edited.bpmn> (or <edited.bpmn.ts>)');
28
220
  return 2;
29
221
  }
222
+ const original = readFileSync(originalPath, 'utf8');
30
223
  const baselinePath = flagValue(argv, '--baseline');
31
- const result = mergeBpmn(readFileSync(originalPath, 'utf8'), readFileSync(editedPath, 'utf8'), {
32
- ...(baselinePath ? { baseline: readFileSync(baselinePath, 'utf8') } : {}),
33
- });
34
- const out = flagValue(argv, '-o') ?? 'merged.bpmn';
224
+ const explicitBaseline = baselinePath ? readFileSync(baselinePath, 'utf8') : undefined;
225
+ // An edited source is compiled here and the baseline derived from the original, so
226
+ // the brownfield loop writes nothing but the merged file (#1871).
227
+ const isSource = editedPath.endsWith('.ts');
228
+ let edited;
229
+ let baseline = explicitBaseline;
230
+ let derived;
231
+ let derive;
232
+ if (isSource) {
233
+ // Before anything compiles: a missing stamp, or a flag that disagrees with it. The
234
+ // digest check, which refuses an original that changed since the decompile, runs
235
+ // once the baseline's source is derived (compileSides).
236
+ const decompiled = decompileOptions(argv, editedPath, originalPath, explicitBaseline !== undefined);
237
+ if (typeof decompiled === 'number')
238
+ return decompiled;
239
+ const sides = await compileSides(argv, editedPath, originalPath, original, explicitBaseline, decompiled);
240
+ if (typeof sides === 'number')
241
+ return sides;
242
+ ({ edited, baseline, derived, derive } = sides);
243
+ if (explicitBaseline !== undefined) {
244
+ // No stamp check under --baseline, but a readable stamp still says how to digest
245
+ // the merged file, so a merge written over the original restamps as it does without.
246
+ const stamp = readStamp(readFileSync(editedPath, 'utf8'));
247
+ if (stamp !== undefined && !('error' in stamp))
248
+ derive = stampedDecompile(stamp, openCliLibrary(argv));
249
+ }
250
+ }
251
+ else {
252
+ edited = readFileSync(editedPath, 'utf8');
253
+ }
254
+ const result = mergeBpmn(original, edited, baseline !== undefined ? { baseline } : {});
255
+ // The source form merges in place by default: a `merged.bpmn` beside the original is
256
+ // one more `.bpmn` for the next reader to open by mistake — the very leftover the
257
+ // source form exists to avoid. It is safe because the stamp check above refused an
258
+ // original that changed since the decompile.
259
+ const out = flagValue(argv, '-o') ?? (isSource ? originalPath : 'merged.bpmn');
35
260
  writeFileSync(out, result.xml);
261
+ // Written over the original: point the source's stamp at the merged file, so the next
262
+ // edit-and-merge round on the same source passes the check. The merged original is
263
+ // what the source, as it now stands, decompiles from; its digest is that of the merged
264
+ // file decompiled with the stamped options, which is what the next check derives.
265
+ // Written elsewhere, the original is unchanged and so is the stamp; a source with no
266
+ // readable stamp (possible only under --baseline) keeps none.
267
+ let restamped = false;
268
+ if (derive && resolve(out) === resolve(originalPath)) {
269
+ const source = readFileSync(editedPath, 'utf8');
270
+ let next;
271
+ try {
272
+ next = restampSource(source, basename(originalPath), await decompiledDigest(result.xml, derive));
273
+ }
274
+ catch (error) {
275
+ // The merge stands; the old stamp makes the next round refuse, never revert.
276
+ console.error(`bpmn-merge: could not decompile the merged ${basename(originalPath)} to restamp ${basename(editedPath)} ` +
277
+ `(${error instanceof Error ? error.message : String(error)}); decompile it again before the next edit`);
278
+ }
279
+ if (next !== undefined && next !== source) {
280
+ writeFileSync(editedPath, next);
281
+ restamped = true;
282
+ }
283
+ }
36
284
  const { layout } = result;
37
285
  reportResult({
38
286
  path: resolve(out),
39
287
  preserved: result.preserved.length,
40
288
  authored: result.authored.length,
41
289
  removed: result.removed.length,
290
+ ...(isSource ? { baseline: derived ? 'derived' : 'file', restamped } : {}),
42
291
  placed: layout.placed.length,
43
292
  routed: layout.routed.length + layout.rerouted.length,
44
293
  ...(layout.resized.length || layout.moved.length ? { resized: layout.resized, moved: layout.moved } : {}),
@@ -47,6 +296,13 @@ export function run(argv) {
47
296
  // should dwarf the authored one, and a reader who sees otherwise has learned something.
48
297
  console.log(`bpmn-merge: wrote ${basename(out)} (${result.preserved.length} preserved, ` +
49
298
  `${result.authored.length} authored, ${result.removed.length} removed)`);
299
+ if (derived) {
300
+ console.log(`bpmn-merge: compiled ${basename(editedPath)} and derived the baseline from ${basename(originalPath)} in memory ` +
301
+ `(${derived.style} decompile${derived.lifted ? `, ${derived.lifted} connector task(s) lifted` : ''}); no intermediate file written`);
302
+ }
303
+ if (restamped) {
304
+ console.log(`bpmn-merge: restamped ${basename(editedPath)} for the merged ${basename(originalPath)}, so it merges again after the next edit`);
305
+ }
50
306
  // The diagram: what the edit added is drawn, and an existing shape moves only when a
51
307
  // full lane, pool or sub-process had to grow — say so, by id, when it did.
52
308
  if (layout.placed.length || layout.routed.length || layout.rerouted.length) {
@@ -0,0 +1,86 @@
1
+ /**
2
+ * merge-source — the two compiles `bpmn merge` runs itself when it is handed the
3
+ * edited SOURCE (`bpmn merge X.bpmn.ts --original X.bpmn`), so the brownfield loop
4
+ * writes no intermediate `.bpmn` (UiPath/builder-sdk#1871).
5
+ *
6
+ * The file-based pipeline needs two compiled documents beside the original:
7
+ *
8
+ * decompile X.bpmn -> X.bpmn.ts
9
+ * compile X.bpmn.ts -o X.baseline.bpmn # BEFORE the edit
10
+ * (edit X.bpmn.ts)
11
+ * compile X.bpmn.ts -o X.edited.bpmn
12
+ * merge X.edited.bpmn --original X.bpmn --baseline X.baseline.bpmn -o X.bpmn
13
+ *
14
+ * Agents left `X.baseline.bpmn` and `X.edited.bpmn` in the project, and the next
15
+ * reader of `*.bpmn` opened the wrong one. Both are derivable: the edited document is
16
+ * the compile of the source, and the baseline is the compile of a FRESH decompile of
17
+ * the original — which is what `X.bpmn.ts` was before the edit, because decompile is a
18
+ * function of the original and the options it was given. That holds only while the
19
+ * original is the file the source was decompiled from: if it changed since, its changes
20
+ * are in the derived baseline and not in the source, and the merge would revert them.
21
+ * So `bpmn decompile` stamps the source with the digest of the source it wrote and its
22
+ * options (decompile-stamp.ts); merge-cli.ts refuses a source whose stamp is missing,
23
+ * passes the stamped options here, and refuses when the source this derives digests
24
+ * differently — the derived baseline is then not what the author started from. This makes both in
25
+ * memory: `decompilePipeline` (the same code `bpmn decompile` runs, lifts and their
26
+ * verification included) for the baseline's source, and `serialize`, with the
27
+ * library, bindings and resources the edited compile uses, for both.
28
+ *
29
+ * The baseline only has to agree with the edited compile on what the author did NOT
30
+ * touch, and that holds when it was decompiled with the options the author's source
31
+ * was — the ones the stamp records: the connector lift (`connectors`) changes how a
32
+ * connector task compiles, and a dropped unused binding (`keepUnusedBindings`) changes
33
+ * the process extension block. The nested style does not change the compiled graph —
34
+ * `bpmn decompile` writes the nested source only when it builds the same graph as the
35
+ * flat one, flow ids included — but it is reproduced too, so the baseline is built
36
+ * from the same text the author started from.
37
+ *
38
+ * Nothing here prints or reads argv; merge-cli.ts does.
39
+ */
40
+ import type { Library } from '../core/library.js';
41
+ import { type BpmnSerializeOpts } from './serialize.js';
42
+ import { type DecompilePipelineResult } from './decompile-pipeline.js';
43
+ /** What both in-memory compiles need, and how to decompile the original. */
44
+ export interface SourceMergeOptions {
45
+ /** The library, bindings and resources `compile` would use; the edited and baseline compiles share them. */
46
+ serialize: BpmnSerializeOpts;
47
+ /** Absolute path of this package's `bpmn-sdk.js`, which the baseline source builds against. */
48
+ sdkEntry: string;
49
+ /** The decompile style the author's source was written in (default `nested`). */
50
+ style?: 'explicit' | 'nested';
51
+ /**
52
+ * The library the decompile lifts connector tasks with — `undefined` for
53
+ * `--connectors verbatim`, or when no library opens, which is what `bpmn decompile`
54
+ * did with the same options.
55
+ */
56
+ liftLibrary?: Library;
57
+ /** As `bpmn decompile --keep-flow-ids`. */
58
+ keepFlowIds?: boolean;
59
+ /** As `bpmn decompile --keep-unused-bindings`. */
60
+ keepUnusedBindings?: boolean;
61
+ }
62
+ /** The baseline merge derived from the original. */
63
+ export interface DerivedBaseline {
64
+ /** `compile(decompile(original))`, the document a `--baseline` file would hold. */
65
+ xml: string;
66
+ /** What the decompile did: the lifts, the bindings it dropped. */
67
+ decompile: DecompilePipelineResult;
68
+ }
69
+ /**
70
+ * `compile(decompile(original))`, made in memory: the baseline the file-based pipeline
71
+ * writes to `X.baseline.bpmn` before the edit.
72
+ *
73
+ * @param original - The original `.bpmn` text.
74
+ * @param opts - The compile context and the decompile options.
75
+ * @returns The baseline document and what the decompile did.
76
+ */
77
+ export declare function deriveBaseline(original: string, opts: SourceMergeOptions): Promise<DerivedBaseline>;
78
+ /**
79
+ * The stamp digest of `xml` decompiled with `opts`'s options: what `bpmn decompile`
80
+ * would record for it. Merge restamps the source with this after writing over the
81
+ * original, so the next round's check compares like with like.
82
+ *
83
+ * @param xml - The merged `.bpmn` text.
84
+ * @param opts - The decompile options the baseline was derived with.
85
+ */
86
+ export declare function decompiledDigest(xml: string, opts: Omit<SourceMergeOptions, 'serialize'>): Promise<string>;
@@ -0,0 +1,39 @@
1
+ import { serialize } from './serialize.js';
2
+ import { buildSource } from './lift-verify.js';
3
+ import { decompilePipeline } from './decompile-pipeline.js';
4
+ import { sourceDigest } from './decompile-stamp.js';
5
+ /**
6
+ * `compile(decompile(original))`, made in memory: the baseline the file-based pipeline
7
+ * writes to `X.baseline.bpmn` before the edit.
8
+ *
9
+ * @param original - The original `.bpmn` text.
10
+ * @param opts - The compile context and the decompile options.
11
+ * @returns The baseline document and what the decompile did.
12
+ */
13
+ export async function deriveBaseline(original, opts) {
14
+ const decompiled = await decompileAs(original, opts);
15
+ const built = await buildSource(decompiled.source, opts.sdkEntry);
16
+ return { xml: await serialize(built, opts.serialize), decompile: decompiled };
17
+ }
18
+ /**
19
+ * The stamp digest of `xml` decompiled with `opts`'s options: what `bpmn decompile`
20
+ * would record for it. Merge restamps the source with this after writing over the
21
+ * original, so the next round's check compares like with like.
22
+ *
23
+ * @param xml - The merged `.bpmn` text.
24
+ * @param opts - The decompile options the baseline was derived with.
25
+ */
26
+ export async function decompiledDigest(xml, opts) {
27
+ return sourceDigest((await decompileAs(xml, opts)).source);
28
+ }
29
+ /** `decompilePipeline` with the options `bpmn decompile` was given. */
30
+ function decompileAs(xml, opts) {
31
+ return decompilePipeline(xml, {
32
+ importSpecifier: opts.sdkEntry,
33
+ style: opts.style ?? 'nested',
34
+ keepFlowIds: opts.keepFlowIds === true,
35
+ keepUnusedBindings: opts.keepUnusedBindings === true,
36
+ sdkEntry: opts.sdkEntry,
37
+ ...(opts.liftLibrary ? { library: opts.liftLibrary } : {}),
38
+ });
39
+ }
@@ -76,11 +76,26 @@ export function registerBpmnCommands(program) {
76
76
  });
77
77
  family
78
78
  .command('merge')
79
- .description('Merge an edited process with its original BPMN artifact.')
80
- .argument('<edited>', 'edited .bpmn path')
79
+ .description('Merge an edited process with its original BPMN artifact. Given the edited .bpmn.ts source, merge compiles it, '
80
+ + 'derives the baseline from --original (decompile, then compile) in memory, and writes the result over '
81
+ + '--original unless -o is given, so no intermediate .bpmn is needed. The source must carry the '
82
+ + '`// @decompiled-from` stamp `bpmn decompile` writes: merge refuses, writing nothing, when --original changed '
83
+ + 'since the decompile or the stamp is missing, and derives the baseline with the decompile options it records.')
84
+ .argument('<edited>', 'edited .bpmn path, or the edited .bpmn.ts source')
81
85
  .option('--original <file>', '(required) original .bpmn path, the artifact to merge into')
82
- .option('-o, --output <file>', 'merged output path')
83
- .option('--baseline <file>', 'compiled pristine decompile')
86
+ .option('-o, --output <file>', 'merged output path (default: merged.bpmn; for an edited .bpmn.ts, --original itself)')
87
+ .option('--baseline <file>', 'compiled pristine decompile (derived from --original when <edited> is a .bpmn.ts)')
88
+ // For an edited .bpmn.ts: how the original was decompiled. The source's stamp
89
+ // records it, so these are never needed; one that disagrees with the stamp is refused …
90
+ .option('--style <style>', 'edited .bpmn.ts: the decompile style, nested or explicit (read from the stamp; refused if it disagrees)')
91
+ .option('--connectors <mode>', 'edited .bpmn.ts: lift or verbatim, as it was decompiled (read from the stamp; refused if it disagrees)')
92
+ .option('--keep-flow-ids', 'edited .bpmn.ts: it was decompiled with --keep-flow-ids (read from the stamp; refused if it disagrees)')
93
+ .option('--keep-unused-bindings', 'edited .bpmn.ts: it was decompiled with --keep-unused-bindings (read from the stamp; refused if it disagrees)')
94
+ // … and compile's inputs, which both in-memory compiles use.
95
+ .option('--library <dir>', 'edited .bpmn.ts: connector library directory')
96
+ .option('--connectors-local <dir>', 'edited .bpmn.ts: connection-resolved connector overlay')
97
+ .option('--bindings <file>', 'edited .bpmn.ts: bindings.json path')
98
+ .option('--resources <file>', 'edited .bpmn.ts: resource ledger that registry prepare writes (default .flow-sdk/resources.json)')
84
99
  .allowExcessArguments()
85
100
  .action(async (_edited, options, command) => {
86
101
  const pair = namedOrLegacySecond(command, {
@@ -93,6 +108,16 @@ export function registerBpmnCommands(program) {
93
108
  const argv = [original, edited];
94
109
  addValue(argv, '-o', options.output);
95
110
  addValue(argv, '--baseline', options.baseline);
111
+ addValue(argv, '--style', options.style);
112
+ addValue(argv, '--connectors', options.connectors);
113
+ if (options.keepFlowIds)
114
+ argv.push('--keep-flow-ids');
115
+ if (options.keepUnusedBindings)
116
+ argv.push('--keep-unused-bindings');
117
+ addValue(argv, '--library', options.library);
118
+ addValue(argv, '--connectors-local', options.connectorsLocal);
119
+ addValue(argv, '--bindings', options.bindings);
120
+ addValue(argv, '--resources', options.resources);
96
121
  await invoke('bpmn merge', () => import('../../bpmn/merge-cli.js'), argv);
97
122
  });
98
123
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uipath/maestro-builder-sdk",
3
- "version": "6.94.6",
3
+ "version": "6.95.0",
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",
@@ -74,7 +74,8 @@
74
74
  "merge-original-option",
75
75
  "prepare-action-option",
76
76
  "json-result",
77
- "prepare-resource"
77
+ "prepare-resource",
78
+ "bpmn-merge-source"
78
79
  ],
79
80
  "files": [
80
81
  "dist",
@@ -111,5 +112,5 @@
111
112
  "@types/node": "^22.7.0",
112
113
  "esbuild": "^0.28.1"
113
114
  },
114
- "gitref": "12cb23df83e2177d2b1ccc2c731e9b80298a12ba"
115
+ "gitref": "13b0485c8d353f4129c4b6d192b1432c5f9fc0b2"
115
116
  }