All files / lib/core/reactive proxyHandler.js

86.67% Statements 917/1058
89.52% Branches 282/315
93.54% Functions 29/31
86.67% Lines 917/1058

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 1059415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 1322540x 1079530x 1079530x 1320121x 2x 2x 243008x 243008x 243115x 1322540x 1322540x 1322540x 42x 1322540x 1322540x 415x 415x 415x 415x 415x 415x 415x 458x 2x 2x 458x 458x 415x 415x 415x 415x 415x 415x 415x 6x 6x 415x 415x 415x 415x 415x 415x 415x 415x 1x     1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 415x 415x 415x 415x 415x 415x 415x 447x 152x 152x 447x 447x     295x 295x 390x 189x 189x 295x 447x       447x       295x 65x 63x 63x 295x 230x 230x 138x 138x 230x 447x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 547x 547x 547x 547x 547x 510x 510x 510x 499x 499x 510x 11x 48x 48x 48x 48x 48x 48x 547x 52x 52x 52x 45x 45x 7x 7x 7x 7x 3x 3x 7x 4x 4x     547x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 2279x 415x 415x 415x 415x 415x 415x 415x 415x 118x 118x 118x 118x 118x 26x 26x 26x 30x 30x 26x 26x 26x 26x 26x 118x 118x 415x 415x 415x 415x 415x 384x 4x 4x 384x 384x 415x 415x 415x 415x 415x 415x 415x 488167x     488167x 488167x 728952x 488164x 488164x 240788x 728952x 3x 3x 240785x 240785x 3x 488167x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 488167x 3x 3x 488164x 488164x 488164x 488164x 488167x 488167x 488167x 45x 45x 488119x 488167x 415x 415x 415x 415x 415x 415x 415x 415x 415x 25x 3x 3x 3x 25x 4x 4x 4x 4x 1x 1x 1x 3x 4x 4x 25x           25x 8x 8x 8x 1x 1x 8x 8x 8x 8x 8x 8x 8x 1x 1x 8x 8x 2x 2x 8x 8x 6x 6x 6x 6x 6x 6x 1x 1x 6x 6x 8x 8x 8x 24x 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 23x 2x 2x 1x 1x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 23x                         23x                                     23x                                     25x 5x 5x 5x 5x 5x 5x 17x 17x 17x 5x 15x 12x 12x 12x 12x 12x 17x 17x 17x 17x 5x 5x 2x 5x 5x 5x 5x             25x 415x 415x 415x 415x 415x 415x 415x 415x 415x 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 415x 415x 415x 415x 415x 415x 415x 415x 415x 415x 2939x 2279x 2279x 487563x 149x 149x 487563x 2279x 2279x 348783x 616x 616x 348783x 2279x 2279x 655x 20x 20x 655x 2279x 2279x 519x     519x 2279x 2279x 52x 1x 1x 52x 2279x 2279x 2279x 2939x 2939x 415x 415x 415x 415x 415x 415x 415x 415x 415x 487593x 4x 4x 487593x 487593x 487593x 487593x 487593x 487593x 487593x 487593x 487593x 487593x 487593x 487593x 487593x 487593x 487593x 487593x 45x 1x 1x 1x 45x 44x 44x 44x 44x 44x 44x 44x 44x 44x 45x 487593x 487593x 232x 232x 487593x 487593x 487593x 487593x 269x 269x 487593x 487593x 487593x 487593x 487593x 487593x 487593x 2x 487593x 2x 2x 2x       2x 487593x 487593x 26x 26x 487593x 487593x 487529x 487529x 487529x 487529x 487529x 487529x 487529x 6073x 6073x 487529x 487529x 487590x 487590x 487593x 415x 415x 415x 415x 415x 415x 415x 415x 415x 348783x 5x 5x 348783x 605x 605x 348783x 70x 70x 348779x 118x 118x 347985x 348779x 25x 25x 348779x 25x 25x 347935x 348783x 9x 9x 4x 4x 5x 5x 347926x 347926x 348193x 347816x 347816x 347926x 347926x 348771x 706x 529x 529x 529x 529x 529x 7x 7x 529x 529x 529x 529x 529x 529x 529x 529x 529x 529x 505x 505x 529x 529x 529x 529x 177x 177x 348771x 242463x 242463x 241805x 241805x 658x 658x 104757x 348783x 415x 415x 415x 415x 415x 415x 415x 415x 53x 53x 53x 53x 1x 1x 53x 53x 53x 53x 13x 13x 53x 53x 53x 9x 9x 53x 53x 53x 53x 53x 53x 1x 1x 53x 53x 53x 53x 415x 415x 415x 415x 415x 415x 415x 415x 655x 655x 415x 415x 415x 415x 415x 415x 415x 415x 415x 519x     519x 519x 415x 415x 415x 415x 415x 415x 415x 415x 663x 3x 3x 663x     663x     660x 660x 663x 660x 660x 660x 660x 660x 660x 660x 660x 663x 415x  
/**
 * @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)) {
      return;
    }
    this.onChange();
  }
 
  /**
   * 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];
    }
    if (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) {
    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.computedKeys.has(key)) {
      return { enumerable: true, configurable: true };
    }
    return Reflect.getOwnPropertyDescriptor(target, key);
  }
 
  /**
   * 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;
  }
}