@jacebenson/jsn 5.5.5-dev.197.1 → 5.5.5-dev.199.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.5-dev.197.1",
3
+ "version": "5.5.5-dev.199.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,5 +1,7 @@
1
1
  import { searchFlows, formatFlowSearch } from '../flow-search.js';
2
2
  import fs from 'node:fs';
3
+ import { prepareFlowClone, cloneFlow } from '../flow-clone.js';
4
+ import { canUsePicker } from '../helpers.js';
3
5
  import { formatRecordForDisplay, formatCommandList, getStringField, interactiveList } from '../helpers.js';
4
6
  import { discoverFlowContextFields, normalizeFlowContext, summarizeFlowContexts, formatFlowContextSummary, aggregateFlowContextMappings, mergeFlowContextStats, buildFlowContextQuery } from '../flow-context.js';
5
7
  import { declareCapabilities } from '../capabilities.js';
@@ -44,6 +46,7 @@ const FLOW_COMMANDS = [
44
46
  { name: 'status [identifier]', description: 'Check whether a flow is actually able to run' },
45
47
  { name: 'publish [identifier]', description: 'Publish (activate) a flow, or a custom action with --action' },
46
48
  { name: 'test [identifier]', description: 'Execute a record-triggered flow against one record' },
49
+ { name: 'clone [identifier]', description: 'Duplicate an inactive Draft flow using native Designer copy (alias: copy)' },
47
50
  { name: 'create', description: 'Create a draft flow: guided in a terminal, JSON manifest in scripts' },
48
51
  { name: 'update [identifier]', description: 'Update a draft, or a published flow whose definition reports write access (alias: edit)' },
49
52
  { name: 'doctor', description: 'Check whether this instance can publish flows at all' },
@@ -70,7 +73,7 @@ function triggerGuidance(trigger) {
70
73
  };
71
74
  }
72
75
 
73
- declareCapabilities('flows', { mutationSubcommands: ['create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
76
+ declareCapabilities('flows', { mutationSubcommands: ['clone', 'copy', 'create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
74
77
 
75
78
  function renderChecks(checks) {
76
79
  return checks.map((c) => {
@@ -386,6 +389,29 @@ export function flowsCmd(wrap) {
386
389
  });
387
390
  }),
388
391
  })
392
+ .command({
393
+ command: 'clone [identifier]',
394
+ aliases: ['copy'],
395
+ describe: 'Duplicate a supported inactive Draft through native Designer copy',
396
+ builder: y => y
397
+ .option('name', { type: 'string', describe: 'New unique name; required in automation, defaults to source name + copy interactively' })
398
+ .option('force', { type: 'boolean', default: false, describe: 'Approve this clone without confirmation' })
399
+ .epilogue('Same source scope and security/domain policy. Never publishes, activates or executes.\n'
400
+ + 'Select an aligned named in-progress update set first. Unsupported graph categories fail before allocation.\n'
401
+ + 'Live acceptance is pending. Partial failures retain the new identity; reconcile before retrying.'),
402
+ handler: wrap(async (argv, app) => {
403
+ app.requireInstance();
404
+ const identifier = await pickFlow(argv, app);
405
+ if (identifier === undefined) return;
406
+ const plan = await prepareFlowClone(app.sdk, app.getEffectiveInstance(), identifier, { ...argv, interactive: canUsePicker(app, argv) });
407
+ await confirmDesignerMutation(argv, app,
408
+ `Clone ${plan.source.name} (${plan.source.id}) as ${JSON.stringify(plan.name)} in ${plan.scope}; inactive Draft, source unchanged`,
409
+ ['flows', 'clone', plan.source.id, '--name', plan.name]);
410
+ const result = await cloneFlow(app.sdk, app.getEffectiveInstance(), plan);
411
+ return app.ok(result, { summary: `Cloned inactive Draft ${result.flow.name} (${result.flow.id}); source unchanged; capture verified`,
412
+ breadcrumbs: [{ action: 'show', cmd: `jsn flows show ${result.flow.id}`, description: 'Inspect the cloned Draft' }] });
413
+ }),
414
+ })
389
415
  .command({
390
416
  command: 'create',
391
417
  describe: 'Create a draft flow from a JSON manifest or guided prompts',
@@ -0,0 +1,36 @@
1
+ import { SaxesParser } from 'saxes';
2
+ import { isSysId } from './resolve-record.js';
3
+
4
+ // Reuse the previously reviewed strict parent/version XML contract.
5
+ export function verifyCopyCapture(payload, flowId, versionId) {
6
+ if (typeof payload !== 'string' || !isSysId(versionId)) return false;
7
+ const parser = new SaxesParser({ xmlns: false });
8
+ const stack = [];
9
+ const parents = [];
10
+ let parent;
11
+ let invalid = false;
12
+ parser.on('doctype', () => { invalid = true; });
13
+ parser.on('error', () => { invalid = true; });
14
+ parser.on('opentag', tag => {
15
+ stack.push(tag.name);
16
+ if (tag.name === 'sys_hub_flow') {
17
+ if (parent) invalid = true;
18
+ parent = { depth: stack.length, fields: {} };
19
+ parents.push(parent);
20
+ } else if (parent && stack.length === parent.depth + 1 && ['sys_id', 'version_record'].includes(tag.name)) {
21
+ if (Object.hasOwn(parent.fields, tag.name)) invalid = true;
22
+ parent.fields[tag.name] = '';
23
+ }
24
+ });
25
+ const text = value => {
26
+ if (parent && stack.length === parent.depth + 1 && Object.hasOwn(parent.fields, stack.at(-1))) parent.fields[stack.at(-1)] += value;
27
+ };
28
+ parser.on('text', text);
29
+ parser.on('cdata', text);
30
+ parser.on('closetag', () => {
31
+ if (parent && stack.length === parent.depth) parent = undefined;
32
+ stack.pop();
33
+ });
34
+ try { parser.write(payload).close(); } catch { return false; }
35
+ return !invalid && parents.length === 1 && parents[0].fields.sys_id?.trim() === flowId && parents[0].fields.version_record?.trim() === versionId;
36
+ }
@@ -0,0 +1,425 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { readFlowSafeEditStatus, flowSafeEditRequest } from './flow-safe-edit.js';
3
+ import { createVerifiedFlowVersion } from './flow-versioning.js';
4
+ import { isDeepStrictEqual } from 'node:util';
5
+ import { AppError, CodeAPI, errUsage } from './errors.js';
6
+ import { assertSafeExactMatch } from './helpers.js';
7
+ import { resolveRecord, unwrapSysId, isSysId } from './resolve-record.js';
8
+ import { readProcessFlow, readCurrentUpdateSet } from './flow-create.js';
9
+ import { readEffectiveUpdateSet } from './context.js';
10
+ import { verifyCopyCapture } from './flow-clone-capture.js';
11
+
12
+ const raw = value => value && typeof value === 'object' && 'value' in value ? value.value : value;
13
+ const collections = ['triggerInstances', 'actionInstances', 'inputs', 'outputs'];
14
+ // Native copy handles allocation. Unknown graph contracts must be rejected BEFORE
15
+ // asking it to allocate, not reconstructed through the create-manifest adapter.
16
+ const unsupported = ['flowLogicInstances', 'subFlowInstances', 'flowVariables', 'flowCatalogVariables', 'stages', 'connection_configurations', 'deletedFlowLogicInstances', 'nonCriticalErrors'];
17
+ const contextual = ['id', 'name', 'copiedFrom', 'internalName', 'flowCatalogVariableModelId', 'versionRecordId', 'version', 'created', 'updated', 'updatedBy', 'security', 'canWriteProtection', 'userCanRead', 'isFlowEntitled', 'userHasRolesAssignedToFlow'];
18
+ const preserved = ['masterSnapshotId', 'deleted', 'description', 'scope', 'scopeDisplayName', 'scopeName', 'scopeLogo', 'scopeProtectionPolicyReadOnly', 'status', 'active', 'protection', 'type', 'annotation', 'natlang', 'category', 'remoteTriggerSysId', 'access', 'serviceCatalogCallable', 'clientCallable', 'runAs', 'domainName', 'domainId', 'compilerBuild', 'runWithRoles', 'allowHighSecurityRoles', 'pharmacy', 'startingIndexOfErrorHandlingInstances', 'flowPriority', 'attributes', 'authoredOnReleaseVersion', 'generationSource', 'displayNameAfterPreview', 'substatus', 'flowEngineVersion', 'masterSnapshot', 'labelCacheAsJsonString', 'latestSnapshot', 'snapshot', 'isPublished', 'savedAsJson', 'jsonSnapshot'];
19
+ const triggerKeys = ['id', 'flowSysId', 'remoteSysId', 'name', 'inputs', 'outputs', 'displayText', 'deleted', 'metadata', 'comment', 'type', 'triggerDefinitionId', 'publishedVersion', 'userCanRead', 'triggerType', 'hasDynamicOutputs'];
20
+ const actionKeys = ['id', 'flowSysId', 'order', 'displayText', 'uiUniqueIdentifier', 'deleted', 'metadata', 'parent', 'comment', 'generationSource', 'uiComponentIndex', 'actionTypeSysId', 'inputs', 'actionType', 'parentActionTypeId', 'compiledSnapshot', 'aliasIds', 'internalName', 'name', 'type', 'snapshot'];
21
+ const pill = /^\{\{([a-f0-9]{32}|[a-f0-9-]{36})(\.[A-Za-z0-9_.]+)\}\}$/;
22
+ export const flowCloneDigest = value => {
23
+ const canonical = item => Array.isArray(item) ? item.map(canonical) : item && typeof item === 'object'
24
+ ? Object.fromEntries(Object.keys(item).sort().map(key => [key, canonical(item[key])])) : item;
25
+ return createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
26
+ };
27
+ function refuse(message) { throw errUsage(`${message}. No clone allocated.`); }
28
+ function empty(value) { return Array.isArray(value) ? value.length === 0 : value && typeof value === 'object' && Object.keys(value).length === 0; }
29
+ function knownKeys(value, allowed, path) {
30
+ const unknown = Object.keys(value).filter(key => !allowed.includes(key));
31
+ if (unknown.length) refuse(`Unverified provider fields at ${path}: ${unknown.join(', ')}`);
32
+ }
33
+ function variableEntries(items) { return items.flatMap(item => [item, ...variableEntries(item.children || [])]); }
34
+ function owned(source) {
35
+ return [...source.triggerInstances, ...source.actionInstances, ...variableEntries(source.inputs), ...variableEntries(source.outputs)];
36
+ }
37
+ function validateValues(value, path = 'definition') {
38
+ if (!value || typeof value !== 'object') return;
39
+ if (Array.isArray(value)) return value.forEach((item, index) => validateValues(item, `${path}[${index}]`));
40
+ // A complete typed value pill is a known reference. Embedded pills, scripts
41
+ // containing pills and opaque binding encodings are not safe to certify.
42
+ if (typeof value.value === 'string' && value.value.includes('{{')) {
43
+ if (value.scriptActive || !pill.test(value.value)) refuse(`Unsupported embedded/script binding at ${path}`);
44
+ }
45
+ for (const [key, child] of Object.entries(value)) validateValues(child, `${path}.${key}`);
46
+ }
47
+ export function validateCloneSource(source) { return validateCloneDefinition(source, true); }
48
+
49
+ function validateCloneDefinition(source, requireSavedVersion) {
50
+ if (!source || source.type !== 'flow' || !isSysId(source.id)) refuse('A readable Flow definition is required');
51
+ if (source.active !== false || source.status !== 'draft' || source.deleted !== false) refuse('Only inactive, nondeleted Draft sources are supported');
52
+ if (source.security?.can_read !== true || source.security?.can_write !== true) refuse('Source must explicitly permit read and write');
53
+ for (const field of ['scope', 'domainId', 'domainName', 'access', 'protection', 'runAs', 'runWithRoles', 'description']) {
54
+ if (!Object.hasOwn(source, field)) refuse(`Source security/property inventory is missing ${field}`);
55
+ }
56
+ knownKeys(source, [...collections, ...unsupported, ...contextual, ...preserved], 'flow');
57
+ for (const key of unsupported) if (source[key] !== undefined && !empty(source[key])) refuse(`Clone verification does not yet support nonempty ${key}`);
58
+ if (source.startingIndexOfErrorHandlingInstances !== -1) refuse('Error-handler graph cloning is not yet verified');
59
+ for (const key of collections) if (!Array.isArray(source[key])) refuse(`Unreadable ${key}`);
60
+ if (source.triggerInstances.length !== 1) refuse('Exactly one record trigger is required');
61
+ for (const trigger of source.triggerInstances) {
62
+ knownKeys(trigger, triggerKeys, 'trigger');
63
+ if (!['record_create', 'record_update', 'record_create_or_update'].includes(trigger.type) || trigger.deleted !== false) refuse('Unsupported trigger lifecycle/family');
64
+ if (trigger.remoteSysId) refuse('Remote trigger cloning is not verified');
65
+ }
66
+ for (const action of source.actionInstances) {
67
+ knownKeys(action, actionKeys, 'action');
68
+ if (action.parent || action.compiledSnapshot || action.snapshot || action.aliasIds?.length || action.deleted !== false) refuse('Nested/runtime/aliased action cloning is not verified');
69
+ if (!isSysId(action.actionTypeSysId) || action.actionType?.state !== 'published') refuse('Action must reference a published reusable definition');
70
+ }
71
+ if (source.masterSnapshotId || source.latestSnapshot || source.masterSnapshot || source.snapshot || source.isPublished || source.jsonSnapshot) refuse('Source has runtime snapshot state');
72
+ for (const item of [...source.triggerInstances, ...source.actionInstances]) {
73
+ if (!isSysId(item.id) || item.flowSysId !== source.id) refuse('Component identity/ownership is incomplete');
74
+ }
75
+ if (!isSysId(source.versionRecordId) && (requireSavedVersion || ![undefined, null, ''].includes(source.versionRecordId))) refuse('Source has no readable saved version pointer');
76
+ const identities = new Set([source.id]);
77
+ for (const item of owned(source)) {
78
+ if (!item.id) continue; // nested anonymous schema children have no identity
79
+ if (!isSysId(item.id) || identities.has(item.id)) refuse('Ambiguous owned component identity');
80
+ identities.add(item.id);
81
+ if (item.flowSysId !== undefined && item.flowSysId !== source.id) refuse('Invalid component ownership');
82
+ if (item.uiUniqueIdentifier) {
83
+ if (identities.has(item.uiUniqueIdentifier)) refuse('Duplicate UI identity');
84
+ identities.add(item.uiUniqueIdentifier);
85
+ }
86
+ }
87
+ if (!isSysId(source.flowCatalogVariableModelId) || identities.has(source.flowCatalogVariableModelId)) refuse('Missing or reused catalog model identity');
88
+ validateValues(source);
89
+ return { collections, unsupported, preserved, contextual };
90
+ }
91
+
92
+ // The editor save re-materializes a provider label on mapping-provider variables
93
+ // that lacked one. Accept only the exact type label the provider would derive;
94
+ // a different, missing or foreign value still fails structural comparison.
95
+ function normalizeProviderLabels(source, destination) {
96
+ const pairs = (a = [], b = [], visit) => a.forEach((item, index) => b[index] && visit(item, b[index]));
97
+ const variables = (a, b) => pairs(a, b, (from, to) => {
98
+ // Definition GETs use type_label; the save serializer uses typeLabel.
99
+ if (from.attributes && !Object.hasOwn(from.attributes, 'uiTypeLabel') && to.attributes &&
100
+ Object.hasOwn(to.attributes, 'uiTypeLabel') && to.attributes.uiTypeLabel === (to.type_label ?? to.typeLabel)) {
101
+ delete to.attributes.uiTypeLabel;
102
+ }
103
+ variables(from.children, to.children);
104
+ });
105
+ variables(source.inputs, destination.inputs);
106
+ variables(source.outputs, destination.outputs);
107
+ pairs(source.triggerInstances, destination.triggerInstances, (from, to) => { variables(from.inputs, to.inputs); variables(from.outputs, to.outputs); });
108
+ pairs(source.actionInstances, destination.actionInstances, (from, to) => { variables(from.inputs, to.inputs); variables(from.outputs, to.outputs); });
109
+ return destination;
110
+ }
111
+
112
+ function nativeCloneComparable(source, destination) {
113
+ const result = normalizeProviderLabels(source, structuredClone(destination));
114
+ for (const [index, action] of result.actionInstances.entries()) {
115
+ const original = source.actionInstances[index];
116
+ const definitionId = a => a.actionType?.id ?? a.actionType?.fId;
117
+ const definitionState = a => a.actionType?.state ?? a.actionType?.fState;
118
+ if (action.compiledSnapshot && action.compiledSnapshot !== original?.compiledSnapshot) {
119
+ if (!original || original.compiledSnapshot !== '' || action.snapshot || action.parent || action.aliasIds?.length ||
120
+ definitionId(original) !== original.actionTypeSysId || definitionState(original) !== 'published' ||
121
+ definitionState(action) !== 'published' || !isSysId(action.actionTypeSysId) ||
122
+ action.actionTypeSysId !== original.actionTypeSysId || definitionId(action) !== action.actionTypeSysId ||
123
+ action.compiledSnapshot !== action.actionTypeSysId) throw new Error('Unverified native action snapshot derivation');
124
+ action.compiledSnapshot = original.compiledSnapshot;
125
+ }
126
+ }
127
+ return result;
128
+ }
129
+
130
+ // Identity maps apply only to owned identity/ownership paths and complete typed
131
+ // input pills. User scripts, conditions, arbitrary keys and literal IDs stay exact.
132
+ export function verifyClonedFlow(source, destination, name) {
133
+ return verifyCloneGraph(source, destination, name, true);
134
+ }
135
+
136
+ // Private provisional contract: only the destination pointer may be absent, and
137
+ // only while native save/version creation is still pending. Source stays strict.
138
+ function verifyCloneGraph(source, destination, name, requireSavedVersion) {
139
+ validateCloneSource(source);
140
+ // The native editor preserves flow-local UI identifiers and, for a flat
141
+ // published reusable action, materializes compiledSnapshot as that definition
142
+ // identity. This is destination-only: runtime-bearing sources still refuse.
143
+ const comparable = nativeCloneComparable(source, destination);
144
+ try { validateCloneDefinition(comparable, requireSavedVersion); }
145
+ catch (cause) { throw new Error(`Destination definition invalid: ${cause.message.replace(/\. No clone allocated\.$/, '')}`, { cause }); }
146
+ if (destination.name !== name || destination.scope !== source.scope || destination.copiedFrom !== source.id) throw new Error('Clone identity/name/scope/provenance mismatch');
147
+ const before = owned(source), after = owned(destination);
148
+ if (before.length !== after.length) throw new Error('Clone owned component count changed');
149
+ const old = new Set([source.id, source.flowCatalogVariableModelId, ...before.flatMap(item => [item.id, item.uiUniqueIdentifier]).filter(Boolean)]);
150
+ const fresh = new Set();
151
+ const mapping = new Map();
152
+ function allocate(a, b) {
153
+ if (!a) { if (b) throw new Error('Unexpected owned identity'); return; }
154
+ if (!b || old.has(b) || fresh.has(b)) throw new Error('Clone reused or omitted an owned identity');
155
+ fresh.add(b); mapping.set(a, b);
156
+ }
157
+ allocate(source.id, destination.id);
158
+ allocate(source.flowCatalogVariableModelId, destination.flowCatalogVariableModelId);
159
+ before.forEach((item, index) => {
160
+ allocate(item.id, after[index].id);
161
+ if (item.uiUniqueIdentifier && item.uiUniqueIdentifier === after[index].uiUniqueIdentifier) mapping.set(item.uiUniqueIdentifier, item.uiUniqueIdentifier);
162
+ else allocate(item.uiUniqueIdentifier, after[index].uiUniqueIdentifier);
163
+ });
164
+ const ref = value => mapping.get(value) || value;
165
+ function values(value) {
166
+ if (Array.isArray(value)) return value.map(values);
167
+ if (!value || typeof value !== 'object') return value;
168
+ const result = Object.fromEntries(Object.entries(value).map(([key, child]) => [key, values(child)]));
169
+ if (!value.scriptActive && typeof value.value === 'string' && pill.test(value.value)) {
170
+ result.value = value.value.replace(pill, (_all, id, path) => `{{${ref(id)}${path}}}`);
171
+ if (value.displayValue === value.value) result.displayValue = result.value;
172
+ }
173
+ return result;
174
+ }
175
+ function component(item) {
176
+ const result = values(item);
177
+ for (const key of ['id', 'uiUniqueIdentifier', 'flowSysId']) if (Object.hasOwn(item, key)) result[key] = ref(item[key]);
178
+ if (item.children) result.children = item.children.map(component);
179
+ return result;
180
+ }
181
+ for (const key of collections) {
182
+ if (!isDeepStrictEqual(source[key].map(component), comparable[key])) throw new Error(`Clone changed or miswired ${key}`);
183
+ }
184
+ for (const key of [...preserved, ...unsupported]) if (!isDeepStrictEqual(source[key], destination[key])) throw new Error(`Clone did not preserve ${key}`);
185
+ return { verified: true, identity_count: mapping.size, inventory: { preserved, regenerated: ['id', 'flowCatalogVariableModelId', 'component.id'], flow_local_ui_identity: 'preserved or remapped with typed references', derived: ['flat published action compiledSnapshot linked to unchanged reusable definition'], contextual, unsupported_nonempty: unsupported } };
186
+ }
187
+
188
+ async function readSavedCloneVersion(sdk, flow) {
189
+ const rows = await sdk.list('sys_hub_flow_version', new URLSearchParams({ sysparm_query: `sys_id=${flow.versionRecordId}^flow=${flow.id}`, sysparm_limit: '2', sysparm_fields: 'sys_id,flow,payload' }));
190
+ if (!Array.isArray(rows) || rows.length !== 1 || raw(rows[0].flow) !== flow.id || raw(rows[0].sys_id) !== flow.versionRecordId) throw new Error('Exact saved version is not readable');
191
+ const payload = JSON.parse(raw(rows[0].payload));
192
+ if (payload?.id !== flow.id || payload.name !== flow.name || payload.scope !== flow.scope) throw new Error('Saved version identity/name/scope mismatch');
193
+ // Independently link each saved component/value to the current definition.
194
+ // Parameter schemas differ between native serialized and GET forms; the full
195
+ // serialized schemas are compared source-to-destination below, not flattened.
196
+ const valueTree = values => (values || []).map(value => ({ name: value.name, value: value.value, scriptActive: value.scriptActive, children: valueTree(value.children) }));
197
+ for (const key of collections) {
198
+ if (!Array.isArray(payload[key]) || payload[key].length !== flow[key].length) throw new Error(`Saved version has incomplete ${key}`);
199
+ payload[key].forEach((item, index) => {
200
+ const current = flow[key][index];
201
+ if (item.id !== current.id || item.flowSysId !== current.flowSysId || !isDeepStrictEqual(valueTree(item.inputs), valueTree(current.inputs))) throw new Error(`Saved version has stale identity/input values in ${key}`);
202
+ });
203
+ }
204
+ return payload;
205
+ }
206
+
207
+ export function verifyClonedVersions(source, destination) {
208
+ destination = nativeCloneComparable(source, destination);
209
+ // Version serialization records the compiler engine version. A freshly saved
210
+ // draft is uncompiled (0); requiring the source's compiled value would demand
211
+ // a compilation this workflow never performs. Only that exact draft state is
212
+ // accepted - any other engine version still fails the structural comparison.
213
+ if (destination.engineVersion === 0 && Number.isInteger(source.engineVersion) && source.engineVersion > 0) {
214
+ destination.engineVersion = source.engineVersion;
215
+ }
216
+ const ownedIds = new Set([source.id, source.flowCatalogVariableModelId, ...collections.flatMap(key => source[key].map(item => item.id)).filter(Boolean)]);
217
+ for (const key of collections) for (const item of destination[key]) {
218
+ if (item.id && ownedIds.has(item.id)) throw new Error('Saved version reused an owned database identity');
219
+ }
220
+ const mapping = new Map([[source.id, destination.id], [source.flowCatalogVariableModelId, destination.flowCatalogVariableModelId]]);
221
+ for (const key of collections) {
222
+ const before = key === 'inputs' || key === 'outputs' ? variableEntries(source[key]) : source[key];
223
+ const after = key === 'inputs' || key === 'outputs' ? variableEntries(destination[key]) : destination[key];
224
+ if (before.length !== after.length) throw new Error(`Saved version changed ${key}`);
225
+ before.forEach((item, index) => { for (const field of ['id', 'uiUniqueIdentifier']) if (item[field]) mapping.set(item[field], after[index][field]); });
226
+ }
227
+ function translate(value) {
228
+ if (Array.isArray(value)) return value.map(translate);
229
+ if (!value || typeof value !== 'object') return value;
230
+ const result = Object.fromEntries(Object.entries(value).map(([key, child]) => [key, translate(child)]));
231
+ if (!value.scriptActive && typeof value.value === 'string' && pill.test(value.value)) {
232
+ result.value = value.value.replace(pill, (_all, id, path) => `{{${mapping.get(id) || id}${path}}}`);
233
+ if (value.displayValue === value.value) result.displayValue = result.value;
234
+ }
235
+ return result;
236
+ }
237
+ function component(item) {
238
+ const result = translate(item);
239
+ for (const field of ['id', 'uiUniqueIdentifier', 'flowSysId']) if (item[field]) result[field] = mapping.get(item[field]) || item[field];
240
+ if (item.children) result.children = item.children.map(component);
241
+ return result;
242
+ }
243
+ const expected = translate(source);
244
+ for (const key of collections) expected[key] = source[key].map(component);
245
+ // These are version-level provenance/permission fields, never graph content.
246
+ const omitted = new Set(contextual);
247
+ const stable = value => {
248
+ const result = structuredClone(Object.fromEntries(Object.entries(value).filter(([key]) => !omitted.has(key))));
249
+ // Native version serialization omits this mapper on these two fixed record
250
+ // trigger outputs; current ProcessFlow schemas agree. Never strip mapper
251
+ // metadata from action inputs, authored schemas, or arbitrary outputs.
252
+ for (const trigger of result.triggerInstances || []) for (const output of trigger.outputs || []) {
253
+ if (((output.name === 'current' && output.type === 'document_id') || (output.name === 'table_name' && output.type === 'table_name')) &&
254
+ output.parameter?.name === output.name && output.parameter?.type === output.type &&
255
+ output.parameter?.attributes?.element_mapping_provider === 'com.glide.flow_design.action.data.FlowDesignVariableMapper') {
256
+ delete output.parameter.attributes.element_mapping_provider;
257
+ }
258
+ }
259
+ return result;
260
+ };
261
+ const before = stable(expected), after = stable(destination);
262
+ // Measured native save omission: triggerInstances[].inputs[].parameter's
263
+ // own empty choice lists only. Validate both parameter shapes and their input
264
+ // names; never walk defaults, values, children, or unknown provider payloads.
265
+ for (const [index, trigger] of before.triggerInstances.entries()) {
266
+ for (const [inputIndex, input] of trigger.inputs.entries()) {
267
+ const saved = after.triggerInstances?.[index]?.inputs?.[inputIndex];
268
+ const parameter = input.parameter, savedParameter = saved?.parameter;
269
+ if (!parameter || !savedParameter || typeof input.name !== 'string' ||
270
+ input.name !== saved.name || parameter.name !== input.name || savedParameter.name !== input.name ||
271
+ typeof parameter.type !== 'string' || parameter.type !== savedParameter.type ||
272
+ !Array.isArray(parameter.children) || !Array.isArray(savedParameter.children)) continue;
273
+ for (const field of ['choices', 'defaultChoices']) {
274
+ if (Array.isArray(parameter[field]) && parameter[field].length === 0 && !Object.hasOwn(savedParameter, field)) delete parameter[field];
275
+ }
276
+ }
277
+ }
278
+ if (!isDeepStrictEqual(before, after)) throw new Error('Saved version content/schema was not preserved under the explicit identity map');
279
+ return true;
280
+ }
281
+
282
+ // Full native save: preserve every readable field, including typed schemas and
283
+ // unknown nested provider metadata. The shipped editor removes only reusable
284
+ // action inputs/steps (not instance inputs), and emits label_cache separately.
285
+ export function serializeNativeClone(flow) {
286
+ const body = structuredClone(flow);
287
+ body.deletedActions = [];
288
+ body.deletedTriggers = [];
289
+ body.label_cache = JSON.parse(body.labelCacheAsJsonString || '[]');
290
+ body.aliasOverride = { aliasOverrideMappings: [] };
291
+ body.clientSessionId = randomUUID();
292
+ for (const action of body.actionInstances) {
293
+ delete action.actionType.inputs;
294
+ delete action.actionType.steps;
295
+ }
296
+ return body;
297
+ }
298
+
299
+ async function ownedCloneLease(sdk, instance, id) {
300
+ const user = await sdk.getCurrentUser({ touchLastSeen: false });
301
+ const rows = await sdk.list('sys_hub_flow_safe_edit', new URLSearchParams({ sysparm_query: `flow=${id}`, sysparm_limit: '2', sysparm_fields: 'sys_id,flow,user' }));
302
+ const status = await readFlowSafeEditStatus(sdk, instance, id);
303
+ if (!isSysId(user?.sys_id) || !Array.isArray(rows) || rows.length !== 1 ||
304
+ !isSysId(raw(rows[0].sys_id)) || raw(rows[0].flow) !== id || raw(rows[0].user) !== user.sys_id ||
305
+ status.canUserEdit !== true || status.currentEditor) throw new Error('Native clone lease ownership is unconfirmed; no save or release attempted');
306
+ return raw(rows[0].sys_id);
307
+ }
308
+
309
+ // Call only for a positively acknowledged allocation owned by this invocation,
310
+ // or an explicitly approved recovery of that exact retained allocation.
311
+ export async function completeNativeClone(sdk, instance, source, flow, name) {
312
+ verifyCloneGraph(source, flow, name, false);
313
+ const leaseId = await ownedCloneLease(sdk, instance, flow.id);
314
+ let failure, completed;
315
+ try {
316
+ const response = await sdk.request(`${instance}/api/now/processflow/flow?sysparm_transaction_scope=${encodeURIComponent(flow.scope)}`, {
317
+ method: 'PUT', body: JSON.stringify(serializeNativeClone(flow)),
318
+ });
319
+ if (response?.error || response?.result?.error || response?.result?.errors?.length) throw new Error('Native save returned flow errors');
320
+ completed = await readProcessFlow(sdk, instance, flow.id, flow.scope);
321
+ verifyCloneGraph(source, completed, name, false);
322
+ await createVerifiedFlowVersion(sdk, { instance, flowId: flow.id, scope: flow.scope, type: 'Save', annotation: '' });
323
+ completed = await readProcessFlow(sdk, instance, flow.id, flow.scope);
324
+ verifyClonedFlow(source, completed, name);
325
+ // The update-set XML for this record is generated from the parent write, so it
326
+ // still carries the pre-version record pointer. Re-saving the identical owned
327
+ // graph once after version creation makes the exact parent capture reference
328
+ // the current saved version; it creates no new version and changes no content.
329
+ const refresh = await sdk.request(`${instance}/api/now/processflow/flow?sysparm_transaction_scope=${encodeURIComponent(flow.scope)}`, {
330
+ method: 'PUT', body: JSON.stringify(serializeNativeClone(completed)),
331
+ });
332
+ if (refresh?.error || refresh?.result?.error || refresh?.result?.errors?.length) throw new Error('Native capture-refresh save returned flow errors');
333
+ completed = await readProcessFlow(sdk, instance, flow.id, flow.scope);
334
+ verifyClonedFlow(source, completed, name);
335
+ } catch (error) { failure = error; }
336
+ // Recheck exact lease identity/user before release, including failure paths.
337
+ // Never acquire/take over another session and never delete the flow itself.
338
+ try {
339
+ if (await ownedCloneLease(sdk, instance, flow.id) !== leaseId) throw new Error('Native clone lease changed; release refused');
340
+ const { deleteResult } = await flowSafeEditRequest(sdk, instance, flow.id, 'delete');
341
+ if (deleteResult?.deleteSuccess !== true || deleteResult.id !== flow.id) throw new Error('Native clone release was not acknowledged');
342
+ const status = await readFlowSafeEditStatus(sdk, instance, flow.id);
343
+ const leases = await sdk.list('sys_hub_flow_safe_edit', new URLSearchParams({ sysparm_query: `flow=${flow.id}`, sysparm_limit: '2', sysparm_fields: 'sys_id' }));
344
+ if (status.canUserEdit || status.currentEditor || !Array.isArray(leases) || leases.length) throw new Error('Native clone release readback failed');
345
+ } catch (error) { throw new Error(`${failure ? `${failure.message}; ` : ''}Clone ${flow.id} lease release failed: ${error.message}`, { cause: error }); }
346
+ if (failure) throw failure;
347
+ return completed;
348
+ }
349
+
350
+ async function assertUnusedName(sdk, scope, name) {
351
+ const rows = await sdk.list('sys_hub_flow', new URLSearchParams({ sysparm_query: `name=${name}^sys_scope=${scope}`, sysparm_limit: '1', sysparm_fields: 'sys_id,name,sys_scope' }));
352
+ if (!Array.isArray(rows)) refuse('Collision lookup was unreadable');
353
+ if (rows.length) refuse(`A flow named ${JSON.stringify(name)} already exists in the source scope; no overwrite`);
354
+ }
355
+ export async function prepareFlowClone(sdk, instance, identifier, options = {}) {
356
+ try {
357
+ assertSafeExactMatch(identifier);
358
+ const record = await resolveRecord(sdk, { table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow', fields: ['sys_scope', 'name', 'active', 'status'] });
359
+ const id = unwrapSysId(record), scope = raw(record.sys_scope);
360
+ if (!isSysId(id) || !(scope === 'global' || isSysId(scope))) refuse('Unreadable native source scope or identity');
361
+ const source = await readProcessFlow(sdk, instance, id, scope);
362
+ if (source.id !== id || source.scope !== scope) refuse('Source definition identity/scope mismatch');
363
+ validateCloneSource(source);
364
+ if (!options.name && !options.interactive) refuse('--name is required for automation');
365
+ const name = options.name ?? `${source.name} copy`;
366
+ if (typeof name !== 'string' || !name.trim()) refuse('--name must be nonempty');
367
+ assertSafeExactMatch(name);
368
+ await assertUnusedName(sdk, scope, name);
369
+ const saved_version = await readSavedCloneVersion(sdk, source);
370
+ return { source, scope, name, source_digest: flowCloneDigest(source), saved_version, version_digest: flowCloneDigest(saved_version) };
371
+ } catch (cause) {
372
+ if (cause instanceof AppError) throw cause;
373
+ throw new AppError(CodeAPI, `Clone preflight failed: ${cause.message}`, 'No clone allocated.', 0, cause);
374
+ }
375
+ }
376
+
377
+ export async function cloneFlow(sdk, instance, plan, { capturePolls = 21, pollDelay = 250 } = {}) {
378
+ let id, stage = 'preflight';
379
+ let allocationAttempted = false;
380
+ try {
381
+ validateCloneSource(plan.source);
382
+ if (flowCloneDigest(plan.source) !== plan.source_digest) refuse('Clone plan changed');
383
+ await assertUnusedName(sdk, plan.scope, plan.name);
384
+ const current = await readCurrentUpdateSet(sdk), effective = await readEffectiveUpdateSet(sdk);
385
+ const setId = raw(current?.sys_id || current?.sysId);
386
+ if (!isSysId(setId) || raw(current?.state) !== 'in progress' || raw(current?.name) === 'Default' || effective.sys_id !== setId) refuse('Select a named in-progress update set and align the effective session before cloning');
387
+ // No session context writes. Caller selection must already be aligned.
388
+ const sourceBefore = await readProcessFlow(sdk, instance, plan.source.id, plan.scope);
389
+ if (flowCloneDigest(sourceBefore) !== plan.source_digest) refuse('Source changed after confirmation');
390
+ if (flowCloneDigest(plan.saved_version) !== plan.version_digest || flowCloneDigest(await readSavedCloneVersion(sdk, sourceBefore)) !== plan.version_digest) refuse('Source saved version changed after confirmation');
391
+ stage = 'native_copy'; allocationAttempted = true;
392
+ // Source-confirmed Designer contract. Exactly one allocation, no fallbacks.
393
+ const response = await sdk.request(`${instance}/api/now/processflow/flow/${plan.source.id}/copy?sysparm_transaction_scope=${encodeURIComponent(plan.scope)}`, { method: 'POST', body: JSON.stringify({ name: plan.name, scope: plan.scope }) });
394
+ const allocated = response?.result?.data;
395
+ if (!isSysId(allocated) || allocated === plan.source.id) throw new Error('Provider returned no fresh clone identity');
396
+ id = allocated;
397
+ stage = 'definition_readback';
398
+ let flow = await readProcessFlow(sdk, instance, id, plan.scope);
399
+ const graph = verifyCloneGraph(plan.source, flow, plan.name, false);
400
+ stage = 'native_save_version_release';
401
+ flow = await completeNativeClone(sdk, instance, plan.source, flow, plan.name);
402
+ stage = 'saved_version';
403
+ if (!isSysId(flow.versionRecordId) || flow.versionRecordId === plan.source.versionRecordId) throw new Error('No fresh saved version pointer');
404
+ const savedVersion = await readSavedCloneVersion(sdk, flow);
405
+ verifyClonedVersions(plan.saved_version, savedVersion);
406
+ stage = 'update_set_capture';
407
+ let captures;
408
+ for (let attempt = 0; attempt < capturePolls; attempt++) {
409
+ const rows = await sdk.list('sys_update_xml', new URLSearchParams({ sysparm_query: `update_set=${setId}^name=sys_hub_flow_${id}`, sysparm_limit: '2', sysparm_fields: 'sys_id,name,update_set,action,payload' }));
410
+ if (!Array.isArray(rows)) throw new Error('Unreadable update-set capture');
411
+ if (rows.length === 1 && raw(rows[0].name) === `sys_hub_flow_${id}` && raw(rows[0].update_set) === setId && raw(rows[0].action) === 'INSERT_OR_UPDATE' && verifyCopyCapture(raw(rows[0].payload), id, flow.versionRecordId)) { captures = rows; break; }
412
+ if (attempt + 1 < capturePolls) await new Promise(resolve => setTimeout(resolve, pollDelay));
413
+ }
414
+ if (!captures) throw new Error('Exact new parent/version XML capture not verified within bounded read polling');
415
+ stage = 'source_and_context_preservation';
416
+ const sourceAfter = await readProcessFlow(sdk, instance, plan.source.id, plan.scope);
417
+ if (flowCloneDigest(sourceAfter) !== plan.source_digest) throw new Error('Source digest changed during clone');
418
+ const finalSet = await readCurrentUpdateSet(sdk), finalEffective = await readEffectiveUpdateSet(sdk);
419
+ if (!isDeepStrictEqual(current, finalSet) || !isDeepStrictEqual(effective, finalEffective)) throw new Error('Capture context changed during clone');
420
+ return { flow, source: { id: plan.source.id, unchanged: true, before_digest: plan.source_digest, after_digest: flowCloneDigest(sourceAfter) }, graph, version: { id: flow.versionRecordId, flow: id }, capture: { update_set: setId, parent: id, version: flow.versionRecordId, records: captures.map(row => raw(row.sys_id)) }, context_unchanged: true, published: false, activated: false, executed: false };
421
+ } catch (cause) {
422
+ if (!allocationAttempted && cause instanceof AppError) throw cause;
423
+ throw new AppError(CodeAPI, `Flow clone ${id ? `allocated ${id}, verification failed` : allocationAttempted ? 'allocation outcome uncertain' : 'failed before allocation'} at ${stage}: ${cause.message}`, `${id ? `Inspect flows show ${id}.` : allocationAttempted ? `Reconcile source ${plan.source.id} and name ${JSON.stringify(plan.name)} before retrying.` : 'No clone allocated.'} No automatic retry, cleanup, publish or execution.`, 0, cause);
424
+ }
425
+ }