All files / packages/fds-uif/core/src merge.ts

89.24% Statements 83/93
73.8% Branches 31/42
50% Functions 1/2
89.24% Lines 83/93

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 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474                                                                                41x   381x 381x         33x         32x         29x                       29x 29x   29x 29x           192x             5x 5x                                         28x 28x   28x 54x 54x       1x   53x     53x     27x                                                   27x 27x 27x 27x                 33x         1x   1x         3x         3x       2x         2x         24x 24x       3x     27x                                               27x     5x       2x                     2x 2x   2x     3x               27x                 27x                 3x 3x                                     28x     27x               24x   24x 24x         27x 52x 52x       27x 27x 51x   51x         27x               27x     27x   27x                               87x         7x     166x 166x       1x         64x 64x         29x 29x     28x         31x 30x                                   41x     85x                                                                         32x                       13x     12x 12x     1x    
/**
 * @fds-uif/core - Merge Utilities
 *
 * Deep merge utilities for combining UIF foundation and system definitions.
 *
 * Merge semantics:
 * - Scalars: System replaces foundation
 * - Objects: Deep merge recursively
 * - Identified arrays: Merge by identifier; matching IDs merge, new IDs append
 * - Primitive arrays: Replace wholesale
 * - `$remove` marker: Explicitly delete inherited item
 * - `$before` marker: Insert new item before a named sibling
 * - `$after` marker: Insert new item after a named sibling
 */
 
import { UifDuplicateIdentifierError, UifMergeError } from './errors.js';
import {
  IDENTIFIED_ARRAYS,
  MARKER_AFTER,
  MARKER_BEFORE,
  MARKER_REMOVE,
  MERGE_MARKERS,
  PROP_EXTENDS,
} from './constants.js';
import type {
  AfterMarkerItem,
  BeforeMarkerItem,
  MergeOptions,
  PlainObject,
  RemoveMarkerItem,
  WarningHandler,
} from './types.js';
 
// ============================================================================
// Type Guards
// ============================================================================
 
/** Check if a value is a plain object (not null, not array, not class instance). */
function isPlainObject(value: unknown): value is PlainObject {
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
    return false;
  }
  const proto = Object.getPrototypeOf(value);
  return proto === Object.prototype || proto === null;
}
 
/** Check if an item has the $remove marker. */
function hasRemoveMarker(item: unknown): item is RemoveMarkerItem {
  return isPlainObject(item) && item[MARKER_REMOVE] === true;
}
 
/** Check if an item has the $before marker. */
function hasBeforeMarker(item: unknown): item is BeforeMarkerItem {
  return isPlainObject(item) && typeof item[MARKER_BEFORE] === 'string';
}
 
/** Check if an item has the $after marker. */
function hasAfterMarker(item: unknown): item is AfterMarkerItem {
  return isPlainObject(item) && typeof item[MARKER_AFTER] === 'string';
}
 
// ============================================================================
// Utility Functions
// ============================================================================
 
/**
 * Get the identifier field for an array at a given path.
 * @returns The field name if it's an identified array, undefined otherwise.
 */
function getIdentifierField(path: string): string | undefined {
  const segments = path.split('.');
  const lastSegment = segments[segments.length - 1] ?? '';
  // Handle indexed paths like "children[0].children"
  const cleanSegment = lastSegment.replace(/\[\d+\]$/, '');
  return IDENTIFIED_ARRAYS[cleanSegment];
}
 
/** Get the identifier value from an array item. */
function getIdentifier(item: unknown, identifierField: string): string | undefined {
  if (isPlainObject(item) && typeof item[identifierField] === 'string') {
    return item[identifierField] as string;
  }
  return undefined;
}
 
/** Strip merge markers from an item, returning a new object. */
function stripMarkers(item: PlainObject): PlainObject {
  const { [MARKER_REMOVE]: _r, [MARKER_BEFORE]: _b, [MARKER_AFTER]: _a, ...rest } = item;
  return rest;
}
 
// ============================================================================
// Array Index Building
// ============================================================================
 
interface IndexedItem {
  item: unknown;
  index: number;
}
 
/**
 * Build an index of base array items by their identifier.
 * @throws {UifDuplicateIdentifierError} If duplicates are found.
 */
function buildBaseIndex(
  base: unknown[],
  identifierField: string,
  path: string,
): { index: Map<string, IndexedItem>; items: unknown[] } {
  const index = new Map<string, IndexedItem>();
  const items: unknown[] = [];
 
  for (let i = 0; i < base.length; i++) {
    const item = base[i];
    const id = getIdentifier(item, identifierField);
 
    if (id !== undefined) {
      if (index.has(id)) {
        throw new UifDuplicateIdentifierError(path, identifierField, id);
      }
      index.set(id, { item, index: i });
    }
 
    items.push(item);
  }
 
  return { index, items };
}
 
// ============================================================================
// Extension Item Categorization
// ============================================================================
 
interface PositionalInsert {
  item: PlainObject;
  marker: typeof MARKER_BEFORE | typeof MARKER_AFTER;
  reference: string;
}
 
interface CategorizedItems {
  removedIds: Set<string>;
  positionalInserts: PositionalInsert[];
  mergeItems: Array<{ id: string; item: PlainObject }>;
  appendItems: unknown[];
}
 
/** Categorize extension items by their merge behavior. */
function categorizeExtensionItems(
  extension: unknown[],
  identifierField: string,
  baseIndex: Map<string, IndexedItem>,
): CategorizedItems {
  const removedIds = new Set<string>();
  const positionalInserts: PositionalInsert[] = [];
  const mergeItems: Array<{ id: string; item: PlainObject }> = [];
  const appendItems: unknown[] = [];
 
  for (const extItem of extension) {
    // Non-object items just get appended
    if (!isPlainObject(extItem)) {
      appendItems.push(extItem);
      continue;
    }
 
    const id = getIdentifier(extItem, identifierField);
 
    // Handle $remove marker
    if (hasRemoveMarker(extItem)) {
      if (id !== undefined) {
        removedIds.add(id);
      }
      continue;
    }
 
    // Handle positional markers
    if (hasBeforeMarker(extItem)) {
      positionalInserts.push({
        item: stripMarkers(extItem),
        marker: MARKER_BEFORE,
        reference: extItem[MARKER_BEFORE],
      });
      continue;
    }
 
    if (hasAfterMarker(extItem)) {
      positionalInserts.push({
        item: stripMarkers(extItem),
        marker: MARKER_AFTER,
        reference: extItem[MARKER_AFTER],
      });
      continue;
    }
 
    // If item exists in base, schedule for merge
    if (id !== undefined && baseIndex.has(id)) {
      mergeItems.push({ id, item: extItem });
      continue;
    }
 
    // New item without markers - append at end
    appendItems.push(extItem);
  }
 
  return { removedIds, positionalInserts, mergeItems, appendItems };
}
 
// ============================================================================
// Positional Insertion
// ============================================================================
 
interface InsertPosition {
  position: number;
  isBefore: boolean;
  item: PlainObject;
}
 
/**
 * Process positional inserts, handling missing references.
 */
function processPositionalInserts(
  inserts: PositionalInsert[],
  siblingIndex: Map<string, number>,
  result: unknown[],
  identifierField: string,
  path: string,
  onWarning?: WarningHandler,
): InsertPosition[] {
  const insertPositions: InsertPosition[] = [];
 
  for (const { item, marker, reference } of inserts) {
    const refIndex = siblingIndex.get(reference);
 
    if (refIndex === undefined) {
      // Reference not found - warn and append at end
      onWarning?.(`${marker} reference "${reference}" not found at ${path}`, {
        type: 'positional-marker-not-found',
        path,
        details: {
          marker,
          reference,
          available: Array.from(siblingIndex.keys()),
        },
      });
 
      // Append at end as fallback
      result.push(item);
      const newId = getIdentifier(item, identifierField);
      if (newId !== undefined) {
        siblingIndex.set(newId, result.length - 1);
      }
    } else {
      insertPositions.push({
        position: refIndex,
        isBefore: marker === MARKER_BEFORE,
        item,
      });
    }
  }
 
  return insertPositions;
}
 
/**
 * Apply positional inserts to an array.
 * Sorts by position descending to maintain correct indices during insertion.
 */
function applyPositionalInserts(result: unknown[], positions: InsertPosition[]): void {
  // Sort by position descending so we can insert without affecting indices
  positions.sort((a, b) => {
    if (a.position !== b.position) {
      return b.position - a.position;
    }
    // For same position, $after comes before $before (in reverse order)
    return a.isBefore ? 1 : -1;
  });
 
  for (const { position, isBefore, item } of positions) {
    const insertAt = isBefore ? position : position + 1;
    result.splice(insertAt, 0, item);
  }
}
 
// ============================================================================
// Array Merging
// ============================================================================
 
/**
 * Merge two identified arrays using identifier-based matching.
 */
function mergeIdentifiedArrays(
  base: unknown[],
  extension: unknown[],
  identifierField: string,
  path: string,
  onWarning?: WarningHandler,
): unknown[] {
  // Build index of base items
  const { index: baseIndex, items: result } = buildBaseIndex(base, identifierField, path);
 
  // Categorize extension items
  const { removedIds, positionalInserts, mergeItems, appendItems } = categorizeExtensionItems(
    extension,
    identifierField,
    baseIndex,
  );
 
  // Apply merges to existing items
  for (const { id, item } of mergeItems) {
    const existing = baseIndex.get(id);
    if (existing) {
      const merged = deepMerge(existing.item as PlainObject, item, `${path}[${id}]`, onWarning);
      result[existing.index] = merged;
    }
  }
 
  // Remove items marked for removal
  const filtered = result.filter((item) => {
    const id = getIdentifier(item, identifierField);
    return id === undefined || !removedIds.has(id);
  });
 
  // Build sibling index for positional inserts
  const siblingIndex = new Map<string, number>();
  for (let i = 0; i < filtered.length; i++) {
    const id = getIdentifier(filtered[i], identifierField);
    if (id !== undefined) {
      siblingIndex.set(id, i);
    }
  }
 
  // Process and apply positional inserts
  const insertPositions = processPositionalInserts(
    positionalInserts,
    siblingIndex,
    filtered,
    identifierField,
    path,
    onWarning,
  );
  applyPositionalInserts(filtered, insertPositions);
 
  // Append remaining items
  filtered.push(...appendItems);
 
  return filtered;
}
 
// ============================================================================
// Deep Merge
// ============================================================================
 
/**
 * Deep merge two objects with UIF-specific semantics.
 */
function deepMerge<T extends PlainObject>(
  base: T,
  extension: PlainObject,
  path: string = '',
  onWarning?: WarningHandler,
): T {
  const result: PlainObject = { ...base };
 
  for (const [key, extValue] of Object.entries(extension)) {
    // Skip internal markers
    if (key.startsWith('$')) {
      continue;
    }
 
    const baseValue = base[key];
    const currentPath = path ? `${path}.${key}` : key;
 
    // Skip undefined/null extension values
    if (extValue === undefined || extValue === null) {
      continue;
    }
 
    // New key - just assign
    if (baseValue === undefined) {
      result[key] = extValue;
      continue;
    }
 
    // Both are arrays
    if (Array.isArray(baseValue) && Array.isArray(extValue)) {
      const identifierField = getIdentifierField(currentPath);
      result[key] = identifierField
        ? mergeIdentifiedArrays(baseValue, extValue, identifierField, currentPath, onWarning)
        : extValue; // Primitive array - replace wholesale
      continue;
    }
 
    // Both are objects
    if (isPlainObject(baseValue) && isPlainObject(extValue)) {
      result[key] = deepMerge(baseValue, extValue, currentPath, onWarning);
      continue;
    }
 
    // Type mismatch
    if (typeof baseValue !== typeof extValue) {
      const baseType = Array.isArray(baseValue) ? 'array' : typeof baseValue;
      const extType = Array.isArray(extValue) ? 'array' : typeof extValue;
 
      // Allow scalar to overwrite anything
      if (!isPlainObject(extValue) && !Array.isArray(extValue)) {
        result[key] = extValue;
        continue;
      }
 
      throw new UifMergeError(currentPath, baseType, extType, baseValue, extValue);
    }
 
    // Same type scalars - extension wins
    result[key] = extValue;
  }
 
  return result as T;
}
 
// ============================================================================
// Public API
// ============================================================================
 
/**
 * Merge a UIF system onto a foundation, producing a combined definition.
 *
 * This function implements the UIF merge semantics:
 * - Scalars: System value replaces foundation value
 * - Objects: Deep merge recursively
 * - Identified arrays (states, children, etc.): Merge by identifier
 * - Primitive arrays (restrict): Replace wholesale
 * - `$remove` marker: Delete inherited item
 * - `$before`/`$after` markers: Position new items relative to siblings
 *
 * @param base - The base UIF definition (typically a foundation)
 * @param extension - The extending UIF definition (typically a system)
 * @param options - Merge options including warning handler
 * @returns The merged UIF definition
 *
 * @example
 * ```ts
 * import { merge } from '@fds-uif/core';
 *
 * // Basic usage
 * const merged = merge(foundation, system);
 *
 * // With warning handler for debugging
 * const merged = merge(foundation, system, {
 *   onWarning: (msg, ctx) => console.warn(msg, ctx),
 * });
 * ```
 */
export function merge<T extends PlainObject>(base: T, extension: PlainObject, options: MergeOptions = {}): T {
  return deepMerge(base, extension, '', options.onWarning);
}
 
/**
 * Merge and clean - removes 'extends' property from the result.
 * Use this when producing final resolved UIFs.
 */
export function mergeAndClean<T extends PlainObject>(
  base: T,
  extension: PlainObject,
  options: MergeOptions = {},
): T {
  const merged = merge(base, extension, options);
 
  if (PROP_EXTENDS in merged) {
    const { [PROP_EXTENDS]: _, ...rest } = merged;
    return rest as T;
  }
 
  return merged;
}