All files / core/src types.ts

100% Statements 6/6
100% Branches 0/0
100% Functions 0/0
100% Lines 6/6

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                1x 1x 1x 1x 1x 1x                                                                          
import type { $ZodError, $ZodIssue } from '@zod/core';
import type { input, output, ZodArray, ZodObject, ZodSafeParseResult } from 'zod/v4';
import type { ARRAY_MUTATIONS, BATCH_MUTATIONS, MAP_MUTATIONS, OBJECT_MUTATIONS, SET_MUTATIONS } from './constant.js';
import type { Linkables } from './enum.js';
import type { DerivedRef, ImmutableRef, MutableRef } from './ref.js';
 
export type Enum<T> = T[keyof T];
export type Primitive = string | number | boolean | bigint | symbol | undefined | null | MethodLike | Date | RegExp;
 
export type Recursive = boolean | 'flat';
export type MethodLike = (...args: unknown[]) => unknown;
export type KeyLike = string | number | symbol;
export type ObjLike = {
  [key: KeyLike]: unknown;
};
 
export type Linkable = object | unknown[] | Set<unknown> | Map<KeyLike, unknown>;
export type LinkableSchema = ZodObject | ZodArray;
export type ImmutableOutput<S> = Immutable<ModelOutput<S>>;
export type ReadonlyLink = Immutable<Linkable>;
 
export type ModelArray = ZodArray;
export type ModelObject = ZodObject;
export type ModelInput<S> = input<S>;
export type ModelOutput<S> = output<S>;
export type ModelError = $ZodError;
export type ModelIssue = $ZodIssue;
export type ModelIssues = ModelIssue[];
export type ParseResult<T> = ZodSafeParseResult<T>;
 
export type StateTracker = (init: Linkable, key: KeyLike) => boolean;
export type StateKeyTracker = (key: KeyLike) => boolean;
export type StatePublicTracker = (init: Linkable, observers: StateObserverList, key: KeyLike) => void;
export type StateObserver = {
  readonly id: string;
  readonly states: WeakMap<State, Set<KeyLike>>;
  readonly assign: (init: Linkable, observers: StateObserverList) => StateKeyTracker;
  readonly onChange: (event: StateChange) => void;
  readonly destroy: () => void;
  readonly reset: () => void;
  readonly run: <R>(fn: () => R) => R;
  name?: string;
};
 
export type BatchMutation = (typeof BATCH_MUTATIONS)[number] | `${(typeof BATCH_MUTATIONS)[number]}`;
export type SetMutation = (typeof SET_MUTATIONS)[number] | `${(typeof SET_MUTATIONS)[number]}`;
export type MapMutation = (typeof MAP_MUTATIONS)[number] | `${(typeof MAP_MUTATIONS)[number]}`;
export type ArrayMutation = (typeof ARRAY_MUTATIONS)[number] | `${(typeof ARRAY_MUTATIONS)[number]}`;
export type ObjectMutation = (typeof OBJECT_MUTATIONS)[number] | `${(typeof OBJECT_MUTATIONS)[number]}`;
export type StateMutation = ArrayMutation | ObjectMutation | SetMutation | MapMutation | BatchMutation;
 
export type StateBaseOptions = {
  cloned?: boolean;
  strict?: boolean;
  ordered?: boolean;
  deferred?: boolean;
  recursive?: Recursive;
  immutable?: boolean;
  observable?: boolean;
  silentInit?: boolean;
  compare?: (a: unknown, b: unknown) => number;
};
export type StateOptions<S extends LinkableSchema = LinkableSchema> = StateBaseOptions & { schema?: S };
 
export type AnchorSettings = StateBaseOptions & {
  production: boolean;
  safeObservation: boolean;
  safeObservationThreshold: number;
  closureWarning?: boolean;
};
 
export type StateSubscriber<T> = (snapshot: T, event: StateChange, emitter?: string) => void;
export type StateUnsubscribe = () => void;
export type StateDestroyer = () => void;
export type StateSubscribeFn<T> = ((
  handle: StateSubscriber<T>,
  receiver?: Linkable,
  recursive?: boolean
) => StateUnsubscribe) & {
  all: (handle: StateSubscriber<T>, receiver?: Linkable, recursive?: boolean) => StateUnsubscribe;
};
export type StateSubscriberList<T extends Linkable = Linkable> = Set<StateSubscriber<T>>;
export type StateObserverList = Set<StateObserver>;
export type StateSubscriptionMap = Map<Linkable, StateUnsubscribe>;
export type StateLinkFn = (childKey: KeyLike, childState: Linkable, receiver?: Linkable) => void;
export type StateUnlinkFn = (childState: Linkable) => void;
 
export type State<T extends Linkable = Linkable> = T;
export type StateMetadata<
  T extends Linkable = Linkable,
  S extends LinkableSchema = LinkableSchema,
  RootType extends Linkable = Linkable,
  RootSchema extends LinkableSchema = LinkableSchema,
  ParentType extends Linkable = Linkable,
  ParentSchema extends LinkableSchema = LinkableSchema,
> = {
  id: string;
  type: Linkables;
  cloned: boolean;
  configs: StateBaseOptions;
  observers: StateObserverList;
  subscribers: StateSubscriberList<T>;
  subscriptions: StateSubscriptionMap;
  exceptionHandlers: StateExceptionHandlerList;
  root?: StateMetadata<RootType, RootSchema>;
  parent?: StateMetadata<ParentType, ParentSchema>;
  schema?: S;
};
 
export type MapMutator<K, V> = {
  set(key: K, value: V): void;
  delete(key: K): void;
  clear(): void;
};
 
export type SetMutator<V> = {
  add(value: V): void;
  delete(value: V): void;
  clear(): void;
};
 
export type ArrayMutator<T> = {
  push(...items: T[]): void;
  pop(): T | undefined;
  shift(): T | undefined;
  unshift(...items: T[]): void;
  splice(start: number, deleteCount?: number, ...items: T[]): T[];
  reverse(): T[];
  sort(compareFn?: (a: T, b: T) => number): T[];
  fill(value: T, start?: number, end?: number): T[];
  copyWithin(target: number, start: number, end?: number): T[];
};
 
export type StateMutator<T extends Linkable> = T extends Set<infer U>
  ? SetMutator<U>
  : T extends Map<infer K, infer V>
    ? MapMutator<K, V>
    : T extends Array<infer U>
      ? ArrayMutator<U>
      : never;
 
export type StateGetter<T extends Linkable> = (target: T, prop: keyof T | KeyLike, receiver?: unknown) => unknown;
export type StateSetter<T extends Linkable> = (
  target: T,
  prop: keyof T | KeyLike,
  value?: unknown,
  receiver?: unknown
) => unknown;
export type StateRemover<T extends Linkable> = (target: T, prop: keyof T | KeyLike, receiver?: unknown) => unknown;
 
export type StateRelation = {
  link: StateLinkFn;
  unlink: StateUnlinkFn;
};
 
export type StateGateway<T extends Linkable = Linkable> = {
  getter: StateGetter<T>;
  setter: StateSetter<T>;
  remover: StateRemover<T>;
  broadcaster: Broadcaster;
  mutator?: StateMutator<T>;
};
 
export type StateController<T extends Linkable = Linkable, S extends LinkableSchema = LinkableSchema> = {
  meta: StateMetadata<T, S>;
  destroy: StateDestroyer;
  subscribe: StateSubscribeFn<T>;
};
 
export type StatePropGetter<T extends Linkable = Linkable> = (
  target: T,
  prop: keyof T,
  receiver?: unknown
) => T[keyof T];
 
export type TrapOverrides = {
  configs: StateBaseOptions;
  mutator?: WeakMap<WeakKey, MethodLike>;
};
 
export type StateChange = {
  type: 'init' | StateMutation;
  keys: KeyLike[];
  prev?: unknown;
  value?: unknown;
  error?: ModelError;
  emitter?: string;
};
export type BatchChange = StateChange & {
  changes: KeyLike[];
};
 
export type StateException = StateChange & {
  error: Error | ModelError;
  issues?: ModelIssues;
};
 
export type StateExceptionHandler = (exception: StateException) => void;
export type StateExceptionHandlerList = Set<StateExceptionHandler>;
 
export type PipeTransformer<T, R> = (value: T) => Partial<R>;
 
export type SubscribeFactoryInit = {
  link: StateLinkFn;
  unlink: StateUnlinkFn;
};
 
export type NestedPath<T> = T extends Array<infer U>
  ? `${number}` | (NestedPath<U> extends infer P ? (P extends string ? `${number}.${P}` : never) : never)
  : T extends object
    ? {
        [K in keyof T]: K extends string
          ? `${K}` | (NestedPath<T[K]> extends infer P ? (P extends string ? `${K}.${P}` : never) : never)
          : never;
      }[keyof T]
    : never;
 
export type ExceptionType = {
  error: ModelError | Error;
  message: string;
};
export type ExceptionMap<T extends ObjLike | Array<unknown>> = {
  [K in NestedPath<T>]?: ExceptionType;
};
export type StateExceptionMap<T extends ObjLike | Array<unknown>> = {
  errors: ExceptionMap<T>;
  destroy: StateUnsubscribe;
};
 
export type Immutable<T> = T extends Primitive
  ? T
  : T extends Map<infer K, infer V>
    ? ReadonlyMap<Immutable<K>, Immutable<V>>
    : T extends Set<infer U>
      ? ReadonlySet<Immutable<U>>
      : T extends object
        ? {
            readonly [P in keyof T]: Immutable<T[P]>;
          }
        : T extends Array<infer U>
          ? ReadonlyArray<Immutable<U>>
          : T;
 
export type Mutable<T> = T extends ReadonlyMap<infer K, infer V>
  ? Map<K, V>
  : T extends ReadonlySet<infer U>
    ? Set<U>
    : T extends ReadonlyArray<infer U>
      ? {
          -readonly [P in keyof T]: P extends keyof Array<U> ? Array<U>[P] : never;
        }
      : {
          -readonly [P in keyof T]: T[P];
        };
 
export type MutationKey<T> = T extends ReadonlyMap<unknown, unknown>
  ? MapMutation
  : T extends ReadonlySet<unknown>
    ? SetMutation
    : T extends ReadonlyArray<unknown>
      ? ArrayMutation
      : keyof T;
 
export type MergedType<T> = { [P in keyof T]: T[P] } & {};
 
export type MutablePart<T, K extends MutationKey<T>[]> = T extends ReadonlyMap<infer M, infer V>
  ? T & {
      -readonly [P in K[number]]: P extends keyof Map<M, V> ? Map<M, V>[P] : never;
    }
  : T extends ReadonlySet<infer U>
    ? T & {
        -readonly [P in K[number]]: P extends keyof Set<U> ? Set<U>[P] : never;
      }
    : T extends ReadonlyArray<infer U>
      ? T & {
          -readonly [P in K[number]]: P extends keyof Array<U> ? Array<U>[P] : never;
        }
      : MergedType<
          Omit<T, K[number]> & {
            -readonly [P in K[number]]: P extends keyof T ? T[P] : never;
          }
        >;
 
/**
 * Extracts the keys of an object that are not readonly.
 *
 * This type uses conditional types to determine which properties of T are writable:
 * 1. For each property P in T, it creates a test object with P as the only property
 * 2. It then checks if this property can be made non-readonly
 * 3. If it can, the key P is included in the result
 *
 * @template T - The object type to extract writable keys from
 * @returns A union of keys that are not readonly in T
 */
export type WritableKeys<T> = {
  [P in keyof T]-?: (<Q>() => Q extends { [K in P]: T[K] } ? 1 : 2) extends <R>() => R extends {
    -readonly [K in P]: T[K];
  }
    ? 1
    : 2
    ? P
    : never;
}[keyof T];
 
/**
 * Creates a new type containing only the writable properties of T.
 *
 * This type combines WritableKeys with Pick to create a new object type
 * that only includes the properties of T that are not readonly.
 *
 * @template T - The object type to pick writable properties from
 * @returns A new object type with only the writable properties of T
 */
export type Writable<T> = Pick<T, WritableKeys<T>>;
 
/**
 * Anchor function interface that provides state management capabilities.
 *
 * @template T - The type of the initial state
 * @template S - The schema type for validation
 */
export interface Anchor {
  /**
   * Creates a reactive state with optional configuration.
   *
   * @param init - Initial state value
   * @param options - Configuration options for the state
   * @returns Reactive state object
   */
  <T extends Linkable, S extends LinkableSchema = LinkableSchema>(init: T, options?: StateOptions<S>): State<T>;
 
  /**
   * Creates a reactive state with schema validation.
   *
   * @param init - Initial state value
   * @param schema - Zod schema for validation
   * @param options - Configuration options
   * @returns Validated reactive state object
   */
  <S extends LinkableSchema, T extends ModelInput<S>>(init: T, schema: S, options?: StateBaseOptions): ModelOutput<S>;
 
  /**
   * Creates an immutable reactive state with schema validation.
   *
   * @param init - Initial state value
   * @param schema - Zod schema for validation
   * @param options - Configuration options with immutable flag
   * @returns Immutable validated reactive state object
   */
  <S extends LinkableSchema, T extends ModelInput<S>>(
    init: T,
    schema: S,
    options?: StateBaseOptions & { immutable: true }
  ): ImmutableOutput<S>;
 
  // Initializer methods.
 
  /**
   * Creates a raw reactive state without making a clone of the initial state.
   *
   * @param init - Initial state value
   * @param options - Configuration options
   * @returns Raw reactive state object
   */
  raw<T extends Linkable, S extends LinkableSchema = LinkableSchema>(init: T, options?: StateOptions<S>): State<T>;
 
  /**
   * Creates a flat reactive state that only tracks top-level properties.
   *
   * @param init - Initial array state
   * @param options - Configuration options
   * @returns Flat reactive array state
   */
  flat<T extends unknown[], S extends LinkableSchema = LinkableSchema>(init: T, options?: StateOptions<S>): State<T>;
 
  /**
   * Creates an ordered reactive array that maintains sort order based on the provided comparison function.
   *
   * @template T - The type of the array elements
   * @template S - The schema type for validation
   * @param init - Initial array state
   * @param compare - Comparison function to determine sort order
   * @param options - Configuration options
   * @returns Ordered reactive array state
   */
  ordered<T extends unknown[], S extends LinkableSchema = LinkableSchema>(
    init: T,
    compare: (a: T[number], b: T[number]) => number,
    options?: StateOptions<S>
  ): State<T>;
 
  /**
   * Creates a reactive state with schema validation.
   *
   * @param schema - Zod schema for validation
   * @param init - Initial state value
   * @param options - Configuration options
   * @returns Validated reactive state object
   */
  model<S extends LinkableSchema, T extends ModelInput<S>>(
    schema: S,
    init: T,
    options?: StateBaseOptions
  ): ModelOutput<S>;
 
  /**
   * Creates an immutable reactive state with schema validation.
   *
   * @template S - The schema type for validation.
   * @template T - The input type for the schema.
   * @param schema - Zod schema for validation.
   * @param init - Initial state value.
   * @param options - Configuration options with immutable flag set to true.
   * @returns Immutable validated reactive state object.
   */
  model<S extends LinkableSchema, T extends ModelInput<S>>(
    schema: S,
    init: T,
    options?: StateBaseOptions & { immutable: true }
  ): Immutable<ModelOutput<S>>;
 
  /**
   * Creates an immutable reactive state.
   *
   * @param init - Initial state value
   * @param options - Configuration options
   * @returns Immutable reactive state object
   */
  immutable<T extends Linkable, S extends LinkableSchema = LinkableSchema>(
    init: T,
    options?: StateOptions<S>
  ): Immutable<T>;
 
  /**
   * Creates an immutable reactive state with schema validation.
   *
   * @param init - Initial state value
   * @param schema - Zod schema for validation
   * @param options - Configuration options
   * @returns Immutable validated reactive state object
   */
  immutable<S extends LinkableSchema, T extends ModelInput<S>>(
    init: T,
    schema: S,
    options?: StateBaseOptions
  ): ImmutableOutput<S>;
 
  // Accessibility methods.
 
  /**
   * Checks if a given state is reactive.
   *
   * @template T - The type of the state
   * @param state - The state to check
   * @returns True if the state is reactive, false otherwise
   */
  has<T extends State>(state: T): boolean;
 
  /**
   * Gets the current state value.
   *
   * @param state - The reactive state
   * @returns Current state value
   */
  get<T extends Linkable>(state: State<T>): T;
 
  /**
   * Finds and returns a reactive state instance that matches the given initial state.
   *
   * This method is used to retrieve an existing reactive state instance when you have
   * a reference to the original state object. It's particularly useful when you need
   * to access a state that was previously created but don't have a direct reference
   * to its reactive wrapper.
   *
   * @template T - The type of the state object
   * @param {T} init - The initial state object to find the reactive instance for
   * @returns {T} The reactive state instance if found, otherwise the original object
   */
  find<T extends Linkable>(init: T): T;
 
  /**
   * Creates a read-only version of the given state.
   *
   * This method returns an `Immutable<T>` type, which is a deep readonly version of the state.
   * It is useful for scenarios where you want to ensure that a state object
   * cannot be modified, providing immutability guarantees while
   * enabling optimizations for read-only access by bypassing reactive traps.
   *
   * The returned object is a proxy that prevents direct mutations.
   *
   * @param state - The state object to make read-only.
   * @returns A read-only proxy of the state.
   */
  read<T extends State>(state: T): Immutable<T>;
 
  /**
   * Retrieves the exception map for a given state, allowing access to validation errors and exceptions.
   *
   * This method returns a **StateExceptionMap** which contains:
   * - **errors**: A map of property paths to their corresponding validation errors
   * - **destroy**: A function to unsubscribe from the exception map
   *
   * @template T - The type of the state object or array
   * @param {T} state - The reactive state object or array to get exceptions for
   * @returns {StateExceptionMap<T>} An object containing the error map and unsubscribe function
   */
  catch<T extends ObjLike | Array<unknown>>(state: T): StateExceptionMap<T>;
 
  /**
   * Registers an exception handler for a given state to catch and handle errors during state mutations.
   *
   * This method allows you to set up error handling for a specific state. When an error occurs
   * during a state mutation (such as a Zod validation error), the provided handler function
   * will be called with details about the exception.
   *
   * @template T - The type of the state
   * @param state - The reactive state to attach the exception handler to
   * @param handler - The exception handler function that will be called when an error occurs
   * @returns A function that can be called to unsubscribe/remove the exception handler
   */
  catch<T extends State>(state: T, handler: StateExceptionHandler): StateUnsubscribe;
 
  /**
   * Creates a snapshot of the current state.
   *
   * @param state - The reactive state
   * @returns State snapshot
   */
  snapshot<T extends Linkable>(state: State<T>): T;
 
  /**
   * Makes a readonly state writable.
   *
   * @param state - The readonly state
   * @returns Writable state object
   */
  writable<T extends ReadonlyLink>(state: T): Mutable<T>;
 
  /**
   * Makes a readonly state writable with specific contracts.
   *
   * @param init - The readonly state
   * @param contracts - Keys that should be mutable
   * @returns Partially writable state object
   */
  writable<T extends ReadonlyLink, K extends MutationKey<T>[]>(init: T, contracts?: K): MutablePart<T, K>;
 
  // Utility methods.
 
  /**
   * Assigns properties from source to target object.
   *
   * @param target - Target object
   * @param source - Source object with properties to assign
   */
  assign<T, K>(target: Map<T, K>, source: Map<T, K> | Record<KeyLike, K>): void;
  assign<T extends unknown[]>(target: T, source: { [key: string]: T[number] } | Record<string, T[number]>): void;
  assign<T extends object>(target: T, source: Partial<T>): void;
 
  /**
   * Removes keys from a collection.
   *
   * @param target - Target collection
   * @param keys - Keys to remove
   */
  remove<T, K>(target: Map<T, K>, ...keys: Array<T>): void;
  remove<T extends unknown[]>(target: T, ...keys: Array<string>): void;
  remove<T extends object>(target: T, ...keys: Array<keyof T>): void;
 
  /**
   * Clears all entries from a collection.
   *
   * @param target - Target collection to clear
   */
  clear<T>(target: T): void;
 
  /**
   * Destroys a reactive state and cleans up all associated resources.
   *
   * This function retrieves the controller associated with the given state
   * and calls its destroy method, effectively cleaning up all observers,
   * subscribers, and references. If the state does not exist, an error is logged.
   *
   * @template T The type of the state to destroy.
   * @param {T} state - The reactive state to destroy.
   */
  destroy<T extends State>(state: T): void;
 
  /**
   * Configures global Anchor settings.
   *
   * @param {Partial<AnchorSettings>} config - Partial configuration object
   */
  configure(config: Partial<AnchorSettings>): void;
 
  /**
   * Gets the global Anchor settings.
   * @returns {AnchorSettings}
   */
  configs(): AnchorSettings;
}
 
export type AnchorInternalFn = <T extends Linkable, S extends LinkableSchema>(
  init: T,
  options: StateOptions<S>,
  root?: StateMetadata,
  parent?: StateMetadata
) => State<T>;
 
/**
 * Function type for broadcasting state changes to subscribers.
 *
 * @param snapshot - The current state snapshot
 * @param event - The state change event details
 * @param emitter - Optional emitter identifier
 */
export type BroadcastFn = (snapshot: Linkable, event: StateChange, emitter?: string) => void;
 
/**
 * Function type for emitting state changes to subscribers.
 *
 * @param event - The state change event details
 * @param prop - Optional property key that was changed
 */
export type EmitFn = (event: StateChange, prop?: KeyLike) => void;
 
/**
 * Interface for broadcasting state changes to subscribers.
 */
export type Broadcaster = {
  /**
   * Emits a state change event.
   *
   * @param event - The state change event details
   * @param prop - Optional property key that was changed
   */
  emit: EmitFn;
 
  /**
   * Catches and handles Zod validation errors that occur during state mutations.
   *
   * @param error - The Zod validation error that occurred
   * @param event - The state change event that triggered the error
   */
  catch: (error: ModelError, event: StateChange) => boolean;
 
  /**
   * Broadcasts a state change to all subscribers.
   *
   * @param snapshot - The current state snapshot
   * @param event - The state change event details
   * @param emitter - Optional emitter identifier
   */
  broadcast: BroadcastFn;
};
 
export interface SubscribeFn {
  /**
   * Create a new subscription from an existing anchored state.
   * This is a convenience function to subscribe to changes of an already anchored state.
   *
   * @template T The type of the state.
   * @param state - The anchored state object to subscribe from.
   * @param handler - The subscriber function to call on state changes.
   * @param recursive - Whether to recursively subscribe to child states (Default: follow).
   * @returns A function to unsubscribe from the subscribed state.
   */ <T>(state: T, handler: StateSubscriber<T>, recursive?: boolean): StateUnsubscribe;
 
  /**
   * Subscribe to changes in the provided state and log it to the console.
   * This is a convenience method that uses `console.log` as the subscriber function.
   *
   * @template T The type of the state.
   * @param state The anchored state object to subscribe to.
   * @returns A function to unsubscribe from the logging subscription.
   */
  log<T extends Linkable>(state: State<T>): StateUnsubscribe;
 
  /**
   * Pipe changes of the source state to a target state.
   * This function allows you to synchronize changes from a source state to a target state,
   * with an optional transformation function to modify the data during the transfer.
   *
   * @template Source The type of the source state.
   * @template Target The type of the target state.
   * @param source The source state object to pipe from.
   * @param target The target state object to pipe to.
   * @param transform An optional function to transform the source state before assigning it to the target.
   * @returns A function to unsubscribe from the piping operation.
   */
  pipe<Source extends State, Target extends Linkable>(
    source: Source,
    target: Target,
    transform?: PipeTransformer<Source, Target>
  ): StateUnsubscribe;
 
  /**
   * Bind two states together, synchronizing changes between them.
   * This function allows you to keep two states in sync, with optional transformation functions
   * to modify the data during the transfer in both directions.
   *
   * @template Left The type of the left state.
   * @template Right The type of the right state.
   * @param left The left state object to bind.
   * @param right The right state object to bind.
   * @param transformLeft An optional function to transform the left state before assigning it to the right.
   * @param transformRight An optional function to transform the right state before assigning it to the left.
   * @returns A function to unsubscribe from the binding operation.
   */
  bind<Left extends State, Right extends State>(
    left: Left,
    right: Right,
    transformLeft?: PipeTransformer<Left, Right>,
    transformRight?: PipeTransformer<Right, Left>
  ): StateUnsubscribe;
 
  /**
   * Resolves the [StateController] for a given anchored state.
   * This allows direct access to the [set] methods of the controller.
   *
   * @template T The type of the state.
   * @param state The anchored state object.
   * @returns The [StateController] if not found.
   */
  resolve<T extends Linkable>(state: State<T>): StateController<T> | undefined;
}
 
export type DevTool = {
  /**
   * A callback that will be called when a property is accessed.
   * @param {StateMetadata} meta - State metadata associated with the event.
   * @param {KeyLike} prop
   */
  onGet?: <T extends Linkable, S extends LinkableSchema>(meta: StateMetadata<T, S>, prop: KeyLike) => void;
  /**
   * A callback that will be called when a property is set.
   * @param {StateMetadata} meta - State metadata associated with the event.
   * @param {KeyLike} prop
   * @param {unknown} value
   */
  onSet?: <T extends Linkable, S extends LinkableSchema>(
    meta: StateMetadata<T, S>,
    prop: KeyLike,
    value: unknown
  ) => void;
  /**
   * A callback that will be called when a property is deleted.
   * @param {StateMetadata} meta
   * @param {KeyLike} prop
   */
  onDelete?: <T extends Linkable, S extends LinkableSchema>(meta: StateMetadata<T, S>, prop: KeyLike) => void;
  /**
   * A callback that will be called when a method is called.
   * @param {StateMetadata} meta - State metadata associated with the event.
   * @param {string} method
   * @param {unknown[]} args
   */
  onCall?: <T extends Linkable, S extends LinkableSchema>(
    meta: StateMetadata<T, S>,
    method: string,
    args: unknown[]
  ) => void;
  /**
   * A callback that will be called when a state is initialized.
   * @param {StateMetadata} meta - State metadata associated with the event.
   */
  onInit?: <T extends Linkable, S extends LinkableSchema>(init: T, meta: StateMetadata<T, S>) => void;
  /**
   * A callback that will be called when a bulk assignment is performed.
   * @param {StateMetadata} meta - State metadata associated with the event.
   * @param {ObjLike} source
   */
  onAssign?: <T extends Linkable, S extends LinkableSchema>(meta: StateMetadata<T, S>, source: ObjLike) => void;
  /**
   * A callback that will be called when a bulk removal is performed.
   * @param {StateMetadata} meta - State metadata associated with the event.
   * @param {KeyLike[]} props
   */
  onRemove?: <T extends Linkable, S extends LinkableSchema>(meta: StateMetadata<T, S>, props: KeyLike[]) => void;
  /**
   * A callback that will be called when a state is cleared.
   * @param {StateMetadata} meta - State metadata associated with the event.
   */
  onClear?: <T extends Linkable, S extends LinkableSchema>(meta: StateMetadata<T, S>) => void;
  /**
   * A callback that will be called when a state is destroyed.
   * @param {StateMetadata} meta - State metadata associated with the event.
   */
  onDestroy?: <T extends Linkable, S extends LinkableSchema>(init: T, meta: StateMetadata<T, S>) => void;
  /**
   * A callback that will be called when a subscriber is added.
   * @param {StateMetadata} meta - State metadata associated with the event.
   * @param {StateSubscriber<Linkable>} handler
   */
  onSubscribe?: <T extends Linkable, S extends LinkableSchema>(
    meta: StateMetadata<T, S>,
    handler: StateSubscriber<T>,
    receiver?: Linkable
  ) => void;
  /**
   * A callback that will be called when a subscriber is removed.
   * @param {StateMetadata} meta - State metadata associated with the event.
   * @param {StateSubscriber<Linkable>} handler
   */
  onUnsubscribe?: <T extends Linkable, S extends LinkableSchema>(
    meta: StateMetadata<T, S>,
    handler: StateSubscriber<T>,
    receiver?: Linkable
  ) => void;
  /**
   * A callback that will be called when a child reference is linked.
   * @param {StateMetadata} meta
   * @param {StateMetadata} child
   */
  onLink?: <T extends Linkable, S extends LinkableSchema>(meta: StateMetadata<T, S>, child: StateMetadata) => void;
  /**
   * A callback that will be called when a child reference is unlinked.
   * @param {StateMetadata} meta
   * @param {StateMetadata} child
   */
  onUnlink?: <T extends Linkable, S extends LinkableSchema>(meta: StateMetadata<T, S>, child: StateMetadata) => void;
  /**
   * A callback that will be called when a state is being tracked by an observer.
   * @param {StateMetadata} meta
   * @param {StateObserver} observer
   */
  onTrack?: <T extends Linkable, S extends LinkableSchema>(
    meta: StateMetadata<T, S>,
    observer: StateObserver,
    key: KeyLike
  ) => void;
  /**
   * A callback that will be called when a state is no longer being tracked by an observer.
   * @param {StateMetadata} meta
   * @param {StateObserver} observer
   */
  onUntrack?: <T extends Linkable, S extends LinkableSchema>(
    meta: StateMetadata<T, S>,
    observer: StateObserver
  ) => void;
};
 
export type Assignable = ObjLike | Map<unknown, unknown> | Array<unknown>;
export type AssignablePart<T> = Partial<Record<keyof T, T[keyof T]>>;
export type StateBinding<T, B> = B extends StateBindingRef<T>
  ? StateBindingRef<T>
  : B extends ObjLike
    ? BindingProp<T, B>
    : never;
export type StateBindingRef<T> = {
  get value(): T;
  set value(value: T);
};
export type BindingProp<T, O> = [O, BindingKeys<T, O>];
export type BindingKeys<T, O> = WritableKeys<{ [K in keyof O]: O[K] extends T ? K : never }>;
 
export const AsyncStatus = {
  Idle: 'idle',
  Error: 'error',
  Success: 'success',
  Pending: 'pending',
} as const;
 
export type AsyncStatus = Enum<typeof AsyncStatus>;
 
export type AsyncState<T, E extends Error = Error> = {
  readonly data: T;
  readonly status: AsyncStatus;
  readonly promise: Promise<T | undefined>;
  readonly start: (init?: T) => Promise<T | undefined>;
  readonly abort: (error?: E) => void;
  readonly error?: E;
};
export type AsyncOptions = StateOptions & {
  deferred?: boolean;
};
 
/**
 * A function type that represents an asynchronous operation that can be cancelled.
 * @template R - The return type of the async operation
 * @param signal - An AbortSignal that can be used to cancel the operation or check for cancellation.
 * @returns A Promise that resolves with the result of the operation
 */
export type AsyncHandler<R> = (signal: AbortSignal) => Promise<R>;
 
type RefScopeValue = {
  init: unknown;
  value: unknown;
};
 
export type RefStack = {
  index: number;
  states: Map<number, RefScopeValue>;
};
 
export type ValueRef<T> = MutableRef<T> | ImmutableRef<T> | DerivedRef<T>;
 
export type EffectHandler<T> = (event: StateChange) => StateUnsubscribe | T;