All files / src/web/flowable/roundTrip structuralMerge.ts

95.72% Statements 224/234
85.53% Branches 136/159
98.41% Functions 62/63
95.71% Lines 201/210

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439                                      72x 4x 4x                                     8x       12581x       2441x 2441x 6282x 141x   6141x 6141x 446x 446x   5695x   2441x       2441x 6299x 6296x   3x       3x 2x 2x   1x         2441x 2441x       12228x 12228x 605x     11623x 11623x 183x   11440x 38x   11402x       3272x 3272x 1441x   1831x       2335x 2335x 2335x 952x     1383x 1383x 1383x       1383x 2335x 2335x 1x         28x 2x   26x 26x 26x 17x   26x 15x         60x     60x 60x 60x 28x   60x 48x         11921x       10934x     10934x 10889x   45x             18551x 7617x   10934x       301x   264x       32x   5x                 550x 318x 318x   232x       3341x 3272x   69x       9411x 9411x 5535x   3876x       2526x 2538x 2441x       1502x 2299x 2174x 1502x 2312x 2173x 1502x       224x 220x 106x       2547x 2547x 2604x 2604x 2604x 2604x   2547x       1075x       18x       8x       8x       2547x 2602x 2602x 2584x   18x 18x 10x 10x   8x 8x 2x 2x   6x 6x 4x   2x                   224x 224x         106x   118x 118x 113x   5x 5x                   331x 225x     225x   225x 1x           330x 326x 106x 106x 106x 106x 106x 224x 224x 224x     106x 106x       2346x 2346x 916x   1430x 1430x 1421x   9x       2365x 30x   2335x 2335x 2335x 2335x 2335x                 2378x 2378x 2378x 1421x 1421x   957x 957x 944x 944x   13x 13x 13x                   6201x 2397x 2378x   19x 12x 12x 12x   7x 5x   2x 2x           6154x 6188x 2441x 2441x 2441x 2441x 2441x 2378x 2378x 2378x     2441x 2441x    
import type {
	Document as XmlDocument,
	Element as XmlElement,
	Node as XmlNode,
} from '@xmldom/xmldom';
import { FLOWABLE_ATTRIBUTE_KEYS } from '../types';
import { XMLNS_NAMESPACE } from './constants';
import {
	buildXmlIdentity,
	detachNode,
	getElementChildren,
	getLocalName,
	getNodeDocument,
	insertAfter,
	isSameElementType,
	serializer,
	setTextContentPreservingComments,
} from './xmlUtils';
 
const editableActivitiAttributes = new Set(FLOWABLE_ATTRIBUTE_KEYS.map((key) => `activiti:${key}`));
const editableLegacyAttributes = new Set(FLOWABLE_ATTRIBUTE_KEYS);
const overlayManagedChildNames = new Set([
	'extensionElements',
	'documentation',
	'conditionExpression',
	'script',
	'multiInstanceLoopCharacteristics',
]);
 
interface NodePlacement {
	node: XmlNode;
	existedHere: boolean;
}
 
export interface StructuralMergeContext {
	originalById: Map<string, XmlElement>;
	preserveUnmatchedLexicalNodes: boolean;
}
 
function shouldPreserveUnmatchedLexicalNodes(sourceHasLexicalNodes: boolean, context: StructuralMergeContext): boolean {
	return context.preserveUnmatchedLexicalNodes && !sourceHasLexicalNodes;
}
 
function shouldSyncStructuralAttribute(attributeName: string): boolean {
	return !editableActivitiAttributes.has(attributeName) && !editableLegacyAttributes.has(attributeName as typeof FLOWABLE_ATTRIBUTE_KEYS[number]);
}
 
function applySourceStructuralAttributes(target: XmlElement, source: XmlElement): Map<string, string> {
	const sourceAttributes = new Map<string, string>();
	for (const attribute of Array.from(source.attributes)) {
		if (!shouldSyncStructuralAttribute(attribute.name)) {
			continue;
		}
		sourceAttributes.set(attribute.name, attribute.value);
		if (attribute.name === 'xmlns' || attribute.name.startsWith('xmlns:')) {
			target.setAttributeNS(XMLNS_NAMESPACE, attribute.name, attribute.value);
			continue;
		}
		target.setAttribute(attribute.name, attribute.value);
	}
	return sourceAttributes;
}
 
function removeMissingStructuralAttributes(target: XmlElement, sourceAttributes: Map<string, string>): void {
	for (const attribute of Array.from(target.attributes)) {
		if (!shouldSyncStructuralAttribute(attribute.name) || sourceAttributes.has(attribute.name)) {
			continue;
		}
		Iif (attribute.name === 'xmlns') {
			target.removeAttribute('xmlns');
			continue;
		}
		if (attribute.name.startsWith('xmlns:')) {
			target.removeAttributeNS(XMLNS_NAMESPACE, attribute.localName || attribute.name.slice(6));
			continue;
		}
		target.removeAttribute(attribute.name);
	}
}
 
export function syncStructuralAttributes(target: XmlElement, source: XmlElement): void {
	const sourceAttributes = applySourceStructuralAttributes(target, source);
	removeMissingStructuralAttributes(target, sourceAttributes);
}
 
function isStructuralChild(parent: XmlElement, child: XmlElement): boolean {
	const childLocalName = getLocalName(child);
	if (overlayManagedChildNames.has(childLocalName)) {
		return false;
	}
 
	const parentLocalName = getLocalName(parent);
	if (parentLocalName === 'definitions' && (childLocalName === 'signal' || childLocalName === 'message')) {
		return false;
	}
	if (parentLocalName === 'process' && childLocalName === 'dataObject') {
		return false;
	}
	return true;
}
 
function getStructuralChildKey(parent: XmlElement, child: XmlElement): string {
	const id = child.getAttribute('id');
	if (id) {
		return `id:${child.namespaceURI || ''}:${getLocalName(child)}:${id}`;
	}
	return buildXmlIdentity(`structural:${getLocalName(parent)}`, child);
}
 
function maybeSyncLeafText(target: XmlElement, source: XmlElement): void {
	const sourceElements = getElementChildren(source);
	const targetElements = getElementChildren(target);
	if (sourceElements.length > 0 || targetElements.length > 0) {
		return;
	}
 
	const sourceHasComments = Array.from(source.childNodes).some((node) => node.nodeType === node.COMMENT_NODE || node.nodeType === node.PROCESSING_INSTRUCTION_NODE);
	const targetHasComments = Array.from(target.childNodes).some((node) => node.nodeType === node.COMMENT_NODE || node.nodeType === node.PROCESSING_INSTRUCTION_NODE);
	Iif (sourceHasComments || targetHasComments) {
		return;
	}
 
	const sourceText = source.textContent || '';
	const targetText = target.textContent || '';
	if (sourceText !== targetText) {
		setTextContentPreservingComments(target, sourceText);
	}
}
 
function indexNodeById(idMap: Map<string, XmlElement>, node: XmlNode): void {
	if (node.nodeType !== node.ELEMENT_NODE) {
		return;
	}
	const element = node as XmlElement;
	const id = element.getAttribute('id');
	if (id) {
		idMap.set(id, element);
	}
	for (const child of getElementChildren(element)) {
		indexNodeById(idMap, child);
	}
}
 
function removeNodeIds(idMap: Map<string, XmlElement>, node: XmlNode): void {
	Iif (node.nodeType !== node.ELEMENT_NODE) {
		return;
	}
	const element = node as XmlElement;
	const id = element.getAttribute('id');
	if (id) {
		idMap.delete(id);
	}
	for (const child of getElementChildren(element)) {
		removeNodeIds(idMap, child);
	}
}
 
function isXmlDeclarationNode(node: XmlNode): boolean {
	return node.nodeType === node.PROCESSING_INSTRUCTION_NODE && node.nodeName.toLowerCase() === 'xml';
}
 
function isStructuralNonElementNode(node: XmlNode): boolean {
	Iif (isXmlDeclarationNode(node)) {
		return false;
	}
	if (node.nodeType === node.TEXT_NODE) {
		return (node.nodeValue || '').trim().length > 0;
	}
	return node.nodeType === node.COMMENT_NODE
		|| node.nodeType === node.PROCESSING_INSTRUCTION_NODE
		|| node.nodeType === node.CDATA_SECTION_NODE
		|| node.nodeType === node.DOCUMENT_TYPE_NODE;
}
 
function isStructuralChildNode(parent: XmlElement, child: XmlNode): boolean {
	if (child.nodeType === child.ELEMENT_NODE) {
		return isStructuralChild(parent, child as XmlElement);
	}
	return isStructuralNonElementNode(child);
}
 
function getNonElementNodeKey(node: XmlNode): string {
	switch (node.nodeType) {
		case node.TEXT_NODE:
			return `text:${node.nodeValue || ''}`;
		case node.CDATA_SECTION_NODE:
			return `cdata:${node.nodeValue || ''}`;
		case node.COMMENT_NODE:
			return `comment:${node.nodeValue || ''}`;
		case node.PROCESSING_INSTRUCTION_NODE:
			return `pi:${node.nodeName}:${node.nodeValue || ''}`;
		case node.DOCUMENT_TYPE_NODE:
			return `doctype:${serializer.serializeToString(node)}`;
		default:
			return `node:${node.nodeType}:${serializer.serializeToString(node)}`;
	}
}
 
function getDocumentChildKey(child: XmlNode): string {
	if (child.nodeType === child.ELEMENT_NODE) {
		const element = child as XmlElement;
		return `element:${element.namespaceURI || ''}:${getLocalName(element)}`;
	}
	return getNonElementNodeKey(child);
}
 
function getStructuralNodeKey(parent: XmlElement, child: XmlNode): string {
	if (child.nodeType === child.ELEMENT_NODE) {
		return getStructuralChildKey(parent, child as XmlElement);
	}
	return getNonElementNodeKey(child);
}
 
function getElementOrderKey(parent: XmlElement, child: XmlElement): string {
	const id = child.getAttribute('id');
	if (id) {
		return `id:${child.namespaceURI || ''}:${getLocalName(child)}:${id}`;
	}
	return buildXmlIdentity(`order:${getLocalName(parent)}`, child);
}
 
function didElementChildOrderChange(target: XmlElement, source: XmlElement): boolean {
	const leftKeys = getElementChildren(source).map((child) => getElementOrderKey(target, child));
	const rightKeys = getElementChildren(target).map((child) => getElementOrderKey(target, child));
	return JSON.stringify(leftKeys) !== JSON.stringify(rightKeys);
}
 
export function didStructuralElementChildOrderChange(target: XmlElement, source: XmlElement): boolean {
	const leftKeys = getElementChildren(source)
		.filter((child) => isStructuralChild(source, child))
		.map((child) => getElementOrderKey(source, child));
	const rightKeys = getElementChildren(target)
		.filter((child) => isStructuralChild(target, child))
		.map((child) => getElementOrderKey(target, child));
	return JSON.stringify(leftKeys) !== JSON.stringify(rightKeys);
}
 
function didDocumentElementOrderChange(leftChildren: XmlNode[], rightChildren: XmlNode[]): boolean {
	const leftKeys = leftChildren.filter((child) => child.nodeType === child.ELEMENT_NODE).map((child) => getDocumentChildKey(child));
	const rightKeys = rightChildren.filter((child) => child.nodeType === child.ELEMENT_NODE).map((child) => getDocumentChildKey(child));
	return JSON.stringify(leftKeys) !== JSON.stringify(rightKeys);
}
 
function createNodeBuckets(children: XmlNode[], getKey: (child: XmlNode) => string): Map<string, XmlNode[]> {
	const buckets = new Map<string, XmlNode[]>();
	for (const child of children) {
		const key = getKey(child);
		const bucket = buckets.get(key) || [];
		bucket.push(child);
		buckets.set(key, bucket);
	}
	return buckets;
}
 
function takeBucketNode(buckets: Map<string, XmlNode[]>, key: string): XmlNode | undefined {
	return buckets.get(key)?.shift();
}
 
function findNextStableNode(parent: XmlNode, placements: NodePlacement[], index: number): XmlNode | undefined {
	return placements.slice(index + 1).find((candidate) => candidate.existedHere && candidate.node.parentNode === parent)?.node;
}
 
function findPreviousPlacedNode(parent: XmlNode, placements: NodePlacement[], index: number): XmlNode | undefined {
	return placements.slice(0, index).reverse().find((candidate) => candidate.node.parentNode === parent)?.node;
}
 
function findFirstRelevantChild(parent: XmlNode, isRelevant: (child: XmlNode) => boolean, excludedNode: XmlNode): XmlNode | undefined {
	return Array.from(parent.childNodes).find((child) => isRelevant(child) && child !== excludedNode);
}
 
function placeNodes(parent: XmlNode, placements: NodePlacement[], isRelevant: (child: XmlNode) => boolean): void {
	for (let index = 0; index < placements.length; index++) {
		const placement = placements[index];
		if (placement.existedHere) {
			continue;
		}
		const nextStable = findNextStableNode(parent, placements, index);
		if (nextStable) {
			parent.insertBefore(placement.node, nextStable);
			continue;
		}
		const previousPlaced = findPreviousPlacedNode(parent, placements, index);
		if (previousPlaced) {
			insertAfter(parent, placement.node, previousPlaced);
			continue;
		}
		const firstRelevantChild = findFirstRelevantChild(parent, isRelevant, placement.node);
		if (firstRelevantChild) {
			parent.insertBefore(placement.node, firstRelevantChild);
		} else {
			parent.appendChild(placement.node);
		}
	}
}
 
function resolveDocumentTargetChild(
	target: XmlDocument,
	sourceChild: XmlNode,
	targetChildrenByKey: Map<string, XmlNode[]>,
): NodePlacement {
	const targetDocumentElement = target.documentElement;
	if (
		sourceChild.nodeType === sourceChild.ELEMENT_NODE
		&& targetDocumentElement?.nodeType === sourceChild.nodeType
		&& isSameElementType(targetDocumentElement, sourceChild as XmlElement)
	) {
		return { node: targetDocumentElement, existedHere: targetDocumentElement.parentNode === target };
	}
	const matchedNode = takeBucketNode(targetChildrenByKey, getDocumentChildKey(sourceChild));
	if (matchedNode) {
		return { node: matchedNode, existedHere: matchedNode.parentNode === target };
	}
	const importedNode = target.importNode(sourceChild, true);
	return { node: importedNode, existedHere: false };
}
 
function removeUnkeptDocumentChildren(
	target: XmlDocument,
	keptChildren: Set<XmlNode>,
	sourceHasLexicalNodes: boolean,
	documentElementOrderChanged: boolean,
	context: StructuralMergeContext,
): void {
	for (const child of Array.from(target.childNodes).filter((node) => !isXmlDeclarationNode(node))) {
		Iif (!keptChildren.has(child) && child.nodeType !== child.ELEMENT_NODE && shouldPreserveUnmatchedLexicalNodes(sourceHasLexicalNodes, context)) {
			continue;
		}
		const shouldRemove = !keptChildren.has(child)
			&& (child.nodeType === child.ELEMENT_NODE || sourceHasLexicalNodes || !documentElementOrderChanged);
		if (shouldRemove) {
			detachNode(child);
		}
	}
}
 
export function syncDocumentLexicalNodes(target: XmlDocument, source: XmlDocument, context: StructuralMergeContext): void {
	const sourceChildren = Array.from(source.childNodes).filter((node) => !isXmlDeclarationNode(node));
	const targetChildren = Array.from(target.childNodes).filter((node) => !isXmlDeclarationNode(node));
	const sourceHasLexicalNodes = sourceChildren.some((node) => node.nodeType !== node.ELEMENT_NODE);
	const documentElementOrderChanged = didDocumentElementOrderChange(sourceChildren, targetChildren);
	const targetChildrenByKey = createNodeBuckets(targetChildren, getDocumentChildKey);
	const keptChildren = new Set<XmlNode>();
	const placements = sourceChildren.map((sourceChild) => {
		const placement = resolveDocumentTargetChild(target, sourceChild, targetChildrenByKey);
		keptChildren.add(placement.node);
		return placement;
	});
 
	placeNodes(target, placements, (child) => !isXmlDeclarationNode(child));
	removeUnkeptDocumentChildren(target, keptChildren, sourceHasLexicalNodes, documentElementOrderChanged, context);
}
 
function getMatchedStructuralNodeById(sourceElement: XmlElement, context: StructuralMergeContext): XmlNode | undefined {
	const id = sourceElement.getAttribute('id');
	if (!id) {
		return undefined;
	}
	const matchedById = context.originalById.get(id);
	if (matchedById && isSameElementType(matchedById, sourceElement)) {
		return matchedById;
	}
	return undefined;
}
 
function syncMatchedStructuralElement(targetChild: XmlNode, sourceChild: XmlNode, context: StructuralMergeContext): void {
	if (targetChild.nodeType !== targetChild.ELEMENT_NODE || sourceChild.nodeType !== sourceChild.ELEMENT_NODE) {
		return;
	}
	const targetElement = targetChild as XmlElement;
	const sourceElement = sourceChild as XmlElement;
	syncStructuralAttributes(targetElement, sourceElement);
	reconcileStructuralChildren(targetElement, sourceElement, context);
	maybeSyncLeafText(targetElement, sourceElement);
}
 
function resolveStructuralTargetChild(
	target: XmlElement,
	sourceChild: XmlNode,
	targetChildrenByKey: Map<string, XmlNode[]>,
	context: StructuralMergeContext,
): NodePlacement {
	const sourceElement = sourceChild.nodeType === sourceChild.ELEMENT_NODE ? sourceChild as XmlElement : undefined;
	const matchedById = sourceElement ? getMatchedStructuralNodeById(sourceElement, context) : undefined;
	if (matchedById) {
		syncMatchedStructuralElement(matchedById, sourceChild, context);
		return { node: matchedById, existedHere: matchedById.parentNode === target };
	}
	const matchedByKey = takeBucketNode(targetChildrenByKey, getStructuralNodeKey(target, sourceChild));
	if (matchedByKey) {
		syncMatchedStructuralElement(matchedByKey, sourceChild, context);
		return { node: matchedByKey, existedHere: matchedByKey.parentNode === target };
	}
	const importedNode = getNodeDocument(target).importNode(sourceChild, true);
	indexNodeById(context.originalById, importedNode);
	return { node: importedNode, existedHere: false };
}
 
function removeUnkeptStructuralChildren(
	target: XmlElement,
	keptChildren: Set<XmlNode>,
	sourceHasLexicalNodes: boolean,
	elementChildOrderChanged: boolean,
	context: StructuralMergeContext,
): void {
	for (const child of Array.from(target.childNodes).filter((node) => isStructuralChildNode(target, node))) {
		if (keptChildren.has(child)) {
			continue;
		}
		if (child.nodeType === child.ELEMENT_NODE) {
			removeNodeIds(context.originalById, child);
			detachNode(child);
			continue;
		}
		if (shouldPreserveUnmatchedLexicalNodes(sourceHasLexicalNodes, context)) {
			continue;
		}
		Eif (sourceHasLexicalNodes || !elementChildOrderChanged) {
			detachNode(child);
		}
	}
}
 
export function reconcileStructuralChildren(target: XmlElement, source: XmlElement, context: StructuralMergeContext): void {
	const sourceChildren = Array.from(source.childNodes).filter((child) => isStructuralChildNode(source, child));
	const targetChildren = Array.from(target.childNodes).filter((child) => isStructuralChildNode(target, child));
	const sourceHasLexicalNodes = sourceChildren.some((child) => child.nodeType !== child.ELEMENT_NODE);
	const elementChildOrderChanged = didElementChildOrderChange(target, source);
	const targetChildrenByKey = createNodeBuckets(targetChildren, (child) => getStructuralNodeKey(target, child));
	const keptChildren = new Set<XmlNode>();
	const placements = sourceChildren.map((sourceChild) => {
		const placement = resolveStructuralTargetChild(target, sourceChild, targetChildrenByKey, context);
		keptChildren.add(placement.node);
		return placement;
	});
 
	placeNodes(target, placements, (child) => isStructuralChildNode(target, child));
	removeUnkeptStructuralChildren(target, keptChildren, sourceHasLexicalNodes, elementChildOrderChanged, context);
}