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

92.35% Statements 326/353
83.57% Branches 229/274
100% Functions 45/45
95.77% Lines 295/308

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 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228                                                        22x                                       9x   9x 9x     9x 1x       71x   8x 58x 58x 457x 457x         457x 457x   58x     8x               9x   9x   9x 9x 9x 3x 3x   3x       9x             273x   273x 273x   273x 472x 107x   365x     365x     166x               5x               5x             14x 14x 14x   14x 3x 3x     11x 4x 4x 4x 4x   4x         7x                                           22x                                                                     44x   44x 68x   68x       68x 68x   68x 68x 13x           55x         68x 1x                                       31x 31x   31x     31x 31x   31x   31x     7x 12x 12x   12x   12x 12x 12x                                           32x   32x 1x     31x   217x 31x   186x   186x 31x         31x                                                   4x   4x 2x 2x                                                             4x 4x                   22x 14x 14x 20x 20x 20x     14x               22x 12x 16x 16x 16x 16x 9x                   22x       22x 22x 22x   22x   22x                   5x   5x 2x 2x                                                                         19x 34x   34x       34x 34x 34x   34x 7x 7x                 34x 1x                       22x   22x       22x     22x             22x 88x 18x       22x                         4x   4x 1x 1x                                                                   88x   18x 6x 6x     12x 13x         13x 8x                               25x   25x   25x   25x 2x 3x       25x 1x 1x               25x 4x 7x 7x   7x 7x 7x                                         30x   30x       30x     30x     30x 22x       30x 7x 11x                 30x 5x 5x                 30x 1x               30x 1x             30x                                                                           21x   8x   8x 8x   8x 8x 5x 5x     8x 8x 8x 8x     8x         11x   11x 19x 19x 21x       11x               7x     7x           11x 11x 19x 19x 21x 10x 10x 10x 10x   10x                 11x               5x 2x                     5x 3x                         11x 11x   11x 10x 5x 5x 5x 5x 5x                                                         3x   2x         1x                     2x         1x                         11x 5x 5x 8x     5x 8x 3x             22x   22x       22x 22x   22x 11x     11x   11x 11x   11x 7x                       5x     5x   5x 1x 1x                                                                             10x 1x                     10x 1x                           2x 2x 1x 1x 1x   2x       10x 10x 2x                             11x 1x 1x                                       10x 2x 2x                             2x   2x 1x                       11x   11x 11x   11x 11x 11x 11x 11x   11x                                                                         3x     3x 3x 3x             3x 2x     2x 2x     2x   2x 2x      
/**
 * @fds-uif/core - Validation Utilities
 *
 * Utilities for validating UIF definitions beyond schema validation.
 * These checks ensure semantic correctness after merging.
 */
 
import {
  UifConflictingMarkersError,
  UifDuplicateIdentifierError,
  UifInvalidStateReferenceError,
  UifVariantConflictError,
} from './errors.js';
import { IDENTIFIED_ARRAYS, MARKER_AFTER, MARKER_BEFORE } from './constants.js';
import type {
  PlainObject,
  ValidationError,
  ValidationOptions,
  ValidationResult,
  Variant,
  VariantChildChange,
} from './types.js';
 
// ============================================================================
// Constants
// ============================================================================
 
/** Error codes for validation errors */
export const ValidationErrorCode = {
  DUPLICATE_IDENTIFIER: 'UIF_DUPLICATE_IDENTIFIER',
  INVALID_STATE_REFERENCE: 'UIF_INVALID_STATE_REFERENCE',
  CONFLICTING_MARKERS: 'UIF_CONFLICTING_MARKERS',
  VARIANT_CONFLICT: 'UIF_VARIANT_CONFLICT',
  INVALID_EXTENSIONS: 'UIF_INVALID_EXTENSIONS',
} as const;
 
// ============================================================================
// Utility Functions
// ============================================================================
 
/**
 * Calculate Levenshtein distance between two strings.
 * Used for "did you mean?" suggestions.
 *
 * Optimized with early termination when distance exceeds threshold.
 */
function levenshteinDistance(a: string, b: string, maxDistance?: number): number {
  // Early termination for identical strings
  Iif (a === b) return 0;
 
  const aLen = a.length;
  const bLen = b.length;
 
  // Early termination if length difference exceeds max distance
  if (maxDistance !== undefined && Math.abs(aLen - bLen) > maxDistance) {
    return maxDistance + 1;
  }
 
  // Use single array instead of matrix for memory efficiency
  const row: number[] = Array.from({ length: bLen + 1 }, (_, i) => i);
 
  for (let i = 1; i <= aLen; i++) {
    let prev = i;
    for (let j = 1; j <= bLen; j++) {
      const cost = a[i - 1] === b[j - 1] ? 0 : 1;
      const current = Math.min(
        row[j] + 1, // deletion
        prev + 1, // insertion
        row[j - 1] + cost, // substitution
      );
      row[j - 1] = prev;
      prev = current;
    }
    row[bLen] = prev;
  }
 
  return row[bLen];
}
 
/**
 * Find the closest match for a string from a list of candidates.
 * Returns undefined if no close match is found.
 */
function findClosestMatch(target: string, candidates: string[], maxDistance = 2): string | undefined {
  const targetLower = target.toLowerCase();
  let bestMatch: string | undefined;
  let bestDistance = maxDistance + 1;
 
  for (const candidate of candidates) {
    const distance = levenshteinDistance(targetLower, candidate.toLowerCase(), bestDistance);
    if (distance < bestDistance) {
      bestDistance = distance;
      bestMatch = candidate;
      // Early exit if we found an exact match
      Iif (distance === 0) break;
    }
  }
 
  return bestDistance <= maxDistance ? bestMatch : undefined;
}
 
/**
 * Get a value from a nested object using a dot-notation path.
 */
function getByPath(obj: unknown, path: string): unknown {
  Iif (!path) return obj;
 
  const parts = path.split('.');
  let current: unknown = obj;
 
  for (const part of parts) {
    if (current === null || current === undefined) {
      return undefined;
    }
    Iif (typeof current !== 'object') {
      return undefined;
    }
    current = (current as Record<string, unknown>)[part];
  }
 
  return current;
}
 
/**
 * Format a path for user-friendly display.
 * Converts "structure.children[0].name" to "structure > children[0] > name"
 */
function formatPathForDisplay(path: string): string {
  return path.replaceAll('.', ' > ').replaceAll(/\[(\d+)\]/g, '[$1]');
}
 
/**
 * Format the path line for error messages.
 * Notes that this is a path in the merged UIF, not a source file location.
 */
function formatPathLine(path: string): string {
  return `Path (in merged UIF): ${formatPathForDisplay(path)}`;
}
 
/**
 * Deep equality check for values (more reliable than JSON.stringify).
 */
function deepEqual(a: unknown, b: unknown): boolean {
  Iif (a === b) return true;
  Iif (a === null || b === null) return false;
  Iif (typeof a !== typeof b) return false;
 
  if (Array.isArray(a) && Array.isArray(b)) {
    Iif (a.length !== b.length) return false;
    return a.every((val, i) => deepEqual(val, b[i]));
  }
 
  if (typeof a === 'object' && typeof b === 'object') {
    const aKeys = Object.keys(a);
    const bKeys = Object.keys(b);
    Iif (aKeys.length !== bKeys.length) return false;
    return aKeys.every(
      (key) =>
        Object.hasOwn(b, key) &&
        deepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),
    );
  }
 
  return false;
}
 
// ============================================================================
// Identifier Validation
// ============================================================================
 
/**
 * Configuration for identifier validation.
 */
interface IdentifierConfig {
  /** JSON path pattern to the array */
  path: string;
  /** The field used as identifier */
  field: string;
  /** Whether to validate recursively (for nested children) */
  recursive?: boolean;
}
 
/**
 * All identified arrays in UIF and their configuration.
 */
const IDENTIFIER_CONFIGS: IdentifierConfig[] = [
  { path: 'states', field: IDENTIFIED_ARRAYS.states },
  { path: 'structure.modifiers', field: IDENTIFIED_ARRAYS.modifiers },
  { path: 'structure.variants', field: IDENTIFIED_ARRAYS.variants },
  { path: 'structure.variants.*.options', field: IDENTIFIED_ARRAYS.options },
  { path: 'stateClasses', field: IDENTIFIED_ARRAYS.stateClasses },
  { path: 'structure.children', field: IDENTIFIED_ARRAYS.children, recursive: true },
  { path: 'accessibility.requirements', field: IDENTIFIED_ARRAYS.requirements },
];
 
/**
 * Result of identifier validation.
 */
export interface IdentifierValidationResult {
  /** Whether all identifiers are valid (no duplicates) */
  valid: boolean;
  /** List of duplicate identifier errors */
  errors: Array<{
    path: string;
    field: string;
    duplicate: string;
  }>;
}
 
/**
 * Check an array for duplicate identifiers.
 */
function checkArrayDuplicates(
  arr: unknown[],
  field: string,
  path: string,
  errors: IdentifierValidationResult['errors'],
  recursive: boolean = false,
  childrenField: string = 'children',
): void {
  const seen = new Set<string>();
 
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
 
    Iif (typeof item !== 'object' || item === null) {
      continue;
    }
 
    const record = item as Record<string, unknown>;
    const identifier = record[field];
 
    Eif (typeof identifier === 'string') {
      if (seen.has(identifier)) {
        errors.push({
          path: `${path}[${i}]`,
          field,
          duplicate: identifier,
        });
      } else {
        seen.add(identifier);
      }
    }
 
    // Recursively check children if configured
    if (recursive && Array.isArray(record[childrenField])) {
      checkArrayDuplicates(
        record[childrenField] as unknown[],
        field,
        `${path}[${i}].${childrenField}`,
        errors,
        recursive,
        childrenField,
      );
    }
  }
}
 
/**
 * Validate paths containing wildcards.
 */
function validateWildcardPath(
  uif: unknown,
  config: IdentifierConfig,
  errors: IdentifierValidationResult['errors'],
): void {
  const parts = config.path.split('.');
  const wildcardIndex = parts.indexOf('*');
 
  Iif (wildcardIndex === -1) return;
 
  // Get path up to wildcard
  const prePath = parts.slice(0, wildcardIndex).join('.');
  const postPath = parts.slice(wildcardIndex + 1).join('.');
 
  const preValue = prePath ? getByPath(uif, prePath) : uif;
 
  if (!Array.isArray(preValue)) return;
 
  // Iterate over array items
  for (let i = 0; i < preValue.length; i++) {
    const item = preValue[i];
    const itemPath = prePath ? `${prePath}[${i}]` : `[${i}]`;
 
    const targetArr = postPath ? getByPath(item, postPath) : item;
 
    Eif (Array.isArray(targetArr)) {
      const fullPath = postPath ? `${itemPath}.${postPath}` : itemPath;
      checkArrayDuplicates(targetArr, config.field, fullPath, errors, config.recursive);
    }
  }
}
 
/**
 * Validate that all identified arrays in a UIF have unique identifiers.
 *
 * @param uif - The UIF definition to validate
 * @returns Validation result with any duplicate errors
 *
 * @example
 * ```ts
 * import { validateIdentifiers } from '@fds-uif/core';
 *
 * const result = validateIdentifiers(myUif);
 * if (!result.valid) {
 *   console.error('Duplicate identifiers found:', result.errors);
 * }
 * ```
 */
export function validateIdentifiers(uif: unknown): IdentifierValidationResult {
  const errors: IdentifierValidationResult['errors'] = [];
 
  if (typeof uif !== 'object' || uif === null) {
    return { valid: true, errors: [] };
  }
 
  for (const config of IDENTIFIER_CONFIGS) {
    // Handle paths with wildcards (e.g., 'structure.variants.*.options')
    if (config.path.includes('*')) {
      validateWildcardPath(uif, config, errors);
    } else {
      const arr = getByPath(uif, config.path);
 
      if (Array.isArray(arr)) {
        checkArrayDuplicates(arr, config.field, config.path, errors, config.recursive);
      }
    }
  }
 
  return {
    valid: errors.length === 0,
    errors,
  };
}
 
/**
 * Validate identifiers and throw if duplicates are found.
 *
 * @param uif - The UIF definition to validate
 * @throws {UifDuplicateIdentifierError} If duplicate identifiers are found
 *
 * @example
 * ```ts
 * import { validateIdentifiersOrThrow } from '@fds-uif/core';
 *
 * try {
 *   validateIdentifiersOrThrow(myUif);
 * } catch (error) {
 *   if (error instanceof UifDuplicateIdentifierError) {
 *     console.error('Duplicate found:', error.duplicateValue);
 *   }
 * }
 * ```
 */
export function validateIdentifiersOrThrow(uif: unknown): void {
  const result = validateIdentifiers(uif);
 
  if (!result.valid && result.errors.length > 0) {
    const firstError = result.errors[0];
    throw new UifDuplicateIdentifierError(firstError.path, firstError.field, firstError.duplicate);
  }
}
 
// ============================================================================
// State Reference Validation
// ============================================================================
 
/**
 * Result of state reference validation.
 */
export interface StateReferenceValidationResult {
  /** Whether all state references are valid */
  valid: boolean;
  /** Invalid state references with suggestions */
  errors: Array<{
    state: string;
    path: string;
    suggestion?: string;
  }>;
  /** Available states for reference */
  availableStates: string[];
}
 
/**
 * Validate that stateClasses reference valid states.
 *
 * @param uif - The UIF definition to validate
 * @returns Array of invalid state references (for backwards compatibility)
 */
export function validateStateReferences(uif: unknown): string[] {
  const result = validateStateReferencesDetailed(uif);
  return result.errors.map((e) => e.state);
}
 
/**
 * Validate state references with detailed results.
 *
 * @param uif - The UIF definition to validate
 * @returns Detailed validation result with suggestions
 */
function collectStateNames(states: unknown): string[] {
  if (!Array.isArray(states)) return [];
  const names: string[] = [];
  for (const state of states) {
    Eif (typeof state === 'object' && state !== null) {
      const name = (state as Record<string, unknown>).name;
      Eif (typeof name === 'string') names.push(name);
    }
  }
  return names;
}
 
function checkStateClassReferences(
  stateClasses: unknown,
  stateNames: string[],
  errors: StateReferenceValidationResult['errors'],
): void {
  if (!Array.isArray(stateClasses)) return;
  for (let i = 0; i < stateClasses.length; i++) {
    const sc = stateClasses[i];
    Iif (typeof sc !== 'object' || sc === null) continue;
    const stateRef = (sc as Record<string, unknown>).state;
    if (typeof stateRef === 'string' && !stateNames.includes(stateRef)) {
      errors.push({
        state: stateRef,
        path: `stateClasses[${i}]`,
        suggestion: findClosestMatch(stateRef, stateNames),
      });
    }
  }
}
 
export function validateStateReferencesDetailed(uif: unknown): StateReferenceValidationResult {
  Iif (typeof uif !== 'object' || uif === null) {
    return { valid: true, errors: [], availableStates: [] };
  }
 
  const record = uif as Record<string, unknown>;
  const errors: StateReferenceValidationResult['errors'] = [];
  const stateNames = collectStateNames(record.states);
 
  checkStateClassReferences(record.stateClasses, stateNames, errors);
 
  return { valid: errors.length === 0, errors, availableStates: stateNames };
}
 
/**
 * Validate state references and throw if invalid.
 *
 * @param uif - The UIF definition to validate
 * @throws {UifInvalidStateReferenceError} If invalid state references are found
 */
export function validateStateReferencesOrThrow(uif: unknown): void {
  const result = validateStateReferencesDetailed(uif);
 
  if (!result.valid && result.errors.length > 0) {
    const firstError = result.errors[0];
    throw new UifInvalidStateReferenceError(
      firstError.path,
      firstError.state,
      result.availableStates,
      firstError.suggestion,
    );
  }
}
 
// ============================================================================
// Marker Validation
// ============================================================================
 
/**
 * Result of marker validation.
 */
export interface MarkerValidationResult {
  /** Whether all markers are valid */
  valid: boolean;
  /** Items with conflicting markers */
  errors: Array<{
    path: string;
    identifier?: string;
    beforeValue: string;
    afterValue: string;
  }>;
}
 
/**
 * Validate an array for items with conflicting $before/$after markers.
 */
function checkArrayMarkers(
  arr: unknown[],
  path: string,
  identifierField: string | undefined,
  errors: MarkerValidationResult['errors'],
): void {
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
 
    Iif (typeof item !== 'object' || item === null) {
      continue;
    }
 
    const record = item as Record<string, unknown>;
    const hasBefore = typeof record[MARKER_BEFORE] === 'string';
    const hasAfter = typeof record[MARKER_AFTER] === 'string';
 
    if (hasBefore && hasAfter) {
      const identifier = identifierField ? (record[identifierField] as string) : undefined;
      errors.push({
        path: `${path}[${i}]`,
        identifier,
        beforeValue: record[MARKER_BEFORE] as string,
        afterValue: record[MARKER_AFTER] as string,
      });
    }
 
    // Recursively check children
    if (Array.isArray(record.children)) {
      checkArrayMarkers(record.children as unknown[], `${path}[${i}].children`, 'name', errors);
    }
  }
}
 
/**
 * Validate that no items have both $before and $after markers.
 *
 * @param uif - The UIF definition to validate
 * @returns Validation result
 */
export function validateMarkers(uif: unknown): MarkerValidationResult {
  const errors: MarkerValidationResult['errors'] = [];
 
  Iif (typeof uif !== 'object' || uif === null) {
    return { valid: true, errors: [] };
  }
 
  const record = uif as Record<string, unknown>;
 
  // Check all identified arrays that can have markers
  const arraysToCheck = [
    { path: 'states', arr: record.states, field: 'name' },
    { path: 'structure.modifiers', arr: getByPath(record, 'structure.modifiers'), field: 'name' },
    { path: 'structure.children', arr: getByPath(record, 'structure.children'), field: 'name' },
    { path: 'stateClasses', arr: record.stateClasses, field: 'state' },
  ];
 
  for (const { path, arr, field } of arraysToCheck) {
    if (Array.isArray(arr)) {
      checkArrayMarkers(arr, path, field, errors);
    }
  }
 
  return {
    valid: errors.length === 0,
    errors,
  };
}
 
/**
 * Validate markers and throw if conflicts are found.
 *
 * @param uif - The UIF definition to validate
 * @throws {UifConflictingMarkersError} If conflicting markers are found
 */
export function validateMarkersOrThrow(uif: unknown): void {
  const result = validateMarkers(uif);
 
  if (!result.valid && result.errors.length > 0) {
    const firstError = result.errors[0];
    throw new UifConflictingMarkersError(
      firstError.path,
      firstError.identifier,
      firstError.beforeValue,
      firstError.afterValue,
    );
  }
}
 
// ============================================================================
// Extensions Validation
// ============================================================================
 
/**
 * Result of extensions validation.
 */
export interface ExtensionsValidationResult {
  /** Whether all extensions are structurally valid */
  valid: boolean;
  /** Structural errors found in extensions */
  errors: Array<{
    path: string;
    message: string;
  }>;
}
 
/**
 * Validate a single extensions object.
 */
function checkExtensions(
  extensions: unknown,
  path: string,
  errors: ExtensionsValidationResult['errors'],
): void {
  if (extensions === undefined) return;
 
  if (typeof extensions !== 'object' || extensions === null || Array.isArray(extensions)) {
    errors.push({ path, message: 'extensions must be a plain object' });
    return;
  }
 
  for (const [key, value] of Object.entries(extensions as Record<string, unknown>)) {
    Iif (typeof key !== 'string' || key.length === 0) {
      errors.push({ path: `${path}[""]`, message: 'Namespace key must be a non-empty string' });
      continue;
    }
 
    if (typeof value !== 'object' || value === null || Array.isArray(value)) {
      errors.push({
        path: `${path}["${key}"]`,
        message: `Namespace value for "${key}" must be a plain object`,
      });
    }
  }
}
 
/**
 * Recursively walk a UIF structure tree collecting extensions for validation.
 */
function walkStructureExtensions(
  node: unknown,
  path: string,
  errors: ExtensionsValidationResult['errors'],
): void {
  Iif (typeof node !== 'object' || node === null) return;
 
  const record = node as Record<string, unknown>;
 
  checkExtensions(record.extensions, `${path}.extensions`, errors);
 
  if (Array.isArray(record.children)) {
    for (let i = 0; i < record.children.length; i++) {
      walkStructureExtensions(record.children[i], `${path}.children[${i}]`, errors);
    }
  }
 
  if (Array.isArray(record.modifiers)) {
    for (let i = 0; i < record.modifiers.length; i++) {
      checkExtensions(
        (record.modifiers[i] as Record<string, unknown>)?.extensions,
        `${path}.modifiers[${i}].extensions`,
        errors,
      );
    }
  }
 
  if (Array.isArray(record.variants)) {
    for (let i = 0; i < record.variants.length; i++) {
      const variant = record.variants[i] as Record<string, unknown>;
      checkExtensions(variant?.extensions, `${path}.variants[${i}].extensions`, errors);
 
      Eif (Array.isArray(variant?.options)) {
        for (let j = 0; j < variant.options.length; j++) {
          checkExtensions(
            (variant.options[j] as Record<string, unknown>)?.extensions,
            `${path}.variants[${i}].options[${j}].extensions`,
            errors,
          );
        }
      }
    }
  }
}
 
/**
 * Validate all extensions in a UIF definition.
 *
 * Checks structural rules per the RFC:
 * 1. extensions must be a plain object if present
 * 2. Every key must be a non-empty string
 * 3. Every namespace value must be a plain object
 * 4. No inspection of namespace contents
 */
export function validateExtensions(uif: unknown): ExtensionsValidationResult {
  const errors: ExtensionsValidationResult['errors'] = [];
 
  Iif (typeof uif !== 'object' || uif === null) {
    return { valid: true, errors: [] };
  }
 
  const record = uif as Record<string, unknown>;
 
  // Root-level extensions
  checkExtensions(record.extensions, 'extensions', errors);
 
  // Structure tree
  if (record.structure) {
    walkStructureExtensions(record.structure, 'structure', errors);
  }
 
  // States
  if (Array.isArray(record.states)) {
    for (let i = 0; i < record.states.length; i++) {
      checkExtensions(
        (record.states[i] as Record<string, unknown>)?.extensions,
        `states[${i}].extensions`,
        errors,
      );
    }
  }
 
  // State classes
  if (Array.isArray(record.stateClasses)) {
    for (let i = 0; i < record.stateClasses.length; i++) {
      checkExtensions(
        (record.stateClasses[i] as Record<string, unknown>)?.extensions,
        `stateClasses[${i}].extensions`,
        errors,
      );
    }
  }
 
  // Accessibility
  if (record.accessibility) {
    checkExtensions(
      (record.accessibility as Record<string, unknown>)?.extensions,
      'accessibility.extensions',
      errors,
    );
  }
 
  // Composition
  if (record.composition) {
    checkExtensions(
      (record.composition as Record<string, unknown>)?.extensions,
      'composition.extensions',
      errors,
    );
  }
 
  return {
    valid: errors.length === 0,
    errors,
  };
}
 
// ============================================================================
// Variant Conflict Detection
// ============================================================================
 
/**
 * Result of variant conflict validation.
 */
export interface VariantConflictResult {
  /** Whether there are no conflicts */
  valid: boolean;
  /** Detected conflicts */
  errors: Array<{
    variant1: string;
    variant2: string;
    childName: string;
    property: string;
    value1: unknown;
    value2: unknown;
    severity: 'error' | 'warning';
  }>;
}
 
type ChildChangeMap = Map<
  string,
  Map<string, Array<{ variant: string; option: string; changes: VariantChildChange }>>
>;
 
function recordOptionChildChanges(
  variantName: string,
  option: { value: string; children?: VariantChildChange[] },
  childChanges: ChildChangeMap,
): void {
  if (!option.children) return;
 
  const key = `${variantName}:${option.value}`;
 
  for (const child of option.children) {
    Iif (!child.name) continue;
 
    let childMap = childChanges.get(child.name);
    if (!childMap) {
      childMap = new Map();
      childChanges.set(child.name, childMap);
    }
 
    let entries = childMap.get(key);
    Eif (!entries) {
      entries = [];
      childMap.set(key, entries);
    }
 
    entries.push({ variant: variantName, option: option.value, changes: child });
  }
}
 
function extractVariantChildChanges(variants: Variant[]): ChildChangeMap {
  const childChanges: ChildChangeMap = new Map();
 
  for (const variant of variants) {
    Iif (!variant.options) continue;
    for (const option of variant.options) {
      recordOptionChildChanges(variant.name, option, childChanges);
    }
  }
 
  return childChanges;
}
 
/**
 * Check if two values conflict (are different).
 * Returns false if either value is undefined (no conflict with absence).
 */
function valuesConflict(val1: unknown, val2: unknown): boolean {
  Iif (val1 === undefined || val2 === undefined) {
    return false;
  }
  return !deepEqual(val1, val2);
}
 
type RootChange = { variant: string; option: string; restrict?: string[]; slots?: Record<string, boolean> };
 
function extractRootChanges(variants: Variant[]): Map<string, RootChange[]> {
  const changes = new Map<string, RootChange[]>();
  for (const variant of variants) {
    Iif (!variant.options) continue;
    for (const option of variant.options) {
      if (option.restrict || option.slots) {
        let list = changes.get(variant.name);
        Eif (!list) {
          list = [];
          changes.set(variant.name, list);
        }
        list.push({
          variant: variant.name,
          option: option.value,
          restrict: option.restrict,
          slots: option.slots,
        });
      }
    }
  }
  return changes;
}
 
function checkRootChangeConflict(
  c1: RootChange,
  c2: RootChange,
  errors: VariantConflictResult['errors'],
): void {
  if (c1.restrict && c2.restrict && valuesConflict(c1.restrict, c2.restrict)) {
    errors.push({
      variant1: `${c1.variant}:${c1.option}`,
      variant2: `${c2.variant}:${c2.option}`,
      childName: '(root)',
      property: 'restrict',
      value1: c1.restrict,
      value2: c2.restrict,
      severity: 'error',
    });
  }
 
  if (c1.slots && c2.slots && valuesConflict(c1.slots, c2.slots)) {
    errors.push({
      variant1: `${c1.variant}:${c1.option}`,
      variant2: `${c2.variant}:${c2.option}`,
      childName: '(root)',
      property: 'slots',
      value1: c1.slots,
      value2: c2.slots,
      severity: 'warning',
    });
  }
}
 
function detectRootConflicts(variants: Variant[], errors: VariantConflictResult['errors']): void {
  const rootChanges = extractRootChanges(variants);
  const names = Array.from(rootChanges.keys());
 
  for (let i = 0; i < names.length; i++) {
    for (let j = i + 1; j < names.length; j++) {
      const changes1 = rootChanges.get(names[i])!;
      const changes2 = rootChanges.get(names[j])!;
      for (const c1 of changes1) {
        for (const c2 of changes2) {
          checkRootChangeConflict(c1, c2, errors);
        }
      }
    }
  }
}
 
/**
 * Validate variants for conflicting structural changes.
 *
 * According to the RFC, conflicts occur when:
 * - Two variants modify the same child with incompatible values (Error)
 * - Variant disables a slot that another variant requires (Warning)
 * - Variants specify incompatible element types (Error)
 *
 * Note: Variants within the same variant group are mutually exclusive
 * and won't trigger conflicts against each other.
 *
 * @param uif - The UIF definition to validate
 * @returns Validation result with detected conflicts
 */
type ChildModification = { variant: string; option: string; changes: VariantChildChange };
 
function checkChildModConflict(
  mod1: ChildModification,
  mod2: ChildModification,
  childName: string,
  errors: VariantConflictResult['errors'],
): void {
  if (mod1.variant === mod2.variant) return;
 
  if (
    mod1.changes.restrict !== undefined &&
    mod2.changes.restrict !== undefined &&
    valuesConflict(mod1.changes.restrict, mod2.changes.restrict)
  ) {
    errors.push({
      variant1: `${mod1.variant}:${mod1.option}`,
      variant2: `${mod2.variant}:${mod2.option}`,
      childName,
      property: 'restrict',
      value1: mod1.changes.restrict,
      value2: mod2.changes.restrict,
      severity: 'error',
    });
  }
 
  if (
    mod1.changes.slots !== undefined &&
    mod2.changes.slots !== undefined &&
    valuesConflict(mod1.changes.slots, mod2.changes.slots)
  ) {
    errors.push({
      variant1: `${mod1.variant}:${mod1.option}`,
      variant2: `${mod2.variant}:${mod2.option}`,
      childName,
      property: 'slots',
      value1: mod1.changes.slots,
      value2: mod2.changes.slots,
      severity: 'warning',
    });
  }
}
 
function detectChildConflicts(childChanges: ChildChangeMap, errors: VariantConflictResult['errors']): void {
  for (const [childName, modifications] of childChanges) {
    const allMods: ChildModification[] = [];
    for (const mods of modifications.values()) {
      allMods.push(...mods);
    }
 
    for (let i = 0; i < allMods.length; i++) {
      for (let j = i + 1; j < allMods.length; j++) {
        checkChildModConflict(allMods[i], allMods[j], childName, errors);
      }
    }
  }
}
 
export function validateVariantConflicts(uif: unknown): VariantConflictResult {
  const errors: VariantConflictResult['errors'] = [];
 
  Iif (typeof uif !== 'object' || uif === null) {
    return { valid: true, errors: [] };
  }
 
  const record = uif as PlainObject;
  const structure = record.structure as PlainObject | undefined;
 
  if (!structure || !Array.isArray(structure.variants)) {
    return { valid: true, errors: [] };
  }
 
  const variants = structure.variants as Variant[];
 
  detectChildConflicts(extractVariantChildChanges(variants), errors);
  detectRootConflicts(variants, errors);
 
  return {
    valid: errors.filter((e) => e.severity === 'error').length === 0,
    errors,
  };
}
 
/**
 * Validate variant conflicts and throw if errors are found.
 *
 * @param uif - The UIF definition to validate
 * @throws {UifVariantConflictError} If variant conflicts are found
 */
export function validateVariantConflictsOrThrow(uif: unknown): void {
  const result = validateVariantConflicts(uif);
 
  // Only throw for errors, not warnings
  const errorConflicts = result.errors.filter((e) => e.severity === 'error');
 
  if (errorConflicts.length > 0) {
    const firstError = errorConflicts[0];
    throw new UifVariantConflictError(
      'structure.variants',
      firstError.variant1,
      firstError.variant2,
      firstError.property,
      firstError.childName === '(root)' ? undefined : firstError.childName,
      firstError.value1,
      firstError.value2,
    );
  }
}
 
// ============================================================================
// Comprehensive Validation
// ============================================================================
 
/**
 * Comprehensive UIF validation combining all checks.
 *
 * @param uif - The UIF definition to validate
 * @param options - Validation options
 * @returns Combined validation result
 *
 * @example
 * ```ts
 * import { validateUif } from '@fds-uif/core';
 *
 * const result = validateUif(myUif);
 *
 * if (!result.valid) {
 *   console.error('Validation errors:', result.errors);
 * }
 *
 * if (result.warnings.length > 0) {
 *   console.warn('Validation warnings:', result.warnings);
 * }
 * ```
 */
function collectExtensionsErrors(uif: unknown, errors: ValidationError[]): void {
  for (const error of validateExtensions(uif).errors) {
    errors.push({
      code: ValidationErrorCode.INVALID_EXTENSIONS,
      message: `${error.message}\n\n  ${formatPathLine(error.path)}`,
      path: error.path,
      severity: 'error',
      details: { message: error.message },
    });
  }
}
 
function collectIdentifierErrors(uif: unknown, errors: ValidationError[]): void {
  for (const error of validateIdentifiers(uif).errors) {
    errors.push({
      code: ValidationErrorCode.DUPLICATE_IDENTIFIER,
      message: `Duplicate ${error.field} "${error.duplicate}"\n\n  ${formatPathLine(error.path)}`,
      path: error.path,
      severity: 'error',
      details: { field: error.field, duplicate: error.duplicate },
    });
  }
}
 
function formatStateRefMessage(
  error: { state: string; path: string; suggestion?: string },
  availableStates: string[],
): string {
  let message = `Unknown state "${error.state}"`;
  if (error.suggestion) {
    message += `. Did you mean "${error.suggestion}"?`;
  } else if (EavailableStates.length > 0) {
    message += `\n\n  Available states: ${availableStates.join(', ')}`;
  }
  return `${message}\n\n  ${formatPathLine(error.path)}`;
}
 
function collectStateRefErrors(uif: unknown, errors: ValidationError[]): void {
  const stateResult = validateStateReferencesDetailed(uif);
  for (const error of stateResult.errors) {
    errors.push({
      code: ValidationErrorCode.INVALID_STATE_REFERENCE,
      message: formatStateRefMessage(error, stateResult.availableStates),
      path: error.path,
      severity: 'error',
      suggestion: error.suggestion,
      details: {
        invalidState: error.state,
        availableStates: stateResult.availableStates,
      },
    });
  }
}
 
function collectMarkerErrors(uif: unknown, errors: ValidationError[]): void {
  for (const error of validateMarkers(uif).errors) {
    const identifier = error.identifier ? ` (${error.identifier})` : '';
    errors.push({
      code: ValidationErrorCode.CONFLICTING_MARKERS,
      message: `Item${identifier} has both $before and $after markers\n\n  $before: "${error.beforeValue}"\n  $after: "${error.afterValue}"\n\n  ${formatPathLine(error.path)}`,
      path: error.path,
      severity: 'error',
      details: {
        identifier: error.identifier,
        beforeValue: error.beforeValue,
        afterValue: error.afterValue,
      },
    });
  }
}
 
function collectVariantConflictErrors(
  uif: unknown,
  errors: ValidationError[],
  warnings: ValidationError[],
  includeWarnings: boolean,
): void {
  for (const conflict of validateVariantConflicts(uif).errors) {
    const location = conflict.childName === '(root)' ? 'root structure' : `child "${conflict.childName}"`;
    const item: ValidationError = {
      code: ValidationErrorCode.VARIANT_CONFLICT,
      message: `Variant conflict on "${conflict.property}"\n\n  ${conflict.variant1}: ${JSON.stringify(conflict.value1)}\n  ${conflict.variant2}: ${JSON.stringify(conflict.value2)}\n\n  Location: ${location}`,
      path: 'structure.variants',
      severity: conflict.severity,
      details: {
        variant1: conflict.variant1,
        variant2: conflict.variant2,
        childName: conflict.childName,
        property: conflict.property,
        value1: conflict.value1,
        value2: conflict.value2,
      },
    };
 
    Iif (conflict.severity === 'error') {
      errors.push(item);
    } else if (includeWarnings) {
      warnings.push(item);
    }
  }
}
 
export function validateUif(uif: unknown, options: ValidationOptions = {}): ValidationResult {
  const {
    checkIdentifiers = true,
    checkStateReferences = true,
    checkVariantConflicts = true,
    checkExtensions = true,
    includeWarnings = true,
  } = options;
 
  const errors: ValidationError[] = [];
  const warnings: ValidationError[] = [];
 
  if (checkExtensions) collectExtensionsErrors(uif, errors);
  if (checkIdentifiers) collectIdentifierErrors(uif, errors);
  if (checkStateReferences) collectStateRefErrors(uif, errors);
  collectMarkerErrors(uif, errors);
  if (checkVariantConflicts) collectVariantConflictErrors(uif, errors, warnings, includeWarnings);
 
  return {
    valid: errors.length === 0,
    errors,
    warnings,
  };
}
 
/**
 * Validate UIF and throw if errors are found.
 *
 * @param uif - The UIF definition to validate
 * @param options - Validation options
 * @throws {UifDuplicateIdentifierError} If duplicate identifiers are found
 * @throws {UifInvalidStateReferenceError} If invalid state references are found
 * @throws {UifConflictingMarkersError} If conflicting markers are found
 * @throws {UifVariantConflictError} If variant conflicts are found
 *
 * @example
 * ```ts
 * import { validateUifOrThrow, UifError } from '@fds-uif/core';
 *
 * try {
 *   validateUifOrThrow(myUif);
 *   console.log('UIF is valid!');
 * } catch (error) {
 *   if (error instanceof UifError) {
 *     console.error(`Validation failed: ${error.code}`);
 *   }
 * }
 * ```
 */
export function validateUifOrThrow(uif: unknown, options: ValidationOptions = {}): void {
  const {
    checkIdentifiers = true,
    checkStateReferences = true,
    checkVariantConflicts = true,
    checkExtensions = true,
  } = options;
 
  // Extensions validation
  Eif (checkExtensions) {
    const extensionsResult = validateExtensions(uif);
    Iif (!extensionsResult.valid && extensionsResult.errors.length > 0) {
      const firstError = extensionsResult.errors[0];
      throw new Error(`Invalid extensions: ${firstError.message} at ${firstError.path}`);
    }
  }
 
  // Run each validation in order, throwing on first error
  if (checkIdentifiers) {
    validateIdentifiersOrThrow(uif);
  }
 
  Eif (checkStateReferences) {
    validateStateReferencesOrThrow(uif);
  }
 
  validateMarkersOrThrow(uif);
 
  Eif (checkVariantConflicts) {
    validateVariantConflictsOrThrow(uif);
  }
}