All files / lib/core/renderer domPatch.js

89.32% Statements 1180/1321
80.11% Branches 290/362
97.14% Functions 34/35
89.32% Lines 1180/1321

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 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 323x 323x 646x 644x 323x 323x 323x 323x 4x 4x 319x 323x 256x 256x 256x 256x 256x 256x 6x 6x 6x 6x 6x 6x 6x 6x 6x 24x 24x 24x 24x 24x 24x 24x 24x 24x 6x 6x 6x 6x 6x 6x 6x 6x 6x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 1056x 1056x 83x 83x 1056x 1056x 256x 256x 256x 256x 256x 1055x 1055x     1055x 1055x 2429x 2425x 2425x 2425x 807x 6x 16x 2x 2x 807x 2425x 1055x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 1056x 1056x 1056x 1056x 1056x 1056x 1056x 1056x 1x 1x 1x 1x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1055x 1053x 1053x 1053x 1056x 1056x 256x 256x 256x 256x 256x 256x 256x 256x 256x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 225x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 2023x 2023x 2023x 2023x 6x 2023x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2019x 2019x 2023x 2023x 741x 2023x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 1993x 1993x 2023x 2023x 715x 2023x 20x 20x 20x 20x 20x 1973x 2023x 5x 5x 1968x 1968x 2023x 2023x 2023x 2023x 2023x 1x 2023x 1x 1x 1967x 1967x 2023x 2023x 2023x 2023x   2023x     1967x 1967x 1967x 2023x 914x 914x 906x 906x 914x 1967x 2023x     1967x 1967x 1967x 1967x 1967x 1967x 2020x 1572x 795x 795x 2x 2x 2x 2x 795x 793x 793x 1572x 777x 777x 1572x 1967x 1967x 2019x 2086x 813x 813x         813x 813x 813x 2086x 1273x 1273x 2086x 1967x 1967x 1967x 1967x 2019x 2086x 2086x 2086x 2086x 2086x 20x 20x 20x 2086x 2086x 550x 550x 550x 550x 550x 550x 550x 550x 8x 8x 550x 2086x 1535x 1535x 790x 534x 534x 534x 31x 31x 31x 31x 31x 534x 1535x 745x 745x 1535x 1536x 1x 1x 1x 1x 1x 1x 1x 1x 1x                   1x 1x 1x     1x 1x 1x 1x 1x 2086x 2086x 1967x 1967x 1967x 1967x 2023x   2023x             1967x 1967x 2023x 14x 14x 5x 5x 5x     5x 5x 5x 5x 14x 14x 2023x 256x 256x 256x 256x 256x 256x 256x 256x 1536x 1536x 256x 256x 256x 256x 256x 256x 256x 256x 964x 964x 964x 964x 964x 964x 964x 964x 964x         964x 964x                         964x 964x 964x 911x 911x 31x 31x     31x 1x 1x 31x     31x 911x 964x 964x 964x 899x 899x 899x 899x 23x 23x 8x 7x 7x 8x 23x 15x 9x 9x 9x             9x 15x 15x 899x 876x 876x 876x 876x 34x 34x 34x 34x 1x 1x 1x 1x 1x 1x 34x 876x 16x 2x 2x 16x 876x 899x 964x 256x 256x 256x 256x 256x 256x 256x 328x 328x 328x 328x 328x 328x 256x 256x 256x 256x 256x 256x 256x 328x 328x 336x 336x 308x 7x 7x 3x 3x 7x 4x 4x 7x 308x 336x 328x 256x 256x 256x 256x 256x 256x 256x 790x 790x 481x 13x 13x 4x 4x 12x 9x 9x 13x 481x 790x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 1516x 803x 803x 11x 11x 803x 803x 803x 803x 785x 785x 792x 803x 5x 3x 3x 3x 3x 3x 3x 3x 3x 5x 2x 2x 2x 2x                         2x 2x     2x 2x 2x 1x 1x 2x 2x 2x 803x 787x 787x 785x 785x 961x 961x 785x 787x 787x 803x 713x 1516x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 1774x 1774x 256x 256x 256x 256x 256x 256x 256x 256x 256x 256x 1772x     1772x 1772x 1772x 1772x 1772x 1772x 2x 2x 2x 2x 2x 1x 1x   1x 1x 1x 2x 2x 2x 2x 2x         2x 1772x 1772x 1772x 17x 17x 17x 17x 17x 9x 9x 17x 17x 17x 17x 9x 9x 17x 6x 6x 1x     1x 1x 1x 1x 1x 6x 5x 5x 6x 17x         17x 1772x 1772x 1772x 13x 13x 13x 13x 13x 7x 7x 7x 7x 13x 13x 13x 7x 13x 6x 8x 5x 5x 8x 6x 13x 13x 14x 14x 13x 13x         13x 1772x 1772x 1772x 1772x 1772x 1453x 1453x 10x 10x 10x 10x 10x 10x     10x 10x 9x 9x 9x 9x 9x 1x 1x 1x 8x 8x 8x 8x 8x     8x 8x 9x 8x 8x         8x 8x 8x 9x                 9x 9x 9x 1453x 1772x 1772x 1772x 6x 3x           3x 6x 1772x 5x 5x 1772x 1772x 1772x 142x 142x 46x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 6x 10x 4x 4x 6x 6x 6x 6x 5x 5x 5x         5x 6x 6x 4x 4x 6x 6x 6x 6x 6x 6x 4x 4x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 6x 2x 2x 2x 2x 2x 2x 2x 2x           2x 6x 6x 6x 6x 6x 10x 46x 142x 1772x 1772x 1772x 256x 256x 256x 256x 256x 256x 256x 256x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 256x 256x 256x 256x 256x 256x 256x 256x 51x 51x 51x 51x 52x 5x 5x 52x 51x 51x 256x 256x 256x 256x 256x 256x 256x 3x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 1x 1x 3x 3x 3x 256x 256x 256x 256x 256x 256x 256x 256x 3x       3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 1x 1x 3x 3x 3x 256x 256x 256x 256x 256x 256x 256x 256x 598x 597x 2x 2x 2x 2x 598x 598x 598x 598x 598x     598x 256x 256x 256x 256x 256x 256x 256x 598x 575x 598x 1x 1x 1x 598x 256x 256x 256x 256x 256x 256x 256x 256x 256x 18x 2x 2x 2x 16x 16x 16x 16x 16x 16x 16x 16x 16x   16x 16x 16x 16x 16x 18x 2x 2x       2x 16x 18x 256x 256x 256x 256x 256x 256x 1609x 1579x 1581x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1609x 256x 256x 256x 256x 256x 256x 256x 6x 6x 6x 12x 12x 12x   6x 256x 256x 256x 256x 256x 256x 256x 201x 191x 191x 201x 421x 421x 191x 201x 256x 256x 256x 256x 256x 256x 256x 612x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 612x 256x 256x 256x 256x 256x 256x 1324x 172x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 6x 6x     6x 1324x 256x  
import { AvenxErrorCodes, formatMessage } from '../runtime/AvenxError.js';
import { sanitizeUrlAttribute, isUrlAttribute } from '../security/urlPolicy.js';
import { isEventHandlerAttribute } from '../security/eventAttributes.js';
import { logger } from '../runtime/AvenxLogger.js';
import { HtmlEscaper, SafeHtml } from '../security/escapeHtml.js';
import { isBooleanAttribute } from './constants.js';
import { profile, getComponentProfilingInfo } from '../utils/profiler.js';
import { tracer } from '../trace/tracer.js';
import { traceDomOp, clampDomValue } from '../trace/dom.js';
import { findScope } from './bindingScope.js';
 
const escaper = new HtmlEscaper();
 
/**
 * Compares two class attribute strings as unordered token sets, ignoring extra
 * whitespace and token order, so redundant DOM mutations are skipped when the
 * effective class list is unchanged.
 * @param {string|null} a
 * @param {string|null} b
 * @returns {boolean}
 */
function classTokensEqual(a, b) {
  const tokensOf = (value) => {
    if (value == null) return [];
    return Array.from(new Set(String(value).trim().split(/\s+/).filter(Boolean))).sort();
  };
  const aTokens = tokensOf(a);
  const bTokens = tokensOf(b);
  if (aTokens.length !== bTokens.length) {
    return false;
  }
  return aTokens.every((token, index) => token === bTokens[index]);
}
 
/**
 * Helper to compute transition/animation duration from element computed styles.
 * @param {Element} el
 * @returns {number} duration in ms
 */
function getTransitionDuration(el) {
  if (!el || typeof window === 'undefined' || !window.getComputedStyle) return 0;
  const styles = window.getComputedStyle(el);
  const transitionDelay = styles.transitionDelay || '';
  const transitionDuration = styles.transitionDuration || '';
  const animationDelay = styles.animationDelay || '';
  const animationDuration = styles.animationDuration || '';
 
  const parseTime = (timeStr) => {
    if (!timeStr) return 0;
    const times = timeStr.split(',').map((t) => {
      const match = t.trim().match(/^([0-9.]+)(s|ms)$/i);
      if (!match) return 0;
      const val = parseFloat(match[1]);
      const unit = match[2].toLowerCase();
      return unit === 'ms' ? val : val * 1000;
    });
    return Math.max(...times, 0);
  };
 
  const tDuration = parseTime(transitionDuration);
  const tDelay = parseTime(transitionDelay);
  const aDuration = parseTime(animationDuration);
  const aDelay = parseTime(animationDelay);
 
  return Math.max(tDuration + tDelay, aDuration + aDelay);
}
 
 
/**
 * The DOMParser used for every patch.
 *
 * One instance rather than one per patch. Constructing a DOMParser is not free,
 * and the update path runs it on every component on every flush.
 * @type {DOMParser|null}
 */
let parserInstance = null;
 
/**
 * Returns the shared DOMParser, creating it on first use.
 * @returns {DOMParser} The parser.
 */
function sharedParser() {
  if (!parserInstance) {
    parserInstance = new DOMParser();
  }
  return parserInstance;
}
 
/**
 * Applies the URL policy to every URL-bearing attribute in a parsed tree.
 * @param {Element} root - The root of the freshly parsed render output.
 */
function sanitizeUrlsIn(root) {
  if (!root || typeof root.querySelectorAll !== 'function') {
    return;
  }
  const elements = [root, ...Array.from(root.querySelectorAll('*'))];
  for (const el of elements) {
    if (!el || !el.attributes || typeof el.setAttribute !== 'function') continue;
    // Copied first: sanitising mutates the collection being iterated.
    const attrs = Array.from(el.attributes);
    for (const attr of attrs) {
      if (!isUrlAttribute(attr.name)) continue;
      const safe = sanitizeUrlAttribute(attr.name, attr.value);
      if (safe !== attr.value) {
        el.setAttribute(attr.name, safe);
      }
    }
  }
}
 
/**
 * Handles patching the DOM with new HTML content using a simple diffing algorithm.
 * This approach is more efficient than innerHTML as it preserves existing DOM nodes.
 */
export class DomPatcher {
  /**
   * Patches the target element with the provided HTML.
   * @param {Element} target - The element to patch.
   * @param {string} html - The new HTML content.
   * @param {function(string): any} [resolveExpression] - Function to evaluate expressions.
   * @param {object} [app] - The application context.
   */
  patch(target, html, resolveExpression, app) {
    const { enableProfiling, componentName } = getComponentProfilingInfo(target);
 
    profile(enableProfiling, componentName, 'patch', () => {
      const newDoc = sharedParser().parseFromString(html, 'text/html');
 
      const parserError =
        newDoc && typeof newDoc.querySelector === 'function' ? newDoc.querySelector('parsererror') : null;
      if (parserError) {
        const errorMsg = parserError.textContent ? parserError.textContent.trim() : 'Unknown parsing error';
        logger.warn(formatMessage(AvenxErrorCodes.DOM_PARSING_FAILED, errorMsg, html));
        return;
      }
 
      const newRoot = newDoc.body;
      // Sanitised here, on the whole parsed tree, because this is the one point
      // every rendered node passes through. Doing it only in the attribute-sync
      // path missed the first render, where nodes are inserted wholesale rather
      // than attribute by attribute -- so a javascript: href was live until
      // something else caused that attribute to be re-set.
      sanitizeUrlsIn(newRoot);
      this.flattenTransitionTags(newRoot);
 
      const prevSession = this.sessionElements;
      const prevRoot = this.patchRoot;
      this.sessionElements = new Set();
      this.patchRoot = target;
 
      try {
        this.#patchNode(target, newRoot, true, true, resolveExpression, app);
        this.flushLifecycleHooks(app);
      } finally {
        this.sessionElements = prevSession;
        this.patchRoot = prevRoot;
      }
    });
  }
 
  /**
   * Patches an existing element with a new element structure in-place.
   * @param {Element} oldElement - The existing element.
   * @param {Element} newElement - The new element structure.
   * @param {function(string): any} [resolveExpression] - Function to evaluate expressions.
   * @param {object} [app] - The application context.
   */
  patchElement(oldElement, newElement, resolveExpression, app) {
    const { enableProfiling, componentName } = getComponentProfilingInfo(oldElement);
    profile(enableProfiling, componentName, 'patch', () => {
      this.flattenTransitionTags(newElement);
 
      const prevSession = this.sessionElements;
      const prevRoot = this.patchRoot;
      this.sessionElements = new Set();
      this.patchRoot = oldElement;
 
      try {
        this.#patchNode(oldElement, newElement, false, true, resolveExpression, app);
        this.flushLifecycleHooks(app);
      } finally {
        this.sessionElements = prevSession;
        this.patchRoot = prevRoot;
      }
    });
  }
 
  /**
   * Recursively diffs and patches two nodes.
   * @param {Node} oldNode - The existing DOM node.
   * @param {Node} newNode - The new node structure.
   * @param {boolean} [isBodyWrapper] - Whether the new node is a temporary body wrapper.
   * @param {boolean} [isPatchRoot] - Whether this is the root node of the patching operation.
   * @param {function(string): any} [resolveExpression] - Function to evaluate expressions.
   * @param {object} [app] - The application context.
   * @private
   */
  #patchNode(oldNode, newNode, isBodyWrapper = false, isPatchRoot = false, resolveExpression, app) {
    if (
      !isPatchRoot &&
      oldNode.nodeType === Node.ELEMENT_NODE &&
      oldNode.nodeName === 'SLOT' &&
      oldNode.hasAttribute('data-avenx-transcluded')
    ) {
      if (newNode.nodeType === Node.ELEMENT_NODE) {
        this.#patchAttributes(oldNode, newNode);
        oldNode.setAttribute('data-avenx-transcluded', 'true');
        if (resolveExpression) {
          this.#applyDirectives(oldNode, resolveExpression, app);
        }
      }
      return;
    }
 
    if (
      !isPatchRoot &&
      oldNode.nodeType === Node.ELEMENT_NODE &&
      (oldNode.hasAttribute('data-avenx-comp') || oldNode.hasAttribute('data-avenx-comp-dynamic'))
    ) {
      if (newNode.nodeType === Node.ELEMENT_NODE) {
        this.#patchAttributes(oldNode, newNode);
        const compInstance = oldNode.__avenx_comp_instance;
        if (compInstance && typeof compInstance.__updateTranscludedContent === 'function') {
          compInstance.__updateTranscludedContent(newNode.childNodes);
        }
        if (resolveExpression) {
          this.#applyDirectives(oldNode, resolveExpression, app);
        }
      }
      return;
    }
 
    if (
      !isPatchRoot &&
      oldNode.nodeType === Node.ELEMENT_NODE &&
      (oldNode.tagName.toLowerCase() === 'template' || oldNode.tagName.toLowerCase() === '@for')
    ) {
      if (newNode.nodeType === Node.ELEMENT_NODE) {
        this.#patchAttributes(oldNode, newNode);
      }
      return;
    }
 
    if (!isPatchRoot && oldNode.nodeType === Node.ELEMENT_NODE && oldNode.hasAttribute('data-ax-static')) {
      return;
    }
 
    if (
      !isPatchRoot &&
      oldNode.nodeType === Node.ELEMENT_NODE &&
      newNode.nodeType === Node.ELEMENT_NODE &&
      oldNode.hasAttribute('data-ax-memo') &&
      typeof oldNode.isEqualNode === 'function' &&
      oldNode.isEqualNode(newNode)
    ) {
      return;
    }
 
    if (
      !isPatchRoot &&
      oldNode.nodeType === Node.ELEMENT_NODE &&
      oldNode.hasAttribute('data-ax-deadlock') &&
      typeof oldNode.querySelector === 'function' &&
      oldNode.querySelector('.ax-deadlock-fallback')
    ) {
      return;
    }
 
    // 1. Update attributes if it's an element (skip if it is the temporary body wrapper)
    let skipChildren = false;
    if (!isBodyWrapper && oldNode.nodeType === Node.ELEMENT_NODE && newNode.nodeType === Node.ELEMENT_NODE) {
      this.#patchAttributes(oldNode, newNode);
      if (resolveExpression) {
        skipChildren = this.#applyDirectives(oldNode, resolveExpression, app);
      }
    }
 
    if (skipChildren) {
      return;
    }
 
    // 2. Diff children
    const oldChildrenRaw = Array.from(oldNode.childNodes).filter((child) => !child._isLeaving);
    const newChildrenRaw = Array.from(newNode.childNodes);
 
    const oldChildren = [];
    for (const child of oldChildrenRaw) {
      if (child.nodeType === Node.TEXT_NODE) {
        const last = oldChildren[oldChildren.length - 1];
        if (last && last.nodeType === Node.TEXT_NODE) {
          last.textContent += child.textContent;
          if (child.parentNode) {
            child.parentNode.removeChild(child);
          }
        } else {
          oldChildren.push(child);
        }
      } else {
        oldChildren.push(child);
      }
    }
 
    const newChildren = [];
    for (const child of newChildrenRaw) {
      if (child.nodeType === Node.TEXT_NODE) {
        const last = newChildren[newChildren.length - 1];
        if (last && last.nodeType === Node.TEXT_NODE) {
          last.textContent += child.textContent;
          if (child.parentNode) {
            child.parentNode.removeChild(child);
          }
        } else {
          newChildren.push(child);
        }
      } else {
        newChildren.push(child);
      }
    }
 
    let oldIndex = 0;
    let newIndex = 0;
 
    while (newIndex < newChildren.length) {
      const newChild = newChildren[newIndex];
      let oldChild = oldChildren[oldIndex];
 
      // Skip items managed by ListManager in the old DOM
      while (oldChild && oldChild.nodeType === Node.ELEMENT_NODE && oldChild.hasAttribute('data-ax-list-item')) {
        oldIndex++;
        oldChild = oldChildren[oldIndex];
      }
 
      if (!oldChild) {
        // Add remaining new children
        const isParentSvg =
          oldNode &&
          oldNode.nodeType === Node.ELEMENT_NODE &&
          (oldNode.namespaceURI === 'http://www.w3.org/2000/svg' || oldNode.tagName.toLowerCase() === 'svg');
        const prepared = this.#prepareNode(newChild, isParentSvg, resolveExpression, app);
        oldNode.appendChild(prepared);
        if (tracer.on) {
          traceDomOp('insert', prepared, { into: oldNode.tagName && oldNode.tagName.toLowerCase() });
        }
        this.triggerEnter(prepared, resolveExpression);
      } else if (this.#isSameNodeType(oldChild, newChild)) {
        // Nodes are same type, patch them
        if (oldChild.nodeType === Node.TEXT_NODE) {
          if (oldChild.textContent !== newChild.textContent) {
            const previousText = oldChild.textContent;
            oldChild.textContent = newChild.textContent;
            if (tracer.on) {
              traceDomOp('text', oldChild, {
                from: clampDomValue(previousText),
                to: clampDomValue(newChild.textContent),
              });
            }
          }
        } else {
          this.#patchNode(oldChild, newChild, false, false, resolveExpression, app);
        }
        oldIndex++;
      } else {
        // Nodes are different, replace
        const isParentSvg =
          oldNode &&
          oldNode.nodeType === Node.ELEMENT_NODE &&
          (oldNode.namespaceURI === 'http://www.w3.org/2000/svg' || oldNode.tagName.toLowerCase() === 'svg');
        const prepared = this.#prepareNode(newChild, isParentSvg, resolveExpression, app);
 
        const transitionName = this.getTransitionName(oldChild, resolveExpression);
        if (transitionName) {
          oldNode.insertBefore(prepared, oldChild);
          this.triggerLeave(oldChild, resolveExpression, () => {
            if (oldChild.parentNode === oldNode) {
              if (tracer.on) {
                traceDomOp('remove', oldChild);
              }
              oldNode.removeChild(oldChild);
            }
          }, app);
        } else {
          this.triggerUnmounted(oldChild, app);
          if (tracer.on) {
            traceDomOp('replace', oldChild, { with: prepared.nodeName && prepared.nodeName.toLowerCase() });
          }
          oldNode.replaceChild(prepared, oldChild);
        }
        this.triggerEnter(prepared, resolveExpression);
        oldIndex++;
      }
      newIndex++;
    }
 
    // Re-sync select value after dynamic options are patched.
    if (
      oldNode.nodeType === Node.ELEMENT_NODE &&
      oldNode.nodeName === 'SELECT' &&
      newNode.nodeType === Node.ELEMENT_NODE
    ) {
      const valueAttr = newNode.getAttribute('value');

      if (valueAttr !== null && oldNode.value !== valueAttr) {
        oldNode.value = valueAttr;
      }
    }
 
    // Remove remaining old children (that are not managed by ListManager)
    while (oldIndex < oldChildren.length) {
      const oldChild = oldChildren[oldIndex];
      if (!(oldChild.nodeType === Node.ELEMENT_NODE && oldChild.hasAttribute('data-ax-list-item'))) {
        this.triggerLeave(oldChild, resolveExpression, () => {
          if (oldChild.parentNode === oldNode) {
            if (tracer.on) {
              traceDomOp('remove', oldChild);
            }
            oldNode.removeChild(oldChild);
          }
        }, app);
      }
      oldIndex++;
    }
  }
 
  /**
   * Checks if two nodes are of the same type and name.
   * @param {Node} nodeA
   * @param {Node} nodeB
   * @private
   */
  #isSameNodeType(nodeA, nodeB) {
    return nodeA.nodeType === nodeB.nodeType && nodeA.nodeName === nodeB.nodeName;
  }
 
  /**
   * Syncs attributes from newNode to oldNode.
   * @param {Element} oldNode
   * @param {Element} newNode
   * @private
   */
  #patchAttributes(oldNode, newNode) {
    const oldAttrs = oldNode.attributes;
    const newAttrs = newNode.attributes;
 
    // Track dynamic attribute names for clean attribute removal when dynamic attribute names change
    const newDynAttrStr = newNode.getAttribute ? newNode.getAttribute('data-ax-dyn-attrs') : null;
    const newDynAttrs = newDynAttrStr !== null ? newDynAttrStr.split(',').filter(Boolean) : null;
 
    let prevDynAttrs = oldNode.__avenxDynAttrs || [];
    if (oldNode.getAttribute && oldNode.hasAttribute('data-ax-dyn-attrs')) {
      const attrVal = oldNode.getAttribute('data-ax-dyn-attrs');
      const fromAttr = attrVal ? attrVal.split(',').filter(Boolean) : [];
      prevDynAttrs = Array.from(new Set([...prevDynAttrs, ...fromAttr]));
    }
 
    if (newDynAttrs !== null) {
      for (const oldDynName of prevDynAttrs) {
        if (!newDynAttrs.includes(oldDynName)) {
          if (oldNode.hasAttribute(oldDynName)) {
            oldNode.removeAttribute(oldDynName);
            if (isBooleanAttribute(oldDynName)) {
              oldNode[oldDynName] = false;
            }
          }
        }
      }
      oldNode.__avenxDynAttrs = newDynAttrs;
    }
 
    // Remove old attributes that are gone
    for (let i = oldAttrs.length - 1; i >= 0; i--) {
      const attr = oldAttrs[i];
      if (!newNode.hasAttribute(attr.name)) {
        oldNode.removeAttribute(attr.name);
        if (tracer.on) {
          traceDomOp('remove-attr', oldNode, { name: attr.name, from: clampDomValue(attr.value) });
        }
        if (isBooleanAttribute(attr.name)) {
          oldNode[attr.name] = false;
        }
        if (attr.name === 'value' && ['INPUT', 'TEXTAREA', 'SELECT'].includes(oldNode.nodeName)) {
          oldNode.value = '';
        }
      }
    }
 
    // Add or update attributes
    for (let i = 0; i < newAttrs.length; i++) {
      const attr = newAttrs[i];
      const isBoolean = isBooleanAttribute(attr.name);
 
      if (isBoolean) {
        const isFalsy = attr.value === 'false' || attr.value === null || attr.value === undefined;
        if (isFalsy) {
          if (oldNode.hasAttribute(attr.name)) {
            oldNode.removeAttribute(attr.name);
          }
          oldNode[attr.name] = false;
        } else {
          if (oldNode.getAttribute(attr.name) !== attr.value) {
            const previous = oldNode.getAttribute(attr.name);
            oldNode.setAttribute(attr.name, sanitizeUrlAttribute(attr.name, attr.value));
            if (tracer.on) {
              traceDomOp('attr', oldNode, {
                name: attr.name,
                from: clampDomValue(previous),
                to: clampDomValue(attr.value),
              });
            }
          }
          oldNode[attr.name] = true;
        }
      } else {
        const oldValue = oldNode.getAttribute(attr.name);
        const shouldUpdate =
          attr.name === 'class' ? !classTokensEqual(oldValue, attr.value) : oldValue !== attr.value;
        if (shouldUpdate) {
          // Escaping made the value safe *as an attribute*; only the scheme
          // check makes it safe as a URL. See lib/core/security/urlPolicy.js.
          oldNode.setAttribute(attr.name, sanitizeUrlAttribute(attr.name, attr.value));
          if (tracer.on) {
            traceDomOp('attr', oldNode, {
              name: attr.name,
              from: clampDomValue(oldValue),
              to: clampDomValue(attr.value),
            });
          }
        }
        if (attr.name === 'value' && ['INPUT', 'TEXTAREA', 'SELECT'].includes(oldNode.nodeName)) {
          if (oldNode.value !== attr.value) {
            oldNode.value = attr.value;
          }
        }
      }
    }
  }
 
  /**
   * Cleans an element by removing boolean attributes that evaluate to false.
   * @param {Element} element - The element to clean.
   * @returns {Element} The cleaned element.
   */
  cleanElement(element) {
    if (element && element.nodeType === Node.ELEMENT_NODE) {
      this.flattenTransitionTags(element);
      this.#cleanBooleanAttributes(element);
    }
    return element;
  }
 
  /**
   * Recursively finds and cleans boolean attributes that evaluate to false in a subtree.
   * @param {Element} element - The root element to clean.
   * @private
   */
  #cleanBooleanAttributes(element) {
    const elements = [element, ...element.querySelectorAll('*')];
    for (const el of elements) {
      const attrs = Array.from(el.attributes);
      for (const attr of attrs) {
        if (isBooleanAttribute(attr.name)) {
          const isFalsy = attr.value === 'false' || attr.value === null || attr.value === undefined;
          if (isFalsy) {
            el.removeAttribute(attr.name);
            el[attr.name] = false;
          } else {
            el[attr.name] = true;
          }
        }
      }
    }
  }
 
  /**
   * Cleans boolean attributes of a single element in-place.
   * @param {Element} el
   * @private
   */
  #cleanBooleanAttributesForNode(el) {
    const attrs = Array.from(el.attributes);
    for (const attr of attrs) {
      if (isBooleanAttribute(attr.name)) {
        const isFalsy = attr.value === 'false' || attr.value === null || attr.value === undefined;
        if (isFalsy) {
          el.removeAttribute(attr.name);
          el[attr.name] = false;
        } else {
          el[attr.name] = true;
        }
      }
    }
  }
 
  /**
   * Prepares a node for insertion into the DOM by cleaning its boolean attributes
   * and ensuring correct namespaces for SVG elements.
   * If a node already has the correct namespace, it is prepared in-place without cloning.
   * @param {Node} node - The node to prepare.
   * @param {boolean} [isSvg] - Whether the node is within an SVG context.
   * @param {function(string): any} [resolveExpression] - Function to evaluate expressions.
   * @param {object} [app] - The application context.
   * @returns {Node} The prepared node.
   * @private
   */
  #prepareNode(node, isSvg = false, resolveExpression, app) {
    if (node.nodeType === Node.ELEMENT_NODE) {
      const tagName = node.tagName.toLowerCase();
      if (tagName === 'template' || tagName === '@for') {
        return node;
      }
      const currentIsSvg = isSvg || tagName === 'svg';
 
      let skipChildren = false;
      if (resolveExpression) {
        skipChildren = this.#applyDirectives(node, resolveExpression, app);
      }
 
      if (currentIsSvg) {
        if (node.namespaceURI === 'http://www.w3.org/2000/svg') {
          this.#cleanBooleanAttributesForNode(node);
          if (!skipChildren) {
            const children = Array.from(node.childNodes);
            for (const child of children) {
              this.#prepareNode(child, currentIsSvg, resolveExpression, app);
            }
          }
          return node;
        } else {
          const svgElement = document.createElementNS('http://www.w3.org/2000/svg', tagName);
          const attrs = node.attributes;
          if (attrs) {
            for (let i = 0; i < attrs.length; i++) {
              const attr = attrs[i];
              const isBoolean = isBooleanAttribute(attr.name);
              const isFalsy = attr.value === 'false' || attr.value === null || attr.value === undefined;
              if (isBoolean && isFalsy) {
                svgElement[attr.name] = false;
              } else {
                svgElement.setAttribute(attr.name, sanitizeUrlAttribute(attr.name, attr.value));
                if (isBoolean) {
                  svgElement[attr.name] = true;
                }
              }
            }
          }
          if (resolveExpression) {
            this.#applyDirectives(svgElement, resolveExpression, app);
          }
          if (!skipChildren) {
            const children = Array.from(node.childNodes);
            for (const child of children) {
              svgElement.appendChild(this.#prepareNode(child, currentIsSvg, resolveExpression, app));
            }
          }
          return svgElement;
        }
      } else {
        this.#cleanBooleanAttributesForNode(node);
        if (!skipChildren) {
          const children = Array.from(node.childNodes);
          for (const child of children) {
            this.#prepareNode(child, false, resolveExpression, app);
          }
        }
        return node;
      }
    }
    return node;
  }
 
  /**
   * Resolves the scope an element's bindings belong to.
   *
   * A scoped slot was the first thing to need this; a `<@for>` row needs
   * exactly the same answer, so the walk lives in one module now and both stamp
   * through it.
   * @param {Element} el - The element a binding is attached to.
   * @returns {object|null} The nearest enclosing derived scope, or null.
   * @private
   */
  #getSlotScope(el) {
    return findScope(el);
  }
 
  /**
   * Evaluates and applies directives on a single element.
   * @param {Element} el - The element to evaluate directives on.
   * @param {function(string): any} resolveExpression - The expression evaluator.
   * @param {object} [app] - The application context.
   * @returns {boolean} Whether children evaluation/diffing should be skipped.
   * @private
   */
  #applyDirectives(el, resolveExpression, app) {
    if (!resolveExpression || el.nodeType !== Node.ELEMENT_NODE) {
      return false;
    }
    const slotScope = this.#getSlotScope(el);
    const localResolve = slotScope ? (expr) => resolveExpression(expr, slotScope) : resolveExpression;
    let skipChildren = false;
 
    // 1. data-ax-html
    if (el.hasAttribute('data-ax-html')) {
      const expr = el.getAttribute('data-ax-html');
      try {
        const value = localResolve(expr);
        let resolvedHtml = '';
        if (value instanceof SafeHtml) {
          resolvedHtml = value.toString();
        } else if (value == null) {
          resolvedHtml = '';
        } else {
          resolvedHtml = escaper.escape(value);
        }
        if (el.innerHTML !== resolvedHtml) {
          el.innerHTML = resolvedHtml;
        }
        skipChildren = true;
      } catch (err) {
        logger.warn(
          formatMessage(AvenxErrorCodes.DIRECTIVE_HTML_EVALUATION_FAILED, expr, err.message || err)
        );
      }
    }
 
    // 2. data-ax-show
    if (el.hasAttribute('data-ax-show')) {
      const expr = el.getAttribute('data-ax-show');
      try {
        const value = !!localResolve(expr);
        const hasOriginal = typeof el.__originalDisplay !== 'undefined';
        if (!hasOriginal) {
          el.__originalDisplay = el.style.display || '';
        }
 
        const isCurrentlyVisible = el.style.display !== 'none';
 
        if (!el.axShowInitialized) {
          el.style.display = value ? el.__originalDisplay : 'none';
          el.axShowInitialized = true;
        } else if (value !== isCurrentlyVisible) {
          const transitionName = this.getTransitionName(el, resolveExpression);
          if (transitionName) {
            if (value) {
              el.style.display = el.__originalDisplay;
              this.enter(el, transitionName);
            } else {
              this.leave(el, transitionName, () => {
                el.style.display = 'none';
              });
            }
          } else {
            el.style.display = value ? el.__originalDisplay : 'none';
          }
        }
      } catch (err) {
        logger.warn(
          formatMessage(AvenxErrorCodes.DIRECTIVE_SHOW_EVALUATION_FAILED, expr, err.message || err)
        );
      }
    }
 
    // 3. data-ax-class
    if (el.hasAttribute('data-ax-class')) {
      const expr = el.getAttribute('data-ax-class');
      try {
        const value = localResolve(expr);
        // Clean up classes added by previous data-ax-class evaluation
        if (el.__lastAxClasses) {
          for (const cls of el.__lastAxClasses) {
            el.classList.remove(cls);
          }
        }
 
        const newClasses = [];
        if (typeof value === 'string') {
          newClasses.push(...value.split(/\s+/).filter(Boolean));
        } else if (value && typeof value === 'object') {
          for (const [cls, enabled] of Object.entries(value)) {
            if (enabled) {
              newClasses.push(cls);
            }
          }
        }
 
        for (const cls of newClasses) {
          el.classList.add(cls);
        }
        el.__lastAxClasses = newClasses;
      } catch (err) {
        logger.warn(
          formatMessage(AvenxErrorCodes.DIRECTIVE_CLASS_EVALUATION_FAILED, expr, err.message || err)
        );
      }
    }
 
    // 4. Dynamic Attribute Name Binding (:[attrName]="attrValue")
    const elAttrs = Array.from(el.attributes || []);
    const currentDynAttrs = [];
    for (const attr of elAttrs) {
      const match = attr.name.match(/^:\[(.*)\]$/);
      if (match) {
        const nameExpr = match[1];
        const valExpr = attr.value;
        let resolvedName = null;
        try {
          resolvedName = localResolve(nameExpr);
        } catch (err) {
          logger.warn(`Failed to evaluate dynamic attribute name expression "${nameExpr}": ${err.message || err}`);
        }
 
        if (resolvedName != null && String(resolvedName).trim() !== '') {
          const attrName = String(resolvedName).trim();
          // A dynamic name (:[expr]) that resolves to an on* handler would set
          // an inline handler from a value -- the one on* path the build cannot
          // see. Refuse it, matching the compiled path's AVX_C28.
          if (isEventHandlerAttribute(attrName)) {
            logger.warn(formatMessage(AvenxErrorCodes.SECURITY_BLOCKED_EVENT_ATTRIBUTE, attrName));
            continue;
          }
          let resolvedVal = null;
          if (valExpr) {
            try {
              resolvedVal = localResolve(valExpr);
            } catch (err) {
              logger.warn(`Failed to evaluate dynamic attribute value expression "${valExpr}": ${err.message || err}`);
            }
          }
 
          if (resolvedVal !== false && resolvedVal != null) {
            currentDynAttrs.push(attrName);
            if (resolvedVal === true) {
              el.setAttribute(attrName, 'true');
              if (isBooleanAttribute(attrName)) {
                el[attrName] = true;
              }
            } else {
              el.setAttribute(attrName, sanitizeUrlAttribute(attrName, String(resolvedVal)));
            }
          } else {
            currentDynAttrs.push(attrName);
            if (el.hasAttribute(attrName)) {
              el.removeAttribute(attrName);
              if (isBooleanAttribute(attrName)) {
                el[attrName] = false;
              }
            }
          }
        }
        el.removeAttribute(attr.name);
      }
    }
 
    const prevDynAttrs = el.__avenxDynAttrs || [];
    for (const oldName of prevDynAttrs) {
      if (!currentDynAttrs.includes(oldName)) {
        if (el.hasAttribute(oldName)) {
          el.removeAttribute(oldName);
          if (isBooleanAttribute(oldName)) {
            el[oldName] = false;
          }
        }
      }
    }
    if (currentDynAttrs.length > 0 || prevDynAttrs.length > 0) {
      el.__avenxDynAttrs = currentDynAttrs;
    }
 
    // 5. Custom Directives
    if (app && app.directives) {
      const attrs = Array.from(el.attributes || []);
      for (const attr of attrs) {
        if (attr.name.startsWith('data-ax-')) {
          // Split dot-notation modifiers off the directive name, mirroring the
          // event modifier convention in core/events/bindEvents.js.
          const attrKey = attr.name.slice(8);
          const parts = attrKey.split('.');
          const dirName = parts[0];
          // Ignore built-in core directives
          if (
            dirName === 'show' ||
            dirName === 'class' ||
            dirName === 'html' ||
            dirName === 'static' ||
            dirName === 'transition' ||
            dirName === 'for' ||
            dirName === 'as' ||
            dirName === 'key' ||
            dirName === 'list-item' ||
            dirName === 'key-val' ||
            dirName === 'validate' ||
            dirName === 'validate-messages'
          ) {
            continue;
          }
          if (app.directives.has(dirName)) {
            const expr = attr.value;
            let value;
            if (expr) {
              try {
                value = localResolve(expr);
              } catch (err) {
                logger.warn(
                  `Failed to evaluate custom directive ${dirName} expression "${expr}": ${err.message || err}`
                );
              }
            }
 
            if (!el.__avenx_directives) {
              el.__avenx_directives = new Map();
            }
 
            // Keyed by the full attribute suffix so that two modifier variants of
            // the same directive on one element do not overwrite each other.
            const oldInfo = el.__avenx_directives.get(attrKey);
 
            if (!oldInfo) {
              const modifiers = {};
              for (let i = 1; i < parts.length; i++) {
                if (parts[i]) modifiers[parts[i]] = true;
              }
 
              el.__avenx_directives.set(attrKey, {
                name: dirName,
                value,
                oldValue: undefined,
                expression: expr,
                modifiers,
                mountedCalled: false,
                valueChanged: false,
              });
            } else {
              const oldValue = oldInfo.value;
 
              if (value !== oldValue) {
                oldInfo.oldValue = oldValue;
                oldInfo.value = value;
                oldInfo.expression = expr;
                oldInfo.valueChanged = true;
              } else {
                // The directive value has not changed.
                // Make sure a previous update flag cannot trigger
                // another updated() lifecycle call.
                oldInfo.valueChanged = false;
              }
            }
 
            if (this.sessionElements) {
              this.sessionElements.add(el);
            }
          }
        }
      }
    }
 
    return skipChildren;
  }
 
  /**
   * Recursively applies custom directives to an element and its children.
   * @param {Element} element - The element tree root.
   * @param {function(string): any} resolveExpression - The expression evaluator.
   * @param {object} [app] - The application context.
   */
  applyDirectives(element, resolveExpression, app) {
    const prevSession = this.sessionElements;
    const prevRoot = this.patchRoot;
    this.sessionElements = new Set();
    this.patchRoot = element;
 
    try {
      this.applyDirectivesInternal(element, resolveExpression, app);
      this.flushLifecycleHooks(app);
    } finally {
      this.sessionElements = prevSession;
      this.patchRoot = prevRoot;
    }
  }
 
  /**
   * Recursively applies directives to an element and its children.
   * @param {Element} element - The target element.
   * @param {Function} resolveExpression - Expression resolver callback.
   * @param {object} [app] - The application context.
   */
  applyDirectivesInternal(element, resolveExpression, app) {
    const skip = this.#applyDirectives(element, resolveExpression, app);
    if (!skip) {
      const children = Array.from(element.childNodes);
      for (const child of children) {
        if (child.nodeType === Node.ELEMENT_NODE) {
          this.applyDirectivesInternal(child, resolveExpression, app);
        }
      }
    }
  }
 
  /**
   * Applies the enter transition classes and triggers animation/transition.
   * @param {Element} el - The element to animate.
   * @param {string} transitionName - The transition name (e.g. 'fade').
   */
  enter(el, transitionName) {
    if (el.nodeType !== Node.ELEMENT_NODE) return;
    const name = transitionName || 'ax';
    const enterClass = `${name}-enter`;
    const enterActiveClass = `${name}-enter-active`;
    const enterToClass = `${name}-enter-to`;
 
    if (el._cleanupTransition) {
      el._cleanupTransition();
    }
 
    el.classList.add(enterClass);
    el.classList.add(enterActiveClass);
 
    let resolved = false;
    let timeoutId = null;
 
    const done = () => {
      if (resolved) return;
      resolved = true;
      el.classList.remove(enterActiveClass);
      el.classList.remove(enterToClass);
      el.removeEventListener('transitionend', done);
      el.removeEventListener('animationend', done);
      if (timeoutId) clearTimeout(timeoutId);
      delete el._cleanupTransition;
    };
 
    el._cleanupTransition = done;
 
    el.addEventListener('transitionend', done);
    el.addEventListener('animationend', done);
 
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        if (resolved) return;
        el.classList.remove(enterClass);
        el.classList.add(enterToClass);
 
        const duration = getTransitionDuration(el);
        if (duration === 0) {
          done();
        } else {
          timeoutId = setTimeout(done, duration + 50);
        }
      });
    });
  }
 
  /**
   * Applies the leave transition classes, triggers animation, and cleans up when complete.
   * @param {Element} el - The element to animate.
   * @param {string} transitionName - The transition name (e.g. 'fade').
   * @param {function(): void} removeCallback - Callback invoked when the leave transition completes.
   */
  leave(el, transitionName, removeCallback) {
    if (el.nodeType !== Node.ELEMENT_NODE) {
      if (removeCallback) removeCallback();
      return;
    }
    const name = transitionName || 'ax';
    const leaveClass = `${name}-leave`;
    const leaveActiveClass = `${name}-leave-active`;
    const leaveToClass = `${name}-leave-to`;
 
    if (el._cleanupTransition) {
      el._cleanupTransition();
    }
 
    el._isLeaving = true;
 
    el.classList.add(leaveClass);
    el.classList.add(leaveActiveClass);
 
    let resolved = false;
    let timeoutId = null;
 
    const done = () => {
      if (resolved) return;
      resolved = true;
      el.classList.remove(leaveActiveClass);
      el.classList.remove(leaveToClass);
      el.removeEventListener('transitionend', done);
      el.removeEventListener('animationend', done);
      if (timeoutId) clearTimeout(timeoutId);
      delete el._cleanupTransition;
      delete el._isLeaving;
      if (removeCallback) removeCallback();
    };
 
    el._cleanupTransition = done;
 
    el.addEventListener('transitionend', done);
    el.addEventListener('animationend', done);
 
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        if (resolved) return;
        el.classList.remove(leaveClass);
        el.classList.add(leaveToClass);
 
        const duration = getTransitionDuration(el);
        if (duration === 0) {
          done();
        } else {
          timeoutId = setTimeout(done, duration + 50);
        }
      });
    });
  }
 
  /**
   * Resolves the transition name for an element.
   * @param {Element} el - The element.
   * @param {function(string): any} [resolveExpression] - The expression evaluator.
   * @returns {string|null} The resolved transition name, or null.
   */
  getTransitionName(el, resolveExpression) {
    if (!el || el.nodeType !== Node.ELEMENT_NODE) return null;
    if (!el.hasAttribute('data-ax-transition')) return null;
    const expr = el.getAttribute('data-ax-transition');
    if (!expr) return 'ax';
    if (!resolveExpression) return expr;
    const slotScope = this.#getSlotScope(el);
    const localResolve = slotScope ? (e) => resolveExpression(e, slotScope) : resolveExpression;
    try {
      const val = localResolve(expr);
      return typeof val === 'string' ? val : expr;
    } catch {
      return expr;
    }
  }
 
  /**
   * Triggers the enter transition if transition configurations are present.
   * @param {Element} el - The element.
   * @param {function(string): any} [resolveExpression] - The expression evaluator.
   */
  triggerEnter(el, resolveExpression) {
    if (el.nodeType !== Node.ELEMENT_NODE) return;
    const transitionName = this.getTransitionName(el, resolveExpression);
    if (transitionName) {
      el._transitionName = transitionName;
      this.enter(el, transitionName);
    }
  }
 
  /**
   * Triggers the leave transition or asynchronous unmounting of an element.
   * @param {Element} el - The element leaving.
   * @param {Function} resolveExpression - Expression evaluator callback.
   * @param {Function} removeCallback - Callback to remove element from DOM.
   * @param {object} [app] - The application context.
   */
  triggerLeave(el, resolveExpression, removeCallback, app) {
    if (el.nodeType !== Node.ELEMENT_NODE) {
      if (removeCallback) removeCallback();
      return;
    }
 
    const compInstance = el.__avenx_comp_instance;
    const proceedWithRemoval = () => {
      const done = () => {
        this.triggerUnmounted(el, app);
        if (removeCallback) removeCallback();
      };
      const transitionName = el._transitionName || this.getTransitionName(el, resolveExpression);
      if (transitionName) {
        this.leave(el, transitionName, done);
      } else {
        done();
      }
    };
 
    if (compInstance && typeof compInstance.unmount === 'function') {
      const unmountResult = compInstance.unmount();
      if (unmountResult instanceof Promise) {
        unmountResult.then(proceedWithRemoval);
        return;
      }
    }
    proceedWithRemoval();
  }
 
  /**
   * Flattens <transition> elements inside a root element.
   * @param {Element} node - The root element.
   */
  flattenTransitionTags(node) {
    if (!node || node.nodeType !== Node.ELEMENT_NODE) return;
    const transitions = Array.from(node.querySelectorAll('transition'));
    for (const trans of transitions) {
      const nameAttr = trans.getAttribute('name');
      let transitionValue = 'ax';
      if (nameAttr) {
        if (nameAttr.startsWith('{{') && nameAttr.endsWith('}}')) {
          transitionValue = nameAttr.slice(2, -2).trim();
        } else {
          transitionValue = nameAttr;
        }
      }
      const children = Array.from(trans.childNodes);
      for (const child of children) {
        if (child.nodeType === Node.ELEMENT_NODE) {
          child.setAttribute('data-ax-transition', transitionValue);
        }
        trans.parentNode.insertBefore(child, trans);
      }
      trans.parentNode.removeChild(trans);
    }
  }
 
  /**
   * Checks if a node is in the currently patched DOM tree.
   * @param {Element} el
   * @returns {boolean}
   */
  isNodeInPatchTree(el) {
    if (!this.patchRoot) return false;
    let curr = el;
    while (curr) {
      if (curr === this.patchRoot) return true;
      curr = curr.parentNode || (curr.host && curr.host.nodeType === 1 ? curr.host : null);
    }
    return false;
  }
 
  /**
   * Triggers the unmounted hook recursively on a node and its descendants.
   * @param {Node} node
   * @param {object} app
   */
  triggerUnmounted(node, app) {
    if (!node || node.nodeType !== Node.ELEMENT_NODE) return;
 
    const descendants = Array.from(node.querySelectorAll('*'));
    for (const desc of descendants) {
      this.triggerUnmountedForElement(desc, app);
    }
    this.triggerUnmountedForElement(node, app);
  }
 
  /**
   * Triggers the unmounted hook on a single element.
   * @param {Element} el
   * @param {object} app
   */
  triggerUnmountedForElement(el, app) {
    if (el.__avenx_directives) {
      for (const [dirName, info] of el.__avenx_directives.entries()) {
        if (info.mountedCalled) {
          const dirDef = app && app.directives && app.directives.get(info.name);
          if (dirDef && typeof dirDef.unmounted === 'function') {
            try {
              dirDef.unmounted(el, {
                value: info.value,
                oldValue: info.value,
                expression: info.expression,
                modifiers: info.modifiers,
              });
            } catch (err) {
              logger.warn(`Error in unmounted hook of directive ${dirName}: ${err.message || err}`);
            }
          }
          info.mountedCalled = false;
        }
      }
    }
  }
 
  /**
   * Flushes all lifecycle hooks collected during the patch session.
   * @param {object} app
   */
  flushLifecycleHooks(app) {
    if (!this.sessionElements || !app) return;
    for (const el of this.sessionElements) {
      if (!el.__avenx_directives) continue;
 
      const isConnected = this.isNodeInPatchTree(el);
      if (isConnected) {
        for (const [dirName, info] of el.__avenx_directives.entries()) {
          const dirDef = app.directives.get(info.name);
          if (!dirDef) continue;
 
          if (!info.mountedCalled) {
            if (typeof dirDef.mounted === 'function') {
              try {
                dirDef.mounted(el, {
                  value: info.value,
                  expression: info.expression,
                  modifiers: info.modifiers,
                });
              } catch (err) {
                logger.error(`Error in mounted hook of directive ${dirName}: ${err.message || err}`);
              }
            }
            info.mountedCalled = true;
          } else if (info.valueChanged) {
            if (typeof dirDef.updated === 'function') {
              try {
                dirDef.updated(el, {
                  value: info.value,
                  oldValue: info.oldValue,
                  expression: info.expression,
                  modifiers: info.modifiers,
                });
              } catch (err) {
                logger.error(`Error in updated hook of directive ${dirName}: ${err.message || err}`);
              }
            }
            info.valueChanged = false;
          }
        }
      } else {
        this.triggerUnmounted(el, app);
      }
    }
  }
}