All files / core/src async.ts

100% Statements 95/95
100% Branches 30/30
100% Functions 6/6
100% Lines 95/95

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 1671x 1x 1x                                                                 1x 8x 8x 8x 8x 8x 8x 8x   8x 9x 1x 1x 1x   9x 1x 1x   9x 9x   9x 9x 9x 9x 9x 9x 3x 1x 3x 2x 2x 9x 9x 9x 9x 9x   8x 2x   1x 2x 2x   8x 8x 8x 8x 8x 8x 8x 3x 3x 8x 8x 8x 8x   8x 3x 3x   8x 8x                                               1x 16x 2x 2x   14x   14x 14x   14x 5x 5x 5x 5x   14x 13x 13x 10x 7x 7x   10x 10x 13x 13x 2x 1x 1x   2x 2x 13x   13x 14x 1x 1x 1x 14x 14x  
import { anchor } from './anchor.js';
import { mutable, writable } from './ref.js';
import { type AsyncHandler, type AsyncOptions, type AsyncState, AsyncStatus, type Linkable } from './types.js';
 
export function asyncState<T extends Linkable, E extends Error = Error>(
  fn: AsyncHandler<T>
): AsyncState<T, E> & { data?: T };
export function asyncState<T extends Linkable, E extends Error = Error>(
  fn: AsyncHandler<T>,
  init: T,
  options?: AsyncOptions
): AsyncState<T, E>;
 
/**
 * Creates a reactive state container for managing asynchronous operations with built-in cancellation support.
 *
 * This function initializes a state object that tracks the status of an async operation (idle, pending, success, error)
 * and provides methods to start and abort the operation. The state automatically handles cancellation using
 * AbortController and updates its status accordingly.
 *
 * @template T - The type of data that the async operation will return
 * @template E - The type of error that the async operation might throw (defaults to generic Error)
 *
 * @param fn - An async function that performs the actual operation and accepts an AbortSignal for cancellation
 * @param init - The initial value for the data property
 * @param options - Configuration options for the async state behavior
 * @param options.deferred - If true, the async operation won't start automatically when the state is created
 *
 * @returns An immutable state object containing:
 *   - data: The current data value (initial or from successful async operation)
 *   - status: Current status of the async operation (idle, pending, success, or error)
 *   - start: Function to initiate the async operation
 *   - abort: Function to cancel the ongoing async operation
 *   - error: The error object if the operation failed
 */
export function asyncState<T extends Linkable, E extends Error = Error>(
  fn: AsyncHandler<T>,
  init?: T,
  options?: AsyncOptions
): AsyncState<T, E> {
  let controller: AbortController | undefined;
  let abortError: E | undefined;
  let activePromise: Promise<T | undefined> | undefined;
 
  const start = (async (newInit) => {
    if (writer.status === AsyncStatus.Pending) {
      controller?.abort();
      abortError = undefined;
    }
 
    if (newInit) {
      writer.data = mutable(newInit, options);
    }
 
    controller = new AbortController();
    writer.status = AsyncStatus.Pending;
 
    try {
      activePromise = cancelable(fn, controller.signal);
      const data = await activePromise;
      anchor.assign(writer, { status: AsyncStatus.Success, data: data ? mutable(data, options) : data });
      return data;
    } catch (error) {
      if (controller.signal.aborted && abortError) {
        anchor.assign(writer, { status: AsyncStatus.Error, error: abortError });
      } else {
        anchor.assign(writer, { status: AsyncStatus.Error, error: error as E });
      }
    } finally {
      controller = undefined;
      abortError = undefined;
    }
  }) as AsyncState<T, E>['start'];
 
  const abort = ((error) => {
    if (controller?.signal.aborted) return;
 
    abortError = error;
    controller?.abort(error);
  }) as AsyncState<T, E>['abort'];
 
  const state = mutable<AsyncState<T, E>>(
    {
      data: (init ? mutable(init, options) : undefined) as T,
      status: AsyncStatus.Idle,
      start,
      abort,
      get promise() {
        return activePromise ?? Promise.resolve(undefined);
      },
    },
    { immutable: true }
  );
  const writer = writable(state);
 
  if (!options?.deferred) {
    state.start();
  }
 
  return state as AsyncState<T, E>;
}
 
/**
 * Creates a cancelable promise from a synchronous function.
 * @param fn - A synchronous function that doesn't require an AbortSignal
 * @param signal - The AbortSignal to watch for cancellation
 * @returns A Promise that resolves with the result of the function or rejects if cancelled
 */
export function cancelable<R>(fn: () => R, signal: AbortSignal): Promise<R>;
 
/**
 * Creates a cancelable promise from an asynchronous function.
 * @param fn - An asynchronous function that accepts an AbortSignal for cancellation
 * @param signal - The AbortSignal to pass to the function and watch for cancellation
 * @returns A Promise that resolves with the result of the function or rejects if cancelled
 */
export function cancelable<R>(fn: (signal: AbortSignal) => Promise<R>, signal: AbortSignal): Promise<R>;
 
/**
 * Creates a cancelable promise from either a synchronous or asynchronous function.
 * @param fn - A function that may be synchronous or asynchronous and optionally use an AbortSignal
 * @param signal - The AbortSignal to pass to the function (if it accepts one) and watch for cancellation
 * @returns A Promise that resolves with the result of the function or rejects if cancelled
 */
export function cancelable<R>(fn: (signal: AbortSignal) => Promise<R> | R, signal: AbortSignal): Promise<R> {
  if (signal.aborted) {
    return Promise.reject(signal.reason);
  }
 
  let resolved = false;
 
  return new Promise<R>((resolve, reject) => {
    const result = fn(signal);
 
    const handleAbort = () => {
      if (!resolved) {
        reject(signal.reason);
      }
    };
 
    if (result instanceof Promise) {
      result
        .then((res) => {
          if (!signal?.aborted) {
            resolve(res);
          }
 
          resolved = true;
          signal?.removeEventListener('abort', handleAbort);
        })
        .catch((e) => {
          if (!signal?.aborted) {
            reject(e);
          }
 
          resolved = true;
          signal?.removeEventListener('abort', handleAbort);
        });
 
      signal?.addEventListener('abort', handleAbort, { once: true });
    } else {
      resolve(result);
      resolved = true;
    }
  });
}