import { createContext as createContext$1 } from 'unctx';
import { AsyncLocalStorage } from 'node:async_hooks';
import { Result } from 'neverthrow';
import { Plugin } from 'seroval';

/**
 * @module
 * This module implements the "Effects Handler" pattern, a powerful way to
 * decouple the declaration of side effects (the "what") from their implementation
 * (the "how"). This enables maximum testability and allows for swapping
 * implementations at runtime.
 *
 * ---
 *
 * ### Recommended Usage
 *
 * - For **multiple effects** in an application, use `createEffectSuite` for the best end-to-end type safety.
 * - For a **single effect** or for one-off overrides in tests, use `defineEffect` and its attached `.withHandler()` method for a clean, safe, and ergonomic API.
 *
 * Standalone helpers are also available for backward compatibility and advanced use cases.
 */

/**
 * A unique `Symbol` used as the key for the effects handler map within the context.
 * Using `Symbol.for()` ensures that even if multiple versions of this library
 * are present in a project, they will all share the same symbol, guaranteeing interoperability.
 */
declare const HANDLERS_KEY: unique symbol;
/** A generic type representing the shape of any function. */
type AnyFn = (...args: any[]) => any;
/** An object type where keys are strings and values are functions. Used as a generic constraint. */
type EffectsSchema = Record<string, AnyFn>;
/**
 * Represents a callable effect function. It is an async-first version of the
 * function signature `T`.
 */
type Effect<T extends AnyFn> = (...args: Parameters<T>) => Promise<ReturnType<T>>;
/** A generic mapping of effect names to their concrete handler implementations. */
type Handlers = Record<string, AnyFn>;
type EffectSuiteTools<T extends EffectsSchema> = {
    effects: EffectsSuite<T>;
    createHandlers: (handlers: T) => T;
    withHandlers(handlers: T): {
        overrides: {
            [HANDLERS_KEY]: Handlers;
        };
    };
};
/**
 * The return type of the `defineEffect` function. It is the callable effect
 * function with attached helper methods for easily providing an implementation.
 */
type EffectWithHelpers<T extends AnyFn> = Effect<T> & {
    /**
     * Creates run options with a handler for this specific effect. This is the
     * safest and most convenient way to provide a one-off implementation for an
     * effect, especially in tests.
     * @param implementation The function that implements the effect. Its signature
     * is validated against the effect's definition.
     */
    withHandler: (implementation: T) => {
        overrides: {
            [HANDLERS_KEY]: Handlers;
        };
    };
    /**
     * Creates a single-entry `Handlers` object for this effect. Useful when
     * combining multiple handlers from different effects.
     * @param implementation The function that implements the effect.
     */
    createHandler: (implementation: T) => Handlers;
};
/** The return type of `defineEffects` or the `effects` property from `createEffectSuite`. */
type EffectsSuite<T extends EffectsSchema> = {
    [K in keyof T]: EffectWithHelpers<T[K]>;
};
/** The shape a context must have to support the effects pattern. */
interface EffectsContext extends BaseContext {
    [HANDLERS_KEY]?: Handlers;
}
/**
 * An error thrown when an effect is called but no corresponding handler
 * has been provided in the context at runtime.
 */
declare class EffectHandlerNotFoundError extends Error {
    readonly effectName: string;
    constructor(effectName: string);
}
/**
 * Creates a complete, type-safe suite for managing a domain of **multiple effects**.
 *
 * This is the **recommended entry point** for full applications. It takes a single
 * generic argument (your effects contract) and returns a matched set of tools that
 * provide end-to-end type safety.
 *
 * @template T A `type` or `interface` that defines the effect names and their function signatures.
 */
declare function createEffectSuite<T extends EffectsSchema>(): {
    effects: EffectsSuite<T>;
    createHandlers: (handlers: T) => T;
    withHandlers: (handlers: T) => {
        overrides: {
            [HANDLERS_KEY]: Handlers;
        };
    };
};
/**
 * Defines a **single, typed effect**. This is the recommended way to handle individual
 * effects or one-off overrides in tests.
 *
 * It returns a directly callable, async effect function. For convenience,
 * it also comes with attached helper methods (`.withHandler` and `.createHandler`)
 * to make providing a single implementation safe and easy.
 *
 * @template T The function signature of the effect.
 * @param effectName A unique string identifier for this effect.
 * @returns A callable `Effect` function with attached helpers.
 *
 * @example (Providing a one-off override in a test)
 * ```typescript
 * const getUniqueId = defineEffect<() => string>('getUniqueId');
 *
 * test('should use a predictable ID', async () => {
 *   const user = await run(
 *     createUserTask,
 *     'test-user',
 *     getUniqueId.withHandler(() => 'test-id-123') // ✅ Simple and type-safe!
 *   );
 *   expect(user.id).toBe('test-id-123');
 * });
 * ```
 */
declare function defineEffect<T extends AnyFn>(effectName: string): EffectWithHelpers<T>;
declare function defineEffects<T extends EffectsSchema>(): EffectsSuite<T>;
declare function defineEffects<T extends EffectsSchema>(effectsConfig: T): EffectsSuite<T>;
declare function createHandlers<T extends EffectsSchema>(handlers: T): T;
declare function createHandlers(handlers: Handlers): Handlers;
declare function withHandlers<T extends EffectsSchema>(handlers: T): {
    overrides: {
        [HANDLERS_KEY]: T;
    };
};
declare function withHandlers(handlers: Handlers): {
    overrides: {
        [HANDLERS_KEY]: Handlers;
    };
};
/**
 * [Advanced] Creates run options for a single handler by providing the full
 * effects suite, the name of the effect to handle, and its implementation.
 * @param effectsSuite The full `effects` object from `createEffectSuite` or `defineEffects`.
 * @param effectName The key of the effect within the suite to provide a handler for.
 * @param implementation The function that implements the effect.
 * @example run(myTask, withHandler(effects, 'getUniqueId', () => 'test-id'))
 */
declare function withHandler<T extends EffectsSchema, K extends keyof T>(effectsSuite: EffectsSuite<T>, effectName: K, implementation: T[K]): {
    overrides: {
        [HANDLERS_KEY]: Handlers;
    };
};
/**
 * [Advanced] Creates run options for a single handler by providing its
 * signature via a generic, its name, and its implementation.
 * @template T The function signature of the effect.
 * @param effectName The unique string name of the effect.
 * @param implementation The function that implements the effect.
 * @example run(myTask, withHandler<() => string>('getUniqueId', () => 'test-id'))
 */
declare function withHandler<T extends AnyFn>(effectName: string, implementation: T): {
    overrides: {
        [HANDLERS_KEY]: Handlers;
    };
};
/**
 * [Advanced] A standalone function to create run options for a single handler
 * by providing the effect object and its implementation.
 * @param effect The effect object returned by `defineEffect`.
 * @param implementation The function that implements the effect.
 * @example run(myTask, withHandler(getUniqueId, () => 'test-id'))
 */
declare function withHandler<T extends AnyFn>(effect: EffectWithHelpers<T>, implementation: T): {
    overrides: {
        [HANDLERS_KEY]: Handlers;
    };
};

/**
 * Base context that all contexts must extend.
 * This ensures type safety and provides the minimum required properties.
 */
type BaseContext = {
    readonly scope: Scope;
};
/**
 * Utility type for merging two contexts safely.
 * Properties in B override properties in A.
 */
type MergeContexts<A extends BaseContext, B extends Record<string, unknown>> = Omit<A, keyof B> & B & {
    scope: Scope;
};
/**
 * Utility type for context with optional extensions.
 * Useful for contexts that may or may not have certain dependencies.
 */
type WithOptionalContext<Base extends BaseContext, Extension extends Record<string, unknown>> = Base & Partial<Extension>;
type EnhancedOverrides<C extends BaseContext> = Partial<Omit<C, "scope">> & {
    [HANDLERS_KEY]?: Record<string, any>;
};
/**
 * Type for context validation functions.
 */
type ContextValidator<T> = (value: unknown) => value is T;
/**
 * Schema definition for runtime context validation.
 */
type ContextSchema<T extends BaseContext> = {
    readonly [K in keyof Omit<T, "scope">]: ContextValidator<T[K]>;
};
/**
 * Error thrown when context validation fails.
 */
declare class ContextValidationError extends Error {
    readonly _tag: "ContextValidationError";
    readonly field: string;
    readonly expectedType: string;
    readonly actualValue: unknown;
    constructor(field: string, expectedType: string, actualValue: unknown);
}
/**
 * Represents the execution scope for managing cancellation and cleanup.
 * The scope provides a unified way to handle cancellation across all tasks
 * in a workflow. When the signal is aborted, all tasks should gracefully
 * terminate their operations.
 */
interface Scope {
    /**
     * An AbortSignal that is triggered if the entire `run` operation is cancelled.
     * All tasks within the scope should respect this signal.
     *
     * @example
     * ```typescript
     * const { scope } = getContext();
     * const response = await fetch(url, { signal: scope.signal });
     * ```
     */
    readonly signal: AbortSignal;
}
/**
 * Logger interface for workflow execution logging.
 * Compatible with common logging libraries like winston, pino, console, etc.
 */
interface Logger {
    debug(message: string, ...args: unknown[]): void;
    info(message: string, ...args: unknown[]): void;
    warn(message: string, ...args: unknown[]): void;
    error(message: string, ...args: unknown[]): void;
}
/**
 * A no-op logger that discards all log messages.
 */
declare const noopLogger: Logger;
/**
 * The fundamental unit of work in the library.
 *
 * A Task is an async function that receives a context and an input value,
 * and returns a Promise of an output value. Tasks are composable and can
 * be chained together using a `createWorkflow` function from the `utils` module.
 *
 * @template C The shape of the application's context (must extend BaseContext).
 * @template V The input value type for the task.
 * @template R The resolved output value type of the task.
 */
type Task<C extends BaseContext, V, R> = ((context: C, value: V) => Promise<R>) & {
    /**
     * Internal property used to identify tasks for backtracking.
     * This is automatically set by `defineTask` and should not be manually modified.
     * @internal
     */
    __task_id?: symbol;
    /**
     * Internal property used by the `createWorkflow` utility to store the composed steps.
     * @internal
     */
    __steps?: ReadonlyArray<Task<C, unknown, unknown>>;
    __task_type?: "stream" | "request";
};
/**
 * A special signal used for non-linear control flow.
 *
 * When a task throws this signal, the `run` function will catch it and restart
 * the workflow from the specified target task with a new input value.
 * This enables powerful patterns like state machines and conditional flow control.
 */
declare class BacktrackSignal<C extends BaseContext = BaseContext, V = unknown> extends Error {
    readonly _tag: "BacktrackSignal";
    readonly target: Task<C, V, unknown>;
    readonly value: V;
    constructor(target: Task<C, V, unknown>, value: V);
}
/**
 * Type guard to check if an error is a BacktrackSignal.
 */
declare function isBacktrackSignal(error: unknown): error is BacktrackSignal;
/**
 * A structured error type for all workflow execution failures.
 */
declare class WorkflowError extends Error {
    readonly cause?: unknown;
    readonly taskName?: string;
    readonly taskIndex?: number;
    constructor(message: string, cause?: unknown, taskName?: string, taskIndex?: number);
}
/**
 * Options for the `run` function with default error-throwing behavior.
 */
interface RunOptionsThrow<C extends BaseContext> {
    throw?: true;
    logger?: Logger;
    overrides?: EnhancedOverrides<C>;
    parentSignal?: AbortSignal;
}
/**
 * Options for the `run` function with `Result` return type.
 */
interface RunOptionsResult<C extends BaseContext> {
    throw: false;
    logger?: Logger;
    overrides?: EnhancedOverrides<C>;
    parentSignal?: AbortSignal;
}
type RunOptions<C extends BaseContext> = RunOptionsThrow<C> | RunOptionsResult<C>;
/**
 * Error thrown when `getContext` is called outside of a `run` execution.
 */
declare class ContextNotFoundError extends Error {
    constructor(message?: string);
}
/**
 * The set of tools returned by `createContext<C>()` for working with
 * a specifically typed and isolated Effectively context.
 *
 * All methods within these tools operate on the context of type `C`
 * that was defined when `createContext<C>()` was called. They use an
 * internal `unctx` instance unique to this set of tools.
 *
 * @template C The specific `BaseContext` type this set of tools operates on.
 */
interface ContextTools<C extends BaseContext, G extends BaseContext = DefaultGlobalContext> {
    /**
     * Executes a workflow (a Task or a chain of Tasks) within this specific context.
     *
     * @template V The input value type for the workflow.
     * @template R The result type of the workflow.
     *
     * @param workflow The `Task<C, V, R>` or a compatible task to execute.
     *                 If a `Task<any, V, R>` (from global `defineTask`) is passed,
     *                 it will run within this specific context `C`.
     * @param initialValue The initial input value for the first task.
     * @param options Optional `RunOptions<C>` to control error handling (`throw`),
     *                logging, context overrides specific to this run, and parent cancellation.
     *                Overrides are applied on top of the default context data for these tools.
     *
     * @returns A Promise that resolves to the workflow's final result `R`, or, if
     *          `options.throw` is `false`, a `Promise<Result<R, WorkflowError>>`.
     */
    run<V, R>(workflow: Task<C, V, R> | Task<any, V, R>, // Can run tasks defined globally or for this specific context
    initialValue: V, options?: RunOptionsThrow<C>): Promise<R>;
    run<V, R>(workflow: Task<C, V, R> | Task<any, V, R>, initialValue: V, options: RunOptionsResult<C>): Promise<Result<R, WorkflowError>>;
    /**
     * Retrieves the currently active context of type `C` for this specific
     * `ContextTools` instance.
     *
     * @returns The context object of type `C`.
     * @throws {ContextNotFoundError} If called outside of an active `run` or
     *         `provide` scope managed by *this specific set of tools*.
     */
    getContext: () => C;
    /**
     * Safely retrieves the currently active context of type `C` as a `Result`.
     *
     * @returns `Ok(context)` if the context is active, otherwise `Err(ContextNotFoundError)`.
     */
    getContextSafe: () => Result<C, ContextNotFoundError>;
    /**
     * Retrieves the currently active context of type `C`, or `undefined` if not
     * within an active scope of these tools.
     *
     * @returns The context object `C` or `undefined`.
     */
    getContextOrUndefined: () => C | undefined;
    /**
     * Defines a Task that is strongly typed to operate within context `C`.
     *
     * The provided function `fn` should use `this.getContext()` (or the `getContext`
     * destructured from these tools) to access the context `C`.
     *
     * @template V The input value type for the task's logic.
     * @template R The result type the task's logic will resolve to.
     *
     * @param fn The core asynchronous logic of the task.
     * @param taskNameOrOptions Optional name for the task or `DefineTaskOptions`.
     * @returns A `Task<C, V, R>`, strongly typed to this context.
     */
    defineTask: {
        /**
         * Defines a context-aware Task from a standard async function.
         */
        <V, R>(fn: (value: V) => Promise<R>, taskNameOrOptions?: string | DefineTaskOptions): Task<C, V, R>;
        /**
         * Defines a context-aware Task from an async generator for streaming.
         */
        <V, R>(fn: (value: V) => AsyncGenerator<R, any, unknown> | AsyncIterable<R>, taskNameOrOptions?: string | DefineTaskOptions): Task<C, V, AsyncIterable<R>>;
    };
    /**
     * Executes a function within a new, nested context scope that temporarily
     * includes the specified overrides. This new scope is managed by the same
     * `unctx` instance associated with these `ContextTools`.
     *
     * The `scope` property is always inherited from the parent context of this
     * `provide` call and cannot be overridden.
     *
     * @template Pr The result type of the function `fn`. (Using `Pr` to avoid conflict with `R` from `run`)
     *
     * @param overrides An object with properties to merge into (or override on)
     *                  the current context for the duration of `fn`'s execution.
     *                  Overrides are typed against `C`.
     * @param fn The asynchronous function to execute within the new, modified context.
     *           Calls to `this.getContext()` within this function will resolve to the new context.
     * @param options Optional `ProvideImplOptions` to specify the context merging
     *                strategy (e.g., 'spread' or 'proxy'). Defaults to 'spread'.
     *
     * @returns A Promise that resolves with the result of `fn`.
     *
     * @example
     * ```typescript
     * const { provide, run, defineTask, getContext } = createContext<MyContext>(...);
     *
     * const myInnerTask = defineTask(async () => {
     *   const ctx = getContext(); // Gets MyContext + { temporaryApi: ... }
     *   // ctx.temporaryApi.call();
     * });
     *
     * await provide(
     *   { temporaryApi: new MockApi() },
     *   async () => {
     *     // Code here runs with temporaryApi in context
     *     await run(myInnerTask, undefined);
     *   }
     * );
     * ```
     */
    provide<Pr>(overrides: Partial<Omit<C, "scope" | typeof UNCTX_INSTANCE_SYMBOL> & Record<string | symbol, any>>, fn: () => Promise<Pr>, options?: ProvideImplOptions): Promise<Pr>;
    /**
     * Injects a dependency from the current context `C` using its token.
     *
     * @template T The type of the dependency to inject.
     * @param token The `InjectionToken<T>` for the dependency.
     * @returns The resolved dependency of type `T`.
     * @throws Error if the token is not found in the current context `C`.
     */
    inject<T>(token: InjectionToken<T>): T;
    /**
     * Safely injects a dependency from the current context `C`, returning
     * `undefined` if the token is not found.
     *
     * @template T The type of the dependency to inject.
     * @param token The `InjectionToken<T>` for the dependency.
     * @returns The resolved dependency of type `T`, or `undefined`.
     */
    injectOptional<T>(token: InjectionToken<T>): T | undefined;
    /**
     * Retrieves this toolset's specific context `C_Specific` if active,
     * otherwise falls back to the application's global context `G_AppGlobal`.
     */
    getContextOrGlobal: () => C | G;
}
/**
 * Symbol used to store the unctx instance on context objects for smart function detection
 */
declare const UNCTX_INSTANCE_SYMBOL: unique symbol;
declare function _INTERNAL_setCurrentUnctxInstance(instance: ReturnType<typeof createContext$1<any>> | null): void;
declare function _INTERNAL_getCurrentUnctxInstance(): ReturnType<typeof createContext$1<any>> | null;
/**
 * Internal Helper: Retrieves the context object from the *currently active specific*
 * `unctx` instance, if one is set (via `currentUnctxInstance`).
 *
 * This function is used by "smart" global functions (like `getContext`, `run`, `provide`)
 * to detect if they are operating within a scope established by a specific
 * `createContext().run()` or `createContext().provide()` call.
 *
 * If `currentUnctxInstance` is `null`, it means no specific Effectively context's
 * `run` or `provide` is currently active up the async call stack, so this function
 * will return `undefined`.
 *
 * If `currentUnctxInstance` is set, it attempts to retrieve the context stored
 * by that `unctx` instance for the current asynchronous execution path.
 *
 * @template C The expected type of the context. This is an assertion by the caller.
 * @returns The active specific context object of type `C` if found and compatible,
 *          otherwise `undefined`.
 */
declare function getContextOrUndefinedFromActiveInstance<C extends BaseContext>(): C | undefined;
/**
 * Default context interface that can be used without explicit context creation
 */
interface DefaultGlobalContext extends BaseContext {
}
declare global {
    var __effectively_default_context__: ContextTools<DefaultGlobalContext, DefaultGlobalContext> | undefined;
}
interface DefineTaskOptions {
    name?: string;
    idSymbol?: symbol;
}
/**
 * Defines a context-aware Task, specifying the expected Context type `C`.
 * This overload is for standard async functions.
 *
 * @param fn An async function `(value: V) => Promise<R>`.
 * @param taskNameOrOptions Optional name or configuration for the task.
 */
declare function defineTask<C extends BaseContext, V = any, R = any>(fn: (value: V) => Promise<R>, taskNameOrOptions?: string | DefineTaskOptions): Task<any, V, R>;
/**
 * Defines a context-aware Task, specifying the expected Context type `C`.
 * This overload is for async generator functions (streaming).
 *
 * @param fn An async generator function `(value: V) => AsyncGenerator<R> | AsyncIterable<R>`.
 * @param taskNameOrOptions Optional name or configuration for the task.
 */
declare function defineTask<C extends BaseContext, V = any, R = any>(fn: (value: V) => AsyncGenerator<R> | AsyncIterable<R>, taskNameOrOptions?: string | DefineTaskOptions): Task<any, V, AsyncIterable<R>>;
/**
 * Retrieves the currently active execution context.
 *
 * This "smart" version of `getContext` is the primary way for tasks to access
 * their environment. It operates with the following priority:
 *
 * 1.  **Active Specific Context:** If the current asynchronous flow is operating
 *     within a context established by `createContext<C>().run(...)` or
 *     `createContext<C>().provide(...)`, that specific, typed context is returned.
 *     This is facilitated by `currentUnctxInstance` pointing to the relevant `unctx` store.
 *
 * 2.  **Global Default Context:** If no specific context is active (e.g., when
 *     `getContext` is called at the top level of a module, or within a task
 *     run by the global smart `run` function without a prior specific context),
 *     a shared, global default context object is returned. This global default
 *     is guaranteed to at least satisfy `BaseContext` (containing a `scope`).
 *
 * The generic type parameter `C` allows the caller to assert the expected type of
 * the context.
 *   - If `getContext<UserContext>()` is called within a `run` scope for `UserContext`,
 *     `UserContext` is returned and is fully typed.
 *   - If `getContext<UserContext>()` is called at the top level (global scope),
 *     the global default context object is returned, but **cast** to `UserContext`.
 *     It is the developer's responsibility in such cases to ensure that the
 *     global default context has been appropriately configured (e.g., via
 *     `provideGlobal`) to actually satisfy the `UserContext` interface. Otherwise,
 *     accessing `UserContext`-specific properties might lead to runtime errors
 *     (e.g., `property undefined`).
 *   - If `getContext()` is called with no type argument, it defaults to returning
 *     the `DefaultGlobalContext` type.
 *
 * This function is designed to always return a context object and typically does not throw
 * `ContextNotFoundError` itself (that's more for `getContextLocal`).
 *
 * @template C The expected type of the context. Defaults to `DefaultGlobalContext`.
 * @returns The resolved context, typed as `C`.
 *
 * @example
 * ```typescript
 * import { getContext, createContext, defineTask, type BaseContext, type DefaultGlobalContext } from 'effectively';
 *
 * // 1. Global scope:
 * const globalCtx = getContext(); // Type: DefaultGlobalContext
 * console.log('Global scope signal:', globalCtx.scope.signal.aborted);
 *
 * interface AppEnvContext extends BaseContext { env: string; }
 * // Using provideGlobal to enhance the global context object
 * // await provideGlobal({ env: "production" }, async () => {
 * //   const appEnvCtx = getContext<AppEnvContext>(); // Now safely gets { scope:..., env:"production" }
 * //   console.log(appEnvCtx.env);
 * // });
 *
 * // 2. Specific context scope:
 * interface UserContext extends BaseContext { userId: string; permissions: string[]; }
 * const { run: runUserScope, defineTask: defineUserTask } =
 *   createContext<UserContext>({ userId: 'guest', permissions: [] });
 *
 * const fetchUserData = defineUserTask(async (id: string) => {
 *   const ctx = getContext<UserContext>(); // Type: UserContext. Correctly resolves to the UserContext instance.
 *   console.log(`Fetching data for user ${ctx.userId} (permissions: ${ctx.permissions.join(',')}) with id ${id}`);
 *   if (ctx.userId === 'guest' && id !== 'public') throw new Error("Guest access denied");
 *   return { data: `data_for_${id}` };
 * });
 *
 * // await runUserScope(fetchUserData, 'user123', { overrides: { userId: 'user123', permissions: ['read'] } });
 * ```
 */
declare function getContext(): DefaultGlobalContext;
declare function getContext<C extends BaseContext>(): C;
/**
 * Safely retrieves the currently active execution context as a `Result`.
 *
 * This "smart" version first attempts to resolve a specific context active in the
 * current asynchronous flow. If found, it returns `Ok(context)`.
 * If no specific context is active, it falls back to the global default context
 * and returns `Ok(globalDefaultContext)`.
 *
 * This function itself should generally not throw `ContextNotFoundError` directly,
 * as it aims to always provide a context (even if it's the global default).
 *
 * The type parameter `C` allows the caller to assert the expected shape.
 *
 * @template C The expected type of the context. Defaults to `DefaultGlobalContext`.
 * @returns A `Result<C, ContextNotFoundError>`. `Ok(context)` on success.
 *          It's designed to always return `Ok` because a global default is always available.
 *
 * @example
 * ```typescript
 * const ctxResult = getContextSafe<UserContext>();
 * if (ctxResult.isOk()) {
 *   const userCtx = ctxResult.value; // userCtx is UserContext
 *   // ...
 * }
 * ```
 */
declare function getContextSafe(): Result<DefaultGlobalContext, ContextNotFoundError>;
declare function getContextSafe<C extends BaseContext>(): Result<C, ContextNotFoundError>;
/**
 * Retrieves the currently active execution context, or the global default if no specific one is active.
 *
 * This "smart" version first attempts to resolve a specific context active in the
 * current asynchronous flow. If found, it's returned.
 * If no specific context is active, it falls back to returning the global default context.
 *
 * This function will always return a context object (either specific or global default)
 * due to the presence of `getGlobalDefaultContextObjectSingleton()`.
 * The `| undefined` in the return type for the generic version is a concession to callers
 * who might expect `getContextOrUndefined` to potentially return `undefined`, though
 * in this setup, it's less likely unless `getContextOrUndefinedFromActiveInstance` or
 * `getGlobalDefaultContextObjectSingleton` were to somehow return `undefined` (which
 * they are not designed to do).
 *
 * @template C The expected type of the context. Defaults to `DefaultGlobalContext`.
 * @returns The resolved context typed as `C` (if specific and active) or the global
 *          default context cast to `C`. It should always return a context object.
 *
 * @example
 * ```typescript
 * const userCtx = getContextOrUndefined<UserContext>();
 * // userCtx will be UserContext if active, or DefaultGlobalContext (cast to UserContext) otherwise.
 * // It will not be undefined if getGlobalDefaultContextObjectSingleton() is robust.
 * if (userCtx) { // This check is more for type narrowing if C could truly be undefined.
 *   console.log(userCtx.scope);
 * }
 * ```
 */
declare function getContextOrUndefined(): DefaultGlobalContext;
declare function getContextOrUndefined<C extends BaseContext>(): C;
/**
 * Executes a workflow (a Task or a chain of Tasks) with an initial value and options.
 *
 * This "smart" version of `run` intelligently manages context:
 * 1.  **Inheritance:** It determines the parent context (either an active specific
 *     context or the global default).
 * 2.  **Construction:** It creates a new execution context for this run by merging
 *     the parent's properties with any `overrides` provided in the options.
 * 3.  **Scope Management:** It creates a new, unique `scope` for this run, linking
 *     its cancellation to the parent's scope and any `parentSignal` in options.
 *
 * @param workflow The Task or composed workflow to execute.
 * @param initialValue The initial input value for the first task in the workflow.
 * @param options Optional `RunOptions` to control error handling, logging, context
 *                overrides, and parent cancellation signal.
 *
 * @returns A Promise resolving to the workflow's result `R`, or a `Result<R, WorkflowError>`.
 *
 * @example
 * ```typescript
 * // Example 1: Simple top-level execution
 * const myTask = defineTask(async (name: string) => `Hello, ${name}`);
 * const greeting = await run(myTask, 'World'); // -> "Hello, World"
 *
 * // Example 2: With context overrides
 * interface AppContext extends BaseContext { greeting: string; }
 * const myTaskWithContext = defineTask<AppContext, string, string>(async (name) => {
 *   const { greeting } = getContext<AppContext>();
 *   return `${greeting}, ${name}!`;
 * });
 * const result = await run(myTaskWithContext, 'Again', {
 *   overrides: { greeting: 'Hi there' }
 * }); // -> "Hi there, Again!"
 *
 * // Example 3: Handling errors with a Result type
 * const failingTask = defineTask(async () => { throw new Error('Failure'); });
 * const errorResult = await run(failingTask, null, { throw: false });
 * if (errorResult.isErr()) {
 *   console.log(errorResult.error.message); // -> "Task failed: Failure"
 * }
 * ```
 */
declare function run<V, R>(workflow: Task<any, V, R>, initialValue: V, options?: RunOptionsThrow<BaseContext>): Promise<R>;
declare function run<V, R>(workflow: Task<any, V, R>, initialValue: V, options: RunOptionsResult<BaseContext>): Promise<Result<R, WorkflowError>>;
declare function run<C extends BaseContext, V, R>(workflow: Task<C, V, R>, initialValue: V, options?: RunOptionsThrow<C>): Promise<R>;
declare function run<C extends BaseContext, V, R>(workflow: Task<C, V, R>, initialValue: V, options: RunOptionsResult<C>): Promise<Result<R, WorkflowError>>;
/**
 * Executes a given function within a new context scope that temporarily
 * includes the specified overrides.
 *
 * This "smart" version of `provide` intelligently manages context nesting:
 * 1.  **Nested Provide:** If called from within an already active Effectively context
 *     (e.g., a task calling `provide` for a sub-operation), it creates a new
 *     nested context that inherits from the parent. The `unctx` instance of the
 *     parent context is used to manage this new nested scope.
 * 2.  **Top-Level Provide:** If called outside any active Effectively context,
 *     it uses the global default context as the base and the global `unctx`
 *     instance to manage the new scope.
 *
 * The `scope` (and its `AbortSignal`) from the parent/base context is always
 * inherited by the new context created by `provide` to ensure cancellation
 * propagates correctly. Overrides cannot change the `scope`.
 *
 * @template R The result type of the function `fn`.
 * @template CtxForOverrides Used by overloads to type `overrides` more specifically
 *                           if `provide` is called in a way that implies a known context type.
 *                           Defaults to `BaseContext`.
 *
 * @param overrides An object containing properties to merge into (or override on)
 *                  the parent/base context for the duration of `fn`'s execution.
 *                  The `scope` property cannot be overridden.
 * @param fn The asynchronous function to execute within the new, modified context.
 *           Calls to `getContext()` within this function will resolve to the new context.
 * @param options ParamImplOptions
 * @returns A Promise that resolves with the result of `fn`.
 *
 * @example
 * ```typescript
 * // At top level (uses global context as base)
 * await provide({ myService: mockService }, async () => {
 *   const ctx = getContext(); // ctx will have myService and global defaults
 *   // await run(someTaskThatUsesMyService);
 * });
 *
 * // Nested within a specific context
 * const { run, defineTask, provide: specificProvide } = createContext<UserContext>(...);
 * const myTask = defineTask(async () => {
 *   await specificProvide({ temporaryFlag: true }, async () => {
 *     const innerCtx = getContext<UserContext & { temporaryFlag: boolean }>();
 *     // innerCtx has UserContext properties + temporaryFlag
 *   });
 * });
 * ```
 */
declare function provide<R>(overrides: Partial<Omit<DefaultGlobalContext, "scope"> & Record<string | symbol | number, any>>, fn: () => Promise<R>, options?: ProvideImplOptions): Promise<R>;
declare function provide<C extends BaseContext, R>(overrides: Partial<Omit<C, "scope"> & Record<string | symbol | number, any>>, // `overrides` typed against `C`
fn: () => Promise<R>, options?: ProvideImplOptions): Promise<R>;
/**
 * Creates a new context scope with temporary overrides using a Proxy.
 * This version avoids cloning the parent context object for performance benefits
 * in scenarios with frequent `provide` calls or very large context objects.
 *
 * The returned Proxy layers the `overrides` on top of the `parentContextData`.
 * Property access prioritizes `overrides`. The `scope` property is always
 * inherited from the `parentContextData` and cannot be overridden.
 * The `UNCTX_INSTANCE_SYMBOL` is also specially handled to point to the
 * `unctx` instance managing this new proxied scope.
 *
 * @template R The result type of the function `fn`.
 * @template CtxForOverrides The asserted type of the context including overrides.
 *                           The actual parent context might be `BaseContext` or `DefaultGlobalContext`.
 *
 * @param overrides An object containing properties to make available in the new scope.
 *                  The `scope` property in `overrides` will be ignored.
 * @param fn The asynchronous function to execute within the new proxied context scope.
 *
 * @returns A Promise that resolves with the result of `fn`.
 */
declare function provideWithProxy<R, CtxForOverrides extends BaseContext = BaseContext>(overrides: Partial<Omit<CtxForOverrides, "scope" | typeof UNCTX_INSTANCE_SYMBOL> & Record<string | symbol, any>>, fn: () => Promise<R>): Promise<R>;
/**
 * Defines a Task that is **strictly bound to the currently active specific context**.
 *
 * If no specific Effectively context is active when this function is called
 * (i.e., not within a `run` or `provide` scope initiated by `createContext().tools`),
 * this function will throw a `ContextNotFoundError`.
 *
 * The created Task, when executed by `runLocal` or a context-specific `run`, will
 * operate within that active context `C`. Internal `getContext<C>()` calls within
 * the task's `fn` logic will resolve to this `C`.
 *
 * @template C The specific `BaseContext` type of the *currently active* context.
 *             This is an assertion by the caller; the function checks for any active context.
 * @template V The input value type for the task's logic.
 * @template R The result type the task's logic will resolve to.
 *
 * @param fn The core asynchronous logic of the task.
 * @param taskNameOrOptions Optional name or options for the task.
 * @returns A `Task<C, V, R>`, typed to the asserted active context `C`.
 * @throws {ContextNotFoundError} If no specific context is active when `defineTaskLocal` is called.
 */
declare function defineTaskLocal<C extends BaseContext, V, R>(fn: (value: V) => Promise<R>, taskNameOrOptions?: string | DefineTaskOptions): Task<C, V, R>;
/**
 * Retrieves the **currently active specific context**, throwing an error if none is found.
 * This function *never* falls back to a global default context.
 *
 * @template C The expected type of the active specific context.
 * @returns The active specific context, typed as `C`.
 * @throws {ContextNotFoundError} If no specific context is active.
 */
declare function getContextLocal<C extends BaseContext>(): C;
/**
 * Safely retrieves the **currently active specific context** as a `Result`,
 * returning `Err(ContextNotFoundError)` if none is found.
 * This function *never* falls back to a global default context.
 *
 * @template C The expected type of the active specific context.
 * @returns `Ok(context)` if an active specific context is found, otherwise `Err(ContextNotFoundError)`.
 */
declare function getContextSafeLocal<C extends BaseContext>(): Result<C, ContextNotFoundError>;
/**
 * Retrieves the **currently active specific context**, or `undefined` if none is found.
 * This function *never* falls back to a global default context.
 *
 * @template C The expected type of the active specific context.
 * @returns The active specific context typed as `C`, or `undefined`.
 */
declare function getContextOrUndefinedLocal<C extends BaseContext>(): C | undefined;
/**
 * Executes a workflow **exclusively within the currently active specific context**.
 *
 * If no specific Effectively context is active when `runLocal` is called, it will
 * either throw a `ContextNotFoundError` (if `options.throw` is `true` or default)
 * or return an `Err(WorkflowError)` (if `options.throw` is `false`).
 * It *never* falls back to a global default context.
 *
 * The `workflow` (often created with `defineTaskLocal` or a context-specific `defineTask`)
 * must be compatible with the active context `C`.
 *
 * @template C The specific `BaseContext` type of the *currently active* context.
 * @template V The input value type for the workflow.
 * @template R The result type of the workflow.
 *
 * @param workflow The Task or workflow to execute, typed as `Task<C, V, R>`.
 * @param initialValue The initial input value for the workflow.
 * @param options Optional `RunOptions<C>` for this local run. Overrides apply to the
 *                currently active context.
 *
 * @returns A Promise resolving to `R` or `Result<R, WorkflowError>` based on `options.throw`.
 * @throws {ContextNotFoundError} If `options.throw` is not `false` and no active specific context.
 */
declare function runLocal<C extends BaseContext, V, R>(workflow: Task<C, V, R>, initialValue: V, options?: RunOptionsThrow<C>): Promise<R>;
declare function runLocal<C extends BaseContext, V, R>(workflow: Task<C, V, R>, initialValue: V, options: RunOptionsResult<C>): Promise<Result<R, WorkflowError>>;
/**
 * Executes a function within a new nested scope derived from the **currently active
 * specific context**, including the specified overrides.
 *
 * If no specific Effectively context is active when `provideLocal` is called,
 * it will throw a `ContextNotFoundError`. It *never* falls back to a global default.
 * The `scope` from the active specific context is inherited.
 *
 * @template C The specific `BaseContext` type of the *currently active* context.
 * @template R The result type of the function `fn`.
 *
 * @param overrides An object of properties to merge into (or override on) the
 *                  active specific context `C` for `fn`'s execution.
 * @param fn The asynchronous function to execute. `getContextLocal<C>()` or `getContext<C>()`
 *           within `fn` will resolve to the new nested context.
 * @param options Optional `ProvideImplOptions` (e.g., to specify 'proxy' strategy).
 *
 * @returns A Promise that resolves with the result of `fn`.
 * @throws {ContextNotFoundError} If no active specific context is found.
 */
declare function provideLocal<C extends BaseContext, R>(overrides: Partial<Omit<C, "scope" | typeof UNCTX_INSTANCE_SYMBOL> & Record<string | symbol, any>>, fn: () => Promise<R>, options?: ProvideImplOptions): Promise<R>;
/**
 * Defines a Task that is **always** bound to the global default context.
 *
 * When this task is executed (e.g., via `runGlobal` or even a specific `run`),
 * any internal calls to `getContext()` will resolve to the global default context object,
 * regardless of any other specific context that might have been active when `run` was called.
 *
 * This is useful for creating utility tasks or services that should consistently
 * operate with global settings or state, bypassing any local context overrides.
 *
 * The `fn` (task logic) should use `getContext<DefaultGlobalContext>()` or simply `getContext()`
 * to access the global context.
 *
 * @template V The input value type for the task's logic.
 * @template R The result type the task's logic will resolve to.
 *
 * @param fn The core asynchronous logic of the task.
 * @param taskNameOrOptions Optional name or options for the task.
 * @returns A `Task<DefaultGlobalContext, V, R>`, specifically typed to the global context.
 */
declare const defineTaskGlobal: <V, R>(fn: (value: V) => Promise<R>, taskNameOrOptions?: string | DefineTaskOptions) => Task<DefaultGlobalContext, V, R>;
/**
 * Retrieves the singleton global default context object.
 * This function *always* returns the global default context, ignoring any
 * active specific context.
 *
 * @returns The `DefaultGlobalContext` object.
 */
declare const getContextGlobal: () => DefaultGlobalContext;
/**
 * Executes a workflow **exclusively** within the global default context.
 * Any active specific context that might exist when `runGlobal` is called
 * will be ignored for the execution of this workflow and its tasks.
 * Internal `getContext()` calls within the workflow will resolve to the
 * global default context object.
 *
 * @template V The input value type for the workflow.
 * @template R The result type of the workflow.
 *
 * @param workflow The Task (often created with `defineTaskGlobal`) or workflow to execute.
 *                 It should be typed as `Task<DefaultGlobalContext, V, R>` or `Task<any, V, R>`.
 * @param initialValue The initial input value for the workflow.
 * @param options Optional `RunOptions<DefaultGlobalContext>` for this global run.
 *                Overrides here apply on top of the `globalDefaultContextObject`.
 *
 * @returns A Promise resolving to `R` or `Result<R, WorkflowError>` based on `options.throw`.
 */
declare function runGlobal<V, R>(workflow: Task<DefaultGlobalContext, V, R> | Task<any, V, R>, // Accepts globally or specifically (any) defined tasks
initialValue: V, options?: RunOptionsThrow<DefaultGlobalContext>): Promise<R>;
declare function runGlobal<V, R>(workflow: Task<DefaultGlobalContext, V, R> | Task<any, V, R>, initialValue: V, options: RunOptionsResult<DefaultGlobalContext>): Promise<Result<R, WorkflowError>>;
/**
 * Executes a function within a new scope that is an extension of the
 * **global default context**, including the specified overrides.
 * Any active specific context is ignored.
 *
 * The `scope` from the global default context object is inherited.
 *
 * @template R The result type of the function `fn`.
 *
 * @param overrides An object containing properties to merge into (or override on)
 *                  the global default context for `fn`'s execution.
 * @param fn The asynchronous function to execute. `getContext()` within `fn` will
 *           resolve to the new context based on global defaults + overrides.
 * @param options Optional `ProvideImplOptions` (e.g., to specify 'proxy' strategy).
 *
 * @returns A Promise that resolves with the result of `fn`.
 */
declare const provideGlobal: <R>(overrides: Partial<Omit<DefaultGlobalContext, "scope" | typeof UNCTX_INSTANCE_SYMBOL> & Record<string | symbol, any>>, fn: () => Promise<R>, options?: ProvideImplOptions) => Promise<R>;
/**
 * Validates a context object against a schema.
 * Returns a Result indicating success or failure with detailed error information.
 */
declare function validateContext<C extends BaseContext>(schema: ContextSchema<C>, context: unknown): Result<C, ContextValidationError>;
/**
 * Type-safe context merging function.
 * Combines two contexts, with properties in the second context taking precedence.
 */
declare function mergeContexts<A extends BaseContext, B extends Record<string, unknown>>(contextA: A, contextB: B): MergeContexts<A, B>;
/**
 * Creates a context transformer function that can be used to modify contexts.
 */
declare function createContextTransformer<C1 extends BaseContext, C2 extends BaseContext>(transformer: (ctx: C1) => Omit<C2, "scope">): (ctx: C1) => C2;
/**
 * Type-safe context property accessor.
 * Provides compile-time safety when accessing context properties.
 */
declare function useContextProperty<K extends keyof DefaultGlobalContext>(key: K): DefaultGlobalContext[K];
declare function useContextProperty<C extends BaseContext, K extends keyof C>(key: K): C[K];
/**
 * Requires specific properties to be present in the context.
 * Throws a descriptive error if any required property is missing.
 */
declare function requireContextProperties<C extends BaseContext = DefaultGlobalContext>(...requirements: (keyof C)[]): C;
/**
 * Creates a task that provides additional context to its child task.
 */
declare function withContextEnhancement<C extends BaseContext, Enhancement extends Record<string, unknown>, V, R>(enhancement: Enhancement, task: Task<MergeContexts<C, Enhancement>, V, R>): Task<C, V, R>;
/**
 * Token for dependency injection.
 * A unique symbol used to identify injectable services.
 */
type InjectionToken<T> = symbol & {
    __type?: T;
};
/**
 * Creates a new injection token with type information.
 */
declare function createInjectionToken<T>(description: string): InjectionToken<T>;
/**
 * Injectable service configuration.
 */
interface Injectable<T> {
    provide: InjectionToken<T>;
    useValue?: T;
    useFactory?: () => T | Promise<T>;
}
/**
 * Context provider configuration.
 */
interface ContextProvider<T> {
    provide: InjectionToken<T>;
    value: T;
}
/**
 * Injects a dependency from the current context using its token.
 * Throws an error if the dependency is not found.
 */
declare function inject<T>(token: InjectionToken<T>): T;
/**
 * Safely injects a dependency, returning undefined if not found.
 */
declare function injectOptional<T>(token: InjectionToken<T>): T | undefined;
/**
 * Creates a context provider that supplies a value for a specific token.
 */
declare function createContextProvider<T>(token: InjectionToken<T>): {
    Provider: <C extends BaseContext, V, R>(value: T, task: Task<C & Record<symbol, T>, V, R>) => Task<C, V, R>;
    useValue: () => T;
};
/**
 * Creates a scoped context that temporarily provides additional services.
 */
declare function withScope<C extends BaseContext, V, R>(providers: ContextProvider<unknown>[], task: Task<C, V, R>): Task<C, V, R>;
/**
 * Higher-order function that creates a task with pre-configured dependencies.
 */
declare function withDependencies<C extends BaseContext, Deps extends Record<string, unknown>>(dependencies: Deps): <V, R>(taskFactory: (deps: Deps) => Task<C, V, R>) => Task<C, V, R>;
/**
 * Creates a lazy-loaded dependency that is only instantiated when first accessed.
 */
declare function createLazyDependency<T>(factory: () => T | Promise<T>): () => Promise<T>;
type ProvideStrategy = "spread" | "proxy";
interface ProvideImplOptions {
    strategy?: ProvideStrategy;
}
/**
 * Creates a new, isolated "Effectively" execution environment, providing a
 * set of tools (`ContextTools`) strongly typed to a specific context shape `C`.
 *
 * Each call to `createContext` establishes a distinct context system with its
 * own internal state for asynchronous context propagation (via `unctx` and
 * typically `AsyncLocalStorage`). This ensures that tasks run using tools from
 * one `createContext` call do not interfere with tasks run by tools from another.
 *
 * The `defaultContextDataForC` parameter provides the initial, default values
 * (excluding `scope`) for this specific context type `C`. The `scope` (containing
 * an `AbortSignal`) is managed automatically by the `run` method of the returned tools.
 *
 * @template C The specific type of the context that this environment will manage.
 *             It must extend `BaseContext` (which requires a `scope` property).
 *             Example: `interface UserSessionContext extends BaseContext { userId: string; }`
 *
 * @param defaultContextDataForC An object containing the default properties and values
 *                               for your context type `C`. The `scope` property should
 *                               be omitted as it's managed internally by the `run` method.
 *                               Example: `{ userId: 'guest', tenantId: 'default' }`
 *
 ** @param asyncLocalStorage Optional. An `AsyncLocalStorage` constructor to use for
 *                          asynchronous context propagation. Defaults to the native
 *                          `node:async_hooks.AsyncLocalStorage`. Useful for testing
 *                          or providing polyfills in environments where the native
 *                          version is unavailable or needs to be mocked. If initialization
 *                          with the provided (or default) ALS fails, `unctx` will
 *                          fall back to a synchronous context propagation model for this instance.
 *
 * @returns A `ContextTools<C>` object containing:
 *   - `run`: Executes workflows within this specific context `C`.
 *   - `getContext` (and variants): Retrieves the active context `C`.
 *   - `defineTask`: Creates tasks strongly typed to expect context `C`.
 *   - `provide`: Creates nested scopes with temporary overrides within context `C`.
 *   - `inject` (and `injectOptional`): For dependency injection from context `C`.
 *
 * @example
 * ```typescript
 * import { createContext, defineTask, getContext, run, type BaseContext } from 'effectively';
 *
 * interface MyAppContext extends BaseContext {
 *   appName: string;
 *   logger: Console;
 * }
 *
 * const myAppTools = createContext<MyAppContext>({
 *   appName: 'MyAwesomeApp',
 *   logger: console,
 * });
 *
 * const GreetUserTask = myAppTools.defineTask(
 *   async (userName: string) => {
 *     const ctx = myAppTools.getContext(); // ctx is MyAppContext
 *     ctx.logger.info(`[${ctx.appName}] Preparing greeting for ${userName}`);
 *     return `Hello, ${userName} from ${ctx.appName}!`;
 *   }
 * );
 *
 * async function main() {
 *   const greeting = await myAppTools.run(GreetUserTask, "World");
 *   // myAppTools.logger.info(greeting); // Won't work directly, logger is on context
 *   console.log(greeting); // Output: Hello, World from MyAwesomeApp!
 *
 *   // Example of using provide with these specific tools
 *   await myAppTools.provide({ appName: "TempAppName" }, async () => {
 *     const tempGreeting = await myAppTools.run(GreetUserTask, "TempUser");
 *     console.log(tempGreeting); // Output: Hello, TempUser from TempAppName!
 *   });
 * }
 * main();
 * ```
 */
declare function createContext<C extends BaseContext, G extends BaseContext = DefaultGlobalContext>(defaultContextDataForC: Omit<C, "scope">, // Initial default data for this specific context type
asyncLocalStorage?: typeof AsyncLocalStorage): ContextTools<C>;
/**
 * A utility type that combines a base context with the necessary properties
 * for the effect handler system. Use this when you are manually composing
 * a custom context with the effects system.
 *
 * @template T A type that extends BaseContext.
 *
 * @example
 * ```typescript
 * import { type ContextWithEffects, createContext } from '@doeixd/effectively';
 *
 * interface MyAppContext extends BaseContext {
 *   // ... my app properties
 * }
 *
 * // Use the helper to create the final context type
 * type AppServiceContext = ContextWithEffects<MyAppContext>;
 *
 * const { run } = createContext<AppServiceContext>({ ... });
 * ```
 */
type ContextWithEffects<T extends BaseContext> = T & EffectsContext;
/**
 * A utility type that combines a base context with an effect handlers contract,
 * creating a single, unified type for use with `createContext`. This is the

 * recommended helper for manually composing a context system with a specific
 * set of effect handlers.
 *
 * It provides sane defaults, allowing you to specify only the context, only the
 * handlers, or both.
 *
 * @template TContext The custom context interface to include. Defaults to `BaseContext`.
 * @template THandlers The effect handlers contract (a type mapping effect names to functions). Defaults to an empty object `{}`.
 *
 * @example
 * ```typescript
 * import { type ContextWithHandlers, createContext, type BaseContext } from '@doeixd/effectively';
 *
 * // 1. Define your context and effects contract
 * interface AppContext extends BaseContext {
 *   site: string;
 * }
 * type AppEffects = {
 *   log: (message: string) => void;
 * };
 *
 * // 2. Create the combined type using the helper
 * type AppServiceContext = ContextWithHandlers<AppContext, AppEffects>;
 *
 * // 3. Use the new type with createContext for full type safety
 * const { run } = createContext<AppServiceContext>({ site: 'MYLIGHT' });
 *
 * // `run` is now aware of both `site` and the effects contract.
 * ```
 */
type ContextWithHandlers<TContext extends BaseContext = BaseContext, THandlers extends EffectsSchema = {}> = TContext & {
    [HANDLERS_KEY]?: THandlers;
};

/**
 * A collection of types that are commonly used types.
 *
 */
type _TupleOf<T, N extends number, R extends Array<unknown>> = R["length"] extends N ? R : _TupleOf<T, N, [T, ...R]>;
/**
 * Represents a tuple with a fixed number of elements of type `T`.
 *
 * This type constructs a tuple that has exactly `N` elements of type `T`.
 *
 * @typeParam N - The number of elements in the tuple.
 * @typeParam T - The type of elements in the tuple.
 *
 * @example
 * ```ts
 * import { TupleOf } from "effect/Types"
 *
 * // A tuple with exactly 3 numbers
 * const example1: TupleOf<3, number> = [1, 2, 3]; // valid
 * // @ts-expect-error
 * const example2: TupleOf<3, number> = [1, 2]; // invalid
 * // @ts-expect-error
 * const example3: TupleOf<3, number> = [1, 2, 3, 4]; // invalid
 * ```
 *
 * @category tuples
 * @since 3.3.0
 */
type TupleOf<N extends number, T> = N extends N ? number extends N ? Array<T> : _TupleOf<T, N, []> : never;
/**
 * Represents a tuple with at least `N` elements of type `T`.
 *
 * This type constructs a tuple that has a fixed number of elements `N` of type `T` at the start,
 * followed by any number (including zero) of additional elements of the same type `T`.
 *
 * @typeParam N - The minimum number of elements in the tuple.
 * @typeParam T - The type of elements in the tuple.
 *
 * @example
 * ```ts
 * import { TupleOfAtLeast } from "effect/Types"
 *
 * // A tuple with at least 3 numbers
 * const example1: TupleOfAtLeast<3, number> = [1, 2, 3]; // valid
 * const example2: TupleOfAtLeast<3, number> = [1, 2, 3, 4, 5]; // valid
 * // @ts-expect-error
 * const example3: TupleOfAtLeast<3, number> = [1, 2]; // invalid
 * ```
 *
 * @category tuples
 * @since 3.3.0
 */
type TupleOfAtLeast<N extends number, T> = [...TupleOf<N, T>, ...Array<T>];
/**
 * Returns the tags in a type.
 * @example
 * ```ts
 * import type { Types } from "effect"
 *
 * type Res = Types.Tags<string | { _tag: "a" } | { _tag: "b" } > // "a" | "b"
 * ```
 *
 * @category types
 * @since 2.0.0
 */
type Tags<E> = E extends {
    _tag: string;
} ? E["_tag"] : never;
/**
 * Excludes the tagged object from the type.
 * @example
 * ```ts
 * import type { Types } from "effect"
 *
 * type Res = Types.ExcludeTag<string | { _tag: "a" } | { _tag: "b" }, "a"> // string | { _tag: "b" }
 * ```
 *
 * @category types
 * @since 2.0.0
 */
type ExcludeTag<E, K extends Tags<E>> = Exclude<E, {
    _tag: K;
}>;
/**
 * Extracts the type of the given tag.
 *
 * @example
 * ```ts
 * import type { Types } from "effect"
 *
 * type Res = Types.ExtractTag<{ _tag: "a", a: number } | { _tag: "b", b: number }, "b"> // { _tag: "b", b: number }
 * ```
 *
 * @category types
 * @since 2.0.0
 */
type ExtractTag<E, K extends Tags<E>> = Extract<E, {
    _tag: K;
}>;
/**
 * A utility type that transforms a union type `T` into an intersection type.
 *
 * @since 2.0.0
 * @category types
 */
type UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (x: infer R) => any ? R : never;
/**
 * Simplifies the type signature of a type.
 *
 * @example
 * ```ts
 * import type { Types } from "effect"
 *
 * type Res = Types.Simplify<{ a: number } & { b: number }> // { a: number; b: number; }
 * ```
 *
 * @since 2.0.0
 * @category types
 */
type Simplify<A> = {
    [K in keyof A]: A[K];
} extends infer B ? B : never;
/**
 * Determines if two types are equal.
 *
 * @example
 * ```ts
 * import type { Types } from "effect"
 *
 * type Res1 = Types.Equals<{ a: number }, { a: number }> // true
 * type Res2 = Types.Equals<{ a: number }, { b: number }> // false
 * ```
 *
 * @since 2.0.0
 * @category models
 */
type Equals<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : false;
/**
 * Determines if two types are equal, allowing to specify the return types.
 *
 * @since 3.15.0
 * @category models
 */
type EqualsWith<A, B, Y, N> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? Y : N;
/**
 * Determines if a record contains any of the given keys.
 *
 * @example
 * ```ts
 * import type { Types } from "effect"
 *
 * type Res1 = Types.Has<{ a: number }, "a" | "b"> // true
 * type Res2 = Types.Has<{ c: number }, "a" | "b"> // false
 * ```
 *
 * @since 2.0.0
 * @category models
 */
type Has<A, Key extends string> = (Key extends infer K ? K extends keyof A ? true : never : never) extends never ? false : true;
/**
 * Merges two object where the keys of the left object take precedence in the case of a conflict.
 *
 * @example
 * ```ts
 * import type { Types } from "effect"
 * type MergeLeft = Types.MergeLeft<{ a: number, b: number; }, { a: string }> // { a: number; b: number; }
 * ```
 *
 * @since 2.0.0
 * @category models
 */
type MergeLeft<Source, Target> = MergeRight<Target, Source>;
/**
 * Merges two object where the keys of the right object take precedence in the case of a conflict.
 *
 * @example
 * ```ts
 * import type { Types } from "effect"
 * type MergeRight = Types.MergeRight<{ a: number, b: number; }, { a: string }> // { a: string; b: number; }
 * ```
 *
 * @since 2.0.0
 * @category models
 */
type MergeRight<Target, Source> = Simplify<Source & {
    [Key in keyof Target as Key extends keyof Source ? never : Key]: Target[Key];
}>;
/**
 * @since 2.0.0
 * @category models
 */
type MergeRecord<Source, Target> = MergeLeft<Source, Target>;
/**
 * Describes the concurrency to use when executing multiple Effect's.
 *
 * @since 2.0.0
 * @category models
 */
type Concurrency = number | "unbounded" | "inherit";
/**
 * Make all properties in `T` mutable. Supports arrays, tuples, and records as well.
 *
 * @example
 * ```ts
 * import type { Types } from "effect"
 *
 * type MutableStruct = Types.Mutable<{ readonly a: string; readonly b: number }> // { a: string; b: number; }
 *
 * type MutableArray = Types.Mutable<ReadonlyArray<string>> // string[]
 *
 * type MutableTuple = Types.Mutable<readonly [string, number]> // [string, number]
 *
 * type MutableRecord = Types.Mutable<{ readonly [_: string]: number }> // { [x: string]: number; }
 * ```
 *
 * @since 2.0.0
 * @category types
 */
type Mutable<T> = {
    -readonly [P in keyof T]: T[P];
};
/**
 * Like `Types.Mutable`, but works recursively.
 *
 * @example
 * ```ts
 * import type { Types } from "effect"
 *
 * type DeepMutableStruct = Types.DeepMutable<{
 *   readonly a: string;
 *   readonly b: readonly string[]
 * }>
 * // { a: string; b: string[] }
 * ```
 *
 * @since 3.1.0
 * @category types
 */
type DeepMutable<T> = T extends ReadonlyMap<infer K, infer V> ? Map<DeepMutable<K>, DeepMutable<V>> : T extends ReadonlySet<infer V> ? Set<DeepMutable<V>> : T extends string | number | boolean | bigint | symbol ? T : {
    -readonly [K in keyof T]: DeepMutable<T[K]>;
};
/**
 * Avoid inference on a specific parameter
 *
 * @since 2.0.0
 * @category models
 */
type NoInfer<A> = [A][A extends any ? 0 : never];
/**
 * Invariant helper.
 *
 * @since 2.0.0
 * @category models
 */
type Invariant<A> = (_: A) => A;
/**
 * @since 3.9.0
 * @category models
 */
declare namespace Invariant {
    /**
     * @since 3.9.0
     * @category models
     */
    type Type<A> = A extends Invariant<infer U> ? U : never;
}
/**
 * Covariant helper.
 *
 * @since 2.0.0
 * @category models
 */
type Covariant<A> = (_: never) => A;
/**
 * @since 3.9.0
 * @category models
 */
declare namespace Covariant {
    /**
     * @since 3.9.0
     * @category models
     */
    type Type<A> = A extends Covariant<infer U> ? U : never;
}
/**
 * Contravariant helper.
 *
 * @since 2.0.0
 * @category models
 */
type Contravariant<A> = (_: A) => void;
/**
 * @since 3.9.0
 * @category models
 */
declare namespace Contravariant {
    /**
     * @since 3.9.0
     * @category models
     */
    type Type<A> = A extends Contravariant<infer U> ? U : never;
}
/**
 * @since 2.0.0
 */
type MatchRecord<S, onTrue, onFalse> = {} extends S ? onTrue : onFalse;
/**
 * @since 2.0.0
 */
type NotFunction<T> = T extends Function ? never : T;
/**
 * @since 3.9.0
 */
type NoExcessProperties<T, U> = T & {
    readonly [K in Exclude<keyof U, keyof T>]: never;
};
/**
 * @since 3.15.0
 */
type Ctor<T = {}> = new (...args: Array<any>) => T;

/**
 * @module
 * This module provides a comprehensive suite of utility functions for creating,
 * composing, and enhancing Tasks. These tools enable powerful, declarative
 * workflows with built-in support for flow control, data transformation,
 * error handling, and resource management.
 *
 * The primary method of composition is the `createWorkflow` function, which allows for
 * creating clean, readable, and type-safe chains of operations.
 */

/**
 * Pipes a value through a sequence of functions, from left to right.
 *
 * It takes an initial value and applies each function to the result of the
 * previous one. This is a common pattern in functional programming for creating
 * a data processing pipeline.
 *
 * @param value The initial value to pass into the pipeline.
 * @param fns A sequence of functions to apply in order. Each function must
 *   take the output of the previous function as its input.
 * @returns The final result after all functions have been applied.
 *
 * @example
 * ```typescript
 * const result = pipe(
 *   "  hello world  ",
 *   (s) => s.trim(),
 *   (s) => s.toUpperCase(),
 *   (s) => s.split(' ')
 * ); // result is ["HELLO", "WORLD"]
 *
 * const initialScore = 50;
 * const newScore = pipe(
 *   initialScore,
 *   (score) => score + 10,
 *   (score) => score * 2
 * ); // newScore is 120
 * ```
 */
declare function pipe<A>(value: A): A;
declare function pipe<A, B>(value: A, f1: (a: A) => B): B;
declare function pipe<A, B, C>(value: A, f1: (a: A) => B, f2: (b: B) => C): C;
declare function pipe<A, B, C, D>(value: A, f1: (a: A) => B, f2: (b: B) => C, f3: (c: C) => D): D;
declare function pipe<A, B, C, D, E>(value: A, f1: (a: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E): E;
declare function pipe<A, B, C, D, E, F>(value: A, f1: (a: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E, f5: (e: E) => F): F;
declare function pipe<A, B, C, D, E, F, G>(value: A, f1: (a: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E, f5: (e: E) => F, f6: (f: F) => G): G;
declare function pipe<A, B, C, D, E, F, G, H>(value: A, f1: (a: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E, f5: (e: E) => F, f6: (f: F) => G, f7: (g: G) => H): H;
declare function pipe<A, B, C, D, E, F, G, H, I>(value: A, f1: (a: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E, f5: (e: E) => F, f6: (f: F) => G, f7: (g: G) => H, f8: (h: H) => I): I;
declare function pipe<A, B, C, D, E, F, G, H, I, J>(value: A, f1: (a: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E, f5: (e: E) => F, f6: (f: F) => G, f7: (g: G) => H, f8: (h: H) => I, f9: (i: I) => J): J;
/**
 * Composes a sequence of functions from left to right, creating a new function.
 *
 * It's like `pipe`, but it doesn't take an initial value. Instead, it returns a
 * new function that, when called, will run the composed logic. This is useful
 * for creating reusable, complex functions from smaller, single-purpose ones.
 * The first function can take any number of arguments; the subsequent functions
 * must be unary (take a single argument).
 *
 * @param fns A sequence of functions to compose.
 * @returns A new function that takes the input of the first function and
 *          returns the output of the last function.
 *
 * @example
 * ```typescript
 * const processString = flow(
 *   (s: string) => s.trim(),
 *   (s) => s.toUpperCase(),
 *   (s) => s.replace(" ", "_")
 * );
 *
 * const result = processString("  hello world  "); // "HELLO_WORLD"
 * ```
 */
declare function flow(): <T>(arg: T) => T;
declare function flow<A extends any[], B>(f1: (...args: A) => B): (...args: A) => B;
declare function flow<A extends any[], B, C>(f1: (...args: A) => B, f2: (b: B) => C): (...args: A) => C;
declare function flow<A extends any[], B, C, D>(f1: (...args: A) => B, f2: (b: B) => C, f3: (c: C) => D): (...args: A) => D;
declare function flow<A extends any[], B, C, D, E>(f1: (...args: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E): (...args: A) => E;
declare function flow<A extends any[], B, C, D, E, F>(f1: (...args: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E, f5: (e: E) => F): (...args: A) => F;
declare function flow<A extends any[], B, C, D, E, F, G>(f1: (...args: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E, f5: (e: E) => F, f6: (f: F) => G): (...args: A) => G;
declare function flow<A extends any[], B, C, D, E, F, G, H>(f1: (...args: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E, f5: (e: E) => F, f6: (f: F) => G, f7: (g: G) => H): (...args: A) => H;
declare function flow<A extends any[], B, C, D, E, F, G, H, I>(f1: (...args: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E, f5: (e: E) => F, f6: (f: F) => G, f7: (g: G) => H, f8: (h: H) => I): (...args: A) => I;
declare function flow<A extends any[], B, C, D, E, F, G, H, I, J>(f1: (...args: A) => B, f2: (b: B) => C, f3: (c: C) => D, f4: (d: D) => E, f5: (e: E) => F, f6: (f: F) => G, f7: (g: G) => H, f8: (h: H) => I, f9: (i: I) => J): (...args: A) => J;
/**
 * A function that can be lifted into a Task, taking only the input value.
 * It can be synchronous, asynchronous, or a generator function.
 */
type ValueTransformFn<V, R> = ((value: V) => R) | ((value: V) => Promise<R>) | ((value: V) => Generator<any, R, any>);
/**
 * A function that can be lifted into a Task, taking both context and input value.
 * It can be synchronous or asynchronous.
 */
type ContextAwareFn<C extends BaseContext, V, R> = ((context: C, value: V) => R) | ((context: C, value: V) => Promise<R>);
/**
 * Represents any function or Task that can be a step in a `createWorkflow` pipeline.
 * It will be automatically lifted into a conformant Task if it's not one already.
 */
type WorkflowStep<C extends BaseContext, V, R> = Task<C, V, R> | ValueTransformFn<V, R> | ContextAwareFn<C, V, R>;
/**
 * Chains multiple tasks together into a single, sequential workflow.
 * The output of each task is passed as the input to the next. This is the
 * primary composition utility for the library. Plain functions can be used
 * as steps and will be automatically wrapped in a `Task`.
 *
 * @param tasks A sequence of tasks and functions to execute.
 * @returns A new `Task` representing the entire pipeline.
 *
 * @example
 * ```typescript
 * const workflow = createWorkflow(
 *   fromValue('user-123'),
 *   fetchUser,
 *   map(user => user.name),
 *   (name) => `Hello, ${name}!` // A plain function can be the final step
 * );
 *
 * const greeting = await run(workflow); // "Hello, John Doe!"
 * ```
 */
declare function createWorkflow<C extends BaseContext, V, R1>(s1: WorkflowStep<C, V, R1>): Task<C, V, R1>;
declare function createWorkflow<C extends BaseContext, V, R1, R2>(s1: WorkflowStep<C, V, R1>, s2: WorkflowStep<C, R1, R2>): Task<C, V, R2>;
declare function createWorkflow<C extends BaseContext, V, R1, R2, R3>(s1: WorkflowStep<C, V, R1>, s2: WorkflowStep<C, R1, R2>, s3: WorkflowStep<C, R2, R3>): Task<C, V, R3>;
declare function createWorkflow<C extends BaseContext, V, R1, R2, R3, R4>(s1: WorkflowStep<C, V, R1>, s2: WorkflowStep<C, R1, R2>, s3: WorkflowStep<C, R2, R3>, s4: WorkflowStep<C, R3, R4>): Task<C, V, R4>;
declare function createWorkflow<C extends BaseContext, V, R1, R2, R3, R4, R5>(s1: WorkflowStep<C, V, R1>, s2: WorkflowStep<C, R1, R2>, s3: WorkflowStep<C, R2, R3>, s4: WorkflowStep<C, R3, R4>, s5: WorkflowStep<C, R4, R5>): Task<C, V, R5>;
declare function createWorkflow<C extends BaseContext, V, R1, R2, R3, R4, R5, R6>(s1: WorkflowStep<C, V, R1>, s2: WorkflowStep<C, R1, R2>, s3: WorkflowStep<C, R2, R3>, s4: WorkflowStep<C, R3, R4>, s5: WorkflowStep<C, R4, R5>, s6: WorkflowStep<C, R5, R6>): Task<C, V, R6>;
declare function createWorkflow<C extends BaseContext, V, R1, R2, R3, R4, R5, R6, R7>(s1: WorkflowStep<C, V, R1>, s2: WorkflowStep<C, R1, R2>, s3: WorkflowStep<C, R2, R3>, s4: WorkflowStep<C, R3, R4>, s5: WorkflowStep<C, R4, R5>, s6: WorkflowStep<C, R5, R6>, s7: WorkflowStep<C, R6, R7>): Task<C, V, R7>;
declare function createWorkflow<C extends BaseContext, V, R1, R2, R3, R4, R5, R6, R7, R8>(s1: WorkflowStep<C, V, R1>, s2: WorkflowStep<C, R1, R2>, s3: WorkflowStep<C, R2, R3>, s4: WorkflowStep<C, R3, R4>, s5: WorkflowStep<C, R4, R5>, s6: WorkflowStep<C, R5, R6>, s7: WorkflowStep<C, R6, R7>, s8: WorkflowStep<C, R7, R8>): Task<C, V, R8>;
declare function createWorkflow<C extends BaseContext, V, R1, R2, R3, R4, R5, R6, R7, R8, R9>(s1: WorkflowStep<C, V, R1>, s2: WorkflowStep<C, R1, R2>, s3: WorkflowStep<C, R2, R3>, s4: WorkflowStep<C, R3, R4>, s5: WorkflowStep<C, R4, R5>, s6: WorkflowStep<C, R5, R6>, s7: WorkflowStep<C, R6, R7>, s8: WorkflowStep<C, R7, R8>, s9: WorkflowStep<C, R8, R9>): Task<C, V, R9>;
declare function createWorkflow<C extends BaseContext, V, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10>(s1: WorkflowStep<C, V, R1>, s2: WorkflowStep<C, R1, R2>, s3: WorkflowStep<C, R2, R3>, s4: WorkflowStep<C, R3, R4>, s5: WorkflowStep<C, R4, R5>, s6: WorkflowStep<C, R5, R6>, s7: WorkflowStep<C, R6, R7>, s8: WorkflowStep<C, R7, R8>, s9: WorkflowStep<C, R8, R9>, s10: WorkflowStep<C, R9, R10>): Task<C, V, R10>;
declare function createWorkflow<C extends BaseContext, V, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11>(s1: WorkflowStep<C, V, R1>, s2: WorkflowStep<C, R1, R2>, s3: WorkflowStep<C, R2, R3>, s4: WorkflowStep<C, R3, R4>, s5: WorkflowStep<C, R4, R5>, s6: WorkflowStep<C, R5, R6>, s7: WorkflowStep<C, R6, R7>, s8: WorkflowStep<C, R7, R8>, s9: WorkflowStep<C, R8, R9>, s10: WorkflowStep<C, R9, R10>, s11: WorkflowStep<C, R10, R11>): Task<C, V, R11>;
declare function createWorkflow<C extends BaseContext, V, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12>(s1: WorkflowStep<C, V, R1>, s2: WorkflowStep<C, R1, R2>, s3: WorkflowStep<C, R2, R3>, s4: WorkflowStep<C, R3, R4>, s5: WorkflowStep<C, R4, R5>, s6: WorkflowStep<C, R5, R6>, s7: WorkflowStep<C, R6, R7>, s8: WorkflowStep<C, R7, R8>, s9: WorkflowStep<C, R8, R9>, s10: WorkflowStep<C, R9, R10>, s11: WorkflowStep<C, R10, R11>, s12: WorkflowStep<C, R11, R12>): Task<C, V, R12>;
/**
 * An alias for {@link createWorkflow}.
 *
 * Chains multiple tasks together into a single, sequential workflow.
 * The output of each task is passed as the input to the next. This is the
 * primary composition utility for the library. Plain functions can be used
 * as steps and will be automatically wrapped in a `Task`.
 *
 * @param tasks A sequence of tasks and functions to execute.
 * @returns A new `Task` representing the entire pipeline.
 *
 * @example
 * ```typescript
 * const processUser = chain(
 *   fromValue('user-123'),
 *   fetchUser,
 *   map(user => user.name),
 *   (name) => `Hello, ${name}!`
 * );
 *
 * const greeting = await run(processUser); // "Hello, John Doe!"
 * ```
 * @see {@link createWorkflow}
 */
declare const chain: typeof createWorkflow;
/**
 * Starts a workflow with a static, known value.
 * @param value The static value to begin the workflow with.
 * @example
 * ```typescript
 * const workflow = createWorkflow(
 *   fromValue({ id: 'user-123' }),
 *   map(data => data.id),
 * );
 * const userId = await run(workflow); // "user-123"
 * ```
 */
declare function fromValue<T>(value: T): Task<BaseContext, null, T>;
/**
 * Starts a workflow by awaiting a `Promise`.
 * @param promise The promise to await.
 * @example
 * ```typescript
 * const userIdPromise = Promise.resolve('user-123');
 * const workflow = createWorkflow(fromPromise(userIdPromise), fetchUser);
 * const user = await run(workflow);
 * ```
 */
declare function fromPromise<T>(promise: Promise<T>): Task<BaseContext, null, T>;
/**
 * Starts a workflow by executing an async function that can access the context.
 * @param fn An async function that receives the context and returns a promise.
 * @example
 * ```typescript
 * const workflow = createWorkflow(
 *   fromPromiseFn(ctx => ctx.auth.getUserId()),
 *   fetchUser
 * );
 * const user = await run(workflow);
 * ```
 */
declare function fromPromiseFn<C extends BaseContext, T>(fn: (context: C) => Promise<T>): Task<C, null, T>;
/**
 * **Pipeable Operator:** Transforms the value in a workflow using a mapping function.
 * @param f A synchronous or async function that transforms the value.
 * @example
 * ```typescript
 * const workflow = createWorkflow(
 *   fetchUser, // returns a User object
 *   map(user => user.name) // returns a string
 * );
 * const name = await run(workflow, 'user-123');
 * ```
 */
declare function map<C extends BaseContext, V, R>(f: (value: V, context: C) => R | Promise<R>): Task<C, V, R>;
/**
 * **Pipeable Operator:** Transforms the value in a workflow into a new `Task` by applying function `f`.
 * The function `f` receives the current value and context, and must return a new `Task`.
 * This new `Task` is then executed with the same context and the current value.
 * Also known as `bind` or `chain` in monadic terms.
 *
 * @template C The context type.
 * @template V The input value type for this step of the workflow.
 * @template RNext The result type of the `Task` returned by `f`.
 * @param f A function that takes the current value (`V`) and context (`C`), and returns a new `Task<C, V, RNext>`.
 * @returns A `Task<C, V, RNext>` that represents the execution of the task returned by `f`.
 *
 * @example
 * ```typescript
 * const fetchUserAndThenPosts = createWorkflow(
 *   fetchUser, // Task<C, string, User>
 *   flatMap((user: User, context: C) => fetchPostsForUser(context, user.id)) // user.id is string, fetchPostsForUser returns Task<C, string, Post[]>
 * );
 * // The type of fetchPostsForUser would effectively be Task<C, string, Post[]>
 * // flatMap needs Task<C, User, Post[]> if the task from f uses 'user' as input.
 * // If f uses user.id as input for fetchPostsForUser, the V for fetchPostsForUser is string.
 * // The V for the *returned task from f* should match the input type it expects.
 *
 * // Corrected example logic:
 * const fetchPostsTaskForUser = (user: User): Task<AppContext, User, Post[]> =>
 *   defineTask(async (context: AppContext, u: User) => { // u here is 'user'
 *     return api.fetchPosts(u.id);
 *   });
 *
 * const workflow = createWorkflow(
 *   fetchUserById, // Task<AppContext, string, User>
 *   flatMap((user: User, ctx: AppContext) => fetchPostsTaskForUser(user)) // fetchPostsTaskForUser(user) is Task<AppContext, User, Post[]>
 * );
 * // The resulting workflow takes string (userId) and returns Post[]
 * ```
 */
declare function flatMap<C extends BaseContext, V, RNext>(f: (value: V, context: C) => Task<C, V, RNext>): Task<C, V, RNext>;
/**
 * **Direct Composition:** Transforms the successful output of a task using a mapping function.
 * @param task The task whose output will be mapped.
 * @param f A synchronous or async function to transform the task's result.
 * @example
 * ```typescript
 * const fetchUserName = mapTask(fetchUser, user => user.name);
 * const name = await run(fetchUserName, 'user-123');
 * ```
 */
declare function mapTask<C extends BaseContext, V, A, B>(task: Task<C, V, A>, f: (value: A) => B | Promise<B>): Task<C, V, B>;
/**
 * **Direct Composition:** Executes a task, then uses its result to produce and execute a second task.
 * The function `f` receives the result of the first `task` and must return a new `Task`.
 * This new `Task` is then executed. The context is passed through.
 *
 * @template C The context type.
 * @template In The input type of the initial `task`.
 * @template A The result type of the initial `task` (and input type to `f`).
 * @template RNext The result type of the `Task` returned by `f`.
 * @param task The initial `Task<C, In, A>` to execute.
 * @param f A function that takes the result `A` of the first task and returns a new `Task<C, A, RNext>`.
 *          The returned task will be called with the context and `A` as its input.
 * @returns A new `Task<C, In, RNext>` representing the sequential composition.
 *
 * @example
 * ```typescript
 * const fetchUserById: Task<Ctx, string, User> = defineTask(async (ctx, id) => api.getUser(id));
 * const fetchPostsForUserTask = (user: User): Task<Ctx, User, Post[]> =>
 *   defineTask(async (ctx, u) => api.getPosts(u.id));
 *
 * const fetchUserAndTheirPosts = andThenTask(
 *   fetchUserById,
 *   (user: User) => fetchPostsForUserTask(user) // This returns Task<Ctx, User, Post[]>
 * );
 * // `fetchUserAndTheirPosts` is Task<Ctx, string, Post[]>
 * // When run: fetchUserById('123') -> User -> fetchPostsForUserTask(User)(User) -> Post[]
 * ```
 */
declare function andThenTask<C extends BaseContext, In, A, RNext>(task: Task<C, In, A>, f: (value: A) => Task<C, A, RNext>): Task<C, In, RNext>;
/**
 * **Pipeable Operator:** Creates a new object from the input object, containing only the specified keys.
 * @param keys The keys to pick from the object.
 * @example
 * ```typescript
 * const workflow = createWorkflow(
 *   fetchUser,
 *   pick('id', 'name')
 * );
 * const partialUser = await run(workflow, 'user-123'); // { id: '...', name: '...' }
 * ```
 */
declare function pick<T extends object, K extends keyof T>(...keys: K[]): Task<BaseContext, T, Pick<T, K>>;
/**
 * A higher-order task that conditionally executes another task if a predicate is `true`.
 * @param predicate A function that returns `true` to execute the task.
 * @param task The `Task` to execute conditionally. It must accept and return the same type.
 * @example
 * ```typescript
 * const sendEmailTask = defineTask(user => email.sendWelcome(user));
 * const workflow = createWorkflow(
 *   createUser,
 *   when(user => user.isVerified, sendEmailTask)
 * );
 * ```
 */
declare function when<C extends BaseContext, V>(predicate: (value: V, context: C) => boolean | Promise<boolean>, task: Task<C, V, V>): Task<C, V, V>;
/**
 * A higher-order task that conditionally executes another task if a predicate is `false`.
 * @param predicate A function that returns `false` to execute the task.
 * @param task The `Task` to execute conditionally.
 * @example
 * ```typescript
 * const showUpgradePrompt = defineTask(user => ui.showUpgrade(user));
 * const workflow = createWorkflow(
 *   fetchUser,
 *   unless(user => user.hasProPlan, showUpgradePrompt)
 * );
 * ```
 */
declare function unless<C extends BaseContext, V>(predicate: (value: V, context: C) => boolean | Promise<boolean>, task: Task<C, V, V>): Task<C, V, V>;
/**
 * A higher-order task that executes another task repeatedly as long as a predicate returns `true`.
 * @param task The `Task` to execute in a loop.
 * @param predicate The condition to continue the loop.
 * @example
 * ```typescript
 * const fetchPage = defineTask(token => api.getData({ pageToken: token }));
 * const workflow = doWhile(fetchPage, page => page.hasNextPage);
 * await run(workflow, 'initial_token');
 * ```
 */
declare function doWhile<C extends BaseContext, V>(task: Task<C, V, V>, predicate: (value: V, context: C) => boolean | Promise<boolean>): Task<C, V, V>;
/**
 * **Pipeable Operator:** Performs a side effect (e.g., logging) but passes the input value through unchanged.
 * @param f A function to execute as a side effect.
 * @example
 * ```typescript
 * const workflow = createWorkflow(
 *   fetchUser,
 *   tap(user => console.log(`Processing user: ${user.id}`)),
 *   processUser
 * );
 * ```
 */
declare function tap<C extends BaseContext, V>(f: (value: V, context: C) => void | Promise<void>): Task<C, V, V>;
/**
 * A `Task` that pauses the workflow for a specified duration.
 * @param ms The number of milliseconds to sleep.
 * @example
 * ```typescript
 * const workflow = createWorkflow(
 *   startOperation,
 *   sleep(2000), // wait 2 seconds
 *   finishOperation
 * );
 * ```
 */
declare function sleep(ms: number): Task<BaseContext, any, void>;
/**
 * A higher-order task that performs a side effect if the wrapped `task` throws an error.
 * The original error is always re-thrown after the side effect function `onErrorFn` completes.
 * This utility is useful for logging, metrics, or other observational side effects.
 *
 * `BacktrackSignal`s are ignored by `onErrorFn` and re-thrown immediately.
 *
 * @template C The context type for the task and the error handler.
 * @template V The input value type of the task.
 * @template R The result type of the task if successful.
 * @template E The expected type of the error. If `errorConstructor` is provided,
 *             `onErrorFn` will only be called for errors matching that constructor,
 *             and the `error` parameter will be correctly typed as an instance of `E`.
 * @param task The `Task<C, V, R>` to wrap.
 * @param onErrorFn A function that will be called if `task` throws a matching error.
 *                  It receives the typed error instance and the current context.
 * @param errorConstructor (Optional) The specific error class to catch. If provided,
 *                         the handler will only run for instances of this error.
 * @returns A new `Task<C, V, R>` that incorporates the error tapping behavior.
 *
 * @example
 * ```typescript
 * const resilientTask = tapError(
 *   flakyTask,
 *   (error, context) => { // `error` is a NetworkError instance here
 *     context.logger.error('Network failure occurred', { cause: error });
 *   },
 *   NetworkError // Only tap into NetworkError instances
 * );
 * ```
 */
declare function tapError<C extends BaseContext, V, R, E extends Error = Error>(task: Task<C, V, R>, onErrorFn: (error: E, context: C) => void | Promise<void>, errorConstructor?: new (...args: any[]) => E): Task<C, V, R>;
/**
 * Wraps a `Task` that might throw an error, converting its outcome into a
 * `Result<R, E>` object from `neverthrow`.
 *
 * If the original `task` successfully resolves, this function returns `Ok<R>`.
 * If the original `task` throws an error (and it's not a `BacktrackSignal`),
 * this function catches it and returns `Err<E>`.
 * `BacktrackSignal`s are re-thrown to allow non-linear control flow.
 *
 * @template C The context type for the task.
 * @template V The input value type of the task.
 * @template R The success result type of the task.
 * @template E The expected error type if the task fails (must extend `Error`). Defaults to `Error`.
 * @param task The `Task<C, V, R>` to wrap.
 * @param mapErrorToE An optional function to map a caught `unknown` error value
 *                    to the desired error type `E`. If not provided, a default
 *                    mapper is used which attempts to cast `Error` instances or
 *                    wraps non-`Error` values in a new `Error`.
 * @returns A new `Task<C, V, Result<R, E>>` that always resolves (never throws,
 *          except for `BacktrackSignal`).
 *
 * @example
 * ```typescript
 * const fetchUserTask = defineTask(async (ctx, userId: string) => {
 *   if (userId === 'bad-id') throw new Error('Invalid user ID');
 *   return { id: userId, name: 'John Doe' };
 * });
 *
 * const safeFetchUser = attempt(fetchUserTask);
 *
 * const workflow = createWorkflow(
 *   fromValue('user-123'), // or 'bad-id'
 *   safeFetchUser,
 *   map(result =>
 *     result.match(
 *       user => `User: ${user.name}`,
 *       error => `Failed to fetch user: ${error.message}`
 *     )
 *   )
 * );
 *
 * const outcome = await run(workflow);
 * console.log(outcome);
 * ```
 */
declare function attempt<C extends BaseContext, V, R, E extends Error = Error>(task: Task<C, V, R>, mapErrorToE?: (caughtError: unknown) => E): Task<C, V, Result<R, E>>;
interface RetryOptions<E = Error> {
    /**
     * Maximum number of attempts (including the initial call).
     * @default 3
     */
    attempts?: number;
    /**
     * Initial delay in milliseconds before the first retry.
     * @default 100
     */
    delayMs?: number;
    /**
     * Backoff strategy for delays between retries.
     * - 'fixed': Uses `delayMs` for all retries.
     * - 'exponential': Doubles the delay for each subsequent retry (`delayMs * 2^i`).
     * @default 'exponential'
     */
    backoff?: "fixed" | "exponential";
    /**
     * A function to determine if a specific error should trigger a retry.
     * By default, retries on any error that is not a `BacktrackSignal`.
     * @param error The error thrown by the task.
     * @returns `true` if the task should be retried for this error, `false` otherwise.
     */
    shouldRetry?: (error: E | unknown) => boolean;
    /**
     * An optional jitter function to apply to the delay.
     * 'none': No jitter.
     * 'full': Adds a random amount between 0 and the calculated delay.
     * (value: number) => number: A custom function that takes the calculated delay and returns the jittered delay.
     * @default 'none'
     */
    jitter?: "none" | "full" | ((delay: number) => number);
}
/**
 * Wraps a task with automatic, cancellable retry logic.
 * If the wrapped task fails, it will be retried according to the specified options.
 * The delay between retries can be fixed or exponential and can include jitter.
 * Retries are aborted if the context's scope signal is aborted.
 *
 * @template C The context type, which must include `scope` and can optionally include `logger`.
 * @template V The input value type of the task.
 * @template R The result type of the task.
 * @template E The expected primary error type for the `shouldRetry` predicate.
 * @param task The `Task` to make resilient.
 * @param options Configuration for the retry behavior.
 * @returns A new `Task` that incorporates retry logic.
 *
 * @example
 * ```typescript
 * const resilientFetch = withRetry(fetchData, {
 *   attempts: 5,
 *   delayMs: 200,
 *   backoff: 'exponential',
 *   jitter: 'full',
 *   shouldRetry: (error) => error instanceof NetworkError || error.status === 503,
 * });
 * await run(resilientFetch, requestData);
 * ```
 */
declare function withRetry<C extends BaseContext & {
    logger?: Logger;
}, V, R, E extends Error = Error>(task: Task<C, V, R>, options?: RetryOptions<E>): Task<C, V, R>;
/**
 * Attaches a descriptive name to a task for better logging and debugging.
 * @param task The task to name.
 * @param name The new name for the task.
 * @example
 * ```typescript
 * const fetchTask = defineTask(api.get);
 * const namedFetch = withName(fetchTask, 'GetFromPrimaryAPI');
 * ```
 */
declare function withName<C extends BaseContext, V, R>(task: Task<C, V, R>, name: string): Task<C, V, R>;
/**
 * Creates a memoized version of a `Task` that caches its result based on
 * the input value. The input value is used as a key in an internal Map.
 * For object inputs, a deep equality check is performed to find matching keys.
 * The cache is specific to each instance of the memoized task created by this function.
 *
 * @template C The context type.
 * @template V The input value type for the task. Must be usable as a Map key or comparable with `deepEqual`.
 * @template R The resolved output value type of the task.
 * @param task The `Task` to memoize.
 * @param options Optional configuration for memoization.
 * @param options.cacheKeyFn An optional function to generate a custom cache key from the input value.
 *                         Useful for complex objects or when `deepEqual` is not suitable/performant.
 * @returns A new `Task` that caches results of the original task.
 *
 * @example
 * ```typescript
 * const memoizedFetchConfig = memoize(fetchConfig);
 * await run(memoizedFetchConfig, 'config-a'); // Fetches from network
 * await run(memoizedFetchConfig, 'config-a'); // Returns from cache
 *
 * const memoizedComplexOp = memoize(complexObjectOperation, {
 *   cacheKeyFn: (obj) => obj.id // Use only 'id' property for caching
 * });
 * ```
 */
declare function memoize<C extends BaseContext, V, R>(task: Task<C, V, R>, options?: {
    cacheKeyFn?: (value: V) => string | number | symbol | boolean;
}): Task<C, V, R>;
/**
 * Creates a `Task` that is guaranteed to execute only once. All subsequent
 * calls receive the same cached result. Ideal for initializing singletons.
 * @param task The `Task` to execute once.
 * @example
 * ```typescript
 * const initDb = once(defineTask(() => db.connect()));
 * await run(initDb); // Connects to DB
 * await run(initDb); // Returns existing connection promise
 * ```
 */
declare function once<C extends BaseContext, V, R>(task: Task<C, V, R>): Task<C, V, R>;
/**
 * Custom error thrown when a task wrapped by `withTimeout` exceeds its allocated execution time.
 */
declare class TimeoutError extends Error {
    readonly _tag: "TimeoutError";
    constructor(taskName: string, durationMs: number);
}
/**
 * Wraps a task with a timeout. If the task does not complete within the specified
 * duration, it will be rejected with a `TimeoutError`.
 * The timeout mechanism respects the task's context `AbortSignal`: if the signal
 * is aborted, the timeout timer is cleared.
 *
 * @template C The context type, which must include `scope`.
 * @template V The input value type of the task.
 * @template R The result type of the task.
 * @param task The `Task` to apply the timeout to.
 * @param durationMs The timeout duration in milliseconds. Must be non-negative.
 * @returns A new `Task` that will either resolve with the original task's result
 *          or reject with a `TimeoutError` or an error from the original task
 *          (including an AbortError if the context is cancelled).
 *
 * @example
 * ```typescript
 * const verySlowTask = defineTask(async () => {
 *   await new Promise(resolve => setTimeout(resolve, 5000)); // 5s delay
 *   return 'done';
 * });
 *
 * const quickTask = withTimeout(verySlowTask, 1000); // 1s timeout
 *
 * try {
 *   await run(quickTask, null);
 * } catch (error) {
 *   if (error instanceof TimeoutError) {
 *     console.error('Operation timed out!'); // This will be caught
 *   } else {
 *     console.error('Other error:', error);
 *   }
 * }
 * ```
 */
declare function withTimeout<C extends BaseContext, V, R>(task: Task<C, V, R>, durationMs: number): Task<C, V, R>;
/**
 * A unique symbol used to store StateTools in the context.
 * @internal
 */
declare const STATE_TOOLS_KEY: unique symbol;
/**
 * Tools for interacting with the state managed by `withState`.
 * These are injected into the context for the wrapped task.
 * @template S The type of the state.
 */
interface StateTools<S> {
    /**
     * Retrieves the current value of the encapsulated state.
     * @returns The current state `S`.
     */
    getState: () => S;
    /**
     * Updates the encapsulated state.
     * @param updater Either a new state value `S` or a function that takes the
     *                previous state `(prevState: S)` and returns the new state `S`.
     */
    setState: (updater: S | ((prevState: S) => S)) => void;
}
/**
 * A "hook" to access the state management tools (`getState` and `setState`)
 * from within a task that has been wrapped by `withState`.
 *
 * It retrieves the tools from the current context.
 *
 * @template S The type of the state.
 * @param context The context object, retrieved via `getContext()`.
 * @returns The `StateTools` for interacting with the state.
 * @throws {Error} If called outside of a `withState`-enhanced task's execution scope.
 */
declare function useState<S>(context: BaseContext): StateTools<S>;
/**
 * An enhancer that wraps a task to provide it with a private, encapsulated state.
 * The state is initialized when the task begins and is discarded when it ends.
 *
 * This new implementation is a proper enhancer, making it more composable and
 * improving type inference significantly. The wrapped task can access `getState`
 * and `setState` tools via the `useState(getContext())` hook.
 *
 * @template C The context type of the inner task.
 * @template V The input value type for the task.
 * @template R The result type of the inner task.
 * @template S The type of the encapsulated state.
 *
 * @param initialState A value or a function `(initialValue: V) => S` to create the initial state.
 * @param task The `Task` that will be executed with access to the state tools via context.
 * @returns A new `Task<C, V, { result: R; state: S }>` that returns both the task's
 *          result and the final state.
 *
 * @example
 * ```typescript
 * const innerWorkflow = createWorkflow(
 *   tap((_, ctx) => useState<MyState>(ctx).setState(s => ({ ...s, count: s.count + 1 }))),
 *   map((_, ctx) => useState<MyState>(ctx).getState().count)
 * );
 *
 * const statefulWorkflow = withState(
 *   () => ({ count: 0 }),
 *   innerWorkflow
 * );
 *
 * const final = await run(statefulWorkflow, 'initial-input');
 * // final.result is 1
 * // final.state is { count: 1 }
 * ```
 */
declare function withState<C extends BaseContext, V, R, S>(initialState: S | ((initialValue: V) => S), task: Task<C & {
    [STATE_TOOLS_KEY]: StateTools<S>;
}, V, R>): Task<C, V, {
    result: R;
    state: S;
}>;
interface ThrottleOptions {
    /** Maximum number of calls allowed within the interval. */
    limit: number;
    /** The time interval in milliseconds. */
    intervalMs: number;
}
/**
 * Creates a throttled version of a task that respects a rate limit.
 * Calls exceeding the limit are queued. Queued calls respect cancellation.
 * The throttling is based on a token bucket-like approach where tokens are refilled periodically.
 *
 * @template C The context type, which must include `scope`.
 * @template V The input value type of the task.
 * @template R The result type of the task.
 * @param task The `Task` to throttle.
 * @param options The throttling configuration.
 * @returns A new `Task` that enforces the specified rate limit.
 *
 * @example
 * ```typescript
 * const throttledApiCall = withThrottle(apiCall, { limit: 5, intervalMs: 1000 });
 * // This task can now be called rapidly, but will only execute 5 times per second.
 * // Excess calls are queued and processed as capacity becomes available.
 * ```
 */
declare function withThrottle<C extends BaseContext, V, R>(task: Task<C, V, R>, options: ThrottleOptions): Task<C, V, R>;
/**
 * Configuration options for the `withPoll` utility.
 * @template R The type of the result produced by the task being polled.
 */
interface PollOptions<R> {
    /**
     * The interval in milliseconds between polling attempts.
     * Must be non-negative.
     */
    intervalMs: number;
    /**
     * The total duration in milliseconds after which the polling will time out
     * if the `until` condition is not met. Must be non-negative.
     */
    timeoutMs: number;
    /**
     * A predicate function that is called with the result of each polling attempt.
     * Polling stops when this function returns `true`.
     * @param result The result from the polled task.
     * @returns `true` to stop polling, `false` to continue.
     */
    until: (result: R) => boolean | Promise<boolean>;
    /**
     * An optional name for the polling operation, used in the PollTimeoutError message.
     * If not provided, the name of the wrapped task will be used.
     */
    pollName?: string;
}
/**
 * Custom error thrown by `withPoll` when the `timeoutMs` is reached before
 * the `until` condition returns true.
 */
declare class PollTimeoutError extends TimeoutError {
    constructor(operationName: string, timeoutMs: number);
}
/**
 * Creates a task that repeatedly executes another `taskToPoll` at a specified
 * `intervalMs` until an `until` condition (a predicate function) returns `true`
 * or an overall `timeoutMs` is reached.
 *
 * The polling mechanism is cancellable via the context's `AbortSignal`.
 * If the `timeoutMs` is reached before the `until` condition is met, a `PollTimeoutError` is thrown.
 *
 * @template C The context type, which must include `scope`.
 * @template V The input value type of the task being polled.
 * @template R The result type of the task being polled (and of this polling task).
 * @param taskToPoll The `Task<C, V, R>` to execute repeatedly.
 * @param options Configuration for the polling behavior (`intervalMs`, `timeoutMs`, `until` predicate).
 * @returns A new `Task<C, V, R>` that implements the polling logic.
 *
 * @example
 * ```typescript
 * const checkJobStatusTask = defineTask(async (ctx, jobId: string) => api.getJob(jobId));
 *
 * const waitForJobCompletion = withPoll(checkJobStatusTask, {
 *   intervalMs: 5000,  // Check every 5 seconds
 *   timeoutMs: 300000, // Timeout after 5 minutes
 *   until: (jobStatus) => jobStatus.isComplete || jobStatus.hasFailed,
 *   pollName: 'JobStatusCheck'
 * });
 *
 * try {
 *   const finalJobStatus = await run(waitForJobCompletion, 'job-123');
 *   // ... process finalJobStatus
 * } catch (error) {
 *   if (error instanceof PollTimeoutError) {
 *     console.error('Job status polling timed out:', error.message);
 *   } else {
 *     // Handle errors from checkJobStatusTask itself if they are not caught internally
 *     console.error('Error during job status check:', error);
 *   }
 * }
 * ```
 */
declare function withPoll<C extends BaseContext, V, R>(taskToPoll: Task<C, V, R>, options: PollOptions<R>): Task<C, V, R>;
interface BatchingOptions {
    /**
     * The time window in milliseconds to wait for collecting keys before dispatching the batch.
     * @default 10
     */
    windowMs?: number;
    /**
     * The maximum number of keys to include in a single batch. If this limit is reached
     * before `windowMs` elapses, the batch will be dispatched immediately.
     * @default Infinity (no limit other than windowMs)
     */
    maxBatchSize?: number;
}
/**
 * Creates a task that batches multiple calls for individual keys into a single
 * underlying call to `batchFn`. This is extremely useful for reducing the number
 * of requests to a backend, database, or other I/O-bound service (similar to DataLoader).
 *
 * Calls are collected during a `windowMs` time window or until `maxBatchSize` is reached.
 * Individual calls in the queue respect their context's `AbortSignal`.
 * The `batchFn` itself can be made cancellable by observing the aggregated signal passed to it.
 *
 * @template C The context type. Must include `scope`.
 * @template K The type of the key for each item (e.g., an ID).
 * @template R The type of the result for each key.
 * @param batchFn An asynchronous function that accepts an array of keys (`K[]`),
 *                the parent context (`C`), and an `AbortSignal` for the batch execution.
 *                It must return a `Promise` of an array of results (`R[]`) in the
 *                *same order* as the input keys.
 * @param options Optional configuration for the batching behavior, including `windowMs`
 *                and `maxBatchSize`.
 * @returns A `Task<C, K, R>` that, when called, queues its key and resolves with the
 *          corresponding result from the batched call.
 *
 * @example
 * ```typescript
 * const fetchUsersByIdsBatched = createBatchingTask<AppContext, string, User>(
 *   async (ids, context, batchSignal) => {
 *     // In a real scenario, use batchSignal if your API client supports it
 *     console.log(`[BatchFn] Fetching users for IDs: ${ids.join(', ')} with context`, context.someService);
 *     return UserAPI.getByIds(ids, { signal: batchSignal }); // Assuming API supports signal
 *   },
 *   { windowMs: 20, maxBatchSize: 10 }
 * );
 *
 * // In a workflow:
 * const user1Promise = run(fetchUsersByIdsBatched, 'user-1');
 * const user2Promise = run(fetchUsersByIdsBatched, 'user-2');
 * const [user1, user2] = await Promise.all([user1Promise, user2Promise]);
 * // This would likely result in one call to UserAPI.getByIds(['user-1', 'user-2'])
 * ```
 */
declare function createBatchingTask<C extends BaseContext, K, R>(batchFn: (keys: K[], context: C, batchSignal: AbortSignal) => Promise<R[]>, options?: BatchingOptions): Task<C, K, R>;
interface DebounceOptions {
    /**
     * If true, the AbortSignal from the latest call's context will be linked
     * to the debounced execution. If the latest call's context is aborted
     * before the debounced function executes, the execution can be cancelled.
     * Note: This means only the *latest* call's signal is respected for cancellation
     * of the pending execution.
     * @default true
     */
    linkToLatestSignal?: boolean;
}
/**
 * Creates a debounced version of a task. The task will only be executed
 * after a specified period of inactivity (`durationMs`) following the last call.
 * All calls made during the debounce window (i.e., before the task executes)
 * will receive the same promise, which resolves or rejects with the result of
 * the single eventual execution.
 *
 * This implements a "trailing edge" debounce.
 *
 * @template C The context type, which must include `scope`.
 * @template V The input value type of the task.
 * @template R The result type of the task.
 * @param task The `Task` to debounce.
 * @param durationMs The debounce duration in milliseconds. Must be non-negative.
 * @param options Optional configuration for the debounce behavior.
 * @returns A new, debounced `Task`.
 *
 * @example
 * ```typescript
 * const debouncedSearch = withDebounce(searchApi, 300);
 * // Can be called rapidly; API call only happens 300ms after the last invocation.
 * run(debouncedSearch, 'query1');
 * run(debouncedSearch, 'query2'); // 'query1' call is superseded, 'query2' will be used.
 * ```
 */
declare function withDebounce<C extends BaseContext, V, R>(task: Task<C, V, R>, durationMs: number, options?: DebounceOptions): Task<C, V, R>;

/**
 * @since 2.0.0
 * @category Models
 */
interface Pipeable {
    pipe<A>(this: A): A;
    pipe<A, B = never>(this: A, ab: (_: A) => B): B;
    pipe<A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C;
    pipe<A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D;
    pipe<A, B = never, C = never, D = never, E = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E): E;
    pipe<A, B = never, C = never, D = never, E = never, F = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F): F;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G): G;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H): H;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I): I;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J): J;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K): K;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never, L = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K, kl: (_: K) => L): L;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never, L = never, M = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K, kl: (_: K) => L, lm: (_: L) => M): M;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never, L = never, M = never, N = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K, kl: (_: K) => L, lm: (_: L) => M, mn: (_: M) => N): N;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never, L = never, M = never, N = never, O = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K, kl: (_: K) => L, lm: (_: L) => M, mn: (_: M) => N, no: (_: N) => O): O;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never, L = never, M = never, N = never, O = never, P = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K, kl: (_: K) => L, lm: (_: L) => M, mn: (_: M) => N, no: (_: N) => O, op: (_: O) => P): P;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never, L = never, M = never, N = never, O = never, P = never, Q = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K, kl: (_: K) => L, lm: (_: L) => M, mn: (_: M) => N, no: (_: N) => O, op: (_: O) => P, pq: (_: P) => Q): Q;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never, L = never, M = never, N = never, O = never, P = never, Q = never, R = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K, kl: (_: K) => L, lm: (_: L) => M, mn: (_: M) => N, no: (_: N) => O, op: (_: O) => P, pq: (_: P) => Q, qr: (_: Q) => R): R;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never, L = never, M = never, N = never, O = never, P = never, Q = never, R = never, S = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K, kl: (_: K) => L, lm: (_: L) => M, mn: (_: M) => N, no: (_: N) => O, op: (_: O) => P, pq: (_: P) => Q, qr: (_: Q) => R, rs: (_: R) => S): S;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never, L = never, M = never, N = never, O = never, P = never, Q = never, R = never, S = never, T = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K, kl: (_: K) => L, lm: (_: L) => M, mn: (_: M) => N, no: (_: N) => O, op: (_: O) => P, pq: (_: P) => Q, qr: (_: Q) => R, rs: (_: R) => S, st: (_: S) => T): T;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never, L = never, M = never, N = never, O = never, P = never, Q = never, R = never, S = never, T = never, U = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K, kl: (_: K) => L, lm: (_: L) => M, mn: (_: M) => N, no: (_: N) => O, op: (_: O) => P, pq: (_: P) => Q, qr: (_: Q) => R, rs: (_: R) => S, st: (_: S) => T, tu: (_: T) => U): U;
    pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never, L = never, M = never, N = never, O = never, P = never, Q = never, R = never, S = never, T = never, U = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D, de: (_: D) => E, ef: (_: E) => F, fg: (_: F) => G, gh: (_: G) => H, hi: (_: H) => I, ij: (_: I) => J, jk: (_: J) => K, kl: (_: K) => L, lm: (_: L) => M, mn: (_: M) => N, no: (_: N) => O, op: (_: O) => P, pq: (_: P) => Q, qr: (_: Q) => R, rs: (_: R) => S, st: (_: S) => T, tu: (_: T) => U): U;
}
/**
 * @since 2.0.0
 */
declare const pipeArguments: <A>(self: A, args: IArguments) => unknown;
/**
 * @since 3.15.0
 * @category Models
 */
interface PipeableConstructor {
    new (...args: Array<any>): Pipeable;
}
/**
 * @since 3.15.0
 * @category Prototypes
 */
declare const Prototype: Pipeable;
/**
 * @since 3.15.0
 * @category Constructors
 */
declare const Class: {
    (): PipeableConstructor;
    <TBase extends Ctor>(klass: TBase): TBase & PipeableConstructor;
};

/**
 * @module
 * This module provides a comprehensive, type-safe, and hierarchical approach
 * to error handling in task-based workflows. It distinguishes between expected
 * domain errors (best handled with `Result` types) and unexpected system panics
 * (best handled with `withErrorBoundary`).
 */

/**
 * Options for creating a new custom error type.
 */
interface ErrorTypeOptions {
    /** The name of the error class. This is used in `error.name`. */
    name: string;
    /** An optional parent error class for creating a hierarchy. Defaults to `Error`. */
    parent?: new (...args: any[]) => Error;
}
/**
 * A factory function for creating custom, hierarchical error classes.
 * This utility correctly sets up the prototype chain, ensuring that `instanceof`
 * checks work as expected for both the created class and its parents.
 * The created error will have a constructor that accepts any arguments and passes
 * them to the parent constructor.
 *
 * @template TConstructorArgs An array type representing the arguments accepted by the constructor of the custom error.
 * @param options The configuration for the new error type, including its name and optional parent.
 * @returns A new Error class constructor.
 *
 * @example
 * ```typescript
 * // Create a base error for all database issues.
 * const DatabaseError = createErrorType({ name: 'DatabaseError' });
 *
 * // Create specific errors that inherit from the base error.
 * const ConnectionError = createErrorType({ name: 'ConnectionError', parent: DatabaseError });
 * const QueryError = createErrorType({ name: 'QueryError', parent: DatabaseError });
 *
 * // Usage:
 * try {
 *   throw new ConnectionError('Failed to connect to database.', { cause: originalNetworkError });
 * } catch (e) {
 *   if (e instanceof ConnectionError) {
 *     console.error('Connection issue:', e.message, e.cause);
 *   }
 *   if (e instanceof DatabaseError) {
 *     console.error('Database problem detected.');
 *   }
 * }
 * ```
 */
declare function createErrorType<TConstructorArgs extends any[] = [message?: string, options?: ErrorOptions]>(options: ErrorTypeOptions): new (...args: TConstructorArgs) => Error;
/**
 * A type representing a handler tuple for `withErrorBoundary`.
 * It pairs an error class constructor (`ErrorConstructor`) with a handler function
 * that receives a correctly typed instance of that error (`E`) and the context.
 * The handler should return a value of type `R` (or `Promise<R>`), which is the
 * expected result type of the task being protected.
 *
 * @template C The context type.
 * @template R The result type of the handler (and the task).
 * @template E The specific type of Error this handler deals with.
 */
type ErrorHandlerTuple<C, R, E extends Error> = [
    new (...args: any[]) => E,
    (error: E, context: C) => R | Promise<R>
];
/**
 * An array of ErrorHandlerTuple, allowing for multiple types of errors to be handled.
 * The `any` for the error type in the handler function within the array definition
 * is a concession for heterogeneous arrays; `createErrorHandler` ensures type safety
 * when creating individual tuples.
 */
type ErrorHandlerArray<C, R> = Array<[
    new (...args: any[]) => Error,
    (error: any, context: C) => R | Promise<R>
]>;
/**
 * A utility function for creating a type-safe error handler tuple.
 * Using this ensures that the type of the `error` argument in the handler
 * function is correctly inferred from the provided error class constructor.
 *
 * @template C The context type.
 * @template R The result type that the handler must return (matching the protected task's result type).
 * @template E The specific type of `Error` this handler is for.
 * @param ErrorClass The constructor of the specific error class (e.g., `MyCustomError`).
 * @param handlerFn The function to execute when an error of `ErrorClass` is caught.
 *                  It receives the typed error instance and the current context.
 * @returns A tuple `[ErrorClass, handlerFn]` for use with `withErrorBoundary`'s `handlers` array.
 */
declare function createErrorHandler<C, R, E extends Error>(ErrorClass: new (...args: any[]) => E, handlerFn: (error: E, context: C) => R | Promise<R>): ErrorHandlerTuple<C, R, E>;
/**
 * A higher-order task that acts as a "safety net" for a workflow or task.
 * It catches specified thrown errors (that are instances of `Error`) and delegates
 * them to type-safe handlers. This is the recommended way to handle unexpected
 * system panics or specific operational errors you want to recover from.
 *
 * The boundary matches errors hierarchically using `instanceof`. The provided
 * `handlers` array is evaluated in order, so more specific error handlers
 * should typically be placed before more general ones if their types overlap.
 *
 * If an error is caught and a matching handler is found, the handler's result
 * is returned. If no handler matches, or if the caught item is not an `Error`
 * instance (or is a `BacktrackSignal`), the error is re-thrown.
 *
 * @template C The context type, which must include `scope`.
 * @template V The input value type of the task.
 * @template R The result type of the task (and the error handlers).
 * @param task The `Task<C, V, R>` or workflow to protect.
 * @param handlers An array of `ErrorHandlerTuple` (ideally created with `createErrorHandler`)
 *                 defining which errors to catch and how to handle them.
 * @returns A new `Task<C, V, R>` that incorporates the error boundary logic.
 */
declare function withErrorBoundary<C extends BaseContext, V, R>(task: Task<C, V, R>, handlers: ErrorHandlerArray<C, R>): Task<C, V, R>;
/**
 * Safely wraps a function (synchronous or asynchronous) that may throw,
 * converting its outcome into a `Promise<Result<T, E>>`. This utility ensures
 * that the returned function will never throw directly but will always yield
 * a `Result` object, capturing either the successful value (`Ok<T>`) or the
 * error (`Err<E>`).
 *
 * This is ideal for creating a safe boundary between type-safe `Result`-based
 * code and external libraries or legacy functions that rely on throwing exceptions.
 *
 * @template T The expected type of the successful result of `fn`.
 * @template TArgs The types of the arguments accepted by `fn`.
 * @template E The expected type of the error if `fn` throws (must extend `Error`).
 *               Defaults to `Error`.
 * @param fn The synchronous or asynchronous function to wrap.
 * @param mapErrorToE An optional function to map a caught `unknown` error value
 *                    to the desired error type `E`. If not provided, a default
 *                    mapper is used which attempts to cast `Error` instances or
 *                    wraps non-`Error` values in a new `Error`.
 * @returns A new asynchronous function that takes the same arguments as `fn` but
 *          returns a `Promise<Result<T, E>>` and will not throw.
 *
 * @example
 * ```typescript
 * const riskyJsonParse = (jsonString: string): object => JSON.parse(jsonString); // Throws SyntaxError
 * const safeJsonParse = tryCatch(riskyJsonParse);
 *
 * const result1 = await safeJsonParse('{"foo":"bar"}'); // Ok({ foo: "bar" })
 * const result2 = await safeJsonParse('invalid json');   // Err(SyntaxError(...))
 *
 * if (result2.isErr()) {
 *   console.error("Parsing failed:", result2.error.message);
 * }
 * ```
 */
declare function tryCatch<T, TArgs extends any[], E extends Error = Error>(fn: (...args: TArgs) => T | Promise<T>, mapErrorToE?: (caughtError: unknown) => E): (...args: TArgs) => Promise<Result<T, E>>;

/**
 * A type representing a reusable resource definition, encapsulating the logic for
 * acquiring, releasing, and merging a resource into the context. This pattern
 * promotes reusability and cleans up the call site for `withResources`.
 *
 * @template C The context type.
 * @template R The type of the resource.
 * @template V The input value type for the acquire task.
 * @template K The key under which the resource will be merged into the context.
 */
interface ResourceDefinition<C extends BaseContext, R, V, K extends string> {
    acquire: Task<C, V, R>;
    release: Task<C, R, void>;
    merge: (context: C, resource: R) => C & {
        [P in K]: R;
    };
}
/**
 * A helper to create a reusable resource definition for use with `withResources`.
 *
 * @param key The key to use when merging the resource into the context.
 * @param acquire The task to acquire the resource.
 * @param release The task to release the resource.
 * @returns A `ResourceDefinition` object, which can be passed to `withResources`.
 */
declare function createResource<C extends BaseContext, R, V, K extends string>(key: K, acquire: Task<C, V, R>, release: Task<C, R, void>): ResourceDefinition<C, R, V, K>;
/**
 * Configuration for the `withResource` (bracket) function.
 */
interface BracketConfig<C extends BaseContext, R, V, U> {
    acquire: Task<C, V, R>;
    use: Task<C & Record<string, any>, V, U>;
    release: Task<C, R, void>;
    merge: (context: C, resource: R) => C & Record<string, any>;
}
/**
 * Creates a task that implements the acquire-use-release pattern, ensuring
 * a resource is properly cleaned up even if errors occur during its use.
 * This is the core resource management utility of the library.
 *
 * @param config The bracket configuration object.
 * @returns A new `Task` that encapsulates the entire resource lifecycle.
 *
 * @example
 * ```typescript
 * const withDbConnection = withResource({
 *   acquire: connectToDatabase,
 *   use: performUserQuery,
 *   release: disconnectFromDatabase,
 *   merge: mergeIntoContext('db') // Using the helper for readability
 * });
 *
 * const user = await run(withDbConnection, 'user-123');
 * ```
 */
declare function withResource<C extends {
    scope: Scope;
}, R, V, U>(config: BracketConfig<C, R, V, U>): Task<C, V, U>;
/** The raw `bracket` function. `withResource` is the recommended, more readable alias. */
declare const bracket: typeof withResource;
declare const DisposeSymbol: unique symbol;
declare const AsyncDisposeSymbol: unique symbol;
interface Disposable {
    [DisposeSymbol](): void;
}
interface AsyncDisposable {
    [AsyncDisposeSymbol](): Promise<void>;
}
declare function isDisposable(value: unknown): value is Disposable;
declare function isAsyncDisposable(value: unknown): value is AsyncDisposable;
/**
 * A version of `withResource` for resources that implement the standard `Disposable`
 * or `AsyncDisposable` interface (from the TC39 Explicit Resource Management proposal).
 * The `release` logic is handled automatically by calling `[Symbol.dispose]` or `[Symbol.asyncDispose]`.
 *
 * @param config Configuration with `acquire`, `use`, and `merge`.
 * @returns A task that manages the disposable resource.
 */
declare function withDisposableResource<C extends {
    scope: Scope;
}, R extends Disposable | AsyncDisposable, V, U>(config: {
    acquire: Task<C, V, R>;
    use: Task<C & Record<string, any>, V, U>;
    merge: (context: C, resource: R) => C & Record<string, any>;
}): Task<C, V, U>;
/** The raw `bracketDisposable` function. `withDisposableResource` is the recommended alias. */
declare const bracketDisposable: typeof withDisposableResource;
/**
 * Manages multiple resources for a single `use` task, ensuring all are acquired
 * before use and all are released afterward, even in case of errors. Resources are
 * released in the reverse order of their acquisition.
 *
 * @param resources An array of `ResourceDefinition` objects.
 * @param use The task to execute once all resources have been acquired.
 * @returns A task that encapsulates the entire multi-resource lifecycle.
 */
declare function withResources<C extends {
    scope: Scope;
}, V, U>(resources: Array<ResourceDefinition<C, any, V, any>>, use: Task<any, V, U>): Task<C, V, U>;
/** The raw `bracketMany` function. `withResources` is the recommended alias. */
declare const bracketMany: typeof withResources;
/**
 * **Helper:** Creates a `merge` function for `withResource` that injects the resource
 * into the context under a specified key. This reduces boilerplate and improves readability.
 *
 * @param key The key under which to store the resource in the context.
 *
 * @example
 * ```typescript
 * withResource({
 *   acquire: getDb,
 *   use: useDb,
 *   release: closeDb,
 *   merge: mergeIntoContext('db') // Instead of: (ctx, db) => ({ ...ctx, db })
 * })
 * ```
 */
declare function mergeIntoContext<C extends BaseContext, R, K extends string>(key: K): (context: C, resource: R) => C & {
    [P in K]: R;
};
/**
 * **Helper:** Adapts an object with a specific cleanup method (like `.close()` or `.disconnect()`)
 * to the `AsyncDisposable` interface, making it compatible with `withDisposableResource`.
 *
 * @param resource The resource object to adapt.
 * @param cleanupMethodName The name of the asynchronous cleanup method on the resource.
 * @returns The original resource, now augmented with the `[Symbol.asyncDispose]` method.
 */
declare function asAsyncDisposable<T extends object, K extends keyof T>(resource: T, cleanupMethodName: K): T & AsyncDisposable;
/**
 * Creates context-specific resource management functions for a given context type.
 * This is useful for large applications with a well-defined context, as it provides
 * stronger, built-in type inference for all bracket operations.
 *
 * @param contextTools The context tools returned from `createContext`.
 * @returns An object with context-specific resource management functions.
 */
declare function createBracketTools<C extends BaseContext>(contextTools: {
    defineTask: <V, R>(fn: (value: V) => Promise<R>) => Task<C, V, R>;
    getContext: () => C;
    provide: <R>(overrides: Partial<Omit<C, "scope">>, fn: () => Promise<R>) => Promise<R>;
}): {
    withResource: <R, V, U>(config: BracketConfig<C, R, V, U>) => Task<C, V, U>;
    withDisposableResource: <R extends Disposable | AsyncDisposable, V, U>(config: {
        acquire: Task<C, V, R>;
        use: Task<C & Record<string, any>, V, U>;
        merge: (context: C, resource: R) => C & Record<string, any>;
    }) => Task<C, V, U>;
    withResources: <V, U>(resources: Array<ResourceDefinition<C, any, V, any>>, use: Task<any, V, U>) => Task<C, V, U>;
};
/**
 * An example implementation of a resource that can be managed by the bracket pattern.
 * It implements the `AsyncDisposable` interface for automatic cleanup with `withDisposableResource`.
 */
declare class DatabaseConnection implements AsyncDisposable {
    connectionString: string;
    private _connected;
    constructor(connectionString: string);
    connect(): Promise<this>;
    query(sql: string, params?: any[]): Promise<any>;
    close(): Promise<void>;
    [AsyncDisposeSymbol](): Promise<void>;
}

/**
 * @module
 * This module provides an advanced Circuit Breaker utility for building
 * resilient, production-grade systems that can intelligently handle failure.
 */

/**
 * Configuration options for the Circuit Breaker.
 */
interface CircuitBreakerOptions {
    /**
     * The number of consecutive failures required to trip the circuit and move it to the 'OPEN' state.
     * @default 5
     */
    failureThreshold?: number;
    /**
     * The duration in milliseconds that the circuit will remain 'OPEN' before transitioning to 'HALF-OPEN' to attempt a recovery.
     * @default 30000 (30 seconds)
     */
    openStateTimeoutMs?: number;
    /**
     * A function to determine if a specific error should be counted as a failure.
     * By default, all thrown errors (except for `BacktrackSignal`) are considered failures.
     * @param error The error thrown by the task.
     * @returns `true` if the error should count as a failure, `false` otherwise.
     */
    isFailure?: (error: unknown) => boolean;
}
/**
 * A custom error thrown by the circuit breaker when it is in the 'OPEN' state.
 * This allows consumers to specifically handle this case and, for example,
 * provide a cached response or a graceful fallback UI.
 */
declare class CircuitOpenError extends Error {
    readonly id: string;
    constructor(id: string);
}
/**
 * A higher-order task that wraps another task with the Circuit Breaker pattern.
 *
 * This utility provides intelligent, adaptive resilience by monitoring a task
 * for failures. When a failure threshold is reached, it "trips" the circuit,
 * causing subsequent calls to fail fast without executing the underlying task.
 * After a configured timeout, it enters a "half-open" state to cautiously
 * retry the operation, automatically recovering if the task succeeds.
 *
 * The state of the circuit is managed in memory and is shared across all
 * calls to the returned task *that originated from the same `withCircuitBreaker` call*
 * due to closure. Different calls to `withCircuitBreaker` (even with the same ID)
 * will create distinct circuit breaker instances with their own state.
 *
 * @template C The context type, which must include `scope` and can optionally include a `Logger`.
 * @template V The input type of the task.
 * @template R The result type of the task.
 * @param originalTask The fallible `Task` to protect with the circuit breaker.
 * @param options Configuration for the circuit breaker's behavior. An `id` is
 *                required to uniquely identify the conceptual circuit for logging/errors.
 * @returns A new, resilient `Task` that incorporates the circuit breaker logic.
 */
declare function withCircuitBreaker<C extends {
    scope: Scope;
    logger?: Logger;
}, V, R>(originalTask: Task<C, V, R>, options: CircuitBreakerOptions & {
    id: string;
}): Task<C, V, R>;

/**
 * @module
 * This module provides a powerful and comprehensive suite of utilities for executing
 * tasks in parallel. It offers fine-grained control over concurrency, scheduling,
 * and result handling, for both arrays and iterables of tasks.
 */

/**
 * Defines the priority levels for task scheduling.
 * - `user-blocking`: Highest priority, for tasks critical to user interaction (e.g., animations, input responses).
 * - `user-visible`: Default priority, for tasks that update the UI but are not immediately blocking.
 * - `background`: Lowest priority, for tasks that can be deferred (e.g., logging, pre-fetching).
 */
type TaskPriority = 'user-blocking' | 'user-visible' | 'background';
/**
 * Provides a set of options to control the execution behavior of parallel operations.
 */
interface ParallelOptions {
    /**
     * The maximum number of tasks that are allowed to run concurrently.
     * @default Infinity (no limit)
     */
    concurrency?: number;
    /**
     * The priority for the scheduled tasks, influencing how they are queued by the scheduler.
     * @default 'user-visible'
     */
    priority?: TaskPriority;
    /**
     * If true, tasks are processed in sequential batches. When batching is enabled,
     * the `concurrency` option typically applies to how many batches run in parallel,
     * or how many items *within* a batch run in parallel if the scheduler implementation
     * and batch execution logic support it.
     * The current `executeBatched` runs batches sequentially, with parallelism within each batch.
     * @default false
     */
    batching?: boolean;
    /**
     * The number of tasks to include in each batch when `batching` is enabled.
     * @default 10
     */
    batchSize?: number;
    /**
     * If true, the results array from array-based operations (`all`, `allSettled`)
     * will have the same order as the input tasks array.
     * For stream-based operations, this option is usually ignored as results are yielded on completion.
     * @default true
     */
    preserveOrder?: boolean;
    /**
     * An optional `AbortSignal` to cancel the entire parallel operation.
     * If not provided, it defaults to the `context.scope.signal` of the context
     * in which the parallel utility is invoked.
     */
    signal?: AbortSignal;
}
/**
 * Represents the settled result of a single task executed within a parallel operation
 * like `allSettled` or `stream`.
 * @template T The type of the value if the task is fulfilled.
 */
type ParallelResult<T> = {
    status: 'fulfilled';
    value: T;
    index: number;
} | {
    status: 'rejected';
    reason: unknown;
    index: number;
};
/**
 * Defines the contract for a task scheduler, responsible for executing callbacks
 * (typically wrapping task executions) according to priority and cancellation signals.
 */
interface Scheduler {
    /**
     * Schedules a callback function to be executed.
     * @template T The result type of the callback.
     * @param callback The function to execute.
     * @param options Optional scheduling parameters like priority and signal.
     * @returns A Promise that resolves or rejects with the callback's outcome.
     */
    postTask<T>(callback: () => T | Promise<T>, options?: {
        priority?: TaskPriority;
        signal?: AbortSignal;
    }): Promise<T>;
    /** Indicates if the scheduler is using a native browser/environment scheduling API. */
    readonly isNative: boolean;
}
interface ExperimentalScheduler {
    postTask<T>(callback: () => T | Promise<T>, options?: {
        priority?: 'user-blocking' | 'user-visible' | 'background';
        signal?: AbortSignal;
    }): Promise<T>;
}
declare global {
    var scheduler: ExperimentalScheduler | undefined;
}
/**
 * Gets the best available scheduler for the current environment.
 * It prefers a native scheduler if `globalThis.scheduler.postTask` is available,
 * otherwise, it falls back to a promise-based scheduler using `queueMicrotask` and `setTimeout`.
 */
declare function getScheduler(): Scheduler;
/** A shared, default instance of the scheduler, determined at module load time. */
declare const scheduler: Scheduler;
/**
 * Executes an array of `Task` functions in parallel and returns an array of `ParallelResult`
 * objects, reflecting the outcome (fulfilled or rejected) of each task.
 * This function itself does not reject based on task failures; it always resolves
 * with the settlement status of all provided tasks. It serves as the robust foundation
 * for other higher-level parallel utilities.
 *
 * Cancellation is managed by an `AbortController` that links the `options.signal`
 * (if provided) and the `context.scope.signal`.
 *
 * @template C The context type, which must include `scope`.
 * @template V The common input value type passed to each task.
 * @template R The result type of the tasks if fulfilled.
 * @param tasks An array of `Task<C, V, R>` functions to execute.
 * @param value The common input value `V` that will be passed to each task.
 * @param options Optional `ParallelOptions` to control execution behavior (concurrency, priority, etc.).
 * @param providedContext Optional explicit context `C` to use. If not provided,
 *                        it's retrieved via the global `getContext<C>()`.
 * @returns A Promise that resolves to an array of `ParallelResult<R>` objects.
 */
declare function allSettled<C extends BaseContext, V, R>(tasks: ReadonlyArray<Task<C, V, R>>, value: V, options?: ParallelOptions, providedContext?: C): Promise<ParallelResult<R>[]>;
/** @deprecated Use `allSettled` for capturing all outcomes. This alias might be confusing. */
declare const parallel: typeof allSettled;
/**
 * Executes an array of tasks in parallel. If any task rejects, this function
 * immediately rejects with that task's reason (fail-fast behavior, like `Promise.all`).
 * If all tasks fulfill, it resolves with an array of their values, in the same
 * order as the input tasks.
 *
 * @template C The context type.
 * @template V The common input value for each task.
 * @template R The result type of the tasks.
 * @param tasks An array of `Task<C, V, R>` to execute.
 * @param value The common input value `V` passed to each task.
 * @param options Optional `ParallelOptions`. `preserveOrder` is forced to `true`.
 * @param providedContext Optional explicit context `C`.
 * @returns A Promise resolving to `R[]` or rejecting with the first error.
 */
declare function all<C extends BaseContext, V, R>(tasks: ReadonlyArray<Task<C, V, R>>, value: V, options?: ParallelOptions, providedContext?: C): Promise<R[]>;
/** @deprecated Use `all` for Promise.all-like behavior. */
declare const parallelAll: typeof all;
/**
 * Executes an array of tasks in parallel and resolves with an array containing
 * only the values from successfully fulfilled tasks. Failures are ignored.
 * The order of results is not guaranteed (completion order).
 *
 * @returns A Promise resolving to an array of successfully fulfilled values `R[]`.
 */
declare function some<C extends BaseContext, V, R>(tasks: ReadonlyArray<Task<C, V, R>>, value: V, options?: Omit<ParallelOptions, 'preserveOrder'>, // preserveOrder is effectively false
providedContext?: C): Promise<R[]>;
/** @deprecated Use `some` for collecting successful results. */
declare const parallelSettled: typeof some;
/**
 * Races multiple tasks from an array. Resolves or rejects with the outcome
 * (value or reason) of the first task to settle (fulfill or reject).
 *
 * @returns A Promise that mirrors the first task to settle.
 */
declare function race<C extends BaseContext, V, R>(tasks: ReadonlyArray<Task<C, V, R>>, value: V, options?: Omit<ParallelOptions, 'preserveOrder' | 'batching'>, // These don't apply to race
providedContext?: C): Promise<R>;
/**
 * Executes tasks in parallel. Resolves with the value of the first task to fulfill.
 * If all tasks reject, it rejects with an `AggregateError` containing all rejection reasons.
 * (Behavior similar to `Promise.any`).
 *
 * @returns A Promise resolving with the value of the first successful task `R`.
 */
declare function any<C extends BaseContext, V, R>(tasks: ReadonlyArray<Task<C, V, R>>, value: V, options?: ParallelOptions, // preserveOrder might affect which "first" is chosen if multiple fulfill simultaneously
providedContext?: C): Promise<R>;
/**
 * Executes tasks from an `Iterable` or `AsyncIterable` in parallel, yielding
 * `ParallelResult` objects as tasks settle (fulfill or reject).
 * This is highly memory-efficient for processing large or indefinite sets of tasks,
 * as it does not require all tasks to be held in memory simultaneously.
 * Concurrency is managed to avoid overwhelming resources.
 *
 * @template C The context type.
 * @template V The common input value for each task.
 * @template R The result type of the tasks.
 * @param tasks An `Iterable` or `AsyncIterable` yielding `Task<C, V, R>`.
 * @param inputValue The common input value `V` passed to each task.
 * @param options Optional `ParallelOptions`. `preserveOrder` and `batching` are not applicable
 *                and are omitted from the options type for `stream`.
 * @returns An `AsyncIterable<ParallelResult<R>>` yielding settled results.
 */
declare function stream<C extends BaseContext, V, R>(tasks: Iterable<Task<C, V, R>> | AsyncIterable<Task<C, V, R>>, inputValue: V, options?: Omit<ParallelOptions, 'preserveOrder' | 'batching'>, // These options don't make sense for stream
providedContext?: C): AsyncIterable<ParallelResult<R>>;
/** @deprecated Use `stream` for settled results from an iterable. */
declare const parallelFrom: typeof stream;
/**
 * Executes tasks from an `Iterable` or `AsyncIterable` in parallel and yields
 * only the values from successfully fulfilled tasks, ignoring rejections.
 * Results are yielded as they become available (completion order).
 */
declare function streamSome<C extends BaseContext, V, R>(tasks: Iterable<Task<C, V, R>> | AsyncIterable<Task<C, V, R>>, inputValue: V, options?: Omit<ParallelOptions, 'preserveOrder' | 'batching'>, providedContext?: C): AsyncIterable<R>;
/** @deprecated Use `streamSome` for fulfilled results from an iterable. */
declare const parallelFromSettled: typeof streamSome;
/**
 * Executes tasks from an `Iterable` or `AsyncIterable` in parallel.
 * Yields values from successfully fulfilled tasks. If any task rejects,
 * the iteration immediately stops and the error is thrown (fail-fast).
 */
declare function streamAll<C extends BaseContext, V, R>(tasks: Iterable<Task<C, V, R>> | AsyncIterable<Task<C, V, R>>, inputValue: V, options?: Omit<ParallelOptions, 'preserveOrder' | 'batching'>, providedContext?: C): AsyncIterable<R>;
/** @deprecated Use `streamAll` for fail-fast iteration. */
declare const parallelFromAll: typeof streamAll;
/**
 * Executes tasks from an `Iterable` or `AsyncIterable` in parallel.
 * Resolves with the value of the first task to fulfill.
 * If all tasks reject, it rejects with an `AggregateError` containing all rejection reasons.
 */
declare function streamAny<C extends BaseContext, V, R>(tasks: Iterable<Task<C, V, R>> | AsyncIterable<Task<C, V, R>>, inputValue: V, options?: Omit<ParallelOptions, 'preserveOrder' | 'batching'>, providedContext?: C): Promise<R>;
/**
 * Races tasks from an `Iterable` or `AsyncIterable`. Resolves or rejects with
 * the outcome (value or reason) of the first task to settle.
 * Other pending tasks are signalled to abort.
 *
 * @template C The context type.
 * @template V The common input value for each task.
 * @template R The result type of the tasks.
 * @param tasks An `Iterable` or `AsyncIterable` yielding `Task<C, V, R>`.
 * @param value The common input value `V` passed to each task.
 * @param options Optional `ParallelOptions` (excluding `preserveOrder`, `batching`).
 *                Only `priority` and `signal` are typically relevant.
 * @param providedContext Optional explicit context `C`.
 * @returns A Promise that mirrors the first task to settle.
 */
declare function raceFrom<C extends BaseContext, V, R>(tasks: Iterable<Task<C, V, R>> | AsyncIterable<Task<C, V, R>>, value: V, options?: Omit<ParallelOptions, 'preserveOrder' | 'batching'>, providedContext?: C): Promise<R>;

/**
 * @module
 * This module provides powerful, high-level utilities for managing structured
 * and parallel control flows. It includes operators for fork-join patterns
 * (fail-fast and settled), conditional branching (if-then-else), and
 * type-safe parallel execution with tuple-based results. These tools enable
 * complex concurrent workflows that remain readable, predictable, and type-safe.
 */

/**
 * A type-safe, pipeable operator that forks the workflow into multiple
 * parallel tasks and joins their results into a single, keyed object. Each
 * forked task receives the same input value from the parent workflow.
 * If ANY of the tasks reject, the entire `forkJoin` task rejects with the
 * reason of the first rejecting task (fail-fast behavior from `Promise.all`).
 *
 * @param tasks An object where keys are strings and values are `Task`s.
 * @returns A new `Task` that resolves to an object with the same keys,
 *          but with the resolved results of the tasks as values. The output
 *          type is statically inferred from the input object.
 *
 * @example
 * ```typescript
 * const getDashboardData = createWorkflow( // Assuming createWorkflow from your utils
 *   fromValue('user-123'), // The input userId
 *   forkJoin({
 *     user: fetchUser,          // Task<Ctx, string, User>
 *     posts: fetchPosts,        // Task<Ctx, string, Post[]>
 *   }),
 *   // Result: { user: User, posts: Post[] }
 *   map(data => `Welcome ${data.user.name}, you have ${data.posts.length} posts.`)
 * );
 * ```
 */
declare function forkJoin<C extends BaseContext, V, T extends Record<string, Task<C, V, any>>>(tasks: T): Task<C, V, {
    [K in keyof T]: T[K] extends Task<C, V, infer R> ? R : never;
}>;
/**
 * Represents the settled result of a task when using `forkJoinSettled` or `allTupleSettled`.
 * It's either a success with a value or a failure with a reason.
 */
type SettledTaskResult<R> = Result<R, unknown>;
/**
 * Similar to `forkJoin`, but uses `Promise.allSettled`. This means it waits for
 * ALL tasks to complete (either resolve or reject) and returns an object
 * where each value is a `SettledTaskResult` (a `Result` type from `neverthrow`
 * indicating success or failure). This task itself will not reject unless
 * there's an unexpected error in its own orchestration logic.
 *
 * @param tasks An object where keys are strings and values are `Task`s.
 * @returns A new `Task` that resolves to an object with the same keys,
 *          where each value is a `SettledTaskResult<R>`.
 *
 * @example
 * ```typescript
 * const getOptionalData = createWorkflow(
 *   fromValue('user-123'),
 *   forkJoinSettled({
 *     profile: fetchUserProfile,    // Might fail
 *     settings: fetchUserSettings,  // Might also fail
 *   }),
 *   map(results => {
 *     const profile = results.profile.isOk() ? results.profile.value : null;
 *     const settings = results.settings.isOk() ? results.settings.value : { darkMode: false };
 *     return { profile, settings };
 *   })
 * );
 * ```
 */
declare function forkJoinSettled<C extends BaseContext, V, T extends Record<string, Task<C, V, any>>>(tasks: T): Task<C, V, {
    [K in keyof T]: T[K] extends Task<C, V, infer R> ? SettledTaskResult<R> : never;
}>;
/**
 * Runs an array of tasks in parallel and resolves with a tuple containing
 * the results in the same order. This is a type-safe alternative to `forkJoin`
 * when the result keys are not important and the order is fixed and known.
 * If ANY of the tasks reject, the entire `allTuple` task rejects (fail-fast).
 *
 * It is highly recommended to use `as const` on the input array of tasks
 * to ensure TypeScript infers a precise tuple type for the results.
 *
 * @param tasks An array (preferably, a tuple `[...] as const`) of `Task`s.
 * @returns A `Task` that resolves to a tuple of the results, with types preserved.
 *
 * @example
 * ```typescript
 * const setup = allTuple([
 *   connectToDatabase, // -> Task<Ctx, void, DbConnection>
 *   connectToRedis,    // -> Task<Ctx, void, RedisClient>
 * ] as const); // "as const" is key for precise tuple typing
 *
 * // result will be [DbConnection, RedisClient]
 * const [db, redis] = await run(setup, undefined);
 * ```
 */
declare function allTuple<C extends BaseContext, V, T extends ReadonlyArray<Task<C, V, any>>>(tasks: T): Task<C, V, {
    -readonly [K in keyof T]: T[K] extends Task<C, V, infer R> ? R : never;
}>;
/**
 * Similar to `allTuple`, but uses `Promise.allSettled`. It waits for ALL tasks
 * in the input array/tuple to complete and returns a tuple where each element
 * is a `SettledTaskResult` (a `Result` type indicating success or failure).
 * This task itself will not reject unless there's an unexpected error in its
 * own orchestration logic. Use `as const` for precise output tuple typing.
 *
 * @param tasks An array (preferably, a tuple `[...] as const`) of `Task`s.
 * @returns A `Task` that resolves to a tuple of `SettledTaskResult<R>`.
 *
 * @example
 * ```typescript
 * const [dbResult, redisResult] = await run(
 *   allTupleSettled([connectToDb, connectToRedis] as const),
 *   undefined
 * );
 *
 * if (dbResult.isOk()) { /* use dbResult.value *\/ }
 * if (redisResult.isErr()) { /* handle redis error: redisResult.error *\/ }
 * ```
 */
declare function allTupleSettled<C extends BaseContext, V, T extends ReadonlyArray<Task<C, V, any>>>(tasks: T): Task<C, V, {
    -readonly [K in keyof T]: T[K] extends Task<C, V, infer R> ? SettledTaskResult<R> : never;
}>;
/**
 * A pipeable operator that provides true conditional branching (if-then-else)
 * for workflows. It evaluates a predicate (which can be synchronous or asynchronous)
 * and executes one of two provided `Task`s based on the boolean result.
 * Both the `onTrue` and `onFalse` tasks receive the same input value that `ift` received.
 *
 * @param predicate A sync or async function that receives the current value and context,
 *                  and returns a boolean (`true` or `false`) to determine which path to take.
 * @param onTrue The `Task` to execute if the predicate returns `true`.
 * @param onFalse The `Task` to execute if the predicate returns `false`.
 * @returns A new `Task` whose result type is a union of the result types
 *          of the `onTrue` and `onFalse` tasks, reflecting the two possible outcomes.
 *
 * @example
 * ```typescript
 * const processPayment = createWorkflow( // Assuming createWorkflow from your utils
 *   createOrder,
 *   ift(
 *     async (order, ctx) => await ctx.fraudCheck.isSafe(order), // Async predicate
 *     chargeCreditCard,  // Task<Ctx, Order, ChargeSuccess>
 *     holdForReview      // Task<Ctx, Order, HoldResult>
 *   )
 *   // Result type is ChargeSuccess | HoldResult
 * );
 * ```
 */
declare function ift<C extends BaseContext, V, R1, R2>(predicate: (value: V, context: C) => boolean | Promise<boolean>, onTrue: Task<C, V, R1>, onFalse: Task<C, V, R2>): Task<C, V, R1 | R2>;

/**
 * @module
 * This module provides high-level utilities for parallel data processing. It
 * includes abstractions like `mapReduce`, parallel `filter`, and parallel
 * `groupBy` to operate on collections of data concurrently, leveraging the
 * scheduler from './scheduler.ts' for parallel execution.
 */

/**
 * Configuration options for the `mapReduce` utility.
 * @template C The context type for the mapping task.
 * @template TItem The type of individual items in the input data array.
 * @template RMapped The type of results produced by the mapping task for each item.
 * @template UAccumulator The type of the final accumulated/reduced value.
 */
interface MapReduceOptions<C extends BaseContext, TItem, RMapped, UAccumulator> extends ParallelOptions {
    /** The Task to apply to each item in the data array during the map phase. Receives TItem. */
    map: Task<C, TItem, RMapped>;
    /** A synchronous function to reduce the mapped results into a single value. */
    reduce: (accumulator: UAccumulator, currentMappedResult: RMapped, currentIndex: number, allMappedResults: RMapped[]) => UAccumulator;
    /** The initial value for the accumulator in the reduce phase. */
    initial: UAccumulator;
}
/**
 * Performs a parallel map operation over an array of data items, followed by a
 * sequential reduce operation to produce a single summary value.
 *
 * The mapping `Task` (options.map) is applied to each data item. To achieve parallelism
 * with the scheduler, a new set of tasks is created where each task is bound to an
 * individual item from the input `data` array and expects a dummy input (e.g., `null`).
 * These item-specific tasks are then run in parallel using `scheduler.all` or `scheduler.allSettled`.
 *
 * If any mapping task fails, this `mapReduce` task will reject (fail-fast behavior).
 *
 * @template C The context type. Must include `scope` for cancellation.
 * @template TItem The type of items in the input `data` array.
 * @template RMapped The type of results after the map operation for each item.
 * @template UAccumulator The type of the final reduced value.
 * @param data The array of data items to process.
 * @param options Configuration including the `map` Task, `reduce` function,
 *                `initial` accumulator value, and optional `ParallelOptions`.
 * @returns A `Task` that takes no input (null) and resolves to the final reduced value `UAccumulator`.
 */
declare function mapReduce<C extends BaseContext, TItem, RMapped, UAccumulator>(data: TItem[], options: MapReduceOptions<C, TItem, RMapped, UAccumulator>): Task<C, null, UAccumulator>;
/**
 * **Pipeable Operator:** Filters an array by applying an asynchronous predicate `Task`
 * to each item in parallel. Items for which the predicate resolves to `true` are
 * included in the result array. The predicate tasks are run using `scheduler.allSettled`
 * to ensure all predicates are evaluated; however, if a predicate task unexpectedly
 * throws an error (other than resolving to false), that error will cause this
 * filter task to reject.
 *
 * @template C The context type. Must include `scope` for cancellation.
 * @template VItem The type of items in the array.
 * @param predicateTask A `Task<C, VItem, boolean>` that takes an item and its context,
 *                      and returns a `Promise<boolean>` indicating if the item should be included.
 * @param options Optional `ParallelOptions` to control concurrency of predicate execution.
 * @returns A `Task<C, VItem[], VItem[]>` that receives an array and resolves to the new, filtered array.
 */
declare function filter<C extends BaseContext, VItem>(predicateTaskForItem: Task<C, VItem, boolean>, options?: ParallelOptions): Task<C, VItem[], VItem[]>;
/**
 * **Pipeable Operator:** Groups items in an array into a `Map` based on a key
 * generated by a `keyingTaskOrFn`. The keying operation for each item is run in parallel
 * using `scheduler.all`. If any keying operation fails, the `groupBy` task will reject.
 *
 * @template C The context type. Must include `scope` for cancellation.
 * @template VItem The type of items in the array.
 * @template KKey The type of the key used for grouping (string, number, or symbol).
 * @param keyingTaskOrFn A `Task<C, VItem, KKey>` or a synchronous function `(item: VItem) => KKey`
 *                       that produces the key for an item. If a synchronous function
 *                       is provided, it will be wrapped into a `Task` using `defineTask`.
 * @param options Optional `ParallelOptions` to control concurrency of key generation.
 * @returns A `Task<C, VItem[], Map<KKey, VItem[]>>` that receives an array and resolves to a `Map`.
 */
declare function groupBy<C extends BaseContext, VItem, KKey extends string | number | symbol>(keyingTaskOrFn: Task<C, VItem, KKey> | ((item: VItem) => KKey), // Simpler sync fn signature
options?: ParallelOptions): Task<C, VItem[], Map<KKey, VItem[]>>;

/**
 * @module worker
 * @description
 * This module provides a robust, isomorphic integration with Web Workers,
 * using a reliable JSON-based message protocol and `seroval` for serialization.
 * It features a clean API and zero-latency cancellation via `Atomics`.
 *
 * @features
 * - **Isomorphic:** A single codebase for Node.js (`worker_threads`) and Browser (`Web Worker`).
 * - **Reliable Messaging:** Uses a structured JSON protocol with `seroval` to avoid the complexities
 *   and potential security issues of `eval`, ensuring compatibility across all JS runtimes.
 * - **Robust Streaming:** A dedicated protocol for async iterables ensures all data chunks are delivered
 *   in the correct order without race conditions.
 * - **Zero-Latency Cancellation:** Employs `SharedArrayBuffer` and `Atomics` (when available) for
 *   instantaneous cancellation of long-running tasks.
 * - **Type-Safe API:** Explicit `runOnWorker` and `runStreamOnWorker` functions provide strong
 *   return types, making it clear whether you expect a single value or a stream.
 *
 * @example
 * **1. Worker Script (`my.worker.ts`):**
 * ```ts
 * import { createWorkerHandler, defineTask } from 'path/to/library';
 *
 * const heavyTask = defineTask(async (data: { value: number }) => {
 *   // ... intensive work ...
 *   return data.value * 2;
 * });
 *
 * const streamingTask = defineTask(async function* (count: number) {
 *   for (let i = 0; i < count; i++) {
 *     yield `Update #${i + 1}`;
 *   }
 * });
 *
 * createWorkerHandler({ heavyTask, streamingTask });
 * ```
 *
 * **2. Main Thread Usage:**
 * ```ts
 * import { runOnWorker, runStreamOnWorker, createContext } from 'path/to/library';
 * import { Worker } from 'node:worker_threads';
 *
 * const worker = new Worker(new URL('./my.worker.ts', import.meta.url));
 * const { run } = createContext();
 *
 * // Request-Response
 * const remoteCalc = runOnWorker(worker, 'heavyTask');
 * const result = await run(remoteCalc, { value: 21 }); // --> 42
 *
 * // Streaming
 * const remoteStream = runStreamOnWorker(worker, 'streamingTask');
 * const iterable = await run(remoteStream, 3);
 * for await (const update of iterable) {
 *   console.log(update);
 * }
 *
 * await worker.terminate();
 * ```
 */

/**
 * Represents a worker instance that is compatible in both Browser and Node.js environments.
 * This defines the minimal API surface area that the module relies on.
 */
type IsomorphicWorker = {
    postMessage(message: any, transferList?: readonly any[]): void;
    addEventListener?(type: string, listener: (event: any) => void): void;
    removeEventListener?(type: string, listener: (event: any) => void): void;
    on?(event: string, listener: (...args: any[]) => void): void;
    off?(event: string, listener: (...args: any[]) => void): void;
    terminate(): void | Promise<number>;
};
/**
 * Options for configuring worker-related functions.
 */
interface WorkerOptions {
    /** A list of `seroval` plugins to use for serialization and deserialization. */
    plugins?: Plugin<any, any>[];
    /** A record of isomorphic references available to the worker. */
    references?: Record<string, unknown>;
}
/**
 * Represents the identifier for a remote task, which can be either its string name
 * or the task object itself (which has a `__task_id` property).
 */
type TaskIdentifier = string | {
    __task_id?: symbol;
};
/** A record of Task functions, used for defining a worker's capabilities. */
type WorkerTasks = Record<string, Task<any, any, any>>;
/**
 * A type-safe proxy that mirrors the tasks defined in the worker.
 * Each property corresponds to a task and is itself a valid `Task` object.
 * This is the recommended way to interact with worker tasks.
 */
type Remote<T extends WorkerTasks> = {
    [K in keyof T]: T[K];
};
/**
 * Creates a message handler for a Web Worker. This function initializes the
 * worker's environment, sets up listeners, and executes tasks based on
 * messages from the main thread. After setup, it sends a 'ready' message.
 *
 * @param tasks An object mapping task identifiers to `Task` functions.
 * @param options Optional configuration for plugins or isomorphic references.
 */
declare function createWorkerHandler(tasks: Record<string, Task<any, any, any>>, options?: WorkerOptions): void;
/**
 * Creates a Task that, when executed, runs a specified task on a Web Worker
 * and returns a single result or error.
 *
 * @param worker The `Worker` or `worker_threads.Worker` instance.
 * @param taskId The string identifier of the task registered in the worker, or the Task object itself.
 * @param opOptions Optional configuration for `seroval` plugins.
 * @returns A `Task` that delegates its execution to the worker.
 * @example
 * const remoteTask = runOnWorker(worker, 'double');
 * const result = await run(remoteTask, 21); // result is 42
 */
declare function runOnWorker<C extends BaseContext, V, R>(worker: IsomorphicWorker, taskId: TaskIdentifier, opOptions?: WorkerOptions): Task<C, V, R>;
/**
 * Creates a Task that, when executed, runs a specified streaming task on a Web Worker.
 * It returns an `AsyncIterable` on the main thread that yields results.
 *
 * @param worker The `Worker` or `worker_threads.Worker` instance.
 * @param taskId The string identifier of the streaming task registered in the worker, or the Task object itself.
 * @param opOptions Optional configuration for `seroval` plugins.
 * @returns A `Task` that delegates streaming execution to the worker.
 * @example
 * const remoteStream = runStreamOnWorker(worker, 'eventStream');
 * const iterable = await run(remoteStream, 5); // Request 5 events
 * for await (const event of iterable) {
 *   console.log(event); // "Event #1", "Event #2", ...
 * }
 */
declare function runStreamOnWorker<C extends BaseContext, V, R>(worker: IsomorphicWorker, taskId: TaskIdentifier, opOptions?: WorkerOptions): Task<C, V, AsyncIterable<R>>;
/**
 * Creates a type-safe, ergonomic proxy for interacting with tasks on a Web Worker.
 *
 * This is the recommended way to use worker tasks, as it provides full
 * autocompletion and compile-time safety. The function returns a `Promise` that
 * resolves once it has established a connection with the worker and received
 * metadata about the available tasks. This metadata allows the proxy to
 * reliably distinguish between regular and streaming tasks without fragile heuristics.
 *
 * @template T - A `WorkerTasks` type definition, usually inferred from a type-only import.
 * @param {IsomorphicWorker} worker The `Worker` or `worker_threads.Worker` instance.
 * @param {WorkerOptions} [options] Optional configuration, like `seroval` plugins, to be used for all proxied tasks.
 * @returns {Promise<Remote<T>>} A `Promise` that resolves to the fully configured, type-safe proxy object. The proxy is ready to use once the promise resolves.
 * @throws {Error} Rejects if the worker does not send a 'ready' signal within the initialization timeout (10 seconds). This typically indicates an issue in the worker script, such as not calling `createWorkerHandler` or an error during its startup.
 *
 * @example
 * // 1. Define tasks in the worker file (`my.worker.ts`)
 * //    It's important that the main thread can type-import this.
 * import { createWorkerHandler, defineTask } from '@doeixd/effectively';
 *
 * const sum = defineTask(async (numbers: number[]) => {
 *   return numbers.reduce((a, b) => a + b, 0);
 * });
 *
 * const countStream = defineTask(async function* (limit: number) {
 *   for (let i = 0; i < limit; i++) {
 *     await new Promise(res => setTimeout(res, 100));
 *     yield i + 1;
 *   }
 * });
 *
 * export const tasks = { sum, countStream };
 * createWorkerHandler(tasks);
 *
 * // 2. Use the proxy on the main thread (`main.ts`)
 * import { createWorkerProxy, createContext } from '@doeixd/effectively';
 * import { Worker } from 'node:worker_threads';
 * import type { tasks } from './my.worker.ts'; // Type-only import for <T>
 *
 * async function main() {
 *   const worker = new Worker(new URL('./my.worker.ts', import.meta.url));
 *   const { run } = createContext();
 *
 *   // Note the 'await' here!
 *   const remote = await createWorkerProxy<typeof tasks>(worker);
 *
 *   // Call a regular task
 *   const total = await run(remote.sum, [10, 20, 30]);
 *   console.log(total); // --> 60
 *
 *   // Call a streaming task - the proxy handles it automatically
 *   const stream = await run(remote.countStream, 3);
 *   for await (const value of stream) {
 *     console.log(value); // --> 1, 2, 3
 *   }
 *
 *   // The resolved proxy will throw if you call a non-existent task
 *   try {
 *     await run((remote as any).nonExistentTask, {});
 *   } catch (e) {
 *     console.error(e); // --> ReferenceError: Task "nonExistentTask" is not defined in the worker.
 *   }
 *
 *   await worker.terminate();
 * }
 *
 * main();
 */
declare function createWorkerProxy<T extends WorkerTasks>(worker: IsomorphicWorker, options?: WorkerOptions): Promise<Remote<T>>;

/**
 * @module do-notation
 *
 * Monadic do notation using generator syntax for cleaner async composition.
 * Inspired by Haskell's do notation, this module provides a way to chain
 * monadic operations in a more readable, imperative style while maintaining
 * functional purity.
 */

/**
 * A monadic value that can be yielded in a do block.
 * This represents any value that can be "unwrapped" in monadic composition.
 *
 * Supports:
 * - Tasks: Functions that take (context, value) and return Promise<T>
 * - Promises: Standard JavaScript promises
 * - Results: neverthrow Result<T, E> types
 * - Generators: For yield* delegation to other do blocks
 * - Plain values: Direct values that are returned as-is
 */
type MonadicValue<C extends BaseContext, T> = Task<C, any, T> | Promise<T> | Result<T, any> | Generator<MonadicValue<C, any>, T, any> | T;
/**
 * Utility type to extract the inner type from a MonadicValue.
 */
type Unwrap<T> = T extends Task<any, any, infer R> ? R : T extends Promise<infer R> ? R : T extends Result<infer R, any> ? R : T extends Generator<any, infer R, any> ? R : T;
/**
 * Generator function type for do notation.
 * Each yield should be a MonadicValue that gets unwrapped.
 */
type DoGenerator<C extends BaseContext, T> = Generator<MonadicValue<C, any>, T, any>;
/**
 * Function signature for do block generators.
 */
type DoFunction<C extends BaseContext, V, R> = (value: V) => DoGenerator<C, R>;
/**
 * Executes a generator-based do block, unwrapping each yielded monadic value.
 * This provides Haskell-like do notation for JavaScript/TypeScript.
 *
 * Supports:
 * - yield for unwrapping Tasks, Promises, Results, and plain values
 * - yield* for delegating to other generator functions (composition)
 *
 * @example
 * ```typescript
 * // Basic usage with yield
 * const workflow = doTask(function* (userId: string) {
 *   const user = yield getUser(userId);        // Task<Context, string, User>
 *   const profile = yield getProfile(user.id); // Task<Context, string, Profile>
 *   const settings = yield getSettings(user.id); // Task<Context, string, Settings>
 *
 *   return {
 *     user,
 *     profile,
 *     settings
 *   };
 * });
 *
 * // Composition with yield*
 * function* fetchUserCore(userId: string) {
 *   const user = yield getUser(userId);
 *   const profile = yield getProfile(user.id);
 *   return { user, profile };
 * }
 *
 * const fullWorkflow = doTask(function* (userId: string) {
 *   const coreData = yield* fetchUserCore(userId); // Delegate to sub-generator
 *   const settings = yield getSettings(userId);
 *   return { ...coreData, settings };
 * });
 * ```
 *
 * @param generator A generator function that yields monadic values
 * @returns A Task that executes the generator and unwraps yielded values
 */
declare function doTask<C extends BaseContext, V, R>(generator: DoFunction<C, V, R>): Task<C, V, R>;
/**
 * Creates a do notation wrapper for a specific context type.
 * This allows for better type inference and context handling.
 *
 * @example
 * ```typescript
 * interface MyContext extends BaseContext {
 *   db: Database;
 *   logger: Logger;
 * }
 *
 * const { doTask: myDoTask } = createDoNotation<MyContext>();
 *
 * const workflow = myDoTask(function* (userId: string) {
 *   const user = yield getUser(userId);
 *   const posts = yield getPosts(user.id);
 *   return { user, posts };
 * });
 * ```
 *
 * @returns An object with context-specific do notation functions
 */
declare function createDoNotation<C extends BaseContext>(): {
    doTask: <V, R>(generator: DoFunction<C, V, R>) => Task<C, V, R>;
    /**
     * Convenience function for creating simple do blocks that don't need input.
     */
    doBlock: <R>(generator: () => DoGenerator<C, R>) => Task<C, void, R>;
};
/**
 * Utility function to lift a regular value into the monadic context.
 * Useful for returning plain values from within do blocks.
 *
 * @example
 * ```typescript
 * const workflow = doTask(function* () {
 *   const x = yield getValue();
 *   const y = yield pure(42); // Lifts 42 into the monadic context
 *   return x + y;
 * });
 * ```
 */
declare function pure<T>(value: T): T;
/**
 * Helper function to call a task with a specific input value.
 * This allows you to use tasks that require input parameters in do notation.
 *
 * @example
 * ```typescript
 * const workflow = doTask(function* () {
 *   const user = yield call(getUserById, 'user123');
 *   const profile = yield call(getProfile, user.id);
 *   return { user, profile };
 * });
 * ```
 */
declare function call<C extends BaseContext, V, R>(task: Task<C, V, R>, input: V): Task<C, void, R>;
/**
 * Conditional monadic execution.
 * Executes one of two monadic values based on a condition.
 *
 * @example
 * ```typescript
 * const workflow = doTask(function* (userId: string) {
 *   const user = yield getUser(userId);
 *   const data = yield doWhen(
 *     user.isAdmin,
 *     () => getAdminData(userId),
 *     () => getUserData(userId)
 *   );
 *   return data;
 * });
 * ```
 */
declare function doWhen<C extends BaseContext, T>(condition: boolean, onTrue: () => MonadicValue<C, T>, onFalse: () => MonadicValue<C, T>): MonadicValue<C, T>;
/**
 * Maybe-like conditional execution.
 * Only executes the monadic value if the condition is true.
 *
 * @example
 * ```typescript
 * const workflow = doTask(function* (userId: string) {
 *   const user = yield getUser(userId);
 *   yield doUnless(user.isActive, () => activateUser(userId));
 *   return user;
 * });
 * ```
 */
declare function doUnless<C extends BaseContext, T = void>(condition: boolean, action: () => MonadicValue<C, T>): MonadicValue<C, T | void>;
/**
 * Executes multiple monadic values in sequence and collects their results.
 *
 * @example
 * ```typescript
 * const workflow = doTask(function* (userIds: string[]) {
 *   const users = yield sequence(userIds.map(id => getUser(id)));
 *   return users;
 * });
 * ```
 */
declare function sequence<C extends BaseContext, T>(values: MonadicValue<C, T>[]): Task<C, void, T[]>;
/**
 * Loops over an array, executing a monadic function for each element.
 *
 * @example
 * ```typescript
 * const workflow = doTask(function* (userIds: string[]) {
 *   yield forEach(userIds, function* (userId) {
 *     const user = yield getUser(userId);
 *     yield logUser(user);
 *   });
 * });
 * ```
 */
declare function forEach<C extends BaseContext, T>(items: T[], action: (item: T) => DoGenerator<C, void>): Task<C, void, void>;

/**
 * @module
 * This module provides comprehensive OpenTelemetry integration for observability,
 * tracing, and metrics in your asynchronous workflows. The integration is designed
 * to work seamlessly with existing OpenTelemetry setups while providing graceful

 * fallbacks to a standard logger when OTel providers are not configured.
 */

interface SpanLike {
    setAttributes(attributes: Record<string, unknown>): void;
    setStatus(status: {
        code: number;
        message?: string;
    }): void;
    recordException(exception: Error | string): void;
    end(): void;
}
interface TracerLike {
    startActiveSpan<F extends (span: SpanLike) => unknown>(name: string, options: any, fn: F): ReturnType<F>;
    getActiveSpan(): SpanLike | undefined;
    startSpan(name: string): SpanLike;
}
interface CounterLike {
    add(value: number, attributes?: Record<string, unknown>): void;
}
interface HistogramLike {
    record(value: number, attributes?: Record<string, unknown>): void;
}
interface MeterLike {
    createCounter(name: string, options?: any): CounterLike;
    createHistogram(name: string, options?: any): HistogramLike;
}
/**
 * The shape of a context that includes telemetry providers.
 * All providers are optional, allowing for graceful degradation.
 */
interface TelemetryContext {
    telemetry?: {
        tracer?: TracerLike;
        meter?: MeterLike;
        logger?: Logger;
    };
}
/**
 * Options for configuring an OpenTelemetry span.
 */
interface SpanOptions {
    name?: string;
    attributes?: Record<string, string | number | boolean>;
    kind?: "internal" | "server" | "client" | "producer" | "consumer";
}
/**
 * Options for configuring an OpenTelemetry metric.
 */
interface MetricOptions {
    name: string;
    description?: string;
    unit?: string;
    attributes?: Record<string, string | number | boolean>;
}
/**
 * Creates a span around a task execution with OpenTelemetry integration.
 * Falls back to basic logging if no tracer is available.
 *
 * @param task The task to wrap with a span.
 * @param options Configuration for the span, including name and attributes.
 * @returns A new task that includes tracing logic.
 */
declare function withSpan<C extends BaseContext & TelemetryContext, V, R>(task: Task<C, V, R>, options?: SpanOptions): Task<C, V, R>;
/**
 * Records a metric value using an OpenTelemetry meter or falls back to logging.
 *
 * @param context The current execution context, which may contain telemetry providers.
 * @param type The type of metric to record ('counter' or 'histogram').
 * @param options Configuration for the metric.
 * @param value The value to record. Defaults to 1 for counters.
 */
declare function recordMetric<C extends BaseContext & TelemetryContext>(context: C, type: "counter" | "histogram", options: MetricOptions, value?: number): void;
/**
 * Adds structured attributes to the current active OpenTelemetry span.
 * If no span is active, this function does nothing.
 */
declare function addSpanAttributes<C extends BaseContext & TelemetryContext>(context: C, attributes: Record<string, string | number | boolean>): void;
/**
 * Records an exception in the current active OpenTelemetry span.
 * Falls back to logging if no tracer is available.
 */
declare function recordSpanException<C extends BaseContext & TelemetryContext>(context: C, error: Error): void;
/**
 * A method decorator that automatically wraps an async class method with an OpenTelemetry span.
 * The class instance must have a `context` property that conforms to `TelemetryContext`.
 *
 * @param spanName Optional. The name for the span. If not provided, it defaults to `ClassName.methodName`.
 */
declare function traced(spanName?: string): <This extends {
    context?: TelemetryContext;
}, Args extends any[], Return>(target: (this: This, ...args: Args) => Promise<Return>, context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Promise<Return>>) => (this: This, ...args: Args) => Promise<Return>;
/**
 * An enhancer that wraps a task to automatically measure and record its execution time.
 *
 * @param task The task to time.
 * @param metricName The name for the histogram metric (e.g., 'database.query.duration').
 * @param attributes Optional static attributes to add to the metric.
 * @returns A new task with timing logic.
 */
declare function withTiming<C extends BaseContext & TelemetryContext, V, R>(task: Task<C, V, R>, metricName: string, attributes?: Record<string, string | number | boolean>): Task<C, V, R>;
/**
 * An enhancer that wraps a task to count its successful and failed executions.
 *
 * @param task The task to count.
 * @param counterName The name for the counter metric (e.g., 'api_calls_total').
 * @param attributes Optional static attributes to add to the metric.
 * @returns A new task with counting logic.
 */
declare function withCounter<C extends BaseContext & TelemetryContext, V, R>(task: Task<C, V, R>, counterName: string, attributes?: Record<string, string | number | boolean>): Task<C, V, R>;
/**
 * A comprehensive observability enhancer that combines span tracing, timing, and counting.
 *
 * @param task The task to make observable.
 * @param options Configuration for the span and metrics.
 * @returns A new, fully observable task.
 */
declare function withObservability<C extends BaseContext & TelemetryContext, V, R>(task: Task<C, V, R>, options?: {
    spanName?: string;
    spanAttributes?: Record<string, string | number | boolean>;
    metricAttributes?: Record<string, string | number | boolean>;
    enableTiming?: boolean;
    enableCounting?: boolean;
    metricPrefix?: string;
}): Task<C, V, R>;
/**
 * A helper to create a context object containing telemetry providers.
 *
 * @param providers An object containing `tracer`, `meter`, and/or `logger` instances.
 * @returns A context fragment ready to be used in `createContext` or `run` overrides.
 */
declare function createTelemetryContext(providers: {
    tracer?: TracerLike;
    meter?: MeterLike;
    logger?: Logger;
}): {
    telemetry: {
        tracer?: TracerLike;
        meter?: MeterLike;
        logger?: Logger;
    };
};
/**
 * Utility to safely access the current active span from the context.
 *
 * @param context The current execution context.
 * @returns The active span instance if available, otherwise `null`.
 */
declare function getCurrentSpan<C extends BaseContext & TelemetryContext>(context: C): SpanLike | null;
/**
 * Creates a child span from the current active span in the context.
 *
 * @param context The current execution context.
 * @param name The name for the new child span.
 * @param options Optional configuration for the child span.
 * @returns The new child span instance if a tracer is available, otherwise `null`.
 */
declare function startChildSpan<C extends BaseContext & TelemetryContext>(context: C, name: string, options?: {
    attributes?: Record<string, string | number | boolean>;
}): SpanLike | null;

/**
 * Represents the complete, unified set of tools returned by `createEffectiveSystem`.
 * This type combines the tools from `createContext` and `createEffectSuite`,
 * ensuring they are correctly typed to work together.
 */
type EffectiveSystem<TContext extends BaseContext, TEffects extends EffectsSchema> = ContextTools<ContextWithEffects<TContext>> & EffectSuiteTools<TEffects>;
/**
 * Creates a new, fully integrated "Effectively" system, providing a
 * unified set of tools that are pre-configured to work together with
 * end-to-end type safety.
 *
 * This is the recommended entry point for new applications, as it eliminates
 * the need to manually combine context and effect handler types.
 *
 * @template TContext The specific type of your application's context (e.g., `{ userId: string; }`).
 * @template TEffects The type contract defining your application's effects (e.g., `{ log: (msg: string) => void; }`).
 * @param config An object containing the default data for your context.
 * @returns A complete set of tools (`run`, `getContext`, `effects`, `withHandlers`, etc.)
 *          that are all aware of both your context and your effects contract.
 */
declare function createEffectiveSystem<TContext extends BaseContext, TEffects extends EffectsSchema>(config: {
    context: Omit<TContext, 'scope'>;
}): EffectiveSystem<TContext, TEffects>;

export { AsyncDisposeSymbol, BacktrackSignal, CircuitOpenError, Class, ContextNotFoundError, ContextValidationError, Contravariant, Covariant, DatabaseConnection, DisposeSymbol, EffectHandlerNotFoundError, HANDLERS_KEY, Invariant, PollTimeoutError, Prototype, TimeoutError, WorkflowError, _INTERNAL_getCurrentUnctxInstance, _INTERNAL_setCurrentUnctxInstance, addSpanAttributes, all, allSettled, allTuple, allTupleSettled, andThenTask, any, asAsyncDisposable, attempt, bracket, bracketDisposable, bracketMany, call, chain, createBatchingTask, createBracketTools, createContext, createContextProvider, createContextTransformer, createDoNotation, createEffectSuite, createEffectiveSystem, createErrorHandler, createErrorType, createHandlers, createInjectionToken, createLazyDependency, createResource, createTelemetryContext, createWorkerHandler, createWorkerProxy, createWorkflow, defineEffect, defineEffects, defineTask, defineTaskGlobal, defineTaskLocal, doTask, doUnless, doWhen, doWhile, filter, flatMap, flow, forEach, forkJoin, forkJoinSettled, fromPromise, fromPromiseFn, fromValue, getContext, getContextGlobal, getContextLocal, getContextOrUndefined, getContextOrUndefinedFromActiveInstance, getContextOrUndefinedLocal, getContextSafe, getContextSafeLocal, getCurrentSpan, getScheduler, groupBy, ift, inject, injectOptional, isAsyncDisposable, isBacktrackSignal, isDisposable, map, mapReduce, mapTask, memoize, mergeContexts, mergeIntoContext, noopLogger, once, parallel, parallelAll, parallelFrom, parallelFromAll, parallelFromSettled, parallelSettled, pick, pipe, pipeArguments, provide, provideGlobal, provideLocal, provideWithProxy, pure, race, raceFrom, recordMetric, recordSpanException, requireContextProperties, run, runGlobal, runLocal, runOnWorker, runStreamOnWorker, scheduler, sequence, sleep, some, startChildSpan, stream, streamAll, streamAny, streamSome, tap, tapError, traced, tryCatch, unless, useContextProperty, useState, validateContext, when, withCircuitBreaker, withContextEnhancement, withCounter, withDebounce, withDependencies, withDisposableResource, withErrorBoundary, withHandler, withHandlers, withName, withObservability, withPoll, withResource, withResources, withRetry, withScope, withSpan, withState, withThrottle, withTimeout, withTiming };
export type { AsyncDisposable, BaseContext, BatchingOptions, BracketConfig, CircuitBreakerOptions, Concurrency, ContextAwareFn, ContextProvider, ContextSchema, ContextTools, ContextValidator, ContextWithEffects, ContextWithHandlers, Ctor, DebounceOptions, DeepMutable, DefaultGlobalContext, DefineTaskOptions, Disposable, DoFunction, DoGenerator, Effect, EffectSuiteTools, EffectWithHelpers, EffectiveSystem, EffectsContext, EffectsSchema, EffectsSuite, EnhancedOverrides, Equals, EqualsWith, ErrorHandlerArray, ErrorHandlerTuple, ErrorTypeOptions, ExcludeTag, ExtractTag, Handlers, Has, Injectable, InjectionToken, IsomorphicWorker, Logger, MatchRecord, MergeContexts, MergeLeft, MergeRecord, MergeRight, MetricOptions, MonadicValue, Mutable, NoExcessProperties, NoInfer, NotFunction, ParallelOptions, ParallelResult, Pipeable, PipeableConstructor, PollOptions, ProvideImplOptions, ProvideStrategy, Remote, ResourceDefinition, RetryOptions, RunOptions, RunOptionsResult, RunOptionsThrow, Scheduler, Scope, SettledTaskResult, Simplify, SpanOptions, StateTools, Tags, Task, TaskIdentifier, TaskPriority, TelemetryContext, ThrottleOptions, TupleOf, TupleOfAtLeast, UnionToIntersection, Unwrap, ValueTransformFn, WithOptionalContext, WorkerOptions, WorkerTasks, WorkflowStep };
