All files / lib/core/reactive proxyHandler.js

87.56% Statements 965/1102
89.72% Branches 297/331
93.75% Functions 30/32
87.56% Lines 965/1102

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 1103642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 1345926x 1102173x 1102173x 1342796x 2x 2x 243751x 243751x 243858x 1345926x 1345926x 1345926x 62x 1345926x 1345926x 642x 642x 642x 642x 642x 642x 642x 1141x 2x 2x 1141x 1141x 642x 642x 642x 642x 642x 642x 642x 6x 6x 642x 642x 642x 642x 642x 642x 642x 642x 1x     1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 642x 642x 642x 642x 642x 642x 642x 571x 207x 207x 571x 571x     364x 364x 479x 247x 247x 364x 571x       571x       364x 91x 94x 94x 364x 273x 273x 178x 178x 273x 571x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 667x 667x 667x 667x 667x 629x 629x 629x 615x 615x 629x 14x 52x 52x 52x 52x 52x 52x 667x 58x 58x 58x 49x 49x 9x 13x 8x 8x 3x 3x 8x 6x 6x     667x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 2926x 642x 642x 642x 642x 642x 642x 642x 642x 165x 165x 165x 165x 165x 36x 36x 36x 37x 37x 36x 36x 36x 36x 36x 165x 165x 642x 642x 642x 642x 642x 710x 11x 11x 710x 710x 642x 642x 642x 642x 642x 642x 642x 488546x     488546x 488546x 729428x 488543x 488543x 240885x 729428x 3x 3x 240882x 240882x 3x 488546x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 488546x 3x 3x 488543x 488543x 488543x 488543x 488546x 488546x 488546x 49x 1x 1x 1x 1x 1x 1x 1x 1x 1x 49x 49x 488494x 488546x 642x 642x 642x 642x 642x 642x 642x 642x 642x 33x 3x 3x 3x 33x 8x 8x 8x 8x 1x 1x 1x 7x 8x 8x 33x           29x 9x 9x 9x 1x 1x 9x 9x 9x 9x 9x 9x 9x 1x 1x 9x 9x 2x 2x 9x 9x 7x 7x 7x 7x 7x 7x 1x 1x 7x 7x 9x 9x 9x 27x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 26x 2x 2x 1x 1x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 26x                         26x                                     26x                                     33x 8x 8x 8x 8x 8x 8x 26x 26x 26x 8x 24x 18x 18x 18x 18x 18x 26x 26x 26x 26x 8x 8x 5x 8x 8x 8x 8x             33x 642x 642x 642x 642x 642x 642x 642x 642x 642x 25x 5x 5x 5x 25x 3x 3x 3x 3x 3x 3x 25x 7x 7x 1x 1x 7x 7x 7x 5x 5x 1x 1x 5x 5x 5x 5x 5x 5x 1x 1x 5x 5x 7x 7x 7x 25x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 24x 3x 3x 1x 1x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 23x                               25x 3x 3x 3x 3x 3x 3x 9x 9x 1x 1x 9x 9x 9x 9x 3x 3x 2x 3x 3x 3x 3x 18x                                                             2x 2x 18x     2x 25x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 3763x 2926x 2926x 488160x 268x 268x 488160x 2926x 2926x 371823x 745x 745x 371823x 2926x 2926x 882x 57x 57x 882x 2926x 2926x 992x 8x 8x 992x 2926x 2926x 124x 1x 1x 124x 2926x 2926x 2926x 3763x 3763x 642x 642x 642x 642x 642x 642x 642x 642x 642x 488192x 4x 4x 488192x 488192x 488192x 488192x 488192x 488192x 488192x 488192x 488192x 488192x 488192x 488192x 488192x 488192x 488192x 488192x 47x 1x 1x 1x 47x 46x 46x 46x 46x 46x 46x 46x 46x 46x 47x 488192x 488192x 287x 287x 488192x 488192x 488192x 488192x 326x 326x 488192x 488192x 488192x 488192x 488192x 488192x 488192x 2x 488192x 2x 2x 2x       2x 488192x 488192x 124x 124x 488192x 488192x 487826x 487826x 487826x 487826x 487826x 487826x 487826x 6073x 6073x 487826x 487826x 488189x 488189x 488192x 642x 642x 642x 642x 642x 642x 642x 642x 642x 371823x 5x 5x 371823x 1337x 1337x 371823x 88x 88x 370393x 370393x 370393x 370393x 370393x 370393x 371823x 165x 165x 370228x 371819x 33x 33x 371819x 25x 25x 370170x 371823x 7x 7x 5x 5x 2x 2x 370163x 370163x 370665x 370025x 370025x 370163x 370163x 371811x 845x 531x 531x 531x 531x 531x 7x 7x 531x 531x 531x 531x 531x 531x 531x 531x 531x 531x 505x 505x 531x 531x 531x 531x 314x 314x 371811x 243090x 243090x 242255x 242255x 835x 835x 126228x 371823x 642x 642x 642x 642x 642x 642x 642x 642x 125x 125x 125x 125x 1x 1x 125x 125x 125x 125x 11x 11x 125x 125x 125x 5x 5x 125x 125x 125x 125x 125x 125x 2x 2x 125x 125x 125x 125x 642x 642x 642x 642x 642x 642x 642x 642x 882x 662x 662x 220x 882x 642x 642x 642x 642x 642x 642x 642x 642x 642x 992x 2x 2x 990x 992x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 642x 372267x 372267x 642x 642x 642x 642x 642x 642x 642x 642x 840x 3x 3x 840x     840x     837x 837x 840x 837x 837x 837x 837x 837x 837x 837x 837x 840x 642x  
/**
 * @file proxyHandler.js
 * @description Factory for creating proxy handlers used in reactive state.
 * Handles normal property access and computed property redirection.
 */
 
import { track, trigger, parentMap, AvenxWatcher, depMap, getPropertyPath, setDebugReactivity, isDebugReactivityEnabled } from './watcher.js';
 
import {
  RAW_SYMBOL,
  IS_REACTIVE_PROXY,
  PROXY_REF_SYMBOL,
  NON_REACTIVE_SYMBOL,
} from './symbols.js';
import { tracer } from '../trace/tracer.js';
import { traceWrite, traceCollectionWrite } from '../trace/reactive.js';
import { journal, setPathResolver } from './journal.js';
 
// The journal names a conflicted path in its report; the naming rules already
// live in the watcher. Injecting the resolver keeps the journal free of the
// watcher's surface while still producing "cart.items.0.qty" rather than "qty".
setPathResolver(getPropertyPath);
 
export { setDebugReactivity, isDebugReactivityEnabled };
 
// The symbols moved to ./symbols.js so consumers that only need to recognise a
// reactive value can import them without pulling in the proxy factory. They are
// re-exported here unchanged, so every existing importer is unaffected.
export { RAW_SYMBOL, IS_REACTIVE_PROXY, PROXY_REF_SYMBOL, NON_REACTIVE_SYMBOL };
 
const mutatingArrayMethods = new Set([
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse',
  'copyWithin',
  'fill',
]);
 
/**
 * Checks if the value is a candidate for reactive wrapping.
 * We restrict this to plain objects and arrays to avoid issues with
 * built-in classes (Date, RegExp, Map, Set, Promise) and custom class
 * instances that may contain private fields or internal slots.
 * @param {any} value - The value to check.
 * @returns {boolean} True if the value should be reactive, false otherwise.
 */
export function isReactiveTarget(value) {
  if (value === null || typeof value !== 'object') {
    return false;
  }
  if (value[NON_REACTIVE_SYMBOL]) {
    return false;
  }
  const proto = Object.getPrototypeOf(value);
  return (
    proto === null ||
    proto === Object.prototype ||
    proto === Array.prototype ||
    value instanceof Set ||
    value instanceof Map
  );
}
 
/**
 * Returns the underlying raw object for a reactive proxy.
 * @param {any} target
 * @returns {any}
 */
export function toRaw(target) {
  if (target === null || typeof target !== 'object') {
    return target;
  }
  return target[RAW_SYMBOL] || target;
}
 
/**
 * Returns true when value is an Avenx reactive proxy.
 * @param {any} value
 * @returns {boolean}
 */
export function isReactive(value) {
  return !!(value && typeof value === 'object' && value[IS_REACTIVE_PROXY]);
}
 
/**
 * Marks an object so it will not be wrapped by reactive proxies.
 * @template T
 * @param {T} target
 * @returns {T}
 */
export function markRaw(target) {
  if (target === null || typeof target !== 'object') {
    return target;
  }
  if (!Object.isExtensible(target)) {
    return target;
  }
  if (!target[NON_REACTIVE_SYMBOL]) {
    Object.defineProperty(target, NON_REACTIVE_SYMBOL, {
      value: true,
      writable: false,
      enumerable: false,
      configurable: false,
    });
  }
  return target;
}
 
/**
 * Recursively cleans up parentMap entries for a detached reactive target and its nested properties.
 * @param {any} value
 * @param {Set<any>} [seen]
 */
export function cleanupParentMap(value, seen = new Set()) {
  if (value === null || typeof value !== 'object') {
    return;
  }
  const rawValue = value[RAW_SYMBOL] || value;
  if (seen.has(rawValue)) {
    return;
  }
  seen.add(rawValue);
 
  if (parentMap.has(rawValue)) {
    parentMap.delete(rawValue);
  }
 
  if (rawValue instanceof Map) {
    for (const val of rawValue.values()) {
      cleanupParentMap(val, seen);
    }
  } else if (rawValue instanceof Set) {
    for (const val of rawValue.values()) {
      cleanupParentMap(val, seen);
    }
  } else if (Array.isArray(rawValue)) {
    for (let i = 0; i < rawValue.length; i++) {
      cleanupParentMap(rawValue[i], seen);
    }
  } else {
    // Plain object
    for (const val of Object.values(rawValue)) {
      cleanupParentMap(val, seen);
    }
  }
}
 
 
 
/**
 * Whether anything depends on a key, or on the path that reaches it.
 *
 * A dependency may be recorded at any level: a template reading `cart.items`
 * registers against `items` on the root target, while a write to
 * `cart.items[0].qty` lands on the element object. Walking up `parentMap` is
 * what connects the two.
 * @param {object} target - The raw target that changed.
 * @param {string|symbol|Array<string|symbol>} key - The key or keys that changed.
 * @returns {boolean} True when some watcher depends on the change.
 */
function hasDependentOnPath(target, key) {
  const keys = Array.isArray(key) ? key : [key];
 
  const keysMap = depMap.get(target);
  if (keysMap) {
    for (const k of keys) {
      const watchers = keysMap.get(k);
      if (watchers && watchers.size > 0) {
        return true;
      }
    }
  }
 
  // Walk to the root, asking whether the property that reaches this object is
  // itself observed. A guard on depth is unnecessary: cleanupParentMap keeps
  // the chain acyclic, but a visited set costs nothing and makes that explicit.
  const seen = new Set();
  let current = target;
  while (current && !seen.has(current)) {
    seen.add(current);
    const relation = parentMap.get(current);
    if (!relation) {
      return false;
    }
    const parentKeys = depMap.get(relation.parentTarget);
    if (parentKeys) {
      const watchers = parentKeys.get(relation.parentKey);
      if (watchers && watchers.size > 0) {
        return true;
      }
    }
    current = relation.parentTarget;
  }

  return false;
}
 
/**
 * Factory for creating and managing Proxy handlers for reactive state objects.
 */
export class ProxyHandlerFactory {
  /**
   * @param {object} [options] - Configuration options.
   * @param {string[]} [options.computedKeys] - List of keys that should be treated as computed properties.
   * @param {Function} [options.onChange] - Callback triggered when a property is set.
   * @param {Function|null} [options.onKeysChanged] - Callback triggered when the
   *   root target gains or loses a key, for consumers that cache its key set.
   * @param {boolean|function(): boolean} [options.onlyNotifyObserved] - When true, onChange is
   *   suppressed for writes that no watcher depends on, at any level of the
   *   property path. Off by default so the standalone reactive primitive keeps
   *   notifying for every mutation.
   * @param {Function} [options.getComputedValue] - Function to evaluate a computed property.
   * @param {object} [options.instance] - The component instance for fallback property lookups.
   * @param {boolean} [options.bypassSymbol] - Bypasses Symbol check during lookup.
   * @param {string[]} [options.persist] - List of state keys to persist in localStorage.
   */
  constructor({
    computedKeys = [],
    onChange = () => {},
    onKeysChanged = null,
    onlyNotifyObserved = false,
    getComputedValue = () => undefined,
    instance = null,
    bypassSymbol = false,
    persist = [],
  } = {}) {
    /** @type {Set<string>} */
    this.computedKeys = new Set(computedKeys);
    /** @type {Function} */
    this.onChange = onChange;
    /**
     * Called when the root target gains or loses a key.
     *
     * Distinct from `onChange`, which fires for a *value* change. A consumer
     * that caches the set of names state binds -- the template scope does --
     * needs to know when that set changed, and cannot tell from a value
     * notification. Without it the cache has to be rebuilt on every read, which
     * is `Object.keys()` over the whole state object per expression evaluated.
     * @type {Function|null}
     */
    this.onKeysChanged = onKeysChanged;
    /**
     * Whether onChange is suppressed for writes nothing depends on.
     *
     * Off by default: the standalone reactive primitive promises a
     * notification for every mutation. Components turn it on so that a write
     * to a key no expression reads does not schedule a render.
     * May be a predicate, so a consumer can enable filtering only once it has
     * actually collected dependencies.
     * @type {boolean|function(): boolean}
     */
    this.onlyNotifyObserved = onlyNotifyObserved;
    /** @type {Function} */
    this.getComputedValueReal = getComputedValue;
    /** @type {Set<string>} */
    this.persistKeys = new Set(persist);
    /** @type {WeakMap<object, Proxy>} */
    this.proxyCache = new WeakMap();
    /** @type {Map<string, AvenxWatcher>} */
    this.computedWatchers = new Map();
    /** @type {object|null} */
    this.instance = instance;
    /** @type {boolean} */
    this.bypassSymbol =
      bypassSymbol ||
      (typeof globalThis !== 'undefined' &&
        !!globalThis.__avenx_bypass_symbol__);
    /** @type {object|null} */
    this.rootTarget = null;
  }
  
  /**
   * Evaluates and caches a computed property using an internal AvenxWatcher.
   * @param {string} key - The computed key.
   * @param {object} receiver - The proxy receiver.
   * @returns {any}
   */
  evaluateComputedWatcher(key, receiver) {
    const target = receiver[RAW_SYMBOL] || receiver;
    track(target, key);
 
    let watcher = this.computedWatchers.get(key);
    if (!watcher) {
      watcher = new AvenxWatcher(
        () => this.getComputedValueReal(key, receiver),
        () => {
          trigger(target, key);
          this.notifyChange(target, key);
        },
        { lazy: true },
      );
      this.computedWatchers.set(key, watcher);
    }
    return watcher.evaluate();
  }
  
  /**
   * Cleans up all computed watchers created by this proxy handler.
   */
  teardown() {
    for (const watcher of this.computedWatchers.values()) {
      watcher.teardown();
    }
    this.computedWatchers.clear();
  }
 
  /**
   * Checks if the target object is still connected to the root state.
   * @param {object} target - The target raw object.
   * @returns {boolean}
   */
  isConnected(target) {
    if (!this.rootTarget) {
      return true;
    }
    let current = target;
    while (current) {
      if (current === this.rootTarget) {
        return true;
      }
      const relation = parentMap.get(current);
      if (!relation) {
        break;
      }
      current = relation.parentTarget;
    }
    return false;
  }
 
  /**
   * Notifies about a change if anything actually depends on it.
   *
   * This used to call `onChange()` for every write to any connected target,
   * which scheduled a component update whether or not a single expression read
   * the key. The per-key dependency graph the Proxy layer maintains was
   * therefore discarded at the last step: a component re-rendered in full when
   * a state key nothing referenced changed.
   *
   * `trigger()` alone is not a sufficient replacement. It wakes watchers
   * registered for exactly one target and key, and a nested write such as
   * `items[0].qty = 3` triggers on the inner object while the template's
   * dependency was recorded against `items` on the root. Walking the parent
   * chain is what keeps deep reactivity working while still allowing a write
   * that nothing observes -- at any level of the path -- to be skipped.
   *
   * Filtering is opt-in via `onlyNotifyObserved`. `StateFactory.create(obj,
   * { onChange })` is a public primitive whose documented contract is that
   * onChange fires for every mutation, watchers or not; components opt in
   * because for them onChange means "schedule a re-render", and a re-render
   * for a key no expression reads is exactly the waste being removed.
   * @param {object} target - The target raw object.
   * @param {string|symbol|Array<string|symbol>} [key] - The key that changed.
   *   Omitted for structural changes whose affected keys are not known, which
   *   notify unconditionally.
   */
  notifyChange(target, key) {
    if (!this.isConnected(target)) {
      return;
    }
    // The filter is only sound once the consumer has collected dependencies.
    // Before a component's first render nothing has been read, so every key
    // would look unobserved and no update would ever be scheduled.
    const filtering =
      typeof this.onlyNotifyObserved === 'function' ? this.onlyNotifyObserved() : this.onlyNotifyObserved;
 
    if (filtering && key !== undefined && !hasDependentOnPath(target, key)) {
      if (isDebugReactivityEnabled() && this.instance) {
        const componentName = this.instance.constructor?.name || 'Component';
        const keys = Array.isArray(key) ? key : [key];
        for (const k of keys) {
          if (typeof k !== 'symbol') {
            const propPath = getPropertyPath(target, k);
            console.log(`[Avenx Debug] Skipped render for component "${componentName}" on unobserved key "${propPath || k}"`);
          }
        }
      }
      return;
    }
    this.onChange(key, target);
  }
 
  /**
   * Returns a custom implementation of a Map method.
   * @param {Map} target - The raw Map.
   * @param {string|symbol} key - The property/method key.
   * @param {Proxy} receiver - The Map proxy.
   * @returns {any}
   */
  getMapMethod(target, key, receiver) {
    if (key === 'size') {
      track(target, 'size');
      return target.size;
    }
    if (key === 'get') {
      return (k) => {
        track(target, k);
        const val = target.get(k);
        if (isReactiveTarget(val)) {
          parentMap.set(val, { parentTarget: target, parentKey: k });
          return this.getOrCreateProxy(val);
        }
        return val;
      };
    }
    if (key === 'has') {
      return (k) => {
        track(target, k);
        return target.has(k);
      };
    }
    if (key === 'set') {
      return (k, v) => {
        const rawVal = v && v[RAW_SYMBOL] ? v[RAW_SYMBOL] : v;
        if (journal.active) {
          journal.recordCollection(target, this, 'Map');
        }
        const hasKey = target.has(k);
        const oldValue = target.get(k);
        const valueChanged = oldValue !== rawVal;
 
        target.set(k, rawVal);
 
        if (isReactiveTarget(oldValue)) {
          cleanupParentMap(oldValue);
        }
 
        if (isReactiveTarget(rawVal)) {
          parentMap.set(rawVal, { parentTarget: target, parentKey: k });
        }
 
        if (valueChanged || !hasKey) {
          const token = tracer.on ? traceCollectionWrite(target, k, 'map.set', target.size) : -1;
          try {
            trigger(target, !hasKey ? [k, 'size'] : k);
            this.notifyChange(target, !hasKey ? [k, 'size'] : k);
          } finally {
            if (token >= 0) {
              tracer.leave(token);
            }
          }
        }
        return receiver;
      };
    }
    if (key === 'delete') {
      return (k) => {
        if (journal.active) {
          journal.recordCollection(target, this, 'Map');
        }
        const hasKey = target.has(k);
        const oldValue = target.get(k);
 
        const result = target.delete(k);
 
        if (hasKey) {
          if (isReactiveTarget(oldValue)) {
            cleanupParentMap(oldValue);
          }
 
          const token = tracer.on ? traceCollectionWrite(target, k, 'map.delete', target.size) : -1;
          try {
            trigger(target, [k, 'size']);
            this.notifyChange(target, [k, 'size']);
          } finally {
            if (token >= 0) {
              tracer.leave(token);
            }
          }
        }
 
        return result;
      };
    }
    if (key === 'clear') {
      return () => {
        if (journal.active) {
          journal.recordCollection(target, this, 'Map');
        }
        const size = target.size;
        if (size > 0) {
          const keysMap = depMap.get(target);
          const keysToTrigger = ['size'];
          if (keysMap) {
            keysToTrigger.push(...keysMap.keys());
          }
          target.clear();
          const token = tracer.on ? traceCollectionWrite(target, undefined, 'clear', 0) : -1;
          try {
            trigger(target, keysToTrigger);
            this.notifyChange(target, keysToTrigger);
          } finally {
            if (token >= 0) {
              tracer.leave(token);
            }
          }
        }
      };
    }
    if (key === 'forEach') {
      return (callback, thisArg) => {
        track(target, 'size');
        target.forEach((val, k) => {
          callback.call(
            thisArg,
            isReactiveTarget(val) ? this.getOrCreateProxy(val) : val,
            isReactiveTarget(k) ? this.getOrCreateProxy(k) : k,
            receiver,
          );
        });
      };
    }
    if (key === 'keys') {
      return () => {
        track(target, 'size');
        const iterator = target.keys();
        const self = this;
        return {
          next() {
            const { value, done } = iterator.next();
            return {
              value: done ? undefined : isReactiveTarget(value) ? self.getOrCreateProxy(value) : value,
              done,
            };
          },
          [Symbol.iterator]() {
            return this;
          },
        };
      };
    }
    if (key === 'values') {
      return () => {
        track(target, 'size');
        const iterator = target.values();
        const self = this;
        return {
          next() {
            const { value, done } = iterator.next();
            return {
              value: done ? undefined : isReactiveTarget(value) ? self.getOrCreateProxy(value) : value,
              done,
            };
          },
          [Symbol.iterator]() {
            return this;
          },
        };
      };
    }
    if (key === 'entries' || key === Symbol.iterator) {
      return () => {
        track(target, 'size');
        const iterator = target.entries();
        const self = this;
        return {
          next() {
            const { value, done } = iterator.next();
            let unwrapped;
            if (done) {
              unwrapped = undefined;
            } else {
              unwrapped = [
                isReactiveTarget(value[0]) ? self.getOrCreateProxy(value[0]) : value[0],
                isReactiveTarget(value[1]) ? self.getOrCreateProxy(value[1]) : value[1],
              ];
            }
            return {
              value: unwrapped,
              done,
            };
          },
          [Symbol.iterator]() {
            return this;
          },
        };
      };
    }

    const value = Reflect.get(target, key, target);
    if (typeof value === 'function') {
      return value.bind(target);
    }
    return value;
  }
 
  /**
   * Returns a custom implementation of a Set method.
   * @param {Set} target - The raw Set.
   * @param {string|symbol} key - The property/method key.
   * @param {Proxy} receiver - The Set proxy.
   * @returns {any}
   */
  getSetMethod(target, key, receiver) {
    if (key === 'size') {
      track(target, 'size');
      return target.size;
    }
    if (key === 'has') {
      return (val) => {
        const rawVal = val && val[RAW_SYMBOL] ? val[RAW_SYMBOL] : val;
        track(target, rawVal);
        return target.has(rawVal);
      };
    }
    if (key === 'add') {
      return (val) => {
        if (journal.active) {
          journal.recordCollection(target, this, 'Set');
        }
        const rawVal = val && val[RAW_SYMBOL] ? val[RAW_SYMBOL] : val;
        const hasVal = target.has(rawVal);
        if (!hasVal) {
          target.add(rawVal);
          if (isReactiveTarget(rawVal)) {
            parentMap.set(rawVal, { parentTarget: target, parentKey: rawVal });
          }
          const token = tracer.on ? traceCollectionWrite(target, undefined, 'set.add', target.size) : -1;
          try {
            trigger(target, [rawVal, 'size']);
            this.notifyChange(target, [rawVal, 'size']);
          } finally {
            if (token >= 0) {
              tracer.leave(token);
            }
          }
        }
        return receiver;
      };
    }
    if (key === 'delete') {
      return (val) => {
        if (journal.active) {
          journal.recordCollection(target, this, 'Set');
        }
        const rawVal = val && val[RAW_SYMBOL] ? val[RAW_SYMBOL] : val;
        const hasVal = target.has(rawVal);
 
        const result = target.delete(rawVal);
 
        if (hasVal) {
          if (isReactiveTarget(rawVal)) {
            cleanupParentMap(rawVal);
          }
 
          const token = tracer.on ? traceCollectionWrite(target, undefined, 'set.delete', target.size) : -1;
          try {
            trigger(target, [rawVal, 'size']);
            this.notifyChange(target, [rawVal, 'size']);
          } finally {
            if (token >= 0) {
              tracer.leave(token);
            }
          }
        }
 
        return result;
      };
    }
    if (key === 'clear') {
      return () => {
        if (journal.active) {
          journal.recordCollection(target, this, 'Set');
        }
        const size = target.size;
        if (size > 0) {
          const keysMap = depMap.get(target);
          const keysToTrigger = ['size'];
          if (keysMap) {
            keysToTrigger.push(...keysMap.keys());
          }
          target.clear();
          const token = tracer.on ? traceCollectionWrite(target, undefined, 'clear', 0) : -1;
          try {
            trigger(target, keysToTrigger);
            this.notifyChange(target, keysToTrigger);
          } finally {
            if (token >= 0) {
              tracer.leave(token);
            }
          }
        }
      };
    }
    if (key === 'forEach') {
      return (callback, thisArg) => {
        track(target, 'size');
        target.forEach((val) => {
          if (isReactiveTarget(val)) {
            parentMap.set(val, { parentTarget: target, parentKey: val });
          }
          callback.call(
            thisArg,
            isReactiveTarget(val) ? this.getOrCreateProxy(val) : val,
            isReactiveTarget(val) ? this.getOrCreateProxy(val) : val,
            receiver,
          );
        });
      };
    }
    if (key === 'values' || key === 'keys' || key === Symbol.iterator) {
      return () => {
        track(target, 'size');
        const iterator = target.values();
        const self = this;
        return {
          next() {
            const { value, done } = iterator.next();
            if (!done && isReactiveTarget(value)) {
              parentMap.set(value, { parentTarget: target, parentKey: value });
            }
            return {
              value: done ? undefined : isReactiveTarget(value) ? self.getOrCreateProxy(value) : value,
              done,
            };
          },
          [Symbol.iterator]() {
            return this;
          },
        };
      };
    }
    if (key === 'entries') {
      return () => {
        track(target, 'size');
        const iterator = target.entries();
        const self = this;
        return {
          next() {
            const { value, done } = iterator.next();
            let unwrapped;
            if (done) {
              unwrapped = undefined;
            } else {
              if (isReactiveTarget(value[0])) {
                parentMap.set(value[0], { parentTarget: target, parentKey: value[0] });
              }
              unwrapped = [
                isReactiveTarget(value[0]) ? self.getOrCreateProxy(value[0]) : value[0],
                isReactiveTarget(value[1]) ? self.getOrCreateProxy(value[1]) : value[1],
              ];
            }
            return {
              value: unwrapped,
              done,
            };
          },
          [Symbol.iterator]() {
            return this;
          },
        };
      };
    }
 
    const value = Reflect.get(target, key, target);
    if (typeof value === 'function') {
      return value.bind(target);
    }
    return value;
  }
 
  /**
   * Creates the proxy handler object.
   * @returns {ProxyHandler<object>}
   */
  /**
   * Creates the proxy handler object.
   * @returns {ProxyHandler<object>}
   */
  create() {
    if (!this._sharedHandler) {
      this._sharedHandler = {
        set: (target, key, value) => {
          if (!this.rootTarget) {
            this.rootTarget = target;
          }
          return this.set(target, key, value);
        },
        get: (target, key, receiver) => {
          if (!this.rootTarget) {
            this.rootTarget = target;
          }
          return this.get(target, key, receiver);
        },
        ownKeys: (target) => {
          if (!this.rootTarget) {
            this.rootTarget = target;
          }
          return this.ownKeys(target);
        },
        getOwnPropertyDescriptor: (target, key) => {
          if (!this.rootTarget) {
            this.rootTarget = target;
          }
          return this.getOwnPropertyDescriptor(target, key);
        },
        deleteProperty: (target, key) => {
          if (!this.rootTarget) {
            this.rootTarget = target;
          }
          return this.deleteProperty(target, key);
        },
      };
    }
    return this._sharedHandler;
  }
 
  /**
   * Proxy 'set' trap.
   * @param {object} target - The target object.
   * @param {string|symbol} key - The property key.
   * @param {any} value - The new value.
   * @returns {boolean}
   */
  set(target, key, value) {
    if (value && value[RAW_SYMBOL]) {
      value = value[RAW_SYMBOL];
    }
 
    const isNewRootKey =
      this.onKeysChanged !== null &&
      target === this.rootTarget &&
      typeof key !== 'symbol' &&
      !Object.prototype.hasOwnProperty.call(target, key);
 
    const oldValue = target[key];
    const changed =
      typeof key !== 'symbol' &&
      (oldValue !== value || (Array.isArray(target) && key === 'length'));
 
    // Journaled before the assignment, because whether the key already existed
    // is the difference between restoring a value and deleting one, and that
    // cannot be told apart once the write has landed.
    if (changed && journal.active) {
      if (Array.isArray(target) && key === 'length') {
        // `arr.length = 0` discards elements that no single before/after pair
        // describes, so the whole array is saved instead.
        journal.recordCollection(target, this, 'array');
      } else {
        journal.recordWrite(
          target,
          key,
          oldValue,
          value,
          Object.prototype.hasOwnProperty.call(target, key),
          this
        );
      }
    }
 
    if (isReactiveTarget(oldValue)) {
      cleanupParentMap(oldValue);
    }
 
    target[key] = value;
 
    if (isReactiveTarget(value)) {
      parentMap.set(value, { parentTarget: target, parentKey: key });
    }
 
    // Persist configured root-level state values to localStorage.
    if (
      changed &&
      typeof key !== 'symbol' &&
      target === this.rootTarget &&
      this.persistKeys.has(key) &&
      typeof localStorage !== 'undefined'
    ) {
      try {
        localStorage.setItem(key, JSON.stringify(value));
      } catch {
        // Ignore storage and serialization errors so persistence
        // never breaks normal reactive state updates.
      }
    }
 
    if (isNewRootKey) {
      this.onKeysChanged();
    }
 
    if (changed) {
      const token = tracer.on ? traceWrite(target, key, oldValue, value) : -1;
 
      try {
        trigger(target, key, oldValue, value);
        this.notifyChange(target, key);
      } finally {
        if (token >= 0) {
          tracer.leave(token);
        }
      }
    }
 
    return true;
  }
  /**
   * Proxy 'get' trap.
   * Redirects to evaluateComputedWatcher if the key is a computed property.
   * @param {object} target - The target object.
   * @param {string|symbol} key - The property key.
   * @param {object} receiver - The proxy or object inheriting from the proxy.
   * @returns {any}
   */
  get(target, key, receiver) {
    if (key === IS_REACTIVE_PROXY) {
      return true;
    }
    if (key === RAW_SYMBOL) {
      return target;
    }
    if (key === PROXY_REF_SYMBOL) {
      return target[PROXY_REF_SYMBOL];
    }
    // Computed properties belong to the component's own state object, not to
    // every object reachable through it. One handler is shared by the root and
    // every nested proxy it creates, so an unguarded check made each nested
    // object claim all of the component's computeds: `state.query.total`
    // returned the component's `total`, and `Object.keys(state.query)` listed
    // it. See `isRootTarget`.
    if (this.isRootTarget(target) && this.computedKeys.has(key)) {
      return this.evaluateComputedWatcher(key, receiver);
    }
 
    if (target instanceof Map) {
      return this.getMapMethod(target, key, receiver);
    }
    if (target instanceof Set) {
      return this.getSetMethod(target, key, receiver);
    }
 
    if (!(key in target) && this.instance && key in this.instance) {
      const val = this.instance[key];
      if (typeof val === 'function') {
        return val.bind(this.instance);
      }
      return val;
    }
 
    // Track property access
    if (typeof key !== 'symbol') {
      track(target, key);
    }
 
    const value = Reflect.get(target, key, receiver);
    if (typeof value === 'function') {
      if (Array.isArray(target) && mutatingArrayMethods.has(key)) {
        return (...args) => {
          // `push`, `splice` and `sort` have no single before-and-after pair to
          // journal, so the transaction keeps a copy of the array instead —
          // once, the first time it touches it.
          if (journal.active) {
            journal.recordCollection(target, this, `array.${String(key)}`);
          }
          const result = target[key](...args);
          // The array's contents are deliberately not captured here: cloning
          // the whole array on every push would make tracing a growing list
          // quadratic. The length after the call is enough to explain it.
          const token = tracer.on ? traceCollectionWrite(target, 'length', key, target.length) : -1;
          try {
            trigger(target, 'length');
            this.notifyChange(target, 'length');
          } finally {
            if (token >= 0) {
              tracer.leave(token);
            }
          }
          return result;
        };
      }
      return value.bind(receiver);
    }
    if (isReactiveTarget(value)) {
      parentMap.set(value, { parentTarget: target, parentKey: key });
      if (!this.bypassSymbol && value[PROXY_REF_SYMBOL]) {
        return value[PROXY_REF_SYMBOL];
      }
      return this.getOrCreateProxy(value);
    }
    return value;
  }
 
  /**
   * Proxy 'deleteProperty' trap.
   * @param {object} target - The target object.
   * @param {string|symbol} key - The property key.
   * @returns {boolean}
   */
  deleteProperty(target, key) {
    const hasKey = Reflect.has(target, key);
    const oldValue = target[key];
 
    if (hasKey && typeof key !== 'symbol' && journal.active) {
      journal.recordDelete(target, key, oldValue, Object.prototype.hasOwnProperty.call(target, key), this);
    }
 
    const result = Reflect.deleteProperty(target, key);
 
    if (isReactiveTarget(oldValue)) {
      cleanupParentMap(oldValue);
    }
 
    if (hasKey) {
      if (this.onKeysChanged !== null && target === this.rootTarget && typeof key !== 'symbol') {
        this.onKeysChanged();
      }
      const token = tracer.on ? traceWrite(target, key, oldValue, undefined, 'delete') : -1;
      try {
        trigger(target, key);
        this.notifyChange(target, key);
      } finally {
        if (token >= 0) {
          tracer.leave(token);
        }
      }
    }
    return result;
  }
 
  /**
   * Proxy 'ownKeys' trap.
   * Includes computed keys in the list of keys.
   * @param {object} target - The target object.
   * @returns {Array<string|symbol>}
   */
  ownKeys(target) {
    if (!this.isRootTarget(target)) {
      return Reflect.ownKeys(target);
    }
    return [...Reflect.ownKeys(target), ...this.computedKeys];
  }
 
  /**
   * Proxy 'getOwnPropertyDescriptor' trap.
   * Ensures computed properties appear as own properties.
   * @param {object} target - The target object.
   * @param {string|symbol} key - The property key.
   * @returns {PropertyDescriptor|undefined}
   */
  getOwnPropertyDescriptor(target, key) {
    if (this.isRootTarget(target) && this.computedKeys.has(key)) {
      return { enumerable: true, configurable: true };
    }
    return Reflect.getOwnPropertyDescriptor(target, key);
  }
 
  /**
   * Whether `target` is the state object the computed properties belong to.
   *
   * One handler instance serves a component's root state object and every
   * nested object reached through it, because they share this factory. The
   * computed traps therefore have to ask which object they are answering for:
   * without this, every nested object reported and resolved the component's
   * computed properties as its own. `Object.keys(state.form)` listed them,
   * `{ ...state.form }` copied them, `JSON.stringify(state.query)` serialised
   * them into a request, and `state.query.total` returned a number that has
   * nothing to do with the query string.
   *
   * `rootTarget` is recorded by the trap wrappers on first access, and a nested
   * object can only be reached through the root, so it is always set by the
   * time a nested target arrives here. When it somehow is not, the target is
   * treated as the root -- the previous behaviour, which is correct for the
   * root and is the only object that can be seen first.
   * @param {object} target - The object a trap is answering for.
   * @returns {boolean} True when `target` owns the computed properties.
   * @private
   */
  isRootTarget(target) {
    return !this.rootTarget || target === this.rootTarget;
  }
 
  /**
   * Returns a cached proxy or creates a new proxy for a nested object/array.
   * @param {object | Array} val - The nested object or array.
   * @returns {Proxy} The reactive proxy.
   * @private
   */
  getOrCreateProxy(val) {
    if (!this.bypassSymbol && val[PROXY_REF_SYMBOL]) {
      return val[PROXY_REF_SYMBOL];
    }
    if (val[IS_REACTIVE_PROXY]) {
      return val;
    }
    if (this.proxyCache.has(val)) {
      return this.proxyCache.get(val);
    }
    const proxy = new Proxy(val, this.create());
    this.proxyCache.set(val, proxy);
    if (!this.bypassSymbol && Object.isExtensible(val)) {
      Object.defineProperty(val, PROXY_REF_SYMBOL, {
        value: proxy,
        writable: false,
        enumerable: false,
        configurable: false,
      });
    }
    return proxy;
  }
}