{"version":3,"file":"index.mjs","names":[],"sources":["../src/primitives/internal/utils.ts","../src/primitives/abort-hook.ts","../src/primitives/delay.ts","../src/primitives/defer.ts","../src/primitives/mutex.ts","../src/primitives/deferred.ts","../src/primitives/conditional.ts","../src/primitives/deferred-generator.ts","../src/primitives/internal/logical-context.ts","../src/primitives/logical-context.ts","../src/primitives/async-local.ts","../src/primitives/semaphore.ts","../src/primitives/reader-writer-lock.ts","../src/primitives/async-operator.ts"],"sourcesContent":["// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport { Releasable } from '../../types';\n\n/**\n * A no-op Releasable object that does nothing when released or disposed\n */\nexport const __NOOP_HANDLER = () => {};\nexport const __NOOP_RELEASABLE: Releasable = {\n  release: __NOOP_HANDLER,\n  [Symbol.dispose]: __NOOP_HANDLER,\n} as const;\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport { Releasable } from '../types';\nimport { __NOOP_RELEASABLE } from './internal/utils';\n\nconst toAbortError = (reason: unknown): Error => {\n  if (reason instanceof Error) {\n    return reason;\n  }\n  if (typeof reason === 'string') {\n    return new Error(reason);\n  }\n  return new Error('Operation aborted');\n};\n\n/**\n * Hooks up an abort handler to an AbortSignal and returns a handle for early cleanup\n * @param signal - The AbortSignal to hook up to\n * @param callback - The callback to call when the signal is aborted\n * @returns A Releasable handle that can be used to remove the abort listener early\n */\nexport const onAbort = (\n  signal: AbortSignal | undefined,\n  callback: (error: Error) => void\n): Releasable => {\n  if (!signal) {\n    return __NOOP_RELEASABLE;\n  }\n\n  if (signal.aborted) {\n    try {\n      callback(toAbortError(signal.reason));\n    } catch (error: unknown) {\n      console.warn('AbortHook callback error: ', error);\n    }\n    return __NOOP_RELEASABLE;\n  }\n\n  let abortHandler: (() => void) | undefined;\n  abortHandler = () => {\n    if (abortHandler) {\n      const reason = signal.reason;\n      signal.removeEventListener('abort', abortHandler);\n      abortHandler = undefined;\n\n      try {\n        callback(toAbortError(reason));\n      } catch (error: unknown) {\n        console.warn('AbortHook callback error: ', error);\n      }\n    }\n  };\n\n  const release = (): void => {\n    if (abortHandler) {\n      signal.removeEventListener('abort', abortHandler);\n      abortHandler = undefined;\n    }\n  };\n\n  signal.addEventListener('abort', abortHandler, { once: true });\n\n  // Create the releasable handle\n  const handle: Releasable = {\n    release,\n    [Symbol.dispose]: release,\n  };\n  return handle;\n};\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport { onAbort } from './abort-hook';\n\n/**\n * Helper function to create a delay\n * @param msec - The number of milliseconds to delay\n * @param signal - Optional AbortSignal to cancel the delay\n * @returns A promise that resolves after the delay or rejects if aborted\n */\nexport const delay = (msec: number, signal?: AbortSignal): Promise<void> => {\n  if (signal) {\n    // Check if already aborted\n    if (signal.aborted) {\n      throw new Error('Delay was aborted');\n    }\n\n    // Require aborting handler\n    return new Promise<void>((resolve, reject) => {\n      const abortHandle = onAbort(signal, () => {\n        clearTimeout(timeoutId);\n        reject(new Error('Delay was aborted'));\n      });\n\n      const timeoutId = setTimeout(() => {\n        abortHandle.release();\n        resolve();\n      }, msec);\n    });\n  } else {\n    // Without aborting handler\n    return new Promise<void>((resolve) => {\n      setTimeout(resolve, msec);\n    });\n  }\n};\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\n/**\n * Defer execution of a callback to the next tick.\n * @param fn - The function to execute.\n */\ntype RuntimeSetImmediate = ((callback: () => void) => unknown) | undefined;\n\ntype RuntimeGlobal = typeof globalThis & {\n  setImmediate?: RuntimeSetImmediate;\n};\n\nconst runtimeGlobal = globalThis as RuntimeGlobal;\n\nexport const defer = (fn: () => void): void => {\n  const setImmediateHandler = runtimeGlobal.setImmediate;\n  if (typeof setImmediateHandler === 'function') {\n    setImmediateHandler(fn);\n    return;\n  }\n\n  globalThis.setTimeout(fn, 0);\n};\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport { Mutex, LockHandle } from '../types';\nimport { onAbort } from './abort-hook';\nimport { defer } from './defer';\n\n/**\n * Internal queue item for lock requests\n */\ninterface QueueItem {\n  /** Promise resolver for the lock acquisition */\n  resolve: (handle: LockHandle) => void;\n  /** Promise rejecter for the lock acquisition */\n  reject: (error: Error) => void;\n  /** Optional AbortSignal for cancelling the request */\n  signal?: AbortSignal | undefined;\n}\n\nconst ABORTED_ERROR = () => new Error('Lock acquisition was aborted');\n\n/**\n * Creates a new LockHandle instance\n * @param releaseCallback Callback function to release the lock\n * @returns A LockHandle object with release and dispose functionality\n */\nconst createLockHandle = (releaseCallback: () => void): LockHandle => {\n  let isActive = true;\n\n  const release = (): void => {\n    if (!isActive) {\n      return;\n    }\n    isActive = false;\n    releaseCallback();\n  };\n\n  return {\n    get isActive() {\n      return isActive;\n    },\n    release,\n    [Symbol.dispose]: release,\n  };\n};\n\n/**\n * Creates a new Mutex instance\n * @param maxConsecutiveCalls - The maximum number of consecutive calls to the lockAsync method before yielding control to the next item in the queue\n * @returns A new Mutex for promise-based mutex operations\n */\nexport const createMutex = (maxConsecutiveCalls: number = 20): Mutex => {\n  let isLocked = false;\n  const queue: QueueItem[] = [];\n  let count = 0; // Consecutive execution counter\n\n  const processQueue = (): void => {\n    if (isLocked || queue.length === 0) {\n      return;\n    }\n\n    const item = queue.shift()!;\n\n    // Check if the request was aborted\n    if (item.signal?.aborted) {\n      item.reject(ABORTED_ERROR());\n      // Process next item in queue with counting\n      scheduleNextProcess();\n      return;\n    }\n\n    isLocked = true;\n\n    // Continue to locked awaiter with lockHandle\n    const lockHandle = createLockHandle(releaseLock);\n    item.resolve(lockHandle);\n  };\n\n  const scheduleNextProcess = (): void => {\n    count++;\n\n    // Yield control with defer delay every maxConsecutiveCalls consecutive executions\n    if (count >= maxConsecutiveCalls) {\n      count = 0;\n      defer(processQueue);\n    } else {\n      // Direct call is sufficient since it's controlled by counter\n      processQueue();\n    }\n  };\n\n  const releaseLock = (): void => {\n    if (!isLocked) {\n      return;\n    }\n\n    isLocked = false;\n    // Process next item in queue with batching control\n    scheduleNextProcess();\n  };\n\n  const removeFromQueue = (item: QueueItem): void => {\n    const index = queue.indexOf(item);\n    if (index !== -1) {\n      queue.splice(index, 1);\n    }\n  };\n\n  const lock = async (signal?: AbortSignal): Promise<LockHandle> => {\n    if (signal) {\n      // Check if already aborted\n      if (signal.aborted) {\n        throw ABORTED_ERROR();\n      }\n\n      return new Promise<LockHandle>((resolve, reject) => {\n        // Handle case with AbortSignal\n        const queueItem: QueueItem = {\n          resolve: undefined!,\n          reject: undefined!,\n          signal,\n        };\n\n        const abortHandle = onAbort(signal, () => {\n          removeFromQueue(queueItem);\n          reject(ABORTED_ERROR());\n        });\n\n        // Wrap to clean up\n        queueItem.resolve = (handle: LockHandle) => {\n          abortHandle.release();\n          resolve(handle);\n        };\n        queueItem.reject = (error: Error) => {\n          abortHandle.release();\n          reject(error);\n        };\n\n        queue.push(queueItem);\n        processQueue();\n      });\n    } else {\n      return new Promise<LockHandle>((resolve, reject) => {\n        // Handle case without AbortSignal\n        queue.push({\n          resolve,\n          reject,\n        });\n        processQueue();\n      });\n    }\n  };\n\n  const result: Mutex = {\n    lock,\n    waiter: {\n      wait: lock,\n    },\n    get isLocked() {\n      return isLocked;\n    },\n    get pendingCount() {\n      return queue.length;\n    },\n  };\n\n  return result;\n};\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport { Deferred } from '../types';\nimport { onAbort } from './abort-hook';\n\n/**\n * Creates a new deferred object\n * @param T - The type of the result\n * @param signal - Optional AbortSignal for cancelling the wait\n * @returns A deferred object with a promise, resolve, and reject methods\n */\nexport const createDeferred = <T>(signal?: AbortSignal): Deferred<T> => {\n  let resolve: ((value: T) => void) | undefined;\n  let reject: ((error: any) => void) | undefined;\n\n  // Allocate the promise\n  const promise = new Promise<T>((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n\n  // Register the abort hook\n  const disposer = onAbort(signal, () => {\n    // Release the resolve and reject functions\n    const _reject = reject;\n    if (_reject) {\n      resolve = undefined;\n      reject = undefined;\n\n      // Reject the promise with an error\n      _reject(new Error('Deferred aborted'));\n    }\n  });\n\n  // Return the deferred object\n  return {\n    // The promise that resolves to the result\n    promise,\n    // Resolve the promise with a result\n    resolve: (value: T) => {\n      const _resolve = resolve;\n      if (_resolve) {\n        // Release the resolve and reject functions\n        resolve = undefined;\n        reject = undefined;\n\n        // Release the abort hook\n        disposer.release();\n\n        // Resolve the promise with a result\n        _resolve(value);\n      }\n    },\n    // Reject the promise with an error\n    reject: (error: any) => {\n      const _reject = reject;\n      if (_reject) {\n        // Release the resolve and reject functions\n        resolve = undefined;\n        reject = undefined;\n\n        // Release the abort hook\n        disposer.release();\n\n        // Reject the promise with an error\n        _reject(error);\n      }\n    },\n  };\n};\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport {\n  Deferred,\n  ManuallyConditional,\n  Conditional,\n  LockHandle,\n} from '../types';\nimport { onAbort } from './abort-hook';\nimport { createDeferred } from './deferred';\nimport { __NOOP_HANDLER } from './internal/utils';\n\nconst __NOOP_DUMMY_HANDLE: LockHandle = {\n  get isActive() {\n    return false;\n  },\n  release: __NOOP_HANDLER,\n  [Symbol.dispose]: __NOOP_HANDLER,\n} as const;\n\n/**\n * Creates a conditional that can be automatically triggered\n * @returns A conditional that can be automatically triggered\n */\nexport const createConditional = (): Conditional => {\n  const waiters: Deferred<void>[] = [];\n\n  const trigger = () => {\n    if (waiters.length >= 1) {\n      waiters.shift()!.resolve();\n    }\n  };\n\n  const wait = async (signal?: AbortSignal) => {\n    if (signal?.aborted) {\n      throw new Error('Conditional aborted');\n    }\n    const waiter = createDeferred<void>();\n    waiters.push(waiter);\n    const disposer = onAbort(signal, () => {\n      waiters.splice(waiters.indexOf(waiter), 1);\n      waiter.reject(new Error('Conditional aborted'));\n    });\n    try {\n      await waiter.promise;\n    } finally {\n      disposer.release();\n    }\n    return __NOOP_DUMMY_HANDLE;\n  };\n\n  const result: Conditional = {\n    trigger,\n    wait: wait as any,\n    waiter: {\n      wait,\n    },\n  };\n\n  return result;\n};\n\n/**\n * Creates a conditional that can be manually set and reset\n * @param initialState - Optional initial state of the conditional (Default: false, dropped)\n * @returns A conditional that can be manually set and reset\n */\nexport const createManuallyConditional = (\n  initialState?: boolean\n): ManuallyConditional => {\n  const waiters: Deferred<void>[] = [];\n  let raised = initialState ?? false;\n\n  const trigger = () => {\n    raised = false;\n    const waiter = waiters.shift();\n    if (waiter) {\n      waiter.resolve();\n      raised = false;\n    }\n  };\n\n  const raise = () => {\n    while (waiters.length >= 1) {\n      raised = true;\n      waiters.shift()!.resolve();\n    }\n    raised = true;\n  };\n\n  const drop = () => {\n    raised = false;\n  };\n\n  const wait = async (signal?: AbortSignal) => {\n    if (raised) {\n      return __NOOP_DUMMY_HANDLE;\n    }\n    if (signal?.aborted) {\n      throw new Error('Conditional aborted');\n    }\n    const waiter = createDeferred<void>();\n    waiters.push(waiter);\n    const disposer = onAbort(signal, () => {\n      waiters.splice(waiters.indexOf(waiter), 1);\n      waiter.reject(new Error('Conditional aborted'));\n    });\n    try {\n      await waiter.promise;\n    } finally {\n      disposer.release();\n    }\n    return __NOOP_DUMMY_HANDLE;\n  };\n\n  const result: ManuallyConditional = {\n    trigger,\n    raise,\n    drop,\n    wait: wait as any,\n    waiter: {\n      wait,\n    },\n  };\n\n  return result;\n};\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport { DeferredGenerator, DeferredGeneratorOptions } from '../types';\nimport { createManuallyConditional } from './conditional';\n\ninterface QueuedValue<T> {\n  readonly kind: 'value';\n  readonly value: T;\n}\n\ninterface QueuedCompletion {\n  readonly kind: 'completed';\n}\n\ninterface QueuedError {\n  readonly kind: 'error';\n  readonly error: any;\n}\n\ntype QueuedItem<T> = QueuedValue<T> | QueuedCompletion | QueuedError;\n\n/**\n * Creates a new deferred generator object\n * @param T - The type of the yielded values\n * @param options - Optional options for the deferred generator\n * @returns A deferred generator object with an async generator and control functions\n */\nexport const createDeferredGenerator = <T>(\n  options?: DeferredGeneratorOptions\n): DeferredGenerator<T> => {\n  const maxItemReserved = options?.maxItemReserved;\n  const signal = options?.signal;\n  const queue: QueuedItem<T>[] = [];\n  const arrived = createManuallyConditional();\n  const canReserve = maxItemReserved\n    ? createManuallyConditional(true)\n    : undefined;\n\n  // Allocate the async generator\n  const generator = (async function* () {\n    // Generator iteration loop\n    while (true) {\n      // Process remaining items in the queue\n      while (true) {\n        // Get the next item from the queue\n        const item = queue.shift();\n        // If the queue is not full, raise the signal to release the suspending operator\n        if (maxItemReserved && queue.length === maxItemReserved - 1) {\n          canReserve!.raise();\n        }\n        // No more items, break the loop\n        if (!item) {\n          break;\n        }\n        // Process the item\n        switch (item.kind) {\n          // Yield return a value\n          case 'value':\n            yield item.value;\n            break;\n          // Completed, exit the generator\n          case 'completed':\n            return;\n          // Error, throw an error\n          case 'error':\n            throw item.error;\n        }\n        // When the signal is aborted, throw an error\n        if (signal?.aborted) {\n          throw new Error('Deferred generator aborted');\n        }\n      }\n      // Drop the signal because the queue is empty\n      arrived.drop();\n      // Wait for the signal to be raised, or the signal is aborted\n      try {\n        await arrived.wait(signal);\n      } catch (error: unknown) {\n        // If the signal is aborted, throw a more descriptive error\n        if (error instanceof Error && error.message === 'Conditional aborted') {\n          error.message = 'Deferred generator aborted';\n        }\n        // Rethrow the error\n        throw error;\n      }\n      // When the signal is raised, maybe next item is available\n    }\n  })();\n\n  // Enqueue an item to the queue\n  const enqueue = async (\n    item: QueuedItem<T>,\n    signal: AbortSignal | undefined\n  ) => {\n    while (true) {\n      if (!maxItemReserved || queue.length < maxItemReserved) {\n        const remains = queue.push(item);\n        if (remains === 1) {\n          // Raise the signal to release the consumer\n          arrived.raise();\n        }\n        if (remains === maxItemReserved) {\n          // Drop the signal because the queue is full\n          canReserve!.drop();\n        }\n        break;\n      }\n      // Wait for the signal to be raised, or the signal is aborted\n      try {\n        await canReserve!.wait(signal);\n      } catch (error: unknown) {\n        // If the signal is aborted, throw a more descriptive error\n        if (error instanceof Error && error.message === 'Conditional aborted') {\n          error.message = 'Deferred generator aborted';\n        }\n        // Rethrow the error\n        throw error;\n      }\n    }\n  };\n\n  return {\n    // The async generator that yields values\n    generator,\n    // Yield a value to the generator\n    yield: (value: T, signal?: AbortSignal) =>\n      enqueue({ kind: 'value', value }, signal),\n    // Complete the generator (equivalent to return)\n    return: (signal?: AbortSignal) => enqueue({ kind: 'completed' }, signal),\n    // Throw an error to the generator\n    throw: (error: any, signal?: AbortSignal) =>\n      enqueue({ kind: 'error', error }, signal),\n  };\n};\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\n// Logical context\nexport interface LogicalContext {\n  readonly id: symbol;\n  readonly data: Map<symbol, unknown>;\n}\n\ntype RuntimeCallback = (...args: any[]) => void;\n\ntype RuntimeSetImmediate =\n  | ((callback: RuntimeCallback, ...args: any[]) => unknown)\n  | undefined;\n\ntype RuntimeNextTick =\n  | ((callback: RuntimeCallback, ...args: any[]) => void)\n  | undefined;\n\ntype RuntimeProcess = {\n  nextTick?: RuntimeNextTick;\n};\n\ntype RuntimeGlobal = typeof globalThis & {\n  setImmediate?: RuntimeSetImmediate;\n  process?: RuntimeProcess | undefined;\n};\n\nconst runtimeGlobal = globalThis as RuntimeGlobal;\nconst LOGICAL_CONTEXT_HOOK = Symbol('logical-context-hook');\n\ntype HookedFunction<T extends (...args: any[]) => any> = T & {\n  [LOGICAL_CONTEXT_HOOK]?: true;\n};\n\nconst isHooked = <T extends (...args: any[]) => any>(callback: T) => {\n  return (callback as HookedFunction<T>)[LOGICAL_CONTEXT_HOOK] === true;\n};\n\nconst markAsHooked = <T extends (...args: any[]) => any>(callback: T): T => {\n  (callback as HookedFunction<T>)[LOGICAL_CONTEXT_HOOK] = true;\n  return callback;\n};\n\n// Create a new logical context\nexport const createLogicalContext = (id: symbol): LogicalContext => {\n  return { id, data: new Map() };\n};\n\n// Current logical context (similar to LogicalContext.Current in .NET)\nexport let currentLogicalContext = createLogicalContext(Symbol('[root]'));\n\n// Set the current logical context\nexport const setCurrentLogicalContext = (context: LogicalContext) => {\n  currentLogicalContext = context;\n};\n\n// Logical context adjustment\nexport interface LogicalContextAdjustment {\n  readonly contextToUse: LogicalContext;\n  contextAfter: LogicalContext;\n}\n\n// Trampoline function to run a callback in a specific logical context\nexport const trampoline = <T extends any[]>(\n  adjustment: LogicalContextAdjustment,\n  callback: (...args: T) => any,\n  thisArg?: any,\n  ...args: T\n) => {\n  const previousLogicalContext = currentLogicalContext;\n  currentLogicalContext = adjustment.contextToUse;\n  try {\n    return callback.call(thisArg, ...args);\n  } finally {\n    adjustment.contextAfter = currentLogicalContext;\n    currentLogicalContext = previousLogicalContext;\n  }\n};\n\n// Whether the logical context system is prepared\nlet isPrepared = false;\n\nconst prepareRuntimeHooks = () => {\n  ///////////////////////////////////////////////////////////////\n\n  // Replace the global setTimeout with a version that captures the current logical context\n  if (\n    typeof globalThis.setTimeout !== 'undefined' &&\n    !isHooked(globalThis.setTimeout)\n  ) {\n    const __setTimeout = globalThis.setTimeout;\n    globalThis.setTimeout = markAsHooked(((\n      handler: (...args: any[]) => void,\n      timeout?: number,\n      ...args: any[]\n    ) => {\n      const capturedLogicalContext = currentLogicalContext;\n      return __setTimeout(\n        (...callbackArgs: any[]) => {\n          const adjustment = {\n            contextToUse: capturedLogicalContext,\n          } as LogicalContextAdjustment;\n          trampoline(adjustment, handler, undefined, ...callbackArgs);\n        },\n        timeout,\n        ...args\n      );\n    }) as typeof globalThis.setTimeout);\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace the global setInterval with a version that captures the current logical context\n  if (\n    typeof globalThis.setInterval !== 'undefined' &&\n    !isHooked(globalThis.setInterval)\n  ) {\n    const __setInterval = globalThis.setInterval;\n    globalThis.setInterval = markAsHooked(((\n      handler: (...args: any[]) => void,\n      timeout?: number,\n      ...args: any[]\n    ) => {\n      const capturedLogicalContext = currentLogicalContext;\n      return __setInterval(\n        (...callbackArgs: any[]) => {\n          const adjustment = {\n            contextToUse: capturedLogicalContext,\n          } as LogicalContextAdjustment;\n          trampoline(adjustment, handler, undefined, ...callbackArgs);\n        },\n        timeout,\n        ...args\n      );\n    }) as typeof globalThis.setInterval);\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace the global queueMicrotask with a version that captures the current logical context\n  if (\n    typeof globalThis.queueMicrotask !== 'undefined' &&\n    !isHooked(globalThis.queueMicrotask)\n  ) {\n    const __queueMicrotask = globalThis.queueMicrotask;\n    globalThis.queueMicrotask = markAsHooked((callback: () => void) => {\n      const capturedLogicalContext = currentLogicalContext;\n      return __queueMicrotask(() => {\n        const adjustment = {\n          contextToUse: capturedLogicalContext,\n        } as LogicalContextAdjustment;\n        trampoline(adjustment, callback, undefined);\n      });\n    });\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace the global setImmediate with a version that captures the current logical context (Node.js only)\n  const __setImmediate = runtimeGlobal.setImmediate;\n  if (typeof __setImmediate === 'function' && !isHooked(__setImmediate)) {\n    runtimeGlobal.setImmediate = markAsHooked(((\n      callback: (...args: any[]) => void,\n      ...args: any[]\n    ) => {\n      const capturedLogicalContext = currentLogicalContext;\n      return __setImmediate(\n        (...callbackArgs: any[]) => {\n          const adjustment = {\n            contextToUse: capturedLogicalContext,\n          } as LogicalContextAdjustment;\n          trampoline(adjustment, callback, undefined, ...callbackArgs);\n        },\n        ...args\n      );\n    }) as NonNullable<RuntimeSetImmediate>) as RuntimeSetImmediate;\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace the global process.nextTick with a version that captures the current logical context (Node.js only)\n  const runtimeProcess = runtimeGlobal.process;\n  if (\n    runtimeProcess &&\n    typeof runtimeProcess.nextTick === 'function' &&\n    !isHooked(runtimeProcess.nextTick)\n  ) {\n    const __nextTick = runtimeProcess.nextTick;\n    runtimeProcess.nextTick = markAsHooked(\n      (callback: (...args: any[]) => void, ...args: any[]) => {\n        const capturedLogicalContext = currentLogicalContext;\n        return __nextTick(() => {\n          const adjustment = {\n            contextToUse: capturedLogicalContext,\n          } as LogicalContextAdjustment;\n          trampoline(adjustment, callback, undefined, ...args);\n        });\n      }\n    );\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace requestAnimationFrame with a version that captures the current logical context\n  if (\n    typeof globalThis.requestAnimationFrame !== 'undefined' &&\n    !isHooked(globalThis.requestAnimationFrame)\n  ) {\n    const __requestAnimationFrame = globalThis.requestAnimationFrame;\n    globalThis.requestAnimationFrame = markAsHooked(\n      (callback: FrameRequestCallback) => {\n        const capturedLogicalContext = currentLogicalContext;\n        return __requestAnimationFrame((time: DOMHighResTimeStamp) => {\n          const adjustment = {\n            contextToUse: capturedLogicalContext,\n          } as LogicalContextAdjustment;\n          return trampoline(adjustment, callback, undefined, time);\n        });\n      }\n    );\n  }\n};\n\n// Prepare the logical context system\nexport const prepare = () => {\n  prepareRuntimeHooks();\n\n  if (isPrepared) {\n    return;\n  }\n  isPrepared = true;\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace the Promise functions with versions that capture the current logical context\n  if (typeof Promise !== 'undefined') {\n    const __then = Promise.prototype.then;\n    const __catch = Promise.prototype.catch;\n    const __finally = Promise.prototype.finally;\n\n    // Promise.then()\n    Promise.prototype.then = function <T, TResult1 = T, TResult2 = never>(\n      onFulfilled?:\n        | ((value: T) => TResult1 | PromiseLike<TResult1>)\n        | undefined\n        | null,\n      onRejected?:\n        | ((reason: any) => TResult2 | PromiseLike<TResult2>)\n        | undefined\n        | null\n    ): Promise<TResult1 | TResult2> {\n      const capturedLogicalContext = currentLogicalContext;\n      const resultPromise = __then.call(\n        this,\n        onFulfilled\n          ? (value) => {\n              // Execute the continuation handler in the captured logical context (ConfigureAwait(true) behavior)\n              const adjustment = {\n                contextToUse: capturedLogicalContext,\n              } as LogicalContextAdjustment;\n              return trampoline(adjustment, onFulfilled, undefined, value);\n            }\n          : undefined,\n        onRejected\n          ? (reason) => {\n              // Execute the continuation handler in the captured logical context (ConfigureAwait(true) behavior)\n              const adjustment = {\n                contextToUse: capturedLogicalContext,\n              } as LogicalContextAdjustment;\n              return trampoline(adjustment, onRejected, undefined, reason);\n            }\n          : undefined\n      ) as Promise<TResult1 | TResult2>;\n\n      return resultPromise;\n    };\n\n    // Promise.catch()\n    Promise.prototype.catch = function <T = never>(\n      onRejected?: ((reason: any) => T | PromiseLike<T>) | undefined | null\n    ): Promise<T> {\n      const capturedLogicalContext = currentLogicalContext;\n      const resultPromise = __catch.call(\n        this,\n        onRejected\n          ? (reason) => {\n              // Execute the continuation handler in the captured logical context\n              const adjustment = {\n                contextToUse: capturedLogicalContext,\n              } as LogicalContextAdjustment;\n              return trampoline(adjustment, onRejected, undefined, reason);\n            }\n          : undefined\n      ) as Promise<T>;\n\n      return resultPromise;\n    };\n\n    // Promise.finally()\n    Promise.prototype.finally = function (\n      onFinally?: (() => void) | undefined | null\n    ): Promise<any> {\n      const capturedLogicalContext = currentLogicalContext;\n      const resultPromise = __finally.call(\n        this,\n        onFinally\n          ? () => {\n              // Execute the continuation handler in the captured logical context\n              const adjustment = {\n                contextToUse: capturedLogicalContext,\n              } as LogicalContextAdjustment;\n              return trampoline(adjustment, onFinally, undefined);\n            }\n          : undefined\n      );\n\n      return resultPromise;\n    };\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace EventTarget.prototype.addEventListener with captures the current logical context\n  if (\n    typeof EventTarget !== 'undefined' &&\n    EventTarget.prototype &&\n    EventTarget.prototype.addEventListener\n  ) {\n    const __eventTargetAddEventListener =\n      EventTarget.prototype.addEventListener;\n    EventTarget.prototype.addEventListener = function (\n      this: EventTarget,\n      type: string,\n      listener: EventListenerOrEventListenerObject | null,\n      options?: boolean | AddEventListenerOptions\n    ) {\n      if (listener === null || listener === undefined) {\n        return (__eventTargetAddEventListener as any).call(\n          this,\n          type,\n          listener,\n          options\n        );\n      }\n\n      if (typeof listener === 'function') {\n        const capturedLogicalContext = currentLogicalContext;\n        const wrappedListener = (event: Event) => {\n          const adjustment = {\n            contextToUse: capturedLogicalContext,\n          } as LogicalContextAdjustment;\n          return trampoline(adjustment, listener, event.currentTarget, event);\n        };\n        return __eventTargetAddEventListener.call(\n          this,\n          type,\n          wrappedListener,\n          options\n        );\n      } else if (typeof listener === 'object' && 'handleEvent' in listener) {\n        const capturedLogicalContext = currentLogicalContext;\n        const wrappedListener = {\n          handleEvent: (event: Event) => {\n            const adjustment = {\n              contextToUse: capturedLogicalContext,\n            } as LogicalContextAdjustment;\n            return trampoline(adjustment, () => listener.handleEvent(event));\n          },\n        };\n        return __eventTargetAddEventListener.call(\n          this,\n          type,\n          wrappedListener,\n          options\n        );\n      }\n\n      return (__eventTargetAddEventListener as any).call(\n        this,\n        type,\n        listener,\n        options\n      );\n    };\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace Element.prototype.addEventListener with a version that captures the current logical context\n  if (\n    typeof Element !== 'undefined' &&\n    Element.prototype &&\n    Element.prototype.addEventListener\n  ) {\n    const __elementAddEventListener = Element.prototype.addEventListener;\n    Element.prototype.addEventListener = function (\n      this: Element,\n      type: string,\n      listener: EventListenerOrEventListenerObject | null,\n      options?: boolean | AddEventListenerOptions\n    ) {\n      if (listener === null || listener === undefined) {\n        return (__elementAddEventListener as any).call(\n          this,\n          type,\n          listener,\n          options\n        );\n      }\n\n      if (typeof listener === 'function') {\n        const capturedLogicalContext = currentLogicalContext;\n        const wrappedListener = (event: Event) => {\n          const adjustment = {\n            contextToUse: capturedLogicalContext,\n          } as LogicalContextAdjustment;\n          return trampoline(adjustment, listener, event.currentTarget, event);\n        };\n        return __elementAddEventListener.call(\n          this,\n          type,\n          wrappedListener,\n          options\n        );\n      } else if (typeof listener === 'object' && 'handleEvent' in listener) {\n        const capturedLogicalContext = currentLogicalContext;\n        const wrappedListener = {\n          handleEvent: (event: Event) => {\n            const adjustment = {\n              contextToUse: capturedLogicalContext,\n            } as LogicalContextAdjustment;\n            return trampoline(adjustment, () => listener.handleEvent(event));\n          },\n        };\n        return __elementAddEventListener.call(\n          this,\n          type,\n          wrappedListener,\n          options\n        );\n      }\n\n      return (__elementAddEventListener as any).call(\n        this,\n        type,\n        listener,\n        options\n      );\n    };\n  }\n\n  // Replace XMLHttpRequest with a version that captures the current logical context\n  if (typeof globalThis.XMLHttpRequest !== 'undefined') {\n    const __XMLHttpRequest = globalThis.XMLHttpRequest;\n\n    globalThis.XMLHttpRequest = class extends __XMLHttpRequest {\n      private _userHandlers: Map<string, ((event: any) => void) | null> =\n        new Map();\n\n      constructor() {\n        super();\n\n        // Hook all event handler properties\n        const eventHandlerProperties = [\n          'onreadystatechange',\n          'onloadstart',\n          'onprogress',\n          'onabort',\n          'onerror',\n          'onload',\n          'ontimeout',\n          'onloadend',\n        ];\n\n        eventHandlerProperties.forEach((prop) => {\n          Object.defineProperty(this, prop, {\n            get: () => this._userHandlers.get(prop) || null,\n            set: (newHandler: ((event: any) => void) | null) => {\n              this._userHandlers.set(prop, newHandler);\n\n              if (newHandler && typeof newHandler === 'function') {\n                const capturedLogicalContext = currentLogicalContext;\n\n                // Set the wrapped handler using the parent's property descriptor\n                const wrappedHandler = function (this: any, event: any) {\n                  const adjustment = {\n                    contextToUse: capturedLogicalContext,\n                  } as LogicalContextAdjustment;\n                  return trampoline(adjustment, newHandler, this, event);\n                };\n\n                // Call the parent setter\n                const parentProto = Object.getPrototypeOf(\n                  Object.getPrototypeOf(this)\n                );\n                const descriptor = Object.getOwnPropertyDescriptor(\n                  parentProto,\n                  prop\n                );\n                if (descriptor && descriptor.set) {\n                  descriptor.set.call(this, wrappedHandler);\n                } else {\n                  // Fallback for older browsers or non-standard implementations\n                  (this as any)[`_${prop}`] = wrappedHandler;\n                }\n              } else {\n                // Clear handler\n                const parentProto = Object.getPrototypeOf(\n                  Object.getPrototypeOf(this)\n                );\n                const descriptor = Object.getOwnPropertyDescriptor(\n                  parentProto,\n                  prop\n                );\n                if (descriptor && descriptor.set) {\n                  descriptor.set.call(this, null);\n                } else {\n                  (this as any)[`_${prop}`] = null;\n                }\n              }\n            },\n            configurable: true,\n            enumerable: true,\n          });\n        });\n      }\n\n      addEventListener(\n        type: string,\n        listener: EventListenerOrEventListenerObject | null,\n        options?: boolean | AddEventListenerOptions\n      ) {\n        const capturedLogicalContext = currentLogicalContext;\n\n        if (!listener) {\n          return (super.addEventListener as any)(type, listener, options);\n        }\n\n        if (typeof listener === 'function') {\n          const wrappedListener = (event: Event) => {\n            const adjustment = {\n              contextToUse: capturedLogicalContext,\n            } as LogicalContextAdjustment;\n            return trampoline(adjustment, listener, event.currentTarget, event);\n          };\n          return super.addEventListener(type, wrappedListener, options);\n        } else if (typeof listener === 'object' && 'handleEvent' in listener) {\n          const wrappedListener = {\n            handleEvent: (event: Event) => {\n              const adjustment = {\n                contextToUse: capturedLogicalContext,\n              } as LogicalContextAdjustment;\n              return trampoline(adjustment, () => listener.handleEvent(event));\n            },\n          };\n          return super.addEventListener(type, wrappedListener, options);\n        }\n\n        return super.addEventListener(type, listener, options);\n      }\n    };\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace WebSocket with a version that captures the current logical context\n  if (typeof globalThis.WebSocket !== 'undefined') {\n    const __WebSocket = globalThis.WebSocket;\n\n    globalThis.WebSocket = class extends __WebSocket {\n      private _userHandlers: Map<string, ((event: any) => void) | null> =\n        new Map();\n\n      constructor(url: string | URL, protocols?: string | string[]) {\n        super(url, protocols);\n\n        // Hook all event handler properties\n        const eventHandlerProperties = [\n          'onopen',\n          'onmessage',\n          'onerror',\n          'onclose',\n        ];\n\n        eventHandlerProperties.forEach((prop) => {\n          Object.defineProperty(this, prop, {\n            get: () => this._userHandlers.get(prop) || null,\n            set: (newHandler: ((event: any) => void) | null) => {\n              this._userHandlers.set(prop, newHandler);\n\n              if (newHandler && typeof newHandler === 'function') {\n                const capturedLogicalContext = currentLogicalContext;\n\n                // Set the wrapped handler using the parent's property descriptor\n                const wrappedHandler = function (this: any, event: any) {\n                  const adjustment = {\n                    contextToUse: capturedLogicalContext,\n                  } as LogicalContextAdjustment;\n                  return trampoline(adjustment, newHandler, this, event);\n                };\n\n                // Call the parent setter\n                const parentProto = Object.getPrototypeOf(\n                  Object.getPrototypeOf(this)\n                );\n                const descriptor = Object.getOwnPropertyDescriptor(\n                  parentProto,\n                  prop\n                );\n                if (descriptor && descriptor.set) {\n                  descriptor.set.call(this, wrappedHandler);\n                } else {\n                  // Fallback for older browsers or non-standard implementations\n                  (this as any)[`_${prop}`] = wrappedHandler;\n                }\n              } else {\n                // Clear handler\n                const parentProto = Object.getPrototypeOf(\n                  Object.getPrototypeOf(this)\n                );\n                const descriptor = Object.getOwnPropertyDescriptor(\n                  parentProto,\n                  prop\n                );\n                if (descriptor && descriptor.set) {\n                  descriptor.set.call(this, null);\n                } else {\n                  (this as any)[`_${prop}`] = null;\n                }\n              }\n            },\n            configurable: true,\n            enumerable: true,\n          });\n        });\n      }\n\n      addEventListener(\n        type: string,\n        listener: EventListenerOrEventListenerObject | null,\n        options?: boolean | AddEventListenerOptions\n      ) {\n        const capturedLogicalContext = currentLogicalContext;\n\n        if (!listener) {\n          return (super.addEventListener as any)(type, listener, options);\n        }\n\n        if (typeof listener === 'function') {\n          const wrappedListener = (event: Event) => {\n            const adjustment = {\n              contextToUse: capturedLogicalContext,\n            } as LogicalContextAdjustment;\n            return trampoline(adjustment, listener, event.currentTarget, event);\n          };\n          return super.addEventListener(type, wrappedListener, options);\n        } else if (typeof listener === 'object' && 'handleEvent' in listener) {\n          const wrappedListener = {\n            handleEvent: (event: Event) => {\n              const adjustment = {\n                contextToUse: capturedLogicalContext,\n              } as LogicalContextAdjustment;\n              return trampoline(adjustment, () => listener.handleEvent(event));\n            },\n          };\n          return super.addEventListener(type, wrappedListener, options);\n        }\n\n        return super.addEventListener(type, listener, options);\n      }\n    };\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace MutationObserver with a version that captures the current logical context\n  if (typeof globalThis.MutationObserver !== 'undefined') {\n    const __MutationObserver = globalThis.MutationObserver;\n\n    globalThis.MutationObserver = class extends __MutationObserver {\n      constructor(callback: MutationCallback) {\n        const capturedLogicalContext = currentLogicalContext;\n        const wrappedCallback: MutationCallback = (\n          mutations: MutationRecord[],\n          observer: MutationObserver\n        ) => {\n          const adjustment = {\n            contextToUse: capturedLogicalContext,\n          } as LogicalContextAdjustment;\n          return trampoline(\n            adjustment,\n            callback,\n            undefined,\n            mutations,\n            observer\n          );\n        };\n        super(wrappedCallback);\n      }\n    };\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace ResizeObserver with a version that captures the current logical context\n  if (typeof globalThis.ResizeObserver !== 'undefined') {\n    const __ResizeObserver = globalThis.ResizeObserver;\n\n    globalThis.ResizeObserver = class extends __ResizeObserver {\n      constructor(callback: ResizeObserverCallback) {\n        const capturedLogicalContext = currentLogicalContext;\n        const wrappedCallback: ResizeObserverCallback = (\n          entries: ResizeObserverEntry[],\n          observer: ResizeObserver\n        ) => {\n          const adjustment = {\n            contextToUse: capturedLogicalContext,\n          } as LogicalContextAdjustment;\n          return trampoline(adjustment, callback, undefined, entries, observer);\n        };\n        super(wrappedCallback);\n      }\n    };\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace IntersectionObserver with a version that captures the current logical context\n  if (typeof globalThis.IntersectionObserver !== 'undefined') {\n    const __IntersectionObserver = globalThis.IntersectionObserver;\n\n    globalThis.IntersectionObserver = class extends __IntersectionObserver {\n      constructor(\n        callback: IntersectionObserverCallback,\n        options?: IntersectionObserverInit\n      ) {\n        const capturedLogicalContext = currentLogicalContext;\n        const wrappedCallback: IntersectionObserverCallback = (\n          entries: IntersectionObserverEntry[],\n          observer: IntersectionObserver\n        ) => {\n          const adjustment = {\n            contextToUse: capturedLogicalContext,\n          } as LogicalContextAdjustment;\n          return trampoline(adjustment, callback, undefined, entries, observer);\n        };\n        super(wrappedCallback, options);\n      }\n    };\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace Worker with a version that captures the current logical context\n  if (typeof globalThis.Worker !== 'undefined') {\n    const __Worker = globalThis.Worker;\n\n    globalThis.Worker = class extends __Worker {\n      private _userHandlers: Map<string, ((event: any) => void) | null> =\n        new Map();\n\n      constructor(scriptURL: string | URL, options?: WorkerOptions) {\n        super(scriptURL, options);\n\n        // Hook all event handler properties\n        const eventHandlerProperties = [\n          'onmessage',\n          'onmessageerror',\n          'onerror',\n        ];\n\n        eventHandlerProperties.forEach((prop) => {\n          Object.defineProperty(this, prop, {\n            get: () => this._userHandlers.get(prop) || null,\n            set: (newHandler: ((event: any) => void) | null) => {\n              this._userHandlers.set(prop, newHandler);\n\n              if (newHandler && typeof newHandler === 'function') {\n                const capturedLogicalContext = currentLogicalContext;\n\n                // Set the wrapped handler using the parent's property descriptor\n                const wrappedHandler = function (this: any, event: any) {\n                  const adjustment = {\n                    contextToUse: capturedLogicalContext,\n                  } as LogicalContextAdjustment;\n                  return trampoline(adjustment, newHandler, this, event);\n                };\n\n                // Call the parent setter\n                const parentProto = Object.getPrototypeOf(\n                  Object.getPrototypeOf(this)\n                );\n                const descriptor = Object.getOwnPropertyDescriptor(\n                  parentProto,\n                  prop\n                );\n                if (descriptor && descriptor.set) {\n                  descriptor.set.call(this, wrappedHandler);\n                } else {\n                  // Fallback for older browsers or non-standard implementations\n                  (this as any)[`_${prop}`] = wrappedHandler;\n                }\n              } else {\n                // Clear handler\n                const parentProto = Object.getPrototypeOf(\n                  Object.getPrototypeOf(this)\n                );\n                const descriptor = Object.getOwnPropertyDescriptor(\n                  parentProto,\n                  prop\n                );\n                if (descriptor && descriptor.set) {\n                  descriptor.set.call(this, null);\n                } else {\n                  (this as any)[`_${prop}`] = null;\n                }\n              }\n            },\n            configurable: true,\n            enumerable: true,\n          });\n        });\n      }\n\n      addEventListener(\n        type: string,\n        listener: EventListenerOrEventListenerObject | null,\n        options?: boolean | AddEventListenerOptions\n      ) {\n        const capturedLogicalContext = currentLogicalContext;\n\n        if (!listener) {\n          return (super.addEventListener as any)(type, listener, options);\n        }\n\n        if (typeof listener === 'function') {\n          const wrappedListener = (event: Event) => {\n            const adjustment = {\n              contextToUse: capturedLogicalContext,\n            } as LogicalContextAdjustment;\n            return trampoline(adjustment, listener, event.currentTarget, event);\n          };\n          return super.addEventListener(type, wrappedListener, options);\n        } else if (typeof listener === 'object' && 'handleEvent' in listener) {\n          const wrappedListener = {\n            handleEvent: (event: Event) => {\n              const adjustment = {\n                contextToUse: capturedLogicalContext,\n              } as LogicalContextAdjustment;\n              return trampoline(adjustment, () => listener.handleEvent(event));\n            },\n          };\n          return super.addEventListener(type, wrappedListener, options);\n        }\n\n        return super.addEventListener(type, listener, options);\n      }\n    };\n  }\n\n  ///////////////////////////////////////////////////////////////\n\n  // Replace MessagePort with a version that captures the current logical context\n  if (typeof globalThis.MessagePort !== 'undefined') {\n    const __MessagePort = globalThis.MessagePort;\n\n    // Create a wrapper class for MessagePort\n    const createMessagePortWrapper = (originalPort: MessagePort) => {\n      const _userHandlers = new Map<string, ((event: any) => void) | null>();\n\n      // Hook all event handler properties\n      const eventHandlerProperties = ['onmessage', 'onmessageerror'];\n\n      eventHandlerProperties.forEach((prop) => {\n        Object.defineProperty(originalPort, prop, {\n          get: () => _userHandlers.get(prop) || null,\n          set: (newHandler: ((event: any) => void) | null) => {\n            _userHandlers.set(prop, newHandler);\n\n            if (newHandler && typeof newHandler === 'function') {\n              const capturedLogicalContext = currentLogicalContext;\n\n              // Set the wrapped handler\n              const wrappedHandler = function (this: any, event: any) {\n                const adjustment = {\n                  contextToUse: capturedLogicalContext,\n                } as LogicalContextAdjustment;\n                return trampoline(adjustment, newHandler, this, event);\n              };\n\n              // Set on the original MessagePort\n              const descriptor = Object.getOwnPropertyDescriptor(\n                __MessagePort.prototype,\n                prop\n              );\n              if (descriptor && descriptor.set) {\n                descriptor.set.call(originalPort, wrappedHandler);\n              }\n            } else {\n              // Clear handler\n              const descriptor = Object.getOwnPropertyDescriptor(\n                __MessagePort.prototype,\n                prop\n              );\n              if (descriptor && descriptor.set) {\n                descriptor.set.call(originalPort, null);\n              }\n            }\n          },\n          configurable: true,\n          enumerable: true,\n        });\n      });\n\n      // Hook addEventListener\n      const originalAddEventListener = originalPort.addEventListener;\n      originalPort.addEventListener = function (\n        type: string,\n        listener: EventListenerOrEventListenerObject | null,\n        options?: boolean | AddEventListenerOptions\n      ) {\n        const capturedLogicalContext = currentLogicalContext;\n\n        if (!listener) {\n          return originalAddEventListener.call(\n            this,\n            type,\n            listener as any,\n            options\n          );\n        }\n\n        if (typeof listener === 'function') {\n          const wrappedListener = (event: Event) => {\n            const adjustment = {\n              contextToUse: capturedLogicalContext,\n            } as LogicalContextAdjustment;\n            return trampoline(adjustment, listener, event.currentTarget, event);\n          };\n          return originalAddEventListener.call(\n            this,\n            type,\n            wrappedListener,\n            options\n          );\n        } else if (typeof listener === 'object' && 'handleEvent' in listener) {\n          const wrappedListener = {\n            handleEvent: (event: Event) => {\n              const adjustment = {\n                contextToUse: capturedLogicalContext,\n              } as LogicalContextAdjustment;\n              return trampoline(adjustment, () => listener.handleEvent(event));\n            },\n          };\n          return originalAddEventListener.call(\n            this,\n            type,\n            wrappedListener,\n            options\n          );\n        }\n\n        return originalAddEventListener.call(this, type, listener, options);\n      };\n\n      return originalPort;\n    };\n\n    // Hook MessageChannel constructor to wrap the ports\n    if (typeof globalThis.MessageChannel !== 'undefined') {\n      const __MessageChannel = globalThis.MessageChannel;\n\n      globalThis.MessageChannel = class extends __MessageChannel {\n        constructor() {\n          super();\n          // Wrap both ports\n          createMessagePortWrapper(this.port1);\n          createMessagePortWrapper(this.port2);\n        }\n      };\n    }\n  }\n};\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport {\n  createLogicalContext,\n  currentLogicalContext,\n  prepare,\n  setCurrentLogicalContext,\n} from './internal/logical-context';\n\n/**\n * Set a value in the current logical context\n * @param key The symbol key for the value\n * @param value The value to store\n */\nexport const setLogicalContextValue = <T>(\n  key: symbol,\n  value: T | undefined\n) => {\n  prepare();\n  if (value !== undefined) {\n    currentLogicalContext.data.set(key, value);\n  } else {\n    currentLogicalContext.data.delete(key);\n  }\n};\n\n/**\n * Get a value from the current logical context\n * @param key The symbol key for the value\n * @returns The stored value or undefined if not found\n */\nexport const getLogicalContextValue = <T>(key: symbol) => {\n  prepare();\n  return currentLogicalContext.data.get(key) as T | undefined;\n};\n\n/**\n * Run a handler on a new logical context\n * @param prefix The prefix for the new logical context\n * @param handler The handler to run\n * @returns The result of the handler\n */\nexport const runOnNewLogicalContext = <T>(prefix: string, handler: () => T) => {\n  const previousLogicalContext = currentLogicalContext;\n  setCurrentLogicalContext(\n    createLogicalContext(Symbol(`${prefix}-${crypto.randomUUID()}`))\n  );\n  try {\n    return handler();\n  } finally {\n    setCurrentLogicalContext(previousLogicalContext);\n  }\n};\n\n/**\n * Create a new logical context and switch to it (similar to LogicalContext.SetLogicalContext)\n * @param idPrefix The prefix for the new logical context id\n */\nexport const switchToNewLogicalContext = (idPrefix: string): void => {\n  setCurrentLogicalContext(\n    createLogicalContext(Symbol(`${idPrefix}-${crypto.randomUUID()}`))\n  );\n};\n\n/**\n * Get the current logical context id\n * @returns The current logical context id\n */\nexport const getCurrentLogicalContextId = () => {\n  prepare();\n  return currentLogicalContext.id;\n};\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport {\n  getLogicalContextValue,\n  setLogicalContextValue,\n} from './logical-context';\n\n/**\n * AsyncLocal instance interface\n * @template T The type of the value to store in the async context\n */\nexport interface AsyncLocal<T> {\n  /**\n   * Sets the value in the current async context\n   * @param value The value to set\n   */\n  setValue(value: T | undefined): void;\n\n  /**\n   * Gets the current value in the async context\n   * @returns The current value or undefined if not set\n   */\n  getValue(): T | undefined;\n}\n\n/**\n * Creates a new AsyncLocal instance\n * @template T The type of the value to store in the async context\n * @returns A new AsyncLocal instance\n */\nexport const createAsyncLocal = <T>(): AsyncLocal<T> => {\n  const key = Symbol(`async-local-${crypto.randomUUID()}`);\n  return {\n    setValue: (value: T | undefined) => {\n      setLogicalContextValue(key, value);\n    },\n    getValue: () => {\n      return getLogicalContextValue<T>(key);\n    },\n  };\n};\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport { LockHandle, Semaphore } from '../types';\nimport { onAbort } from './abort-hook';\nimport { defer } from './defer';\n\n/**\n * Internal queue item for semaphore acquisition requests\n */\ninterface QueueItem {\n  /** Promise resolver for the semaphore acquisition */\n  resolve: (handle: LockHandle) => void;\n  /** Promise rejecter for the semaphore acquisition */\n  reject: (error: Error) => void;\n  /** Optional AbortSignal for cancelling the request */\n  signal?: AbortSignal | undefined;\n}\n\nconst ABORTED_ERROR = () => new Error('Semaphore acquisition was aborted');\nconst INVALID_COUNT_ERROR = () =>\n  new Error('Semaphore count must be greater than 0');\n\n/**\n * Creates a new SemaphoreHandle instance\n * @param releaseCallback Callback function to release the semaphore resource\n * @returns A SemaphoreHandle object with release and dispose functionality\n */\nconst createSemaphoreHandle = (releaseCallback: () => void): LockHandle => {\n  let isActive = true;\n\n  const release = (): void => {\n    if (!isActive) {\n      return;\n    }\n    isActive = false;\n    releaseCallback();\n  };\n\n  return {\n    get isActive() {\n      return isActive;\n    },\n    release,\n    [Symbol.dispose]: release,\n  };\n};\n\n/**\n * Creates a new Semaphore instance for managing limited concurrent access\n * @param count The maximum number of concurrent acquisitions allowed (must be greater than 0)\n * @param maxConsecutiveCalls The maximum number of consecutive calls before yielding control\n * @returns A new Semaphore for managing concurrent resource access\n */\nexport const createSemaphore = (\n  count: number,\n  maxConsecutiveCalls: number = 20\n): Semaphore => {\n  if (count < 1) {\n    throw INVALID_COUNT_ERROR();\n  }\n\n  let availableCount = count;\n  const queue: QueueItem[] = [];\n  let consecutiveCallCount = 0;\n\n  const processQueue = (): void => {\n    while (availableCount > 0 && queue.length > 0) {\n      const item = queue.shift()!;\n\n      // Check if the request was aborted\n      if (item.signal?.aborted) {\n        item.reject(ABORTED_ERROR());\n        // Continue processing next item\n        continue;\n      }\n\n      // Acquire a resource\n      availableCount--;\n\n      // Continue to awaiter with semaphoreHandle\n      const semaphoreHandle = createSemaphoreHandle(releaseSemaphore);\n      item.resolve(semaphoreHandle);\n    }\n  };\n\n  const scheduleNextProcess = (): void => {\n    consecutiveCallCount++;\n\n    // Yield control with defer delay every maxConsecutiveCalls consecutive executions\n    if (consecutiveCallCount >= maxConsecutiveCalls) {\n      consecutiveCallCount = 0;\n      defer(processQueue);\n    } else {\n      // Direct call is sufficient since it's controlled by counter\n      processQueue();\n    }\n  };\n\n  const releaseSemaphore = (): void => {\n    availableCount++;\n    // Process next item in queue with batching control\n    scheduleNextProcess();\n  };\n\n  const removeFromQueue = (item: QueueItem): void => {\n    const index = queue.indexOf(item);\n    if (index !== -1) {\n      queue.splice(index, 1);\n    }\n  };\n\n  const acquire = async (signal?: AbortSignal): Promise<LockHandle> => {\n    if (signal) {\n      // Check if already aborted\n      if (signal.aborted) {\n        throw ABORTED_ERROR();\n      }\n\n      // If resource is available immediately and not aborted\n      if (availableCount > 0) {\n        availableCount--;\n        return createSemaphoreHandle(releaseSemaphore);\n      }\n\n      return new Promise<LockHandle>((resolve, reject) => {\n        // Handle case with AbortSignal\n        const queueItem: QueueItem = {\n          resolve: undefined!,\n          reject: undefined!,\n          signal,\n        };\n\n        const abortHandle = onAbort(signal, () => {\n          removeFromQueue(queueItem);\n          reject(ABORTED_ERROR());\n        });\n\n        // Wrap to clean up\n        queueItem.resolve = (handle: LockHandle) => {\n          abortHandle.release();\n          resolve(handle);\n        };\n        queueItem.reject = (error: Error) => {\n          abortHandle.release();\n          reject(error);\n        };\n\n        queue.push(queueItem);\n        processQueue();\n      });\n    } else {\n      // If resource is available immediately\n      if (availableCount > 0) {\n        availableCount--;\n        return createSemaphoreHandle(releaseSemaphore);\n      }\n\n      return new Promise<LockHandle>((resolve, reject) => {\n        // Handle case without AbortSignal\n        queue.push({\n          resolve,\n          reject,\n        });\n        processQueue();\n      });\n    }\n  };\n\n  const result: Semaphore = {\n    acquire,\n    waiter: {\n      wait: acquire,\n    },\n    get availableCount() {\n      return availableCount;\n    },\n    get pendingCount() {\n      return queue.length;\n    },\n  };\n\n  return result;\n};\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport {\n  LockHandle,\n  ReaderWriterLock,\n  ReaderWriterLockOptions,\n  ReaderWriterLockPolicy,\n  Waiter,\n} from '../types';\nimport { onAbort } from './abort-hook';\nimport { defer } from './defer';\n\n/**\n * Internal queue item for read lock requests\n */\ninterface ReadQueueItem {\n  /** Promise resolver for the read lock acquisition */\n  resolve: (handle: LockHandle) => void;\n  /** Promise rejecter for the read lock acquisition */\n  reject: (error: Error) => void;\n  /** Optional AbortSignal for cancelling the request */\n  signal?: AbortSignal | undefined;\n}\n\n/**\n * Internal queue item for write lock requests\n */\ninterface WriteQueueItem {\n  /** Promise resolver for the write lock acquisition */\n  resolve: (handle: LockHandle) => void;\n  /** Promise rejecter for the write lock acquisition */\n  reject: (error: Error) => void;\n  /** Optional AbortSignal for cancelling the request */\n  signal?: AbortSignal | undefined;\n}\n\nconst ABORTED_ERROR = () => new Error('Lock acquisition was aborted');\n\n/**\n * Creates a new ReadLockHandle instance\n * @param releaseCallback Callback function to release the read lock\n * @returns A ReadLockHandle object with release and dispose functionality\n */\nconst createReadLockHandle = (releaseCallback: () => void): LockHandle => {\n  let isActive = true;\n\n  const release = (): void => {\n    if (!isActive) {\n      return;\n    }\n    isActive = false;\n    releaseCallback();\n  };\n\n  return {\n    get isActive() {\n      return isActive;\n    },\n    release,\n    [Symbol.dispose]: release,\n  };\n};\n\n/**\n * Creates a new WriteLockHandle instance\n * @param releaseCallback Callback function to release the write lock\n * @returns A WriteLockHandle object with release and dispose functionality\n */\nconst createWriteLockHandle = (releaseCallback: () => void): LockHandle => {\n  let isActive = true;\n\n  const release = (): void => {\n    if (!isActive) {\n      return;\n    }\n    isActive = false;\n    releaseCallback();\n  };\n\n  return {\n    get isActive() {\n      return isActive;\n    },\n    release,\n    [Symbol.dispose]: release,\n  };\n};\n\n/**\n * Creates a new ReaderWriterLock instance for managing concurrent read and exclusive write access\n * @returns A new ReaderWriterLock with default write-preferring policy\n */\nexport function createReaderWriterLock(): ReaderWriterLock;\n/**\n * Creates a new ReaderWriterLock instance for managing concurrent read and exclusive write access\n * @param maxConsecutiveCalls The maximum number of consecutive calls before yielding control\n * @returns A new ReaderWriterLock with write-preferring policy\n */\nexport function createReaderWriterLock(\n  maxConsecutiveCalls: number\n): ReaderWriterLock;\n/**\n * Creates a new ReaderWriterLock instance for managing concurrent read and exclusive write access\n * @param options Options for configuring the ReaderWriterLock\n * @returns A new ReaderWriterLock with specified options\n */\nexport function createReaderWriterLock(\n  options: ReaderWriterLockOptions\n): ReaderWriterLock;\nexport function createReaderWriterLock(\n  optionsOrMaxCalls?: number | ReaderWriterLockOptions\n): ReaderWriterLock {\n  // Parse parameters for backward compatibility\n  let policy: ReaderWriterLockPolicy = 'write-preferring';\n  let maxConsecutiveCalls = 20;\n\n  if (typeof optionsOrMaxCalls === 'number') {\n    // Legacy API: number parameter\n    maxConsecutiveCalls = optionsOrMaxCalls;\n  } else if (optionsOrMaxCalls) {\n    // New API: options object\n    policy = optionsOrMaxCalls.policy ?? 'write-preferring';\n    maxConsecutiveCalls = optionsOrMaxCalls.maxConsecutiveCalls ?? 20;\n  }\n  let currentReaders = 0;\n  let hasWriter = false;\n  const readQueue: ReadQueueItem[] = [];\n  const writeQueue: WriteQueueItem[] = [];\n  let consecutiveCallCount = 0;\n\n  const processQueues = (): void => {\n    if (policy === 'write-preferring') {\n      // Write-preferring policy: process writers first\n      if (!hasWriter && currentReaders === 0 && writeQueue.length > 0) {\n        const item = writeQueue.shift()!;\n\n        // Check if the request was aborted\n        if (item.signal?.aborted) {\n          item.reject(ABORTED_ERROR());\n          // Continue processing\n          scheduleNextProcess();\n          return;\n        }\n\n        // Acquire write lock\n        hasWriter = true;\n\n        // Continue to awaiter with writeLockHandle\n        const writeLockHandle = createWriteLockHandle(releaseWriteLock);\n        item.resolve(writeLockHandle);\n      }\n      // Process readers only if no writer is active and no writers are waiting\n      else if (!hasWriter && writeQueue.length === 0 && readQueue.length > 0) {\n        // Process all available readers at once\n        const readersToProcess: ReadQueueItem[] = [];\n\n        while (readQueue.length > 0) {\n          const item = readQueue.shift()!;\n\n          // Check if the request was aborted\n          if (item.signal?.aborted) {\n            item.reject(ABORTED_ERROR());\n          } else {\n            readersToProcess.push(item);\n          }\n        }\n\n        // Grant read locks to all non-aborted readers\n        for (const item of readersToProcess) {\n          currentReaders++;\n          const readLockHandle = createReadLockHandle(releaseReadLock);\n          item.resolve(readLockHandle);\n        }\n      }\n    } else {\n      // Read-preferring policy: process readers first\n      if (!hasWriter && readQueue.length > 0) {\n        // Process all available readers at once\n        const readersToProcess: ReadQueueItem[] = [];\n\n        while (readQueue.length > 0) {\n          const item = readQueue.shift()!;\n\n          // Check if the request was aborted\n          if (item.signal?.aborted) {\n            item.reject(ABORTED_ERROR());\n          } else {\n            readersToProcess.push(item);\n          }\n        }\n\n        // Grant read locks to all non-aborted readers\n        for (const item of readersToProcess) {\n          currentReaders++;\n          const readLockHandle = createReadLockHandle(releaseReadLock);\n          item.resolve(readLockHandle);\n        }\n      }\n      // Process writer only if no readers are active\n      else if (!hasWriter && currentReaders === 0 && writeQueue.length > 0) {\n        const item = writeQueue.shift()!;\n\n        // Check if the request was aborted\n        if (item.signal?.aborted) {\n          item.reject(ABORTED_ERROR());\n          // Continue processing\n          scheduleNextProcess();\n          return;\n        }\n\n        // Acquire write lock\n        hasWriter = true;\n\n        // Continue to awaiter with writeLockHandle\n        const writeLockHandle = createWriteLockHandle(releaseWriteLock);\n        item.resolve(writeLockHandle);\n      }\n    }\n  };\n\n  const scheduleNextProcess = (): void => {\n    consecutiveCallCount++;\n\n    // Yield control with defer delay every maxConsecutiveCalls consecutive executions\n    if (consecutiveCallCount >= maxConsecutiveCalls) {\n      consecutiveCallCount = 0;\n      defer(processQueues);\n    } else {\n      // Direct call is sufficient since it's controlled by counter\n      processQueues();\n    }\n  };\n\n  const releaseReadLock = (): void => {\n    if (currentReaders > 0) {\n      currentReaders--;\n      // If this was the last reader, process queues\n      if (currentReaders === 0) {\n        scheduleNextProcess();\n      }\n    }\n  };\n\n  const releaseWriteLock = (): void => {\n    if (hasWriter) {\n      hasWriter = false;\n      scheduleNextProcess();\n    }\n  };\n\n  const removeFromReadQueue = (item: ReadQueueItem): void => {\n    const index = readQueue.indexOf(item);\n    if (index !== -1) {\n      readQueue.splice(index, 1);\n    }\n  };\n\n  const removeFromWriteQueue = (item: WriteQueueItem): void => {\n    const index = writeQueue.indexOf(item);\n    if (index !== -1) {\n      writeQueue.splice(index, 1);\n    }\n  };\n\n  const readLock = async (signal?: AbortSignal): Promise<LockHandle> => {\n    if (signal) {\n      // Check if already aborted\n      if (signal.aborted) {\n        throw ABORTED_ERROR();\n      }\n\n      // Can acquire immediately based on policy\n      const canAcquireImmediately =\n        policy === 'read-preferring'\n          ? !hasWriter // Read-preferring: acquire if no active writer\n          : !hasWriter && writeQueue.length === 0; // Write-preferring: also check no writers waiting\n\n      if (canAcquireImmediately) {\n        currentReaders++;\n        return createReadLockHandle(releaseReadLock);\n      }\n\n      return new Promise<LockHandle>((resolve, reject) => {\n        // Handle case with AbortSignal\n        const queueItem: ReadQueueItem = {\n          resolve: undefined!,\n          reject: undefined!,\n          signal,\n        };\n\n        const abortHandle = onAbort(signal, () => {\n          removeFromReadQueue(queueItem);\n          reject(ABORTED_ERROR());\n        });\n\n        // Wrap to clean up\n        queueItem.resolve = (handle: LockHandle) => {\n          abortHandle.release();\n          resolve(handle);\n        };\n        queueItem.reject = (error: Error) => {\n          abortHandle.release();\n          reject(error);\n        };\n\n        readQueue.push(queueItem);\n        processQueues();\n      });\n    } else {\n      // Can acquire immediately based on policy\n      const canAcquireImmediately =\n        policy === 'read-preferring'\n          ? !hasWriter // Read-preferring: acquire if no active writer\n          : !hasWriter && writeQueue.length === 0; // Write-preferring: also check no writers waiting\n\n      if (canAcquireImmediately) {\n        currentReaders++;\n        return createReadLockHandle(releaseReadLock);\n      }\n\n      return new Promise<LockHandle>((resolve, reject) => {\n        // Handle case without AbortSignal\n        readQueue.push({\n          resolve,\n          reject,\n        });\n        processQueues();\n      });\n    }\n  };\n\n  const writeLock = async (signal?: AbortSignal): Promise<LockHandle> => {\n    if (signal) {\n      // Check if already aborted\n      if (signal.aborted) {\n        throw ABORTED_ERROR();\n      }\n\n      // Can acquire immediately if no readers and no writer\n      if (!hasWriter && currentReaders === 0) {\n        hasWriter = true;\n        return createWriteLockHandle(releaseWriteLock);\n      }\n\n      return new Promise<LockHandle>((resolve, reject) => {\n        // Handle case with AbortSignal\n        const queueItem: WriteQueueItem = {\n          resolve: undefined!,\n          reject: undefined!,\n          signal,\n        };\n\n        const abortHandle = onAbort(signal, () => {\n          removeFromWriteQueue(queueItem);\n          reject(ABORTED_ERROR());\n        });\n\n        // Wrap to clean up\n        queueItem.resolve = (handle: LockHandle) => {\n          abortHandle.release();\n          resolve(handle);\n        };\n        queueItem.reject = (error: Error) => {\n          abortHandle.release();\n          reject(error);\n        };\n\n        writeQueue.push(queueItem);\n        processQueues();\n      });\n    } else {\n      // Can acquire immediately if no readers and no writer\n      if (!hasWriter && currentReaders === 0) {\n        hasWriter = true;\n        return createWriteLockHandle(releaseWriteLock);\n      }\n\n      return new Promise<LockHandle>((resolve, reject) => {\n        // Handle case without AbortSignal\n        writeQueue.push({\n          resolve,\n          reject,\n        });\n        processQueues();\n      });\n    }\n  };\n\n  // Create waiter objects\n  const readWaiter: Waiter = {\n    wait: readLock,\n  };\n\n  const writeWaiter: Waiter = {\n    wait: writeLock,\n  };\n\n  return {\n    readLock,\n    writeLock,\n    readWaiter,\n    writeWaiter,\n    get currentReaders() {\n      return currentReaders;\n    },\n    get hasWriter() {\n      return hasWriter;\n    },\n    get pendingReadersCount() {\n      return readQueue.length;\n    },\n    get pendingWritersCount() {\n      return writeQueue.length;\n    },\n  };\n}\n","// async-primitives - A collection of primitive functions for asynchronous operations in TypeScript/JavaScript.\n// Copyright (c) Kouji Matsui. (@kekyo@mi.kekyo.net)\n// Under MIT.\n// https://github.com/kekyo/async-primitives\n\nimport { AsyncOperator, AsyncOperatorSource, Awaitable } from '../types';\n\ntype SyncIterableFactory<T> = () => Iterable<Awaitable<T>>;\ntype AsyncIterableFactory<T> = () => AsyncIterable<T>;\ntype IteratorFactories<T> = {\n  readonly syncFactory: SyncIterableFactory<T> | undefined;\n  readonly asyncFactory: AsyncIterableFactory<T>;\n};\ntype LinearOperation =\n  | {\n      readonly kind: 'map';\n      readonly selector: (value: unknown, index: number) => Awaitable<unknown>;\n    }\n  | {\n      readonly kind: 'filter';\n      readonly predicate: (value: unknown, index: number) => Awaitable<boolean>;\n    }\n  | {\n      readonly kind: 'choose';\n      readonly selector: (\n        value: unknown,\n        index: number\n      ) => Awaitable<unknown | null | undefined>;\n    }\n  | {\n      readonly kind: 'skipWhile';\n      readonly predicate: (value: unknown, index: number) => Awaitable<boolean>;\n    }\n  | {\n      readonly kind: 'takeWhile';\n      readonly predicate: (value: unknown, index: number) => Awaitable<boolean>;\n    };\ntype LinearRuntimeState =\n  | {\n      readonly kind: 'map' | 'filter' | 'choose' | 'takeWhile';\n      index: number;\n    }\n  | {\n      readonly kind: 'skipWhile';\n      index: number;\n      skipping: boolean;\n    };\ntype LinearPipeline = {\n  readonly sourceFactories: IteratorFactories<unknown>;\n  readonly operations: readonly LinearOperation[];\n};\n\nconst __NO_INITIAL_VALUE = Symbol('no-initial-value');\nconst __LINEAR_SKIP = Symbol('linear-skip');\nconst __LINEAR_STOP = Symbol('linear-stop');\n\nconst createAsyncIterable = <T>(\n  iteratorFactory: () => AsyncGenerator<T, void, unknown>\n): AsyncIterable<T> => ({\n  [Symbol.asyncIterator]: iteratorFactory,\n});\n\nconst createSyncIterable = <T>(\n  iteratorFactory: () => Iterator<Awaitable<T>, void, unknown>\n): Iterable<Awaitable<T>> => ({\n  [Symbol.iterator]: iteratorFactory,\n});\n\nconst createIteratorFactories = <T>(\n  source: AsyncOperatorSource<T>\n): IteratorFactories<T> =>\n  isAsyncIterable(source)\n    ? {\n        syncFactory: undefined,\n        asyncFactory: () => toAsyncIterable(source),\n      }\n    : {\n        syncFactory: () => source,\n        asyncFactory: () => toAsyncIterable(source),\n      };\n\nconst createAsyncOnlyFactories = <T>(\n  asyncFactory: AsyncIterableFactory<T>\n): IteratorFactories<T> => ({\n  syncFactory: undefined,\n  asyncFactory,\n});\n\nconst normalizeIteratorFactories = <T>(\n  iteratorFactoriesOrAsyncFactory:\n    | IteratorFactories<T>\n    | AsyncIterableFactory<T>\n): IteratorFactories<T> =>\n  typeof iteratorFactoriesOrAsyncFactory === 'function'\n    ? createAsyncOnlyFactories(iteratorFactoriesOrAsyncFactory)\n    : iteratorFactoriesOrAsyncFactory;\n\nconst identity = <T>(value: T): T => value;\n\nconst sameValueZero = <T>(left: T, right: T): boolean =>\n  left === right || (left !== left && right !== right);\n\nconst isArraySource = <T>(\n  source: AsyncOperatorSource<T>\n): source is readonly Awaitable<T>[] => Array.isArray(source);\n\nconst isPromiseLike = <T>(value: Awaitable<T>): value is PromiseLike<T> =>\n  ((typeof value === 'object' && value !== null) ||\n    typeof value === 'function') &&\n  typeof (value as PromiseLike<T>).then === 'function';\n\nconst isAsyncIterable = <T>(\n  source: AsyncOperatorSource<T>\n): source is AsyncIterable<Awaitable<T>> =>\n  typeof (source as AsyncIterable<Awaitable<T>>)[Symbol.asyncIterator] ===\n  'function';\n\nconst toAsyncIterable = <T>(source: AsyncOperatorSource<T>): AsyncIterable<T> =>\n  createAsyncIterable(async function* () {\n    if (isAsyncIterable(source)) {\n      for await (const value of source) {\n        yield value as T;\n      }\n    } else {\n      for (const value of source) {\n        yield (isPromiseLike(value) ? await value : value) as T;\n      }\n    }\n  });\n\nconst toIntegerOrInfinity = (value: number): number => {\n  if (Number.isNaN(value) || value === 0) {\n    return 0;\n  }\n  if (!Number.isFinite(value)) {\n    return value;\n  }\n  return Math.trunc(value);\n};\n\nconst normalizeCount = (count: number): number => {\n  if (Number.isNaN(count) || count <= 0) {\n    return 0;\n  }\n  return Math.trunc(count);\n};\n\nconst normalizeRequiredCount = (count: number, name: string): number => {\n  if (!Number.isFinite(count) || count <= 0) {\n    throw new RangeError(`${name} must be greater than 0`);\n  }\n  return Math.trunc(count);\n};\n\nconst isNonNullish = <T>(\n  value: T | null | undefined\n): value is NonNullable<T> => value !== null && value !== undefined;\n\nconst compareValues = <T>(left: T, right: T): number => {\n  if (left < right) {\n    return -1;\n  }\n  if (left > right) {\n    return 1;\n  }\n  return 0;\n};\n\nconst createLinearRuntimeState = (\n  operation: LinearOperation\n): LinearRuntimeState => {\n  switch (operation.kind) {\n    case 'map':\n    case 'filter':\n    case 'choose':\n    case 'takeWhile':\n      return {\n        kind: operation.kind,\n        index: 0,\n      };\n    case 'skipWhile':\n      return {\n        kind: operation.kind,\n        index: 0,\n        skipping: true,\n      };\n  }\n};\n\nconst createLinearPipelineFactories = <T>(\n  pipeline: LinearPipeline\n): IteratorFactories<T> =>\n  createAsyncOnlyFactories(() =>\n    createAsyncIterable(async function* () {\n      const runtimeStates = pipeline.operations.map(createLinearRuntimeState);\n      const applyOperations = async (\n        input: unknown\n      ): Promise<unknown | typeof __LINEAR_SKIP | typeof __LINEAR_STOP> => {\n        let current = input;\n\n        for (\n          let operationIndex = 0;\n          operationIndex < pipeline.operations.length;\n          operationIndex++\n        ) {\n          const operation = pipeline.operations[operationIndex]!;\n          const runtimeState = runtimeStates[operationIndex]!;\n\n          switch (operation.kind) {\n            case 'map': {\n              const selected = operation.selector(current, runtimeState.index);\n              current = isPromiseLike(selected) ? await selected : selected;\n              runtimeState.index++;\n              break;\n            }\n            case 'filter': {\n              const result = operation.predicate(current, runtimeState.index);\n              const included = isPromiseLike(result) ? await result : result;\n              runtimeState.index++;\n              if (!included) {\n                return __LINEAR_SKIP;\n              }\n              break;\n            }\n            case 'choose': {\n              const result = operation.selector(current, runtimeState.index);\n              const selected = isPromiseLike(result) ? await result : result;\n              runtimeState.index++;\n              if (!isNonNullish(selected)) {\n                return __LINEAR_SKIP;\n              }\n              current = selected;\n              break;\n            }\n            case 'skipWhile': {\n              const skipState = runtimeState as Extract<\n                LinearRuntimeState,\n                { kind: 'skipWhile' }\n              >;\n              const result = operation.predicate(current, runtimeState.index);\n              const shouldSkip = isPromiseLike(result) ? await result : result;\n              runtimeState.index++;\n              if (skipState.skipping && shouldSkip) {\n                return __LINEAR_SKIP;\n              }\n              skipState.skipping = false;\n              break;\n            }\n            case 'takeWhile': {\n              const result = operation.predicate(current, runtimeState.index);\n              const shouldTake = isPromiseLike(result) ? await result : result;\n              if (!shouldTake) {\n                return __LINEAR_STOP;\n              }\n              runtimeState.index++;\n              break;\n            }\n          }\n        }\n\n        return current;\n      };\n\n      const { syncFactory, asyncFactory } = pipeline.sourceFactories;\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          const processedValue = await applyOperations(resolvedValue);\n          if (processedValue === __LINEAR_STOP) {\n            return;\n          }\n          if (processedValue !== __LINEAR_SKIP) {\n            yield processedValue as T;\n          }\n        }\n      } else {\n        for await (const value of asyncFactory()) {\n          const processedValue = await applyOperations(value);\n          if (processedValue === __LINEAR_STOP) {\n            return;\n          }\n          if (processedValue !== __LINEAR_SKIP) {\n            yield processedValue as T;\n          }\n        }\n      }\n    })\n  );\n\nconst collectKeysFromSource = async <T, TKey>(\n  source: AsyncOperatorSource<T>,\n  selector: (value: T, index: number) => Awaitable<TKey>\n): Promise<Set<TKey>> => {\n  const { syncFactory, asyncFactory } = createIteratorFactories(source);\n  let index = 0;\n  const keys = new Set<TKey>();\n\n  if (syncFactory !== undefined) {\n    for (const value of syncFactory()) {\n      const resolvedValue = isPromiseLike(value) ? await value : value;\n      const key = selector(resolvedValue as T, index);\n      keys.add(isPromiseLike(key) ? await key : key);\n      index++;\n    }\n  } else {\n    for await (const value of asyncFactory()) {\n      const key = selector(value, index);\n      keys.add(isPromiseLike(key) ? await key : key);\n      index++;\n    }\n  }\n\n  return keys;\n};\n\nconst collectValuesFromSource = async <T>(\n  source: AsyncOperatorSource<T>\n): Promise<Set<T>> => {\n  const { syncFactory, asyncFactory } = createIteratorFactories(source);\n  const values = new Set<T>();\n\n  if (syncFactory !== undefined) {\n    for (const value of syncFactory()) {\n      values.add((isPromiseLike(value) ? await value : value) as T);\n    }\n  } else {\n    for await (const value of asyncFactory()) {\n      values.add(value);\n    }\n  }\n\n  return values;\n};\n\nconst materializeValues = async <T>(\n  iteratorFactories: IteratorFactories<T>\n): Promise<T[]> => {\n  const { syncFactory, asyncFactory } = iteratorFactories;\n  const values: T[] = [];\n\n  if (syncFactory !== undefined) {\n    for (const value of syncFactory()) {\n      values.push((isPromiseLike(value) ? await value : value) as T);\n    }\n  } else {\n    for await (const value of asyncFactory()) {\n      values.push(value);\n    }\n  }\n\n  return values;\n};\n\nconst findExtremeBy = async <T, TKey>(\n  iteratorFactories: IteratorFactories<T>,\n  selector: (value: T, index: number) => Awaitable<TKey>,\n  direction: 'min' | 'max'\n): Promise<T | undefined> => {\n  const { syncFactory, asyncFactory } = iteratorFactories;\n  let index = 0;\n  let hasBestValue = false;\n  let bestValue: T | undefined;\n  let bestKey: TKey | undefined;\n\n  if (syncFactory !== undefined) {\n    for (const value of syncFactory()) {\n      const resolvedValue = (isPromiseLike(value) ? await value : value) as T;\n      const selectedKey = selector(resolvedValue, index);\n      const key = isPromiseLike(selectedKey) ? await selectedKey : selectedKey;\n\n      if (\n        !hasBestValue ||\n        (direction === 'min'\n          ? compareValues(key, bestKey as TKey) < 0\n          : compareValues(key, bestKey as TKey) > 0)\n      ) {\n        hasBestValue = true;\n        bestValue = resolvedValue;\n        bestKey = key;\n      }\n      index++;\n    }\n  } else {\n    for await (const value of asyncFactory()) {\n      const selectedKey = selector(value, index);\n      const key = isPromiseLike(selectedKey) ? await selectedKey : selectedKey;\n\n      if (\n        !hasBestValue ||\n        (direction === 'min'\n          ? compareValues(key, bestKey as TKey) < 0\n          : compareValues(key, bestKey as TKey) > 0)\n      ) {\n        hasBestValue = true;\n        bestValue = value;\n        bestKey = key;\n      }\n      index++;\n    }\n  }\n\n  return bestValue;\n};\n\nconst createAsyncOperator = <T>(\n  iteratorFactoriesOrAsyncFactory:\n    | IteratorFactories<T>\n    | AsyncIterableFactory<T>,\n  linearPipeline?: LinearPipeline | undefined\n): AsyncOperator<T> => {\n  const iteratorFactories = normalizeIteratorFactories(\n    iteratorFactoriesOrAsyncFactory\n  );\n  const { syncFactory, asyncFactory } = iteratorFactories;\n  const iterableFactory = asyncFactory;\n  const appendLinearOperation = <U>(\n    operation: LinearOperation,\n    createFallbackIteratorFactories: () => IteratorFactories<U>\n  ): AsyncOperator<U> => {\n    const nextLinearPipeline: LinearPipeline =\n      linearPipeline === undefined\n        ? {\n            sourceFactories: iteratorFactories as IteratorFactories<unknown>,\n            operations: [operation],\n          }\n        : {\n            sourceFactories: linearPipeline.sourceFactories,\n            operations: [...linearPipeline.operations, operation],\n          };\n    const nextIteratorFactories =\n      linearPipeline === undefined\n        ? createFallbackIteratorFactories()\n        : createLinearPipelineFactories<U>(nextLinearPipeline);\n\n    return createAsyncOperator<U>(nextIteratorFactories, nextLinearPipeline);\n  };\n  const reduce = (async <U>(\n    ...args:\n      | [(previousValue: T, currentValue: T, index: number) => Awaitable<T>]\n      | [(previousValue: U, currentValue: T, index: number) => Awaitable<U>, U]\n  ): Promise<T | U> => {\n    const [reducer] = args;\n    const hasInitialValue = args.length === 2;\n    let accumulator: T | U | typeof __NO_INITIAL_VALUE = hasInitialValue\n      ? args[1]\n      : __NO_INITIAL_VALUE;\n    let index = 0;\n\n    if (syncFactory !== undefined) {\n      for (const value of syncFactory()) {\n        const resolvedValue = (isPromiseLike(value) ? await value : value) as T;\n        if (accumulator === __NO_INITIAL_VALUE) {\n          accumulator = resolvedValue;\n        } else {\n          const reduced = (\n            reducer as (\n              previousValue: T | U,\n              currentValue: T,\n              index: number\n            ) => Awaitable<T | U>\n          )(accumulator, resolvedValue, index);\n          accumulator = isPromiseLike(reduced) ? await reduced : reduced;\n        }\n        index++;\n      }\n    } else {\n      for await (const value of asyncFactory()) {\n        if (accumulator === __NO_INITIAL_VALUE) {\n          accumulator = value;\n        } else {\n          const reduced = (\n            reducer as (\n              previousValue: T | U,\n              currentValue: T,\n              index: number\n            ) => Awaitable<T | U>\n          )(accumulator, value, index);\n          accumulator = isPromiseLike(reduced) ? await reduced : reduced;\n        }\n        index++;\n      }\n    }\n\n    if (accumulator === __NO_INITIAL_VALUE) {\n      throw new TypeError(\n        'Reduce of empty AsyncOperator with no initial value'\n      );\n    }\n\n    return accumulator;\n  }) as AsyncOperator<T>['reduce'];\n\n  const reduceRight = (async <U>(\n    ...args:\n      | [(previousValue: T, currentValue: T, index: number) => Awaitable<T>]\n      | [(previousValue: U, currentValue: T, index: number) => Awaitable<U>, U]\n  ): Promise<T | U> => {\n    const [reducer] = args;\n    const hasInitialValue = args.length === 2;\n    const values = await materializeValues(iteratorFactories);\n    let accumulator: T | U | typeof __NO_INITIAL_VALUE = hasInitialValue\n      ? args[1]\n      : __NO_INITIAL_VALUE;\n\n    for (let index = values.length - 1; index >= 0; index--) {\n      const value = values[index] as T;\n      if (accumulator === __NO_INITIAL_VALUE) {\n        accumulator = value;\n      } else {\n        const reduced = (\n          reducer as (\n            previousValue: T | U,\n            currentValue: T,\n            index: number\n          ) => Awaitable<T | U>\n        )(accumulator, value, index);\n        accumulator = isPromiseLike(reduced) ? await reduced : reduced;\n      }\n    }\n\n    if (accumulator === __NO_INITIAL_VALUE) {\n      throw new TypeError(\n        'ReduceRight of empty AsyncOperator with no initial value'\n      );\n    }\n\n    return accumulator;\n  }) as AsyncOperator<T>['reduceRight'];\n\n  const flat = ((depth?: number) =>\n    createAsyncOperator(\n      createAsyncOnlyFactories(() =>\n        createAsyncIterable(async function* () {\n          const values = await materializeValues(iteratorFactories);\n          for (const value of values.flat(depth)) {\n            yield value;\n          }\n        })\n      )\n    )) as AsyncOperator<T>['flat'];\n\n  return {\n    [Symbol.asyncIterator]: () => asyncFactory()[Symbol.asyncIterator](),\n    map: <U>(selector: (value: T, index: number) => Awaitable<U>) =>\n      appendLinearOperation<U>(\n        {\n          kind: 'map',\n          selector: selector as (\n            value: unknown,\n            index: number\n          ) => Awaitable<unknown>,\n        },\n        () => {\n          const mappedSyncFactory =\n            syncFactory === undefined\n              ? undefined\n              : () =>\n                  createSyncIterable(function* () {\n                    let index = 0;\n\n                    for (const value of syncFactory()) {\n                      const currentIndex = index;\n                      if (isPromiseLike(value)) {\n                        yield value.then((resolvedValue) =>\n                          selector(resolvedValue as T, currentIndex)\n                        ) as Awaitable<U>;\n                      } else {\n                        yield selector(value as T, currentIndex);\n                      }\n                      index++;\n                    }\n                  });\n\n          if (mappedSyncFactory !== undefined) {\n            return {\n              syncFactory: mappedSyncFactory,\n              asyncFactory: () => toAsyncIterable(mappedSyncFactory()),\n            };\n          }\n\n          return createAsyncOnlyFactories(() =>\n            createAsyncIterable(async function* () {\n              let index = 0;\n              for await (const value of iterableFactory()) {\n                const selected = selector(value, index);\n                yield (\n                  isPromiseLike(selected) ? await selected : selected\n                ) as U;\n                index++;\n              }\n            })\n          );\n        }\n      ),\n    flatMap: <U>(\n      selector: (value: T, index: number) => Awaitable<AsyncOperatorSource<U>>\n    ) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          let index = 0;\n          if (syncFactory !== undefined) {\n            const source = syncFactory();\n            if (Array.isArray(source)) {\n              for (\n                let outerIndex = 0;\n                outerIndex < source.length;\n                outerIndex++\n              ) {\n                const value = source[outerIndex] as Awaitable<T>;\n                const resolvedValue = (\n                  isPromiseLike(value) ? await value : value\n                ) as T;\n                const selected = selector(resolvedValue, index);\n                const innerSource = isPromiseLike(selected)\n                  ? await selected\n                  : selected;\n\n                if (isArraySource(innerSource)) {\n                  for (\n                    let innerIndex = 0;\n                    innerIndex < innerSource.length;\n                    innerIndex++\n                  ) {\n                    const innerValue = innerSource[innerIndex] as Awaitable<U>;\n                    yield (\n                      isPromiseLike(innerValue) ? await innerValue : innerValue\n                    ) as U;\n                  }\n                } else if (isAsyncIterable(innerSource)) {\n                  for await (const innerValue of innerSource) {\n                    yield innerValue as U;\n                  }\n                } else {\n                  for (const innerValue of innerSource) {\n                    yield (\n                      isPromiseLike(innerValue) ? await innerValue : innerValue\n                    ) as U;\n                  }\n                }\n                index++;\n              }\n            } else {\n              for (const value of source) {\n                const resolvedValue = (\n                  isPromiseLike(value) ? await value : value\n                ) as T;\n                const selected = selector(resolvedValue, index);\n                const innerSource = isPromiseLike(selected)\n                  ? await selected\n                  : selected;\n\n                if (isArraySource(innerSource)) {\n                  for (\n                    let innerIndex = 0;\n                    innerIndex < innerSource.length;\n                    innerIndex++\n                  ) {\n                    const innerValue = innerSource[innerIndex] as Awaitable<U>;\n                    yield (\n                      isPromiseLike(innerValue) ? await innerValue : innerValue\n                    ) as U;\n                  }\n                } else if (isAsyncIterable(innerSource)) {\n                  for await (const innerValue of innerSource) {\n                    yield innerValue as U;\n                  }\n                } else {\n                  for (const innerValue of innerSource) {\n                    yield (\n                      isPromiseLike(innerValue) ? await innerValue : innerValue\n                    ) as U;\n                  }\n                }\n                index++;\n              }\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              const selected = selector(value, index);\n              const innerSource = isPromiseLike(selected)\n                ? await selected\n                : selected;\n\n              if (isArraySource(innerSource)) {\n                for (\n                  let innerIndex = 0;\n                  innerIndex < innerSource.length;\n                  innerIndex++\n                ) {\n                  const innerValue = innerSource[innerIndex] as Awaitable<U>;\n                  yield (\n                    isPromiseLike(innerValue) ? await innerValue : innerValue\n                  ) as U;\n                }\n              } else if (isAsyncIterable(innerSource)) {\n                for await (const innerValue of innerSource) {\n                  yield innerValue as U;\n                }\n              } else {\n                for (const innerValue of innerSource) {\n                  yield (\n                    isPromiseLike(innerValue) ? await innerValue : innerValue\n                  ) as U;\n                }\n              }\n              index++;\n            }\n          }\n        })\n      ) as AsyncOperator<U>,\n    filter: (predicate: (value: T, index: number) => Awaitable<boolean>) =>\n      appendLinearOperation<T>(\n        {\n          kind: 'filter',\n          predicate: predicate as (\n            value: unknown,\n            index: number\n          ) => Awaitable<boolean>,\n        },\n        () =>\n          createAsyncOnlyFactories(() =>\n            createAsyncIterable(async function* () {\n              let index = 0;\n              if (syncFactory !== undefined) {\n                for (const value of syncFactory()) {\n                  const resolvedValue = (\n                    isPromiseLike(value) ? await value : value\n                  ) as T;\n                  const result = predicate(resolvedValue, index);\n                  if (isPromiseLike(result) ? await result : result) {\n                    yield resolvedValue as T;\n                  }\n                  index++;\n                }\n              } else {\n                for await (const value of iterableFactory()) {\n                  const result = predicate(value, index);\n                  if (isPromiseLike(result) ? await result : result) {\n                    yield value as T;\n                  }\n                  index++;\n                }\n              }\n            })\n          )\n      ),\n    concat: (...sources: AsyncOperatorSource<T>[]) => {\n      const concatenatedSyncFactory =\n        syncFactory !== undefined &&\n        sources.every((source) => !isAsyncIterable(source))\n          ? () =>\n              createSyncIterable(function* () {\n                for (const value of syncFactory()) {\n                  yield value;\n                }\n\n                for (const source of sources as Iterable<Awaitable<T>>[]) {\n                  for (const value of source) {\n                    yield value;\n                  }\n                }\n              })\n          : undefined;\n\n      if (concatenatedSyncFactory !== undefined) {\n        return createAsyncOperator<T>({\n          syncFactory: concatenatedSyncFactory,\n          asyncFactory: () => toAsyncIterable(concatenatedSyncFactory()),\n        }) as AsyncOperator<T>;\n      }\n\n      return createAsyncOperator<T>(\n        createAsyncOnlyFactories(() =>\n          createAsyncIterable(async function* () {\n            if (syncFactory !== undefined) {\n              for (const value of syncFactory()) {\n                yield (isPromiseLike(value) ? await value : value) as T;\n              }\n            } else {\n              for await (const value of iterableFactory()) {\n                yield value as T;\n              }\n            }\n\n            for (const source of sources) {\n              if (isAsyncIterable(source)) {\n                for await (const value of source) {\n                  yield value as T;\n                }\n              } else {\n                for (const value of source) {\n                  yield (isPromiseLike(value) ? await value : value) as T;\n                }\n              }\n            }\n          })\n        )\n      ) as AsyncOperator<T>;\n    },\n    choose: <U>(\n      selector: (value: T, index: number) => Awaitable<U | null | undefined>\n    ) =>\n      appendLinearOperation<NonNullable<U>>(\n        {\n          kind: 'choose',\n          selector: selector as (\n            value: unknown,\n            index: number\n          ) => Awaitable<unknown | null | undefined>,\n        },\n        () =>\n          createAsyncOnlyFactories(() =>\n            createAsyncIterable(async function* () {\n              let index = 0;\n              if (syncFactory !== undefined) {\n                for (const value of syncFactory()) {\n                  const resolvedValue = (\n                    isPromiseLike(value) ? await value : value\n                  ) as T;\n                  const result = selector(resolvedValue, index);\n                  const selected = isPromiseLike(result)\n                    ? await result\n                    : result;\n                  if (isNonNullish(selected)) {\n                    yield selected as NonNullable<U>;\n                  }\n                  index++;\n                }\n              } else {\n                for await (const value of iterableFactory()) {\n                  const result = selector(value, index);\n                  const selected = isPromiseLike(result)\n                    ? await result\n                    : result;\n                  if (isNonNullish(selected)) {\n                    yield selected as NonNullable<U>;\n                  }\n                  index++;\n                }\n              }\n            })\n          )\n      ),\n    slice: (start: number, end?: number) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const normalizedStart = toIntegerOrInfinity(start);\n          const normalizedEnd =\n            end === undefined ? undefined : toIntegerOrInfinity(end);\n\n          if (\n            normalizedStart < 0 ||\n            (normalizedEnd !== undefined && normalizedEnd < 0)\n          ) {\n            const values = await materializeValues(iteratorFactories);\n            for (const value of values.slice(start, end)) {\n              yield value;\n            }\n            return;\n          }\n\n          const startIndex = Math.max(normalizedStart, 0);\n          if (startIndex === Infinity) {\n            return;\n          }\n\n          const endIndex =\n            normalizedEnd === undefined\n              ? undefined\n              : Math.max(normalizedEnd, 0);\n          if (\n            endIndex !== undefined &&\n            endIndex !== Infinity &&\n            endIndex <= startIndex\n          ) {\n            return;\n          }\n\n          let index = 0;\n\n          if (syncFactory !== undefined) {\n            const iterator = syncFactory()[Symbol.iterator]();\n\n            while (true) {\n              if (\n                endIndex !== undefined &&\n                endIndex !== Infinity &&\n                index >= endIndex\n              ) {\n                return;\n              }\n\n              const result = iterator.next();\n              if (result.done) {\n                return;\n              }\n\n              const value = result.value;\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              if (index >= startIndex) {\n                yield resolvedValue as T;\n              }\n              index++;\n            }\n          } else {\n            const iterator = iterableFactory()[Symbol.asyncIterator]();\n\n            while (true) {\n              if (\n                endIndex !== undefined &&\n                endIndex !== Infinity &&\n                index >= endIndex\n              ) {\n                return;\n              }\n\n              const result = await iterator.next();\n              if (result.done) {\n                return;\n              }\n\n              const value = result.value;\n              if (index >= startIndex) {\n                yield value as T;\n              }\n              index++;\n            }\n          }\n        })\n      ) as AsyncOperator<T>,\n    distinct: () =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const seenValues = new Set<T>();\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              if (!seenValues.has(resolvedValue)) {\n                seenValues.add(resolvedValue);\n                yield resolvedValue as T;\n              }\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              if (!seenValues.has(value)) {\n                seenValues.add(value);\n                yield value as T;\n              }\n            }\n          }\n        })\n      ) as AsyncOperator<T>,\n    distinctBy: <TKey>(\n      selector: (value: T, index: number) => Awaitable<TKey>\n    ) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          let index = 0;\n          const seenKeys = new Set<TKey>();\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              const selectedKey = selector(resolvedValue, index);\n              const key = isPromiseLike(selectedKey)\n                ? await selectedKey\n                : selectedKey;\n              if (!seenKeys.has(key)) {\n                seenKeys.add(key);\n                yield resolvedValue as T;\n              }\n              index++;\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              const selectedKey = selector(value, index);\n              const key = isPromiseLike(selectedKey)\n                ? await selectedKey\n                : selectedKey;\n              if (!seenKeys.has(key)) {\n                seenKeys.add(key);\n                yield value as T;\n              }\n              index++;\n            }\n          }\n        })\n      ) as AsyncOperator<T>,\n    skip: (count: number) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const normalizedCount = normalizeCount(count);\n          let skippedCount = 0;\n          for await (const value of iterableFactory()) {\n            if (skippedCount < normalizedCount) {\n              skippedCount++;\n              continue;\n            }\n            yield value as T;\n          }\n        })\n      ) as AsyncOperator<T>,\n    skipWhile: (predicate: (value: T, index: number) => Awaitable<boolean>) =>\n      appendLinearOperation<T>(\n        {\n          kind: 'skipWhile',\n          predicate: predicate as (\n            value: unknown,\n            index: number\n          ) => Awaitable<boolean>,\n        },\n        () =>\n          createAsyncOnlyFactories(() =>\n            createAsyncIterable(async function* () {\n              let index = 0;\n              let skipping = true;\n              if (syncFactory !== undefined) {\n                for (const value of syncFactory()) {\n                  const resolvedValue = (\n                    isPromiseLike(value) ? await value : value\n                  ) as T;\n                  const result = predicate(resolvedValue, index);\n                  if (\n                    skipping &&\n                    (isPromiseLike(result) ? await result : result)\n                  ) {\n                    index++;\n                    continue;\n                  }\n\n                  skipping = false;\n                  yield resolvedValue as T;\n                  index++;\n                }\n              } else {\n                for await (const value of iterableFactory()) {\n                  const result = predicate(value, index);\n                  if (\n                    skipping &&\n                    (isPromiseLike(result) ? await result : result)\n                  ) {\n                    index++;\n                    continue;\n                  }\n\n                  skipping = false;\n                  yield value as T;\n                  index++;\n                }\n              }\n            })\n          )\n      ),\n    take: (count: number) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const normalizedCount = normalizeCount(count);\n          if (normalizedCount === 0) {\n            return;\n          }\n\n          let takenCount = 0;\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              yield (isPromiseLike(value) ? await value : value) as T;\n              takenCount++;\n              if (takenCount >= normalizedCount) {\n                return;\n              }\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              yield value as T;\n              takenCount++;\n              if (takenCount >= normalizedCount) {\n                return;\n              }\n            }\n          }\n        })\n      ) as AsyncOperator<T>,\n    takeWhile: (predicate: (value: T, index: number) => Awaitable<boolean>) =>\n      appendLinearOperation<T>(\n        {\n          kind: 'takeWhile',\n          predicate: predicate as (\n            value: unknown,\n            index: number\n          ) => Awaitable<boolean>,\n        },\n        () =>\n          createAsyncOnlyFactories(() =>\n            createAsyncIterable(async function* () {\n              let index = 0;\n              if (syncFactory !== undefined) {\n                for (const value of syncFactory()) {\n                  const resolvedValue = (\n                    isPromiseLike(value) ? await value : value\n                  ) as T;\n                  const result = predicate(resolvedValue, index);\n                  if (!(isPromiseLike(result) ? await result : result)) {\n                    return;\n                  }\n                  yield resolvedValue as T;\n                  index++;\n                }\n              } else {\n                for await (const value of iterableFactory()) {\n                  const result = predicate(value, index);\n                  if (!(isPromiseLike(result) ? await result : result)) {\n                    return;\n                  }\n                  yield value as T;\n                  index++;\n                }\n              }\n            })\n          )\n      ),\n    pairwise: () =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          let hasPreviousValue = false;\n          let previousValue: T | undefined;\n\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              if (hasPreviousValue) {\n                yield [previousValue as T, resolvedValue] as const;\n              }\n              previousValue = resolvedValue;\n              hasPreviousValue = true;\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              if (hasPreviousValue) {\n                yield [previousValue as T, value as T] as const;\n              }\n              previousValue = value;\n              hasPreviousValue = true;\n            }\n          }\n        })\n      ) as AsyncOperator<readonly [T, T]>,\n    zip: <U>(source: AsyncOperatorSource<U>) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          if (isAsyncIterable(source)) {\n            const otherIterator = source[Symbol.asyncIterator]();\n\n            if (syncFactory !== undefined) {\n              for (const value of syncFactory()) {\n                const otherResult = await otherIterator.next();\n                if (otherResult.done) {\n                  return;\n                }\n\n                yield [\n                  (isPromiseLike(value) ? await value : value) as T,\n                  otherResult.value as U,\n                ] as const;\n              }\n            } else {\n              for await (const value of iterableFactory()) {\n                const otherResult = await otherIterator.next();\n                if (otherResult.done) {\n                  return;\n                }\n\n                yield [value as T, otherResult.value as U] as const;\n              }\n            }\n          } else {\n            const otherIterator = source[Symbol.iterator]();\n\n            if (syncFactory !== undefined) {\n              for (const value of syncFactory()) {\n                const otherResult = otherIterator.next();\n                if (otherResult.done) {\n                  return;\n                }\n\n                yield [\n                  (isPromiseLike(value) ? await value : value) as T,\n                  (isPromiseLike(otherResult.value)\n                    ? await otherResult.value\n                    : otherResult.value) as U,\n                ] as const;\n              }\n            } else {\n              for await (const value of iterableFactory()) {\n                const otherResult = otherIterator.next();\n                if (otherResult.done) {\n                  return;\n                }\n\n                yield [\n                  value as T,\n                  (isPromiseLike(otherResult.value)\n                    ? await otherResult.value\n                    : otherResult.value) as U,\n                ] as const;\n              }\n            }\n          }\n        })\n      ) as AsyncOperator<readonly [T, U]>,\n    scan: <U>(\n      reducer: (\n        previousValue: U,\n        currentValue: T,\n        index: number\n      ) => Awaitable<U>,\n      initialValue: U\n    ) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          let accumulator = initialValue;\n          let index = 0;\n\n          yield accumulator as U;\n\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              const reduced = reducer(accumulator, resolvedValue, index);\n              accumulator = (\n                isPromiseLike(reduced) ? await reduced : reduced\n              ) as U;\n              yield accumulator as U;\n              index++;\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              const reduced = reducer(accumulator, value, index);\n              accumulator = (\n                isPromiseLike(reduced) ? await reduced : reduced\n              ) as U;\n              yield accumulator as U;\n              index++;\n            }\n          }\n        })\n      ) as AsyncOperator<U>,\n    union: (source: AsyncOperatorSource<T>) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const seenValues = new Set<T>();\n\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              if (!seenValues.has(resolvedValue)) {\n                seenValues.add(resolvedValue);\n                yield resolvedValue as T;\n              }\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              if (!seenValues.has(value)) {\n                seenValues.add(value);\n                yield value as T;\n              }\n            }\n          }\n\n          if (isAsyncIterable(source)) {\n            for await (const value of source) {\n              if (!seenValues.has(value)) {\n                seenValues.add(value);\n                yield value as T;\n              }\n            }\n          } else {\n            for (const value of source) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              if (!seenValues.has(resolvedValue)) {\n                seenValues.add(resolvedValue);\n                yield resolvedValue as T;\n              }\n            }\n          }\n        })\n      ) as AsyncOperator<T>,\n    unionBy: <TKey>(\n      source: AsyncOperatorSource<T>,\n      selector: (value: T, index: number) => Awaitable<TKey>\n    ) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const seenKeys = new Set<TKey>();\n          let index = 0;\n\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              const selectedKey = selector(resolvedValue, index);\n              const key = isPromiseLike(selectedKey)\n                ? await selectedKey\n                : selectedKey;\n              if (!seenKeys.has(key)) {\n                seenKeys.add(key);\n                yield resolvedValue as T;\n              }\n              index++;\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              const selectedKey = selector(value, index);\n              const key = isPromiseLike(selectedKey)\n                ? await selectedKey\n                : selectedKey;\n              if (!seenKeys.has(key)) {\n                seenKeys.add(key);\n                yield value as T;\n              }\n              index++;\n            }\n          }\n\n          index = 0;\n          if (isAsyncIterable(source)) {\n            for await (const value of source) {\n              const selectedKey = selector(value, index);\n              const key = isPromiseLike(selectedKey)\n                ? await selectedKey\n                : selectedKey;\n              if (!seenKeys.has(key)) {\n                seenKeys.add(key);\n                yield value as T;\n              }\n              index++;\n            }\n          } else {\n            for (const value of source) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              const selectedKey = selector(resolvedValue, index);\n              const key = isPromiseLike(selectedKey)\n                ? await selectedKey\n                : selectedKey;\n              if (!seenKeys.has(key)) {\n                seenKeys.add(key);\n                yield resolvedValue as T;\n              }\n              index++;\n            }\n          }\n        })\n      ) as AsyncOperator<T>,\n    intersect: (source: AsyncOperatorSource<T>) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const rightValues = await collectValuesFromSource(source);\n          const yieldedValues = new Set<T>();\n\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              if (\n                rightValues.has(resolvedValue) &&\n                !yieldedValues.has(resolvedValue)\n              ) {\n                yieldedValues.add(resolvedValue);\n                yield resolvedValue as T;\n              }\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              if (rightValues.has(value) && !yieldedValues.has(value)) {\n                yieldedValues.add(value);\n                yield value as T;\n              }\n            }\n          }\n        })\n      ) as AsyncOperator<T>,\n    intersectBy: <TKey>(\n      source: AsyncOperatorSource<T>,\n      selector: (value: T, index: number) => Awaitable<TKey>\n    ) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const rightKeys = await collectKeysFromSource(source, selector);\n          const yieldedKeys = new Set<TKey>();\n          let index = 0;\n\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              const selectedKey = selector(resolvedValue, index);\n              const key = isPromiseLike(selectedKey)\n                ? await selectedKey\n                : selectedKey;\n              if (rightKeys.has(key) && !yieldedKeys.has(key)) {\n                yieldedKeys.add(key);\n                yield resolvedValue as T;\n              }\n              index++;\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              const selectedKey = selector(value, index);\n              const key = isPromiseLike(selectedKey)\n                ? await selectedKey\n                : selectedKey;\n              if (rightKeys.has(key) && !yieldedKeys.has(key)) {\n                yieldedKeys.add(key);\n                yield value as T;\n              }\n              index++;\n            }\n          }\n        })\n      ) as AsyncOperator<T>,\n    except: (source: AsyncOperatorSource<T>) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const excludedValues = await collectValuesFromSource(source);\n          const yieldedValues = new Set<T>();\n\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              if (\n                !excludedValues.has(resolvedValue) &&\n                !yieldedValues.has(resolvedValue)\n              ) {\n                yieldedValues.add(resolvedValue);\n                yield resolvedValue as T;\n              }\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              if (!excludedValues.has(value) && !yieldedValues.has(value)) {\n                yieldedValues.add(value);\n                yield value as T;\n              }\n            }\n          }\n        })\n      ) as AsyncOperator<T>,\n    exceptBy: <TKey>(\n      source: AsyncOperatorSource<T>,\n      selector: (value: T, index: number) => Awaitable<TKey>\n    ) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const excludedKeys = await collectKeysFromSource(source, selector);\n          const yieldedKeys = new Set<TKey>();\n          let index = 0;\n\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              const resolvedValue = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              const selectedKey = selector(resolvedValue, index);\n              const key = isPromiseLike(selectedKey)\n                ? await selectedKey\n                : selectedKey;\n              if (!excludedKeys.has(key) && !yieldedKeys.has(key)) {\n                yieldedKeys.add(key);\n                yield resolvedValue as T;\n              }\n              index++;\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              const selectedKey = selector(value, index);\n              const key = isPromiseLike(selectedKey)\n                ? await selectedKey\n                : selectedKey;\n              if (!excludedKeys.has(key) && !yieldedKeys.has(key)) {\n                yieldedKeys.add(key);\n                yield value as T;\n              }\n              index++;\n            }\n          }\n        })\n      ) as AsyncOperator<T>,\n    chunkBySize: (size: number) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const normalizedSize = normalizeRequiredCount(size, 'Chunk size');\n          let chunk: T[] = [];\n\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              chunk.push((isPromiseLike(value) ? await value : value) as T);\n              if (chunk.length >= normalizedSize) {\n                yield chunk;\n                chunk = [];\n              }\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              chunk.push(value);\n              if (chunk.length >= normalizedSize) {\n                yield chunk;\n                chunk = [];\n              }\n            }\n          }\n\n          if (chunk.length > 0) {\n            yield chunk;\n          }\n        })\n      ) as AsyncOperator<T[]>,\n    windowed: (size: number) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const normalizedSize = normalizeRequiredCount(size, 'Window size');\n          const buffer = new Array<T>(normalizedSize);\n          let count = 0;\n          let nextIndex = 0;\n\n          if (syncFactory !== undefined) {\n            for (const value of syncFactory()) {\n              buffer[nextIndex] = (\n                isPromiseLike(value) ? await value : value\n              ) as T;\n              nextIndex = (nextIndex + 1) % normalizedSize;\n              count = Math.min(count + 1, normalizedSize);\n\n              if (count < normalizedSize) {\n                continue;\n              }\n\n              const window = new Array<T>(normalizedSize);\n              for (let index = 0; index < normalizedSize; index++) {\n                window[index] = buffer[\n                  (nextIndex + index) % normalizedSize\n                ] as T;\n              }\n              yield window;\n            }\n          } else {\n            for await (const value of iterableFactory()) {\n              buffer[nextIndex] = value;\n              nextIndex = (nextIndex + 1) % normalizedSize;\n              count = Math.min(count + 1, normalizedSize);\n\n              if (count < normalizedSize) {\n                continue;\n              }\n\n              const window = new Array<T>(normalizedSize);\n              for (let index = 0; index < normalizedSize; index++) {\n                window[index] = buffer[\n                  (nextIndex + index) % normalizedSize\n                ] as T;\n              }\n              yield window;\n            }\n          }\n        })\n      ) as AsyncOperator<T[]>,\n    flat,\n    reverse: () =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const values = await materializeValues(iteratorFactories);\n          values.reverse();\n\n          for (const value of values) {\n            yield value;\n          }\n        })\n      ) as AsyncOperator<T>,\n    toReversed: () =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const values = await materializeValues(iteratorFactories);\n\n          for (const value of [...values].reverse()) {\n            yield value;\n          }\n        })\n      ) as AsyncOperator<T>,\n    sort: (compareFn?: (left: T, right: T) => number) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const values = await materializeValues(iteratorFactories);\n          compareFn === undefined ? values.sort() : values.sort(compareFn);\n\n          for (const value of values) {\n            yield value;\n          }\n        })\n      ) as AsyncOperator<T>,\n    toSorted: (compareFn?: (left: T, right: T) => number) =>\n      createAsyncOperator(() =>\n        createAsyncIterable(async function* () {\n          const values = await materializeValues(iteratorFactories);\n          const sortedValues = [...values];\n          compareFn === undefined\n            ? sortedValues.sort()\n            : sortedValues.sort(compareFn);\n\n          for (const value of sortedValues) {\n            yield value;\n          }\n        })\n      ) as AsyncOperator<T>,\n    forEach: async (\n      action: (value: T, index: number) => Awaitable<void>\n    ): Promise<void> => {\n      let index = 0;\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          const result = action(resolvedValue, index);\n          if (isPromiseLike(result)) {\n            await result;\n          }\n          index++;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          const result = action(value, index);\n          if (isPromiseLike(result)) {\n            await result;\n          }\n          index++;\n        }\n      }\n    },\n    reduce,\n    reduceRight,\n    some: async (\n      predicate: (value: T, index: number) => Awaitable<boolean>\n    ): Promise<boolean> => {\n      let index = 0;\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          const result = predicate(resolvedValue, index);\n          if (isPromiseLike(result) ? await result : result) {\n            return true;\n          }\n          index++;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          const result = predicate(value, index);\n          if (isPromiseLike(result) ? await result : result) {\n            return true;\n          }\n          index++;\n        }\n      }\n      return false;\n    },\n    every: async (\n      predicate: (value: T, index: number) => Awaitable<boolean>\n    ): Promise<boolean> => {\n      let index = 0;\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          const result = predicate(resolvedValue, index);\n          if (!(isPromiseLike(result) ? await result : result)) {\n            return false;\n          }\n          index++;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          const result = predicate(value, index);\n          if (!(isPromiseLike(result) ? await result : result)) {\n            return false;\n          }\n          index++;\n        }\n      }\n      return true;\n    },\n    find: async (\n      predicate: (value: T, index: number) => Awaitable<boolean>\n    ): Promise<T | undefined> => {\n      let index = 0;\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          const result = predicate(resolvedValue, index);\n          if (isPromiseLike(result) ? await result : result) {\n            return resolvedValue;\n          }\n          index++;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          const result = predicate(value, index);\n          if (isPromiseLike(result) ? await result : result) {\n            return value;\n          }\n          index++;\n        }\n      }\n      return undefined;\n    },\n    findIndex: async (\n      predicate: (value: T, index: number) => Awaitable<boolean>\n    ): Promise<number> => {\n      let index = 0;\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          const result = predicate(resolvedValue, index);\n          if (isPromiseLike(result) ? await result : result) {\n            return index;\n          }\n          index++;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          const result = predicate(value, index);\n          if (isPromiseLike(result) ? await result : result) {\n            return index;\n          }\n          index++;\n        }\n      }\n      return -1;\n    },\n    at: async (index: number): Promise<T | undefined> => {\n      const normalizedIndex = toIntegerOrInfinity(index);\n\n      if (normalizedIndex >= 0) {\n        if (normalizedIndex === Infinity) {\n          return undefined;\n        }\n\n        let currentIndex = 0;\n\n        if (syncFactory !== undefined) {\n          for (const value of syncFactory()) {\n            const resolvedValue = (\n              isPromiseLike(value) ? await value : value\n            ) as T;\n            if (currentIndex === normalizedIndex) {\n              return resolvedValue;\n            }\n            currentIndex++;\n          }\n        } else {\n          for await (const value of iterableFactory()) {\n            if (currentIndex === normalizedIndex) {\n              return value;\n            }\n            currentIndex++;\n          }\n        }\n        return undefined;\n      }\n\n      if (normalizedIndex === -Infinity) {\n        return undefined;\n      }\n\n      const lookback = Math.abs(normalizedIndex);\n      const buffer = new Array<T>(lookback);\n      let count = 0;\n      let nextIndex = 0;\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          buffer[nextIndex] = (isPromiseLike(value) ? await value : value) as T;\n          nextIndex = (nextIndex + 1) % lookback;\n          count = Math.min(count + 1, lookback);\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          buffer[nextIndex] = value;\n          nextIndex = (nextIndex + 1) % lookback;\n          count = Math.min(count + 1, lookback);\n        }\n      }\n\n      return count === lookback ? buffer[nextIndex] : undefined;\n    },\n    includes: async (\n      searchElement: T,\n      fromIndex?: number\n    ): Promise<boolean> => {\n      const normalizedFromIndex = toIntegerOrInfinity(fromIndex ?? 0);\n\n      if (normalizedFromIndex < 0) {\n        const values = await materializeValues(iteratorFactories);\n        return values.includes(searchElement, normalizedFromIndex);\n      }\n\n      if (normalizedFromIndex === Infinity) {\n        return false;\n      }\n\n      let index = 0;\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          if (\n            index >= normalizedFromIndex &&\n            sameValueZero(resolvedValue, searchElement)\n          ) {\n            return true;\n          }\n          index++;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          if (\n            index >= normalizedFromIndex &&\n            sameValueZero(value, searchElement)\n          ) {\n            return true;\n          }\n          index++;\n        }\n      }\n      return false;\n    },\n    indexOf: async (searchElement: T, fromIndex?: number): Promise<number> => {\n      const normalizedFromIndex = toIntegerOrInfinity(fromIndex ?? 0);\n\n      if (normalizedFromIndex < 0) {\n        const values = await materializeValues(iteratorFactories);\n        return values.indexOf(searchElement, normalizedFromIndex);\n      }\n\n      if (normalizedFromIndex === Infinity) {\n        return -1;\n      }\n\n      let index = 0;\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          if (index >= normalizedFromIndex && resolvedValue === searchElement) {\n            return index;\n          }\n          index++;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          if (index >= normalizedFromIndex && value === searchElement) {\n            return index;\n          }\n          index++;\n        }\n      }\n      return -1;\n    },\n    lastIndexOf: async (\n      searchElement: T,\n      fromIndex?: number\n    ): Promise<number> => {\n      const values = await materializeValues(iteratorFactories);\n      return fromIndex === undefined\n        ? values.lastIndexOf(searchElement)\n        : values.lastIndexOf(searchElement, fromIndex);\n    },\n    findLast: async (\n      predicate: (value: T, index: number) => Awaitable<boolean>\n    ): Promise<T | undefined> => {\n      let index = 0;\n      let foundValue: T | undefined;\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          const result = predicate(resolvedValue, index);\n          if (isPromiseLike(result) ? await result : result) {\n            foundValue = resolvedValue;\n          }\n          index++;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          const result = predicate(value, index);\n          if (isPromiseLike(result) ? await result : result) {\n            foundValue = value;\n          }\n          index++;\n        }\n      }\n\n      return foundValue;\n    },\n    findLastIndex: async (\n      predicate: (value: T, index: number) => Awaitable<boolean>\n    ): Promise<number> => {\n      let index = 0;\n      let foundIndex = -1;\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          const result = predicate(resolvedValue, index);\n          if (isPromiseLike(result) ? await result : result) {\n            foundIndex = index;\n          }\n          index++;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          const result = predicate(value, index);\n          if (isPromiseLike(result) ? await result : result) {\n            foundIndex = index;\n          }\n          index++;\n        }\n      }\n\n      return foundIndex;\n    },\n    min: async (): Promise<T | undefined> =>\n      findExtremeBy(iteratorFactories, identity, 'min'),\n    minBy: async <TKey>(\n      selector: (value: T, index: number) => Awaitable<TKey>\n    ): Promise<T | undefined> =>\n      findExtremeBy(iteratorFactories, selector, 'min'),\n    max: async (): Promise<T | undefined> =>\n      findExtremeBy(iteratorFactories, (value) => value, 'max'),\n    maxBy: async <TKey>(\n      selector: (value: T, index: number) => Awaitable<TKey>\n    ): Promise<T | undefined> =>\n      findExtremeBy(iteratorFactories, selector, 'max'),\n    groupBy: async <TKey>(\n      selector: (value: T, index: number) => Awaitable<TKey>\n    ): Promise<Map<TKey, T[]>> => {\n      let index = 0;\n      const groupedValues = new Map<TKey, T[]>();\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          const selectedKey = selector(resolvedValue, index);\n          const key = isPromiseLike(selectedKey)\n            ? await selectedKey\n            : selectedKey;\n          const existingGroup = groupedValues.get(key);\n          if (existingGroup) {\n            existingGroup.push(resolvedValue);\n          } else {\n            groupedValues.set(key, [resolvedValue]);\n          }\n          index++;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          const selectedKey = selector(value, index);\n          const key = isPromiseLike(selectedKey)\n            ? await selectedKey\n            : selectedKey;\n          const existingGroup = groupedValues.get(key);\n          if (existingGroup) {\n            existingGroup.push(value);\n          } else {\n            groupedValues.set(key, [value]);\n          }\n          index++;\n        }\n      }\n\n      return groupedValues;\n    },\n    countBy: async <TKey>(\n      selector: (value: T, index: number) => Awaitable<TKey>\n    ): Promise<Map<TKey, number>> => {\n      let index = 0;\n      const counts = new Map<TKey, number>();\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          const selectedKey = selector(resolvedValue, index);\n          const key = isPromiseLike(selectedKey)\n            ? await selectedKey\n            : selectedKey;\n          counts.set(key, (counts.get(key) ?? 0) + 1);\n          index++;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          const selectedKey = selector(value, index);\n          const key = isPromiseLike(selectedKey)\n            ? await selectedKey\n            : selectedKey;\n          counts.set(key, (counts.get(key) ?? 0) + 1);\n          index++;\n        }\n      }\n\n      return counts;\n    },\n    join: async (separator?: string): Promise<string> => {\n      const normalizedSeparator = separator ?? ',';\n      let isFirst = true;\n      let result = '';\n\n      if (syncFactory !== undefined) {\n        for (const value of syncFactory()) {\n          const resolvedValue = (\n            isPromiseLike(value) ? await value : value\n          ) as T;\n          if (!isFirst) {\n            result += normalizedSeparator;\n          }\n          result += resolvedValue == null ? '' : String(resolvedValue);\n          isFirst = false;\n        }\n      } else {\n        for await (const value of iterableFactory()) {\n          if (!isFirst) {\n            result += normalizedSeparator;\n          }\n          result += value == null ? '' : String(value);\n          isFirst = false;\n        }\n      }\n\n      return result;\n    },\n    toArray: async (): Promise<T[]> => materializeValues(iteratorFactories),\n  };\n};\n\n/**\n * Creates a chainable async operator pipeline from an iterable of values or promise-like values\n * @param source - Source iterable to resolve\n * @returns A lazy async operator pipeline\n */\nexport const from = <T>(source: AsyncOperatorSource<T>): AsyncOperator<T> =>\n  createAsyncOperator(createIteratorFactories(source));\n"],"mappings":";;;;;;;;;;;;;AAUA,IAAa,uBAAuB;AACpC,IAAa,oBAAgC;CAC3C,SAAS;EACR,OAAO,UAAU;CACnB;;;ACND,IAAM,gBAAgB,WAA2B;AAC/C,KAAI,kBAAkB,MACpB,QAAO;AAET,KAAI,OAAO,WAAW,SACpB,QAAO,IAAI,MAAM,OAAO;AAE1B,wBAAO,IAAI,MAAM,oBAAoB;;;;;;;;AASvC,IAAa,WACX,QACA,aACe;AACf,KAAI,CAAC,OACH,QAAO;AAGT,KAAI,OAAO,SAAS;AAClB,MAAI;AACF,YAAS,aAAa,OAAO,OAAO,CAAC;WAC9B,OAAgB;AACvB,WAAQ,KAAK,8BAA8B,MAAM;;AAEnD,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