All files / core/src factory.ts

100% Statements 153/153
100% Branches 56/56
100% Functions 9/9
100% Lines 153/153

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                      1x                             1x 1x 1x                               1x 645x 645x 645x 645x 645x   645x 64x     63x 63x 63x     64x 63x   176x 113x   113x 113x 176x   63x 63x 63x     63x     63x   63x 63x 64x 645x                         1x 644x 644x   644x 58x   58x 58x 58x   58x 2x 2x 2x 2x 58x 58x 644x                                   1x 644x 644x 644x 644x 644x 644x 644x   644x   180x 180x 180x 1x 1x 1x   179x   166x     163x     166x   152x   41x 45x 41x 41x 152x   166x 166x       180x 2x 2x 2x 2x 2x 2x 2x 2x     177x   180x 169x 242x   242x 8x 8x 242x 169x   180x     180x 180x   644x 1x 1x 1x   644x 644x                                     1x 644x 644x   644x   16x   16x 1x 1x 1x 1x     16x 1x 1x 1x 1x 1x   1x 1x   16x 3x 3x 3x   3x 3x   16x 21x   21x 5x   5x 4x 4x 5x 21x     14x 14x     14x 14x 14x   14x 14x 14x 14x   14x 14x 14x 14x 14x 14x   16x 16x   644x 644x  
import type {
  Broadcaster,
  KeyLike,
  Linkable,
  ObjLike,
  State,
  StateMetadata,
  StateSubscribeFn,
  StateSubscriber,
  SubscribeFactoryInit,
} from './types.js';
import {
  BROADCASTER_REGISTRY,
  CONTROLLER_REGISTRY,
  EXCEPTION_HANDLER_REGISTRY,
  INIT_GATEWAY_REGISTRY,
  INIT_REGISTRY,
  META_INIT_REGISTRY,
  META_REGISTRY,
  MUTATOR_REGISTRY,
  RELATION_REGISTRY,
  SORTER_REGISTRY,
  STATE_REGISTRY,
  SUBSCRIBER_REGISTRY,
  SUBSCRIPTION_REGISTRY,
} from './registry.js';
import { captureStack } from './exception.js';
import { shortId, softEntries, softValues } from './utils/index.js';
import { getDevTool } from './dev.js';
 
/**
 * Creates a factory function for linking child states to a parent state.
 *
 * This factory generates a function that establishes a connection between a child state and its parent,
 * allowing state changes in the child to propagate up through the state tree. The linking process
 * involves subscribing to the child state's changes and broadcasting them with an updated path that
 * includes the child's key.
 *
 * @template T - The type of the parent state
 * @param init - The initial value of the parent state
 * @param meta - The metadata associated with the parent state
 * @returns {(childPath: KeyLike, childState: State, receiver?: State) => void}
 *          A function that links a child state to the parent state
 */
export function createLinkFactory<T extends Linkable>(
  init: T,
  meta: StateMetadata<T>
): (childPath: KeyLike, childState: State, receiver?: State) => void {
  const devTool = getDevTool();
  const broadcaster = BROADCASTER_REGISTRY.get(init) as Broadcaster;
 
  return (childPath: KeyLike, childState: State, receiver?: State): void => {
    if (meta.subscriptions.has(childState)) return;
 
    // Get the controller for the child state
    const childInit = STATE_REGISTRY.get(childState) as Linkable;
    const childMeta = META_REGISTRY.get(childInit) as StateMetadata;
    const childController = CONTROLLER_REGISTRY.get(childState);
 
    // If the child state has a valid controller with subscribe method
    if (typeof childController?.subscribe === 'function') {
      const childHandler: StateSubscriber<unknown> = (_, event, emitter) => {
        // Ignore init events to prevent duplicate notifications
        if (event && event.type !== 'init') {
          const keys = [childPath, ...event.keys] as KeyLike[];
          // Broadcast the event with modified path to include the key
          broadcaster.broadcast(init, { ...event, keys }, emitter);
        }
      };
 
      Object.defineProperty(childHandler, '__internal_id__', {
        value: meta.id,
      });
 
      // Subscribe to the child state changes
      const childUnsubscribe = childController.subscribe(childHandler, receiver);
 
      // Store the unsubscribe function for cleanup
      meta.subscriptions.set(childState, childUnsubscribe);
 
      devTool?.onLink?.(meta, childMeta);
    }
  };
}
 
/**
 * Creates a factory function for unlinking child states from a parent state.
 *
 * This factory generates a function that removes the connection between a child state and its parent,
 * cleaning up subscriptions and preventing further state change propagation from the child to the parent.
 * The unlinking process involves calling the stored unsubscribe function for the child state and
 * removing the subscription reference from the tracking map.
 *
 * @param meta - The metadata object associated with the child state
 * @returns {(childState: Linkable) => void} A function that unlinks a child state from the parent state
 */
export function createUnlinkFactory<T extends Linkable>(meta: StateMetadata<T>): (childState: Linkable) => void {
  const devTool = getDevTool();
  const { subscriptions } = meta;
 
  return (childState: State) => {
    const unsubscribe = subscriptions.get(childState);
 
    if (typeof unsubscribe === 'function') {
      unsubscribe();
      subscriptions.delete(childState);
 
      if (devTool?.onUnlink) {
        const childInit = STATE_REGISTRY.get(childState) as Linkable;
        const childMeta = META_REGISTRY.get(childInit) as StateMetadata;
        devTool.onUnlink(meta, childMeta);
      }
    }
  };
}
 
/**
 * Creates a factory function for subscribing to state changes.
 *
 * This factory generates a function that allows observers to subscribe to state changes,
 * immediately notifying them with the current state. It manages subscriber registration,
 * handles duplicate subscriptions, links child states for nested reactivity, and provides
 * an unsubscribe mechanism. When the last subscriber is removed, it automatically cleans
 * up all child state subscriptions.
 *
 * @template T - The type of the state being subscribed to
 * @param init - The initial state value
 * @param state - The state associated with the init
 * @param meta - The metadata associated with the init
 * @param helper - Utilities to handle the subscriptions
 * @returns {StateSubscribeFn<T>} A function that subscribes a handler to state changes
 */
export function createSubscribeFactory<T extends Linkable>(
  init: T,
  state: State<T>,
  meta: StateMetadata<T>,
  helper: SubscribeFactoryInit
): StateSubscribeFn<T> {
  const devTool = getDevTool();
  const { subscribers, subscriptions } = meta;
 
  const subscribeFn = (handler: StateSubscriber<T>, receiver?: State, recursive = meta.configs.recursive) => {
    // Immediately notify the handler with the current state.
    try {
      handler(init, { type: 'init', keys: [] });
    } catch (error) {
      captureStack.error.external('Unable to execute the subscription handler function', error as Error);
      return () => {};
    }
 
    const unsubscribeFn = () => {
      // Do nothing if no subscribers left for potential multiple unsubscribe calls.
      if (!subscribers.size) return;
 
      // Remove the handler from active subscribers
      subscribers.delete(handler);
 
      // If no more subscribers, clean up resources
      if (subscribers.size <= 0 && recursive) {
        // Unlink all child references if any exist
        if (subscriptions.size) {
          // Iterate over a copy of the subscriptions map to safely unlink
          subscriptions.forEach((_, val) => {
            helper.unlink(val as State);
          });
        }
      }
 
      devTool?.onUnsubscribe?.(meta, handler, receiver);
    };
 
    // Check if the handler is already subscribed.
    // If it is, return an empty unsubscribe function to prevent duplicate notifications.
    if (subscribers.has(handler)) {
      captureStack.warning.external(
        'Duplicate subscription',
        'Attempted to subscribe to a state using the same handler multiple times.',
        'Subscription handler already registered',
        subscribeFn
      );
      return unsubscribeFn;
    }
 
    // Add the handler to the list of active subscribers
    subscribers.add(handler);
 
    if (recursive && !(Array.isArray(init) && meta.configs.recursive === 'flat')) {
      for (const [key, value] of softEntries(init as ObjLike)) {
        const childState = INIT_REGISTRY.get(value as Linkable) as State;
 
        if (childState && !subscriptions.has(childState) && childState !== receiver) {
          helper.link(key, childState, (receiver ?? state) as State);
        }
      }
    }
 
    devTool?.onSubscribe?.(meta, handler, receiver);
 
    // Return the unsubscribe function
    return unsubscribeFn;
  };
 
  subscribeFn.all = (handler: StateSubscriber<T>, receiver?: State, recursive = meta.configs.recursive) => {
    Object.defineProperty(handler, '__internal_id__', { value: shortId() });
    return subscribeFn(handler, receiver, recursive);
  };
 
  return subscribeFn;
}
 
/**
 * Creates a factory function for destroying a state and cleaning up all associated resources.
 *
 * This factory generates a function that completely destroys a state by:
 * 1. Unsubscribing all active subscriptions to child states
 * 2. Clearing all subscribers and subscriptions
 * 3. Removing the state from all internal registries (INIT, META, REFERENCE, STATE, CONTROLLER, SUBSCRIBER,
 * SUBSCRIPTION)
 *
 * This cleanup process ensures no memory leaks and properly disconnects the state from the reactive system.
 *
 * @template T - The type of the state being destroyed
 * @param init - Initial state value
 * @param state - The state object to be destroyed and removed from registries
 * @param meta - The metadata associated with the state
 * @returns {() => void} A function that destroys the state and cleans up all resources
 */
export function createDestroyFactory<T extends Linkable>(init: T, state: State<T>, meta: StateMetadata<T>): () => void {
  const devTool = getDevTool();
  const { observers, subscribers, subscriptions, exceptionHandlers } = meta;
 
  const handler = (propagation?: boolean) => {
    // Prevents destroying a state that is already destroyed.
    if (!INIT_REGISTRY.has(init)) return;
 
    if (propagation && subscribers.size) {
      const error = new Error('State is active');
      captureStack.error.internal('Attempted to destroy state that still active', error, handler);
      return;
    }
 
    // Removing the destroyed state from all observers.
    if (observers.size) {
      for (const observer of observers) {
        if (observer.states.has(init)) {
          observer.states.delete(init);
        }
      }
 
      observers.clear();
    }
 
    if (subscriptions.size) {
      for (const unsubscribe of subscriptions.values()) {
        unsubscribe?.();
      }
 
      subscriptions.clear();
    }
 
    for (const childInit of softValues(init as { [key: string]: Linkable })) {
      const childState = INIT_REGISTRY.get(childInit as Linkable) as State;
 
      if (childState) {
        const childController = CONTROLLER_REGISTRY.get(childState);
 
        if (!childController?.meta.subscribers.size) {
          (childController?.destroy as (prop: boolean) => void)(true);
        }
      }
    }
 
    // Cleaning up the subscriber list.
    subscribers.clear();
    exceptionHandlers.clear();
 
    // Remove the state from STATE_REGISTRY and STATE_LINK.
    INIT_REGISTRY.delete(init);
    META_REGISTRY.delete(init);
    SORTER_REGISTRY.delete(init);
 
    RELATION_REGISTRY.delete(init);
    MUTATOR_REGISTRY.delete(init);
    BROADCASTER_REGISTRY.delete(init);
    INIT_GATEWAY_REGISTRY.delete(init);
 
    STATE_REGISTRY.delete(state);
    CONTROLLER_REGISTRY.delete(state);
    SUBSCRIBER_REGISTRY.delete(state);
    SUBSCRIPTION_REGISTRY.delete(state);
    EXCEPTION_HANDLER_REGISTRY.delete(state);
    META_INIT_REGISTRY.delete(meta as StateMetadata);
 
    devTool?.onDestroy?.(init, meta);
  };
 
  return handler;
}