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 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 | 822x 91x 731x 731x 54x 48x 45x 53x 43x 43x 43x 43x 306x 306x 10x 10x 42x 42x 42x 84x 84x 84x 84x 1x 83x 83x 41x 41x 41x 41x 41x 41x 41x 54x 54x 54x 1x 1x 1x 53x 5x 5x 48x 3x 3x 45x 2x 2x 43x 38x 38x 5x 41x 41x 41x 5x 5x 2x 2x 2x 2x 2x 3x 41x 41x 41x 3x 3x 41x 5x 5x 5x 5x 5x 5x 14x 9x 1x 1x 8x 5x 8x 8x 5x 10x 5x 5x 5x 5x 5x 5x 5x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 2x 1x 2x 2x 2x 1x 42x 42x 42x 38x 38x 38x 38x 41x 82x 82x 41x 41x 41x 78x 78x 78x 41x 41x 41x 41x 43x 43x 10x 8x 5x 5x 5x 5x 5x 5x 9x 5x 5x 5x 195x 317x 317x 316x 316x 121x 121x 195x 5x 5x 190x 43x 43x 147x 67x 67x 80x 80x 161x 161x 332x 332x 15x 15x 15x 317x 159x 54x 19x 19x 19x 19x | /**
* @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
* - `$wrap` marker: Wrap named siblings inside a new parent node
*/
import { UifDuplicateIdentifierError, UifMergeError } from './errors.js';
import {
IDENTIFIED_ARRAYS,
MARKER_AFTER,
MARKER_BEFORE,
MARKER_REMOVE,
MARKER_WRAP,
MERGE_MARKERS,
PROP_EXTENDS,
PROP_EXTENSIONS,
} from './constants.js';
import type {
AfterMarkerItem,
BeforeMarkerItem,
MergeOptions,
PlainObject,
RemoveMarkerItem,
WarningHandler,
WrapMarkerItem,
} 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';
}
/** Check if an item has the $wrap marker. */
function hasWrapMarker(item: unknown): item is WrapMarkerItem {
return isPlainObject(item) && Array.isArray(item[MARKER_WRAP]);
}
// ============================================================================
// 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.at(-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 {
Eif (isPlainObject(item) && typeof item[identifierField] === 'string') {
return item[identifierField];
}
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, [MARKER_WRAP]: _w, ...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);
Eif (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 WrapItem {
item: PlainObject;
targets: string[];
}
interface CategorizedItems {
removedIds: Set<string>;
positionalInserts: PositionalInsert[];
mergeItems: Array<{ id: string; item: PlainObject }>;
wrapItems: WrapItem[];
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 wrapItems: WrapItem[] = [];
const appendItems: unknown[] = [];
for (const extItem of extension) {
// Non-object items just get appended
Iif (!isPlainObject(extItem)) {
appendItems.push(extItem);
continue;
}
const id = getIdentifier(extItem, identifierField);
// Handle $remove marker
if (hasRemoveMarker(extItem)) {
Eif (id !== undefined) {
removedIds.add(id);
}
continue;
}
// Handle $wrap marker
if (hasWrapMarker(extItem)) {
wrapItems.push({
item: stripMarkers(extItem),
targets: extItem[MARKER_WRAP],
});
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, wrapItems, 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);
Eif (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);
}
}
// ============================================================================
// $wrap Processing
// ============================================================================
/**
* Apply $wrap directives: each wrap item adopts named children from the result
* array into a new parent node, inserting it at the position of the first
* adopted child.
*
* If the wrapper declares its own `children`, the adopted nodes are deep-merged
* into them by name so the system can augment foundation children with classes,
* modifiers, etc.
*/
function applyWrapItems(
items: unknown[],
wrapItems: WrapItem[],
identifierField: string,
path: string,
onWarning?: WarningHandler,
): unknown[] {
if (wrapItems.length === 0) return items;
let result = [...items];
for (const { item: wrapper, targets } of wrapItems) {
let firstIndex = -1;
const adopted: PlainObject[] = [];
const adoptedIndices = new Set<number>();
for (const targetName of targets) {
const idx = result.findIndex((child) => isPlainObject(child) && child[identifierField] === targetName);
if (idx === -1) {
onWarning?.(`$wrap target "${targetName}" not found in children`, {
type: 'unknown',
path,
details: { targetName },
});
continue;
}
if (firstIndex === -1 || idx < firstIndex) {
firstIndex = idx;
}
adopted.push(result[idx] as PlainObject);
adoptedIndices.add(idx);
}
Iif (adopted.length === 0) continue;
// Remove adopted children from the result
result = result.filter((_, i) => !adoptedIndices.has(i));
// Deep-merge adopted children into the wrapper's declared children (if any)
const wrapperChildren = (wrapper.children ?? []) as unknown[];
const mergedChildren = mergeAdoptedChildren(adopted, wrapperChildren, identifierField, path, onWarning);
const wrapperNode: PlainObject = { ...wrapper, children: mergedChildren };
// Clamp insertion index after removals shifted positions
const insertAt = Math.min(firstIndex, result.length);
result.splice(insertAt, 0, wrapperNode);
}
return result;
}
/**
* Merge adopted (foundation) children with the wrapper's declared children.
* Wrapper children that share a name with an adopted child are deep-merged
* (system augments foundation). Adopted children with no wrapper counterpart
* are appended in their original order.
*/
function mergeAdoptedChildren(
adopted: PlainObject[],
wrapperChildren: unknown[],
identifierField: string,
path: string,
onWarning?: WarningHandler,
): unknown[] {
if (wrapperChildren.length === 0) return adopted;
const wrapperIndex = new Map<string, { item: PlainObject; index: number }>();
for (let i = 0; i < wrapperChildren.length; i++) {
const child = wrapperChildren[i];
Eif (isPlainObject(child)) {
const id = getIdentifier(child, identifierField);
Eif (id !== undefined) {
wrapperIndex.set(id, { item: child, index: i });
}
}
}
const result: unknown[] = [];
const usedWrapperIds = new Set<string>();
for (const adoptedChild of adopted) {
const id = getIdentifier(adoptedChild, identifierField);
if (id !== undefined && wrapperIndex.has(id)) {
const wrapperEntry = wrapperIndex.get(id)!;
result.push(deepMerge(adoptedChild, wrapperEntry.item, `${path}[${id}]`, onWarning));
usedWrapperIds.add(id);
} else E{
result.push(adoptedChild);
}
}
// Append any wrapper-declared children that didn't match an adopted child
for (const child of wrapperChildren) {
Eif (isPlainObject(child)) {
const id = getIdentifier(child, identifierField);
Iif (id !== undefined && !usedWrapperIds.has(id)) {
result.push(child);
}
}
}
return result;
}
// ============================================================================
// 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, wrapItems, appendItems } = categorizeExtensionItems(
extension,
identifierField,
baseIndex,
);
// Apply merges to existing items
for (const { id, item } of mergeItems) {
const existing = baseIndex.get(id);
Eif (existing) {
const merged = deepMerge(existing.item as PlainObject, item, `${path}[${id}]`, onWarning);
result[existing.index] = merged;
}
}
// Remove items marked for removal
let filtered = result.filter((item) => {
const id = getIdentifier(item, identifierField);
return id === undefined || !removedIds.has(id);
});
// Apply $wrap directives
filtered = applyWrapItems(filtered, wrapItems, identifierField, path, onWarning);
// 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);
Eif (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
// ============================================================================
/** Merge two arrays: by identifier if the path is a known identified array, otherwise replace. */
function mergeArrayValues(
baseValue: unknown[],
extValue: unknown[],
currentPath: string,
onWarning?: WarningHandler,
): unknown[] {
const identifierField = getIdentifierField(currentPath);
return identifierField
? mergeIdentifiedArrays(baseValue, extValue, identifierField, currentPath, onWarning)
: extValue; // Primitive array — replace wholesale
}
/**
* Resolve a type-mismatch between base and extension values.
* Scalars may overwrite any base type; object/array mismatches throw.
*/
function resolveTypeMismatch(baseValue: unknown, extValue: unknown, currentPath: string): unknown {
if (!isPlainObject(extValue) && !Array.isArray(extValue)) {
return extValue; // Scalar overwriting anything is allowed
}
const baseType = Array.isArray(baseValue) ? 'array' : typeof baseValue;
const extType = Array.isArray(extValue) ? 'array' : typeof extValue;
throw new UifMergeError(currentPath, baseType, extType, baseValue, extValue);
}
/**
* Normalize a class value (string or string[]) into a flat array of class names.
*/
function toClassArray(value: unknown): string[] {
if (Array.isArray(value))
return value.flatMap((v) => (typeof v === 'string' ? v.split(' ').filter(Boolean) : []));
Eif (typeof value === 'string') return value.split(' ').filter(Boolean);
return [];
}
/**
* Merge two `class` values as a deduplicated union, preserving order (base first, then extension additions).
*/
function mergeClassValues(baseValue: unknown, extValue: unknown): string[] {
const base = toClassArray(baseValue);
const ext = toClassArray(extValue);
const seen = new Set(base);
const result = [...base];
for (const cls of ext) {
if (!seen.has(cls)) {
seen.add(cls);
result.push(cls);
}
}
return result;
}
/** Returns true when the current merge path points to `attributes.static.class`. */
function isStaticClassPath(path: string): boolean {
return path.endsWith('.static.class') || path === 'static.class';
}
/** Apply one extension key onto the result object. */
function mergeKey(
result: PlainObject,
base: PlainObject,
key: string,
extValue: unknown,
currentPath: string,
onWarning?: WarningHandler,
): void {
Iif ((MERGE_MARKERS as readonly string[]).includes(key)) return;
if (extValue === undefined || extValue === null) return;
const baseValue = base[key];
if (baseValue === undefined) {
result[key] = extValue;
return;
}
// Special case: `class` under `attributes.static` — union as deduplicated array
if (isStaticClassPath(currentPath)) {
result[key] = mergeClassValues(baseValue, extValue);
return;
}
if (Array.isArray(baseValue) && Array.isArray(extValue)) {
result[key] = mergeArrayValues(baseValue, extValue, currentPath, onWarning);
return;
}
if (isPlainObject(baseValue) && isPlainObject(extValue)) {
result[key] = deepMerge(baseValue, extValue, currentPath, onWarning);
return;
}
Iif (typeof baseValue !== typeof extValue) {
result[key] = resolveTypeMismatch(baseValue, extValue, currentPath);
return;
}
result[key] = extValue; // Same type — extension wins
}
/**
* 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)) {
const currentPath = path ? `${path}.${key}` : key;
// extensions: shallow-merge by namespace (extension's namespace wins entirely)
if (key === PROP_EXTENSIONS && isPlainObject(extValue)) {
const baseValue = base[key];
result[key] = isPlainObject(baseValue) ? { ...baseValue, ...extValue } : extValue;
continue;
}
mergeKey(result, base, key, extValue, currentPath, onWarning);
}
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);
Eif (PROP_EXTENDS in merged) {
const { [PROP_EXTENDS]: _, ...rest } = merged;
return rest as T;
}
return merged;
}
|