All files / core/src async.ts

100% Statements 134/134
100% Branches 48/48
100% Functions 8/8
100% Lines 134/134

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 2391x 1x                                                                   1x 9x 9x 9x 9x 9x 9x 9x   9x 11x 1x 1x 1x   11x 1x 1x   11x 11x   11x 11x   11x 11x   11x 11x 5x 1x 5x 4x 4x 11x 11x 11x 11x 11x   9x 2x   1x   1x 2x 2x   9x 9x 9x 9x 9x 9x 9x 3x 3x 9x 9x 9x 9x   9x 3x 3x   9x 9x         1x                                               1x 18x 2x 2x   16x   16x 16x   16x 5x 5x 5x 5x   16x 15x 15x 10x 7x 7x   10x 10x 15x 15x 4x 3x 3x   4x 4x 15x   15x 16x 1x 1x 1x 16x 16x                                 1x 13x 13x 13x 13x 13x 13x 13x   13x 16x 1x 1x   15x 15x 16x 10x 1x 1x   10x 6x 6x   10x 10x   3x 3x 16x   13x 1x 1x 1x 1x 1x   1x 1x   1x 1x   12x 12x  
import { AsyncStatus } from './constant.js';
import { mutable, writable } from './ref.js';
import type { AsyncHandler, AsyncOptions, AsyncState, Linkable, RetriableOptions } from './types.js';
 
export function query<T extends Linkable, E extends Error = Error>(
  fn: AsyncHandler<T>
): AsyncState<T, E> & { data?: T };
export function query<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 query<T extends Linkable, E extends Error = Error>(
  fn: AsyncHandler<T>,
  init?: T,
  options?: AsyncOptions
): Readonly<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();
    Object.assign(writer, { status: AsyncStatus.Pending, error: undefined });
 
    try {
      activePromise = cancelable(fn, controller.signal);
 
      const data = await activePromise;
      Object.assign(writer, { status: AsyncStatus.Success, data: data ? mutable(data, options) : data });
 
      return data;
    } catch (error) {
      if (controller.signal.aborted && abortError) {
        Object.assign(writer, { status: AsyncStatus.Aborted, error: abortError });
      } else {
        Object.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;
 
    Object.assign(writer, { status: AsyncStatus.Aborted, error: undefined });
 
    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, recursive: false }
  );
  const writer = writable(state);
 
  if (!options?.deferred) {
    state.start();
  }
 
  return state as AsyncState<T, E>;
}
 
/**
 * @deprecated Use "query()" instead.
 */
export const asyncState = query;
 
/**
 * 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;
    }
  });
}
 
/**
 * Executes an asynchronous function with retry logic and optional timeout.
 *
 * This function wraps an async call and automatically retries it on failure up to a specified
 * number of times with configurable delays between attempts. It also supports timeout and
 * cancellation via AbortController.
 *
 * @template T - The type of the value that the promise resolves to
 *
 * @param call - An asynchronous function that accepts an AbortSignal and returns a Promise
 * @param options - Configuration options for retry behavior and timeout
 *
 * @returns A Promise that resolves with the result of the call, or rejects with an error
 *          if all retry attempts fail or if the timeout is reached
 */
export function retriable<T>(call: (signal: AbortSignal) => Promise<T> | T, options?: RetriableOptions) {
  const {
    timeout = 0,
    retryMode = 'exponential',
    maxRetries = 0,
    retryDelay = 1000,
    controller = new AbortController(),
  } = { ...options };
 
  const execute = async (retries = 0) => {
    if (controller.signal.aborted) {
      throw new Error('Call was aborted');
    }
 
    try {
      return await call(controller.signal);
    } catch (error) {
      if (controller.signal.aborted) {
        throw new Error('Call was aborted');
      }
 
      if (retries >= maxRetries) {
        throw error;
      }
 
      const delay = retryMode === 'linear' ? retryDelay : retryDelay * 2 ** retries;
      await new Promise((resolve) => setTimeout(resolve, delay));
 
      return execute(retries + 1);
    }
  };
 
  if (timeout) {
    const timer = new Promise((_, reject) => {
      const timeId = setTimeout(() => {
        controller.abort();
        reject(new Error('Call timed out'));
      }, timeout);
 
      controller.signal.addEventListener('abort', () => clearTimeout(timeId));
    });
 
    return Promise.race([timer, execute()]);
  }
 
  return execute();
}