@uipath/maestro-builder-sdk 6.95.6 → 6.96.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,99 @@
1
+ /**
2
+ * decompile-stamp — the line a family's `decompile` writes at the top of its source to
3
+ * say which original it came from and how, and the reader its `merge` uses to check it.
4
+ * The parts every family shares; each family's own module (`decompile-stamp.ts` for
5
+ * Flow, `bpmn/decompile-stamp.ts`) reads and writes its options.
6
+ *
7
+ * The format is one `//` comment line:
8
+ *
9
+ * // @decompiled-from <file name> sha256:<64 hex>[ <option>]...
10
+ *
11
+ * - `<file name>` is the original's base name, for the messages only; a renamed or
12
+ * copied original with the same bytes still matches.
13
+ * - `sha256:` is the SHA-256 of the SOURCE decompile wrote for the original, without
14
+ * the stamp line and with its SDK import specifier normalized ({@link sourceDigest}),
15
+ * not of the original's bytes. Merge decompiles `--original` again with the recorded
16
+ * options and compares: what it needs is that the baseline it derives is the source
17
+ * the author started from, and this checks exactly that. So a change decompile does
18
+ * not read (line endings, indentation, BPMN's diagram layout) merges, since merge
19
+ * keeps it from the original; a change the source shows, an entry order a decompiler
20
+ * prints as read included, and a change in what decompile makes of the same bytes,
21
+ * are refused.
22
+ * - Each `<option>` is `key=value` or a bare `key`: what the family's decompile was
23
+ * asked for that changes the source it writes.
24
+ *
25
+ * `--import` is never 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.ts --original X`)
30
+ * derives its baseline by decompiling `--original` again. That is the source the author
31
+ * started from only while `--original` is the file the source was decompiled from, with
32
+ * the same options. If the original changed in between, its changes are in the derived
33
+ * baseline and not in the source, so the merge reads them as the author's deletions and
34
+ * reverts them. The stamp lets merge check the first and reproduce the second.
35
+ *
36
+ * Nothing here prints; the CLIs do.
37
+ */
38
+ import { commentText } from './comment-text.js';
39
+ import { bytesToHex, sha256 } from './sha.js';
40
+ /** The marker that starts the stamp line. */
41
+ export const STAMP_MARKER = '// @decompiled-from ';
42
+ /** The SDK import line of a decompiled source: the first `import { … } from '…';`. */
43
+ const IMPORT_RE = /^(import\s*\{[^}]*\}\s*from\s*)["'][^"']+["'];/m;
44
+ /**
45
+ * The digest the stamp records: SHA-256, lowercase hex, of a source as decompile makes
46
+ * it (no stamp line), with the SDK import specifier replaced by a fixed one, so
47
+ * `--import` and the specifier merge decompiles against give the same digest.
48
+ *
49
+ * @param source - The decompiled source, before {@link stampSource}.
50
+ */
51
+ export function sourceDigest(source) {
52
+ return bytesToHex(sha256(source.replace(IMPORT_RE, '$1"@";')));
53
+ }
54
+ /** The stamp line, without a line terminator. */
55
+ export function formatStampLine(stamp) {
56
+ return `${STAMP_MARKER}${commentText(stamp.file)} sha256:${stamp.sha256}${stamp.options.map((o) => ` ${o}`).join('')}`;
57
+ }
58
+ /** `source` with the stamp line in front of it. */
59
+ export function stampSource(source, stamp) {
60
+ return `${formatStampLine(stamp)}\n${source}`;
61
+ }
62
+ const STAMP_RE = /^\/\/ @decompiled-from (.*) sha256:([0-9a-f]{64})((?: \S+)*)\s*$/;
63
+ /**
64
+ * Read the stamp line from a source: the first line that starts with
65
+ * {@link STAMP_MARKER}. The option tokens are returned as written; the family checks
66
+ * them.
67
+ *
68
+ * @returns The stamp and the line it was read from; `undefined` when the source has no
69
+ * stamp line; or `{ error }` when the line does not parse.
70
+ */
71
+ export function readStampLine(source) {
72
+ const line = source.split(/\r?\n/).find((l) => l.startsWith(STAMP_MARKER));
73
+ if (line === undefined)
74
+ return undefined;
75
+ const match = STAMP_RE.exec(line);
76
+ if (!match)
77
+ return { error: `the line does not read as \`${STAMP_MARKER}<file> sha256:<64 hex> <options>\`: ${line}` };
78
+ return {
79
+ file: match[1] ?? '',
80
+ sha256: match[2] ?? '',
81
+ options: (match[3] ?? '').trim().split(' ').filter(Boolean),
82
+ line,
83
+ };
84
+ }
85
+ /**
86
+ * `source` with its stamp line replaced by `line` (no terminator), the line ending kept.
87
+ * The family checks the old stamp first; this only swaps the text.
88
+ *
89
+ * @returns The new source, or `undefined` when `source` has no stamp line.
90
+ */
91
+ export function replaceStampLine(source, line) {
92
+ const lines = source.split('\n');
93
+ const at = lines.findIndex((l) => l.startsWith(STAMP_MARKER));
94
+ if (at < 0)
95
+ return undefined;
96
+ const cr = lines[at]?.endsWith('\r') ? '\r' : '';
97
+ lines[at] = `${line}${cr}`;
98
+ return lines.join('\n');
99
+ }
@@ -122,6 +122,7 @@ export declare const REFUSALS: {
122
122
  readonly BPMN_OUTPUT_VAR_NO_OUTPUT_ROW: "lowering";
123
123
  readonly BPMN_PATH_ALREADY_LEFT: "lowering";
124
124
  readonly BPMN_PATH_NOT_CONTINUED: "lowering";
125
+ readonly BPMN_PAYLOAD_TAG_INVALID: "lowering";
125
126
  readonly BPMN_PLAIN_TASK_ELEMENT_INVALID: "lowering";
126
127
  readonly BPMN_RACE_ARM_NOT_WAIT: "lowering";
127
128
  readonly BPMN_SCRIPT_TASK_TYPE_INVALID: "lowering";
@@ -602,6 +603,7 @@ export declare const REFUSALS: {
602
603
  readonly PARALLEL_TOO_FEW_ARMS: "lint";
603
604
  readonly PATTERN_NO_ATTACHMENT: "lint";
604
605
  readonly PATTERN_NO_PROMPT: "lint";
606
+ readonly PAYLOAD_TYPE_NOT_CHECKED: "lint";
605
607
  readonly PORT_ALREADY_ROUTED: "lowering";
606
608
  readonly PORT_EMPTY_PATH: "lowering";
607
609
  readonly PORT_NO_SOURCE_STEP: "lowering";
@@ -171,6 +171,7 @@ export const REFUSALS = {
171
171
  BPMN_OUTPUT_VAR_NO_OUTPUT_ROW: 'lowering',
172
172
  BPMN_PATH_ALREADY_LEFT: 'lowering',
173
173
  BPMN_PATH_NOT_CONTINUED: 'lowering',
174
+ BPMN_PAYLOAD_TAG_INVALID: 'lowering',
174
175
  BPMN_PLAIN_TASK_ELEMENT_INVALID: 'lowering',
175
176
  BPMN_RACE_ARM_NOT_WAIT: 'lowering',
176
177
  BPMN_SCRIPT_TASK_TYPE_INVALID: 'lowering',
@@ -676,6 +677,7 @@ export const REFUSALS = {
676
677
  PARALLEL_TOO_FEW_ARMS: 'lint',
677
678
  PATTERN_NO_ATTACHMENT: 'lint',
678
679
  PATTERN_NO_PROMPT: 'lint',
680
+ PAYLOAD_TYPE_NOT_CHECKED: 'lint',
679
681
  PORT_ALREADY_ROUTED: 'lowering',
680
682
  PORT_EMPTY_PATH: 'lowering',
681
683
  PORT_NO_SOURCE_STEP: 'lowering',
@@ -14,17 +14,21 @@
14
14
  * `--scripts string` prints every script step as `script({ code })` instead of
15
15
  * as a TypeScript function (the default, where the body allows it).
16
16
  *
17
+ * The source's first line is a stamp (decompile-stamp.ts): the original's name, the
18
+ * digest of the source written, and the options that shaped it. `flow merge
19
+ * <Name>.flow.ts --original <original.flow>` reads it to derive the baseline itself.
20
+ *
17
21
  * Besides the `.flow.ts`, this also emits a per-flow pipeline wrapper
18
22
  * (`<Name>.pipeline.mjs`) that chains decompile → [edit] → compile → merge, so an
19
23
  * agent can run one script for the whole brownfield write-back loop. Pass
20
24
  * `--no-pipeline` to skip it.
21
25
  */
22
26
  import { reportResult } from './cli-result.js';
23
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
24
- import { basename, dirname, join, resolve } from 'node:path';
27
+ import { mkdirSync, writeFileSync } from 'node:fs';
28
+ import { basename, join, resolve } from 'node:path';
25
29
  import { defaultSourceOut, workDirBeside, writeSource } from './workdir.js';
26
- import { decompile } from './decompile.js';
27
- import { resolveFlowRefs } from './ref-resolve.js';
30
+ import { decompileFlowFile, readFlowFile } from './decompile-file.js';
31
+ import { sourceDigest, stampFlowSource } from './decompile-stamp.js';
28
32
  import { flagValue, flagValues, runWhenInvokedDirectly } from './cli-run.js';
29
33
  import { PACKAGE_NAME } from './package-name.js';
30
34
  import { commentText } from './core/comment-text.js';
@@ -59,10 +63,7 @@ export async function run(argv) {
59
63
  // A `.flow` may be SPLIT across sibling files with JSON Reference — resolve
60
64
  // those into one object model before decompiling (design §5; the format's own
61
65
  // read path does the same). A single-file flow walks through untouched.
62
- const flow = resolveFlowRefs(JSON.parse(readFileSync(pos, 'utf8')), {
63
- baseUri: pos,
64
- read: (path) => readFileSync(path, 'utf8'),
65
- });
66
+ const flow = readFlowFile(pos);
66
67
  // Node-type packages the file needs: loaded only when the project trusts them
67
68
  // (package.json nodePackages, or --package), resolved from the .flow's own
68
69
  // directory (node-packages.ts). An untrusted or missing package is a warning,
@@ -72,27 +73,29 @@ export async function run(argv) {
72
73
  console.error(`flow-decompile: warning: ${message}`);
73
74
  if (packages.loaded.length > 0)
74
75
  reportResult({ packages: packages.loaded.map((p) => p.package) });
75
- const ts = decompile(flow, {
76
+ const strict = argv.includes('--strict');
77
+ const ts = decompileFlowFile(pos, flow, {
76
78
  importSpecifier: flagValue(argv, '--import') ?? PACKAGE_NAME,
77
- bestEffort: !argv.includes('--strict'),
79
+ bestEffort: !strict,
78
80
  scripts,
79
81
  // Findings the source cannot carry on its own (a node no trigger reaches, a
80
82
  // pinned core version this SDK lacks, a file-format version outside the
81
83
  // writable band) go to stderr, where the agent running the brownfield loop
82
84
  // reads them before compile refuses.
83
85
  warn: (message) => console.error(`flow-decompile: warning: ${message}`),
84
- // A shell agent node's prompts live in `<source>/agent.json` beside the .flow.
85
- readSidecar: (relativePath) => {
86
- try {
87
- return readFileSync(join(dirname(resolve(pos)), relativePath), 'utf8');
88
- }
89
- catch {
90
- return undefined;
91
- }
92
- },
86
+ });
87
+ // The stamp says which original this came from and how, so `flow merge
88
+ // <Name>.flow.ts --original <original.flow>` can derive the baseline itself and
89
+ // refuse an original that changed since (decompile-stamp.ts).
90
+ const stamped = stampFlowSource(ts, {
91
+ file: basename(pos),
92
+ sha256: sourceDigest(ts),
93
+ scripts,
94
+ strict,
95
+ packages: packages.loaded.map((p) => p.package),
93
96
  });
94
97
  const out = flagValue(argv, '-o') ?? defaultSourceOut(`${baseName(flow)}.flow.ts`);
95
- writeSource(out, ts);
98
+ writeSource(out, stamped);
96
99
  console.log(`flow-decompile: wrote ${basename(out)}`);
97
100
  reportResult({ path: resolve(out) });
98
101
  if (!argv.includes('--no-pipeline')) {
@@ -0,0 +1,16 @@
1
+ import { decompile, type DecompileOptions } from './decompile.js';
2
+ /** A parsed `.flow`, as decompile reads it. */
3
+ export type FlowDocument = Parameters<typeof decompile>[0];
4
+ /**
5
+ * Read the `.flow` at `path`. A `.flow` may be SPLIT across sibling files with JSON
6
+ * Reference; those are resolved into one object model, as the format's own read path
7
+ * does. A single-file flow walks through untouched.
8
+ *
9
+ * @param parts - When given, receives the absolute path of each referenced file read.
10
+ */
11
+ export declare function readFlowFile(path: string, parts?: string[]): FlowDocument;
12
+ /**
13
+ * Decompile `flow`, read from `path`: a shell agent node's prompts live in
14
+ * `<source>/agent.json` beside the `.flow`, and are read from there.
15
+ */
16
+ export declare function decompileFlowFile(path: string, flow: FlowDocument, opts: Omit<DecompileOptions, 'readSidecar'>): string;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * decompile-file — decompile a `.flow` FILE the way `flow decompile` does: references
3
+ * resolved, agent sidecars read beside it. `flow decompile` writes the result;
4
+ * `flow merge` and `flow check --baseline` decompile an original again with it, and
5
+ * merge digests the result against the source's stamp (decompile-stamp.ts), so all
6
+ * three have to make the same source of the same file.
7
+ */
8
+ import { readFileSync } from 'node:fs';
9
+ import { dirname, join, resolve } from 'node:path';
10
+ import { decompile } from './decompile.js';
11
+ import { resolveFlowRefs } from './ref-resolve.js';
12
+ /**
13
+ * Read the `.flow` at `path`. A `.flow` may be SPLIT across sibling files with JSON
14
+ * Reference; those are resolved into one object model, as the format's own read path
15
+ * does. A single-file flow walks through untouched.
16
+ *
17
+ * @param parts - When given, receives the absolute path of each referenced file read.
18
+ */
19
+ export function readFlowFile(path, parts) {
20
+ return resolveFlowRefs(JSON.parse(readFileSync(path, 'utf8')), {
21
+ baseUri: path,
22
+ read: (file) => {
23
+ const text = readFileSync(file, 'utf8');
24
+ if (parts && !parts.includes(resolve(file)))
25
+ parts.push(resolve(file));
26
+ return text;
27
+ },
28
+ });
29
+ }
30
+ /**
31
+ * Decompile `flow`, read from `path`: a shell agent node's prompts live in
32
+ * `<source>/agent.json` beside the `.flow`, and are read from there.
33
+ */
34
+ export function decompileFlowFile(path, flow, opts) {
35
+ return decompile(flow, {
36
+ ...opts,
37
+ readSidecar: (relativePath) => {
38
+ try {
39
+ return readFileSync(join(dirname(resolve(path)), relativePath), 'utf8');
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ },
45
+ });
46
+ }
@@ -0,0 +1,36 @@
1
+ export { sourceDigest, STAMP_MARKER } from './core/decompile-stamp.js';
2
+ /** What `flow decompile` records about the decompile, and `flow merge` reads back. */
3
+ export interface FlowDecompileStamp {
4
+ /** The original's base name. */
5
+ file: string;
6
+ /** `sourceDigest` of the source decompile made of the original, lowercase hex. */
7
+ sha256: string;
8
+ /** The form script steps were printed in. */
9
+ scripts: 'function' | 'string';
10
+ /** Decompile was given `--strict`. */
11
+ strict: boolean;
12
+ /** The node-type packages decompile loaded. */
13
+ packages: string[];
14
+ }
15
+ /** The stamp line, without a line terminator. */
16
+ export declare function formatFlowStamp(stamp: FlowDecompileStamp): string;
17
+ /** `source` with the stamp line in front of it. */
18
+ export declare function stampFlowSource(source: string, stamp: FlowDecompileStamp): string;
19
+ /**
20
+ * Read the stamp from a `.flow.ts` source: the first line that starts with
21
+ * `// @decompiled-from `.
22
+ *
23
+ * @returns The stamp; `undefined` when the source has no stamp line; or `{ error }`
24
+ * naming what is wrong with a stamp line that does not parse.
25
+ */
26
+ export declare function readFlowStamp(source: string): FlowDecompileStamp | {
27
+ error: string;
28
+ } | undefined;
29
+ /**
30
+ * `source` with its stamp line pointed at a new original: the `file` and `sha256`
31
+ * replaced, the options kept. `flow merge` calls this after it writes over the
32
+ * original, so the same source merges again in the next round.
33
+ *
34
+ * @returns The restamped source, or `undefined` when `source` has no readable stamp.
35
+ */
36
+ export declare function restampFlowSource(source: string, file: string, sha256: string): string | undefined;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * decompile-stamp — the line `flow decompile` writes at the top of a `.flow.ts` to say
3
+ * which original it came from and how, and the reader `flow merge` uses to check it.
4
+ * The line's shape, the digest and the line swap are shared with BPMN
5
+ * (`core/decompile-stamp.ts`, which says why the digest is of the source); the options
6
+ * are Flow's:
7
+ *
8
+ * // @decompiled-from <file name> sha256:<64 hex> scripts=<function|string>[ strict][ packages=<name>,...]
9
+ *
10
+ * - `scripts` is the form decompile was asked to print script steps in.
11
+ * - `strict` is present when decompile was given `--strict`, which refuses instead of
12
+ * printing a `// TODO` marker.
13
+ * - `packages` lists the node-type packages decompile loaded, in the order it loaded
14
+ * them: a node from one prints as that package's builder, and as `rawNode(...)` when
15
+ * the package was not loaded. Merge loads them again, as if each were passed with
16
+ * `--package`; the source names them in its imports and runs them anyway.
17
+ *
18
+ * `--import` and `--no-pipeline` are not recorded: neither changes what the source builds.
19
+ *
20
+ * Nothing here prints; the CLIs do.
21
+ */
22
+ import { formatStampLine, readStampLine, replaceStampLine } from './core/decompile-stamp.js';
23
+ export { sourceDigest, STAMP_MARKER } from './core/decompile-stamp.js';
24
+ /** The stamp line, without a line terminator. */
25
+ export function formatFlowStamp(stamp) {
26
+ return formatStampLine({
27
+ file: stamp.file,
28
+ sha256: stamp.sha256,
29
+ options: [
30
+ `scripts=${stamp.scripts}`,
31
+ ...(stamp.strict ? ['strict'] : []),
32
+ ...(stamp.packages.length > 0 ? [`packages=${stamp.packages.join(',')}`] : []),
33
+ ],
34
+ });
35
+ }
36
+ /** `source` with the stamp line in front of it. */
37
+ export function stampFlowSource(source, stamp) {
38
+ return `${formatFlowStamp(stamp)}\n${source}`;
39
+ }
40
+ /**
41
+ * Read the stamp from a `.flow.ts` source: the first line that starts with
42
+ * `// @decompiled-from `.
43
+ *
44
+ * @returns The stamp; `undefined` when the source has no stamp line; or `{ error }`
45
+ * naming what is wrong with a stamp line that does not parse.
46
+ */
47
+ export function readFlowStamp(source) {
48
+ const read = readStampLine(source);
49
+ if (read === undefined || 'error' in read)
50
+ return read;
51
+ const { line } = read;
52
+ const stamp = { file: read.file, sha256: read.sha256, scripts: 'function', strict: false, packages: [] };
53
+ const seen = new Set();
54
+ for (const token of read.options) {
55
+ const [key, value] = token.split('=', 2);
56
+ if (seen.has(key))
57
+ return { error: `\`${key}\` appears twice: ${line}` };
58
+ seen.add(key);
59
+ if (key === 'scripts' && (value === 'function' || value === 'string'))
60
+ stamp.scripts = value;
61
+ else if (key === 'strict' && value === undefined)
62
+ stamp.strict = true;
63
+ else if (key === 'packages' && value)
64
+ stamp.packages = value.split(',');
65
+ else
66
+ return { error: `unknown option \`${token}\`: ${line}` };
67
+ }
68
+ if (!seen.has('scripts'))
69
+ return { error: `\`scripts=\` is missing: ${line}` };
70
+ return stamp;
71
+ }
72
+ /**
73
+ * `source` with its stamp line pointed at a new original: the `file` and `sha256`
74
+ * replaced, the options kept. `flow merge` calls this after it writes over the
75
+ * original, so the same source merges again in the next round.
76
+ *
77
+ * @returns The restamped source, or `undefined` when `source` has no readable stamp.
78
+ */
79
+ export function restampFlowSource(source, file, sha256) {
80
+ const stamp = readFlowStamp(source);
81
+ if (stamp === undefined || 'error' in stamp)
82
+ return undefined;
83
+ return replaceStampLine(source, formatFlowStamp({ ...stamp, file, sha256 }));
84
+ }
package/dist/merge-cli.js CHANGED
@@ -6,6 +6,31 @@
6
6
  * flow-merge <original.flow> <edited.flow | Edited.flow.ts> [-o merged.flow]
7
7
  * [--baseline <baseline.flow> | --baseline-from <original.flow>] [--strict]
8
8
  *
9
+ * A STAMPED `.flow.ts` (the first line `flow decompile` writes, decompile-stamp.ts)
10
+ * needs neither baseline flag: merge derives the baseline from the original itself,
11
+ * as `--baseline-from <original.flow>` does, with the decompile options the stamp
12
+ * records, and writes the result over the original unless `-o` says otherwise
13
+ * (UiPath/builder-sdk#1871 for BPMN, the same loop here). It refuses, writing nothing,
14
+ * when the source it decompiles from the original now does not have the digest the
15
+ * stamp records (`MERGE_ORIGINAL_CHANGED`): the derived baseline would then hold the
16
+ * original's later changes, and the merge would revert them. A change decompile does
17
+ * not read (indentation, line endings, the order of a node's own fields) leaves the
18
+ * digest alone and merges; one the source shows, a reordered header map included, is
19
+ * refused. `--baseline-from` is checked the same way; `--baseline` is the caller's and
20
+ * is not. After a CHECKED merge written over the original (the baseline derived from
21
+ * the original itself), merge decompiles it the same way and rewrites the stamp with
22
+ * that digest, so the next edit-and-merge round on the same source passes the check.
23
+ * Under `--baseline`, or `--baseline-from` another file, the original may hold changes
24
+ * the source lacks, so the stamp is not advanced and the next round refuses rather
25
+ * than reverts them. Only the source form, a stamped `.flow.ts` with neither baseline
26
+ * flag, writes over the original by default; with `--baseline` or `--baseline-from`,
27
+ * as for a `.flow.ts` with no stamp, the default is `merged.flow`, as before the stamp.
28
+ *
29
+ * The original is read as decompile reads it, `$ref`s resolved (decompile-file.ts),
30
+ * so a split `.flow` merges as one document and is written as one file, as compile
31
+ * writes it. Written over the original, the files its `$ref`s named are no longer
32
+ * read; each is listed (`unreferenced` in `--json`), as merge does not delete files.
33
+ *
9
34
  * `--baseline-from <original.flow>` makes merge build the baseline itself
10
35
  * (decompile + compile, nothing written), and an edited `.flow.ts` makes merge
11
36
  * compile it: both compiles tolerate DRAFT nodes, and merge refuses a draft
@@ -47,9 +72,9 @@
47
72
  * merged flow and its agents, as compile does, and written beside the merged
48
73
  * output when it changes.
49
74
  */
50
- import { reportResult } from './cli-result.js';
75
+ import { reportCompileRefusal, reportDiagnostics, reportResult } from './cli-result.js';
51
76
  import { writeJsonFile } from './core/json-file.js';
52
- import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
77
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
53
78
  import { inlineAgentResources, mergeBindingsV2, projectBindingRows, refreshInlineAgentRows } from './bindings-v2.js';
54
79
  import { readBindingsV2, readInlineAgentFiles } from './bindings-v2-files.js';
55
80
  import { basename, dirname, join, relative, resolve } from 'node:path';
@@ -58,14 +83,16 @@ import { sidecarSetFromList } from './merge-sidecars.js';
58
83
  import { isWithin } from './path-within.js';
59
84
  import { flowSources, projectMainFlow, resourceSourcesOfOtherFlows } from './project-resource-users.js';
60
85
  import { flagValue, flagValues, runWhenInvokedDirectly } from './cli-run.js';
86
+ import { readFlowFile } from './decompile-file.js';
87
+ import { readFlowStamp, restampFlowSource, sourceDigest, STAMP_MARKER } from './decompile-stamp.js';
61
88
  import { ensureTypeScriptRuntime } from './node-runtime.js';
62
89
  import { flowCheckOpts, openCliLibrary } from './cli-library.js';
63
90
  import { Bindings } from './bindings.js';
64
91
  import { defaultBindingsFile } from './workdir.js';
65
92
  import { loadNodePackages } from './node-packages.js';
66
- import { baselineFromOriginal, checkEdited, compileSourceDraftTolerant } from './merge-compile.js';
93
+ import { baselineFromOriginal, checkEdited, compileSourceDraftTolerant, decompileOriginal } from './merge-compile.js';
67
94
  import { classifyDrafts, classifyLowering, findingCounts, splitUnplaced } from './edit-scope.js';
68
- const USAGE = 'usage: flow-merge <original.flow> <edited.flow | Edited.flow.ts> [-o merged.flow] '
95
+ const USAGE = 'usage: flow-merge <original.flow> <edited.flow | Edited.flow.ts> [-o merged.flow, or the original for a stamped .flow.ts] '
69
96
  + '[--baseline <baseline.flow> | --baseline-from <original.flow>] [--library <dir>] [--bindings <file>] [--strict]';
70
97
  /**
71
98
  * The agent sidecars beside the flow at `flowPath`: `<source>/agent.json` and each
@@ -195,6 +222,30 @@ function readJsonOrUndefined(path) {
195
222
  return undefined;
196
223
  }
197
224
  }
225
+ /** Refuse the merge with a coded diagnostic; nothing has been written. */
226
+ function refuseMerge(code, message) {
227
+ console.error(`flow-merge: ${message}`);
228
+ reportDiagnostics([{ level: 'error', code, message }]);
229
+ return 1;
230
+ }
231
+ /** The way on from a refused source merge. */
232
+ function redoAdvice(originalPath) {
233
+ return `Decompile ${basename(originalPath)} again (\`flow decompile\`) and reapply the edit to the new source, `
234
+ + 'or merge with --baseline <file>, the compile of the unedited decompile.';
235
+ }
236
+ /**
237
+ * The stamp of an edited `.flow.ts`, read before anything compiles. `undefined` for
238
+ * an edited `.flow` or a source with no stamp (merged as before); an exit code for an
239
+ * unreadable stamp, unless `--baseline` makes the stamp moot.
240
+ */
241
+ function editedStamp(editedPath, originalPath, hasBaseline) {
242
+ const stamp = readFlowStamp(readFileSync(editedPath, 'utf8'));
243
+ if (stamp === undefined || !('error' in stamp))
244
+ return stamp;
245
+ if (hasBaseline)
246
+ return undefined;
247
+ return refuseMerge('MERGE_SOURCE_STAMP_UNREADABLE', `${basename(editedPath)}'s decompile stamp (\`${STAMP_MARKER.trim()}\`) is unreadable — ${stamp.error}. Nothing was written. ${redoAdvice(originalPath)}`);
248
+ }
198
249
  export async function run(argv) {
199
250
  if (argv.length === 0 || argv[0] === '-h' || argv[0] === '--help') {
200
251
  console.error(USAGE);
@@ -214,14 +265,24 @@ export async function run(argv) {
214
265
  return 2;
215
266
  }
216
267
  const editedIsSource = /\.ts$/.test(editedPath);
217
- // Merge compiles a side itself only for --baseline-from or a .flow.ts edited
268
+ // A stamped source says which original it came from and how, so merge derives
269
+ // the baseline from the original itself unless --baseline gives one.
270
+ const read = editedIsSource ? editedStamp(editedPath, originalPath, baselinePath !== undefined) : undefined;
271
+ if (typeof read === 'number')
272
+ return read;
273
+ const stamp = read;
274
+ const derivedFrom = baselineFrom ?? (stamp && !baselinePath ? originalPath : undefined);
275
+ // Merge compiles a side itself only for a derived baseline or a .flow.ts edited
218
276
  // source; both load TypeScript, so both need the type-stripping runtime.
219
- if (baselineFrom || editedIsSource)
277
+ if (derivedFrom || editedIsSource)
220
278
  ensureTypeScriptRuntime();
221
- const library = baselineFrom || editedIsSource ? openCliLibrary(argv) : undefined;
222
- const bindings = baselineFrom || editedIsSource ? new Bindings(flagValue(argv, '--bindings') ?? defaultBindingsFile()) : undefined;
279
+ const library = derivedFrom || editedIsSource ? openCliLibrary(argv) : undefined;
280
+ const bindings = derivedFrom || editedIsSource ? new Bindings(flagValue(argv, '--bindings') ?? defaultBindingsFile()) : undefined;
223
281
  const compileOpts = { library, bindings };
224
- const original = JSON.parse(readFileSync(originalPath, 'utf8'));
282
+ // Resolved as decompile resolves it, so a split `.flow` merges as the document the
283
+ // source was decompiled from.
284
+ const originalParts = [];
285
+ const original = readFlowFile(originalPath, originalParts);
225
286
  let drafts = [];
226
287
  let lowering = [];
227
288
  let diagnostics = [];
@@ -243,18 +304,47 @@ export async function run(argv) {
243
304
  else {
244
305
  edited = JSON.parse(readFileSync(editedPath, 'utf8'));
245
306
  }
246
- if (baselineFrom) {
307
+ if (derivedFrom) {
247
308
  // The baseline is a decompile of the original: load the node-type packages
248
309
  // its definitions name, under the project's trust (package.json nodePackages
249
310
  // or --package), so the decompiled source imports them rather than printing
250
311
  // rawNode(...) — which would differ from the edit and refuse a clean merge.
251
- const packages = await loadNodePackages(baselineFrom, JSON.parse(readFileSync(baselineFrom, 'utf8')), flagValues(argv, '--package'));
312
+ // The ones the stamp records decompile loaded, so they load here too.
313
+ const trusted = [...flagValues(argv, '--package'), ...(stamp?.packages ?? [])];
314
+ const packages = await loadNodePackages(derivedFrom, readFlowFile(derivedFrom), trusted);
252
315
  for (const message of packages.warnings)
253
316
  console.error(`flow-merge: warning: ${message}`);
254
317
  }
255
- const baselineCompile = baselineFrom
256
- ? await baselineFromOriginal(baselineFrom, compileOpts, (m) => console.error(`flow-merge: decompile warning: ${m}`))
257
- : undefined;
318
+ // Decompiled as the stamp records, so the baseline is built from the source the
319
+ // author started from; without a stamp, with decompile's defaults.
320
+ const decompileOpts = stamp ? { scripts: stamp.scripts, strict: stamp.strict } : {};
321
+ let baselineCompile;
322
+ if (derivedFrom) {
323
+ try {
324
+ baselineCompile = await baselineFromOriginal(derivedFrom, compileOpts, (m) => console.error(`flow-merge: decompile warning: ${m}`), decompileOpts);
325
+ }
326
+ catch (error) {
327
+ if (!stamp)
328
+ throw error;
329
+ console.error(`flow-merge: could not derive the baseline from ${basename(derivedFrom)} (decompile, then compile, in memory). `
330
+ + 'Compile the unedited decompile yourself and pass it as --baseline <file>.');
331
+ return reportCompileRefusal(error);
332
+ }
333
+ }
334
+ if (stamp && baselineCompile) {
335
+ // The baseline is the source the author started from only if decompiling the
336
+ // original now gives the source decompile wrote then. Compared by digest, not by
337
+ // the original's bytes, so what decompile does not read (indentation, line
338
+ // endings) passes.
339
+ const actual = sourceDigest(baselineCompile.source);
340
+ if (actual !== stamp.sha256) {
341
+ const name = basename(derivedFrom);
342
+ const packages = stamp.packages.length > 0 ? ', or a node-type package it loads,' : '';
343
+ return refuseMerge('MERGE_ORIGINAL_CHANGED', `${name}${packages} changed since ${basename(editedPath)} was decompiled from ${stamp.file === name ? 'it' : stamp.file}: `
344
+ + `decompiling it now gives a different source (sha256 ${stamp.sha256} recorded, ${actual} now). `
345
+ + `Merging would read those changes as the edit's deletions and revert them, so nothing was written. ${redoAdvice(derivedFrom)}`);
346
+ }
347
+ }
258
348
  const baselineSidecars = baselineCompile?.sidecars;
259
349
  const baseline = baselineCompile ? baselineCompile.flow
260
350
  : baselinePath ? JSON.parse(readFileSync(baselinePath, 'utf8')) : undefined;
@@ -358,7 +448,12 @@ export async function run(argv) {
358
448
  console.error(`flow-merge: ${error.message}`);
359
449
  return 1;
360
450
  }
361
- const out = flagValue(argv, '-o') ?? 'merged.flow';
451
+ // The source form merges in place by default: a `merged.flow` beside the original
452
+ // is one more `.flow` for the next reader to open by mistake. It is safe because the
453
+ // stamp check above refused an original that changed since the decompile. A command
454
+ // that names a baseline keeps the `merged.flow` it wrote before the stamp existed.
455
+ const out = flagValue(argv, '-o') ?? (stamp && !baselinePath && !baselineFrom ? originalPath : 'merged.flow');
456
+ const inPlace = resolve(out) === resolve(originalPath);
362
457
  const outDir = dirOf(out);
363
458
  const targets = merged.sidecars.map((s) => ({ sidecar: s, target: resolve(outDir, s.path) }));
364
459
  const escaping = targets.find(({ target }) => !isWithin(outDir, target));
@@ -388,19 +483,61 @@ export async function run(argv) {
388
483
  });
389
484
  const removed = removals.map((rel) => join(originalDir, rel));
390
485
  for (const dir of removed) {
391
- console.log(`flow-merge: remove ${dir} from the project: the edit removed this agent resource, and copying the candidate cannot delete it`);
486
+ console.log(inPlace
487
+ ? `flow-merge: remove ${dir} from the project: the edit removed this agent resource, and merge does not delete files`
488
+ : `flow-merge: remove ${dir} from the project: the edit removed this agent resource, and copying the candidate cannot delete it`);
489
+ }
490
+ // Written over a split original, the merged flow is one file, so its part files
491
+ // stay on disk with nothing reading them.
492
+ const unreferenced = inPlace ? originalParts : [];
493
+ for (const part of unreferenced) {
494
+ console.log(`flow-merge: remove ${part} from the project: ${basename(originalPath)} is now one file and no longer references it, and merge does not delete files`);
392
495
  }
393
496
  const bindingsV2 = projectBindings(originalDir, originalPath, flow, merged.sidecars, removals);
394
497
  if (bindingsV2 !== undefined) {
395
498
  writeJsonFile(join(outDir, 'bindings_v2.json'), bindingsV2);
396
499
  console.log('flow-merge: wrote bindings_v2.json (connection and agent resource rows, re-derived as compile does)');
397
500
  }
501
+ // Written over the original: point the source's stamp at the merged file, so the
502
+ // next edit-and-merge round on the same source passes the check. Its digest is
503
+ // that of the merged file decompiled with the stamped options, after the sidecars
504
+ // above are written, which is what the next check derives. Only after the check
505
+ // passed against this original: under --baseline, or --baseline-from another file,
506
+ // the original may hold changes the source lacks (the merge kept them, as it should),
507
+ // and a stamp advanced over them would let the next round's derived baseline
508
+ // revert them. Written elsewhere, the original is unchanged and so is the stamp.
509
+ const stampChecked = stamp !== undefined && !baselinePath && derivedFrom !== undefined && resolve(derivedFrom) === resolve(originalPath);
510
+ let restamped = false;
511
+ if (stampChecked && inPlace) {
512
+ const source = readFileSync(editedPath, 'utf8');
513
+ let next;
514
+ try {
515
+ next = restampFlowSource(source, basename(originalPath), sourceDigest(decompileOriginal(originalPath, decompileOpts)));
516
+ }
517
+ catch (error) {
518
+ // The merge stands; the old stamp makes the next round refuse, never revert.
519
+ console.error(`flow-merge: could not decompile the merged ${basename(originalPath)} to restamp ${basename(editedPath)} `
520
+ + `(${error instanceof Error ? error.message : String(error)}); decompile it again before the next edit`);
521
+ }
522
+ if (next !== undefined && next !== source) {
523
+ writeFileSync(editedPath, next);
524
+ restamped = true;
525
+ }
526
+ }
527
+ if (stamp && !baselinePath) {
528
+ console.log(`flow-merge: compiled ${basename(editedPath)} and derived the baseline from ${basename(derivedFrom)} in memory; no intermediate file written`);
529
+ }
530
+ if (restamped) {
531
+ console.log(`flow-merge: restamped ${basename(editedPath)} for the merged ${basename(originalPath)}, so it merges again after the next edit`);
532
+ }
398
533
  reportResult({
399
534
  path: resolve(out),
400
535
  nodes: (flow.nodes ?? []).length,
401
536
  edges: (flow.edges ?? []).length,
537
+ ...(stamp ? { baseline: baselinePath ? 'file' : 'derived', restamped } : {}),
402
538
  ...(targets.length > 0 ? { sidecars: targets.map((t) => t.target) } : {}),
403
539
  ...(removed.length > 0 ? { removed } : {}),
540
+ ...(unreferenced.length > 0 ? { unreferenced } : {}),
404
541
  ...(bindingsV2 !== undefined ? { bindings: join(resolve(outDir), 'bindings_v2.json') } : {}),
405
542
  });
406
543
  return 0;