import { n as Store } from "./@tanstack/hotkeys+[...].mjs";
import { t as EventClient } from "./@tanstack/devtools-event-client+[...].mjs";
//#region node_modules/.pnpm/@tanstack+pacer@0.21.0/node_modules/@tanstack/pacer/dist/utils.js
function isFunction(value) {
	return typeof value === "function";
}
function parseFunctionOrValue(value, ...args) {
	return isFunction(value) ? value(...args) : value;
}
//#endregion
//#region node_modules/.pnpm/@tanstack+pacer@0.21.0/node_modules/@tanstack/pacer/dist/event-client.js
var pacerDevtoolsInstancesByKey = /* @__PURE__ */ new Map();
function registerPacerDevtoolsInstance(key, instance) {
	pacerDevtoolsInstancesByKey.set(key, instance);
}
function cloneJsonSafe(value) {
	if (value === void 0) return;
	try {
		return JSON.parse(JSON.stringify(value));
	} catch {
		return null;
	}
}
function readStoreSnapshot(store) {
	if (typeof store.get === "function") return store.get();
	return store.state;
}
function toPacerDevtoolsWirePayload(instance) {
	return {
		key: instance.key,
		store: { state: cloneJsonSafe(readStoreSnapshot(instance.store)) },
		options: cloneJsonSafe(instance.options)
	};
}
var PacerEventClient = class extends EventClient {
	constructor(props) {
		super({
			pluginId: "pacer",
			debug: props?.debug,
			reconnectEveryMs: 1e3
		});
	}
};
var emitChange = (event, instance) => {
	const key = instance.key;
	if (!key) return;
	registerPacerDevtoolsInstance(key, instance);
	pacerEventClient.emit(event, toPacerDevtoolsWirePayload({
		...instance,
		key
	}));
};
var pacerEventClient = new PacerEventClient();
//#endregion
//#region node_modules/.pnpm/@tanstack+pacer@0.21.0/node_modules/@tanstack/pacer/dist/async-retryer.js
/**
* Creates the default initial state for an AsyncRetryer instance
* @returns The default state with all values reset to initial values
*/
function getDefaultAsyncRetryerState() {
	return {
		currentAttempt: 0,
		executionCount: 0,
		isExecuting: false,
		lastError: void 0,
		lastExecutionTime: 0,
		lastResult: void 0,
		status: "idle",
		totalExecutionTime: 0
	};
}
var defaultOptions$4 = {
	backoff: "exponential",
	baseWait: 1e3,
	maxWait: Infinity,
	enabled: true,
	jitter: 0,
	maxAttempts: 3,
	maxExecutionTime: Infinity,
	maxTotalExecutionTime: Infinity,
	throwOnError: "last"
};
/**
* Provides robust retry functionality for asynchronous functions, supporting configurable backoff strategies,
* attempt limits, timeout controls, and detailed state management. The AsyncRetryer class is designed to help you reliably
* execute async operations that may fail intermittently, such as network requests or database operations,
* by automatically retrying them according to your chosen policy.
*
* ## Retrying Concepts
*
* - **Retrying**: Automatically re-executes a failed async function up to a specified number of attempts.
*   Useful for handling transient errors (e.g., network flakiness, rate limits, temporary server issues).
* - **Backoff Strategies**: Controls the delay between retry attempts (default: `'exponential'`):
*   - `'exponential'`: Wait time doubles with each attempt (1s, 2s, 4s, ...) - **DEFAULT**
*   - `'linear'`: Wait time increases linearly (1s, 2s, 3s, ...)
*   - `'fixed'`: Waits a constant amount of time (`baseWait`) between each attempt
* - **Jitter**: Adds randomness to retry delays to prevent thundering herd problems (default: `0`).
*   Set to a value between 0-1 to apply that percentage of random variation to each delay.
* - **Max Wait**: Caps the maximum wait time between retries (default: `Infinity`).
*   Useful for preventing exponential backoff from growing too large (e.g., cap at 30s even if exponential would be 64s).
* - **Timeout Controls**: Set limits on execution time to prevent hanging operations:
*   - `maxExecutionTime`: Maximum time for a single function call (default: `Infinity`)
*   - `maxTotalExecutionTime`: Maximum time for the entire retry operation (default: `Infinity`)
* - **Abort & Cancellation**: Supports cancellation via an internal `AbortController`. Call `abort()` to stop retries.
*   Use `getAbortSignal()` to make your async function actually cancellable (e.g., with fetch requests).
*
* ## State Management
*
* Uses TanStack Store for fine-grained reactivity. State can be accessed via the `store.state` property.
*
* Available state properties:
* - `currentAttempt`: The current retry attempt number (0 when not executing)
* - `executionCount`: Total number of completed executions (successful or failed)
* - `isExecuting`: Whether the retryer is currently executing the function
* - `lastError`: The most recent error encountered during execution
* - `lastExecutionTime`: Timestamp of the last execution completion in milliseconds
* - `lastResult`: The result from the most recent successful execution
* - `status`: Current execution status ('disabled' | 'idle' | 'executing' | 'retrying')
* - `totalExecutionTime`: Total time spent executing (including retries) in milliseconds
*
* ## Error Handling
*
* The `throwOnError` option controls when errors are thrown (default: `'last'`):
* - `'last'`: Only throws the final error after all retries are exhausted - **DEFAULT**
* - `true`: Throws every error immediately (disables retrying)
* - `false`: Never throws errors, returns `undefined` instead
*
* Callbacks for lifecycle management:
* - `onAbort`: Called when execution is aborted (manually or due to timeouts)
* - `onError`: Called for every error (including during retries)
* - `onLastError`: Called only for the final error after all retries fail
* - `onRetry`: Called before each retry attempt
* - `onSettled`: Called after execution completes (success or failure) of each attempt
* - `onSuccess`: Called when execution succeeds
* - `onExecutionTimeout`: Called when a single execution attempt times out
* - `onTotalExecutionTimeout`: Called when the total execution time times out
*
* ## Usage
*
* - Use for async operations that may fail transiently and benefit from retrying.
* - Configure `maxAttempts`, `backoff`, `baseWait`, `maxWait`, and `jitter` to control retry behavior.
* - Set `maxExecutionTime` and `maxTotalExecutionTime` to prevent hanging operations.
* - Use `onAbort`, `onError`, `onLastError`, `onRetry`, `onSettled`, `onSuccess`, `onExecutionTimeout`, and `onTotalExecutionTimeout` for custom side effects.
* - Call `abort()` to cancel ongoing execution and pending retries.
* - Call `reset()` to reset state and cancel execution.
* - Use `getAbortSignal()` to make your async function cancellable.
* - Use dynamic options (functions) for `maxAttempts`, `baseWait`, and `enabled` based on retryer state.
*
* **Important:** This class is designed for single-use execution. Calling `execute()` multiple times
* on the same instance will abort previous executions. For multiple calls, create a new instance
* each time.
*
* @example
* ```typescript
* // Retry a fetch operation up to 5 times with exponential backoff, jitter, and timeouts
* const retryer = new AsyncRetryer(async (url: string) => {
*   const signal = retryer.getAbortSignal()
*   return await fetch(url, { signal })
* }, {
*   maxAttempts: 5,
*   backoff: 'exponential',
*   baseWait: 1000,
*   jitter: 0.1, // Add 10% random variation to prevent thundering herd
*   maxExecutionTime: 5000, // Abort individual calls after 5 seconds
*   maxTotalExecutionTime: 30000, // Abort entire operation after 30 seconds
*   onRetry: (attempt, error) => console.log(`Retry attempt ${attempt} after error:`, error),
*   onSuccess: (result) => console.log('Success:', result),
*   onError: (error) => console.error('Error:', error),
*   onLastError: (error) => console.error('All retries failed:', error),
* })
*
* const result = await retryer.execute('/api/data')
* ```
*
* @template TFn The async function type to be retried.
*/
var AsyncRetryer = class {
	#abortController;
	/**
	* Creates a new AsyncRetryer instance
	* @param fn The async function to retry
	* @param initialOptions Configuration options for the retryer
	*/
	constructor(fn, initialOptions = {}) {
		this.fn = fn;
		this.store = new Store(getDefaultAsyncRetryerState());
		this.#abortController = null;
		this.setOptions = (newOptions) => {
			this.options = {
				...this.options,
				...newOptions
			};
		};
		this.#setState = (newState) => {
			this.store.setState((state) => {
				const combinedState = {
					...state,
					...newState
				};
				const { isExecuting, currentAttempt } = combinedState;
				return {
					...combinedState,
					status: !this.#getEnabled() ? "disabled" : isExecuting && currentAttempt === 1 ? "executing" : isExecuting && currentAttempt > 1 ? "retrying" : "idle"
				};
			});
			emitChange("AsyncRetryer", this);
		};
		this.#getEnabled = () => {
			return !!parseFunctionOrValue(this.options.enabled, this);
		};
		this.#getMaxAttempts = () => {
			return parseFunctionOrValue(this.options.maxAttempts, this);
		};
		this.#getBaseWait = () => {
			return parseFunctionOrValue(this.options.baseWait, this);
		};
		this.#getMaxWait = () => {
			return parseFunctionOrValue(this.options.maxWait, this);
		};
		this.#calculateJitter = (waitTime) => {
			const jitterAmount = this.options.jitter;
			if (jitterAmount <= 0) return 0;
			try {
				const crypto = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
				if (crypto?.getRandomValues) {
					const array = new Uint32Array(1);
					crypto.getRandomValues(array);
					const randomFactor = array[0] / 4294967295 * 2 - 1;
					return Math.floor(waitTime * jitterAmount * randomFactor);
				}
			} catch {}
			return 0;
		};
		this.#calculateWait = (attempt) => {
			const baseWait = this.#getBaseWait();
			let waitTime;
			switch (this.options.backoff) {
				case "linear":
					waitTime = baseWait * attempt;
					break;
				case "exponential":
					waitTime = baseWait * Math.pow(2, attempt - 1);
					break;
				default:
					waitTime = baseWait;
					break;
			}
			waitTime = Math.min(waitTime, this.#getMaxWait());
			const jitter = this.#calculateJitter(waitTime);
			return Math.max(0, waitTime + jitter);
		};
		this.execute = async (...args) => {
			if (!this.#getEnabled()) return;
			this.abort("new-execution");
			const startTime = Date.now();
			let lastError;
			let result;
			this.#abortController = new AbortController();
			const signal = this.#abortController.signal;
			this.#setState({
				isExecuting: true,
				currentAttempt: 0,
				lastError: void 0
			});
			let totalTimeoutId;
			if (this.options.maxTotalExecutionTime !== Infinity) totalTimeoutId = setTimeout(() => {
				this.options.onTotalExecutionTimeout?.(this);
				this.abort("total-timeout");
			}, this.options.maxTotalExecutionTime);
			let isLastAttempt = false;
			for (let attempt = 1; attempt <= this.#getMaxAttempts(); attempt++) {
				isLastAttempt = attempt === this.#getMaxAttempts();
				this.#setState({ currentAttempt: attempt });
				try {
					if (signal.aborted) return;
					const currentTotalTime = Date.now() - startTime;
					if (this.options.maxTotalExecutionTime !== Infinity && currentTotalTime >= this.options.maxTotalExecutionTime) {
						this.options.onTotalExecutionTimeout?.(this);
						this.abort("total-timeout");
						return;
					}
					if (this.options.maxExecutionTime === Infinity) result = await this.fn(...args);
					else result = await Promise.race([this.fn(...args), new Promise((_, reject) => {
						const timeout = setTimeout(() => {
							this.options.onExecutionTimeout?.(this);
							this.abort("execution-timeout");
							reject(/* @__PURE__ */ new Error(`Execution timeout: ${this.options.maxExecutionTime}ms exceeded`));
						}, this.options.maxExecutionTime);
						signal.addEventListener("abort", () => {
							clearTimeout(timeout);
							reject(/* @__PURE__ */ new Error("Aborted"));
						}, { once: true });
					})]);
					if (signal.aborted) return;
					const totalTime = Date.now() - startTime;
					this.#setState({
						executionCount: this.store.state.executionCount + 1,
						isExecuting: false,
						lastExecutionTime: Date.now(),
						totalExecutionTime: totalTime,
						currentAttempt: 0,
						lastResult: result
					});
					this.options.onSuccess?.(result, args, this);
					return result;
				} catch (error) {
					if (error && typeof error === "object" && "name" in error && error.name === "AbortError") return;
					lastError = error instanceof Error ? error : new Error(String(error));
					this.#setState({ lastError });
					this.options.onError?.(lastError, args, this);
					if (attempt < this.#getMaxAttempts()) {
						this.options.onRetry?.(attempt, lastError, this);
						const wait = this.#calculateWait(attempt);
						if (wait > 0) {
							this.#setState({
								isExecuting: true,
								currentAttempt: attempt + 1
							});
							await new Promise((resolve) => {
								const timeout = setTimeout(() => {
									signal.removeEventListener("abort", onAbort);
									resolve();
								}, wait);
								const onAbort = () => {
									clearTimeout(timeout);
									signal.removeEventListener("abort", onAbort);
									resolve();
								};
								signal.addEventListener("abort", onAbort);
							});
							if (signal.aborted) return;
						}
					}
				} finally {
					this.options.onSettled?.(args, this);
				}
			}
			if (totalTimeoutId) clearTimeout(totalTimeoutId);
			this.#setState({ isExecuting: false });
			this.options.onLastError?.(lastError, this);
			this.options.onSettled?.(args, this);
			if (this.options.throwOnError === "last" && isLastAttempt || this.options.throwOnError === true) throw lastError;
		};
		this.getAbortSignal = () => {
			return this.#abortController?.signal ?? null;
		};
		this.abort = (reason = "manual") => {
			if (this.#abortController) {
				this.#abortController.abort();
				this.#abortController = null;
				this.#setState({ isExecuting: false });
				this.options.onAbort?.(reason, this);
			}
		};
		this.reset = () => {
			this.#setState(getDefaultAsyncRetryerState());
		};
		this.key = initialOptions.key;
		this.options = {
			...defaultOptions$4,
			...initialOptions,
			throwOnError: initialOptions.throwOnError ?? (initialOptions.onError ? false : defaultOptions$4.throwOnError)
		};
		this.#setState(this.options.initialState ?? {});
		if (this.key) pacerEventClient.on("d-AsyncRetryer", (event) => {
			if (event.payload.key !== this.key) return;
			this.#setState(event.payload.store.state);
			this.setOptions(event.payload.options);
		});
	}
	#setState;
	#getEnabled;
	#getMaxAttempts;
	#getBaseWait;
	#getMaxWait;
	#calculateJitter;
	#calculateWait;
};
//#endregion
//#region node_modules/.pnpm/@tanstack+pacer@0.21.0/node_modules/@tanstack/pacer/dist/async-debouncer.js
function getDefaultAsyncDebouncerState() {
	return {
		canLeadingExecute: true,
		errorCount: 0,
		isExecuting: false,
		isPending: false,
		lastArgs: void 0,
		lastResult: void 0,
		maybeExecuteCount: 0,
		settleCount: 0,
		status: "idle",
		successCount: 0
	};
}
var defaultOptions$3 = {
	asyncRetryerOptions: { maxAttempts: 1 },
	enabled: true,
	leading: false,
	trailing: true,
	wait: 0
};
/**
* A class that creates an async debounced function.
*
* Async vs Sync Versions:
* The async version provides advanced features over the sync Debouncer:
* - Returns promises that can be awaited for debounced function results
* - Built-in retry support via AsyncRetryer integration
* - Abort support to cancel in-flight executions
* - Cancel support to prevent pending executions from starting
* - Comprehensive error handling with onError callbacks and throwOnError control
* - Detailed execution tracking (success/error/settle counts)
*
* The sync Debouncer is lighter weight and simpler when you don't need async features,
* return values, or execution control.
*
* What is Debouncing?
* Debouncing ensures that a function is only executed after a specified delay has passed since its last invocation.
* Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
* or input changes where you only want to execute the handler after the events have stopped occurring.
*
* Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
* the function stops being called for the specified delay period.
*
* Error Handling:
* - If an `onError` handler is provided, it will be called with the error and debouncer instance
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
* - The error state can be checked using the underlying store
*
* State Management:
* - The debouncer uses a reactive store for state management
* - Use `initialState` to provide initial state values when creating the async debouncer
* - The state includes canLeadingExecute, error count, execution status, and success/settle counts
* - State can be accessed via the `store` property and its `state` getter
* - The store is reactive and will notify subscribers of state changes
*
* @example
* ```ts
* const asyncDebouncer = new AsyncDebouncer(async (value: string) => {
*   const results = await searchAPI(value);
*   return results; // Return value is preserved
* }, {
*   wait: 500,
*   onError: (error) => {
*     console.error('Search failed:', error);
*   }
* });
*
* // Called on each keystroke but only executes after 500ms of no typing
* // Returns the API response directly
* const results = await asyncDebouncer.maybeExecute(inputElement.value);
* ```
*/
var AsyncDebouncer = class {
	#timeoutId;
	#resolvePreviousPromise;
	constructor(fn, initialOptions) {
		this.fn = fn;
		this.store = new Store(getDefaultAsyncDebouncerState());
		this.asyncRetryers = /* @__PURE__ */ new Map();
		this.#timeoutId = null;
		this.#resolvePreviousPromise = null;
		this.setOptions = (newOptions) => {
			this.options = {
				...this.options,
				...newOptions
			};
			if (!this.#getEnabled()) this.cancel();
		};
		this.#setState = (newState) => {
			this.store.setState((state) => {
				const combinedState = {
					...state,
					...newState
				};
				const { isPending, isExecuting, settleCount } = combinedState;
				return {
					...combinedState,
					status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : isExecuting ? "executing" : settleCount > 0 ? "settled" : "idle"
				};
			});
			emitChange("AsyncDebouncer", this);
		};
		this.#getEnabled = () => {
			return !!parseFunctionOrValue(this.options.enabled, this);
		};
		this.#getWait = () => {
			return parseFunctionOrValue(this.options.wait, this);
		};
		this.maybeExecute = async (...args) => {
			if (!this.#getEnabled()) return void 0;
			this.#cancelPendingExecution();
			this.#setState({
				lastArgs: args,
				maybeExecuteCount: this.store.state.maybeExecuteCount + 1
			});
			if (this.options.leading && this.store.state.canLeadingExecute) {
				this.#setState({ canLeadingExecute: false });
				await this.#execute(...args);
				return this.store.state.lastResult;
			}
			if (this.options.trailing && this.#getEnabled()) this.#setState({ isPending: true });
			return new Promise((resolve, reject) => {
				this.#resolvePreviousPromise = resolve;
				this.#timeoutId = setTimeout(async () => {
					if (this.options.trailing && this.store.state.lastArgs) try {
						await this.#execute(...this.store.state.lastArgs);
					} catch (error) {
						reject(error);
					}
					this.#setState({ canLeadingExecute: true });
					this.#resolvePreviousPromise = null;
					resolve(this.store.state.lastResult);
				}, this.#getWait());
			});
		};
		this.#execute = async (...args) => {
			if (!this.#getEnabled()) return void 0;
			const currentMaybeExecuteCount = this.store.state.maybeExecuteCount + 1;
			try {
				this.#setState({ isExecuting: true });
				const currentAsyncRetryer = new AsyncRetryer(this.fn, {
					...this.options.asyncRetryerOptions,
					key: `${this.key}-retryer-${currentMaybeExecuteCount}`
				});
				this.asyncRetryers.set(currentMaybeExecuteCount, currentAsyncRetryer);
				const result = await currentAsyncRetryer.execute(...args);
				this.#setState({
					lastResult: result,
					successCount: this.store.state.successCount + 1
				});
				this.options.onSuccess?.(result, args, this);
			} catch (error) {
				this.#setState({ errorCount: this.store.state.errorCount + 1 });
				this.options.onError?.(error, args, this);
				if (this.options.throwOnError) throw error;
			} finally {
				this.asyncRetryers.delete(currentMaybeExecuteCount);
				this.#setState({
					isExecuting: false,
					isPending: false,
					lastArgs: void 0,
					settleCount: this.store.state.settleCount + 1
				});
				this.options.onSettled?.(args, this);
			}
			return this.store.state.lastResult;
		};
		this.flush = async () => {
			if (this.store.state.isPending && this.store.state.lastArgs) {
				const { lastArgs } = this.store.state;
				this.#cancelPendingExecution();
				return await this.#execute(...lastArgs);
			}
		};
		this.#resolvePreviousPromiseInternal = () => {
			if (this.#resolvePreviousPromise) {
				this.#resolvePreviousPromise(this.store.state.lastResult);
				this.#resolvePreviousPromise = null;
			}
		};
		this.#clearTimeout = () => {
			if (this.#timeoutId) {
				clearTimeout(this.#timeoutId);
				this.#timeoutId = null;
			}
		};
		this.#cancelPendingExecution = () => {
			this.#clearTimeout();
			this.#resolvePreviousPromiseInternal();
			this.#setState({
				isPending: false,
				lastArgs: void 0
			});
		};
		this.getAbortSignal = (maybeExecuteCount) => {
			const count = maybeExecuteCount ?? this.store.state.maybeExecuteCount;
			return this.asyncRetryers.get(count)?.getAbortSignal() ?? null;
		};
		this.abort = () => {
			this.asyncRetryers.forEach((retryer) => retryer.abort());
			this.asyncRetryers.clear();
			this.#setState({ isExecuting: false });
		};
		this.cancel = () => {
			this.#cancelPendingExecution();
			this.#setState({ canLeadingExecute: true });
		};
		this.reset = () => {
			this.#setState(getDefaultAsyncDebouncerState());
			this.asyncRetryers.forEach((retryer) => retryer.reset());
		};
		this.key = initialOptions.key;
		this.options = {
			...defaultOptions$3,
			...initialOptions,
			throwOnError: initialOptions.throwOnError ?? !initialOptions.onError
		};
		this.#setState(this.options.initialState ?? {});
		if (this.key) pacerEventClient.on("d-AsyncDebouncer", (event) => {
			if (event.payload.key !== this.key) return;
			this.#setState(event.payload.store.state);
			this.setOptions(event.payload.options);
		});
	}
	#setState;
	/**
	* Returns the current debouncer enabled state
	*/
	#getEnabled;
	/**
	* Returns the current debouncer wait state
	*/
	#getWait;
	#execute;
	#resolvePreviousPromiseInternal;
	#clearTimeout;
	/**
	* Internal cancel without resetting the leading execute state
	*/
	#cancelPendingExecution;
};
//#endregion
//#region node_modules/.pnpm/@tanstack+pacer@0.21.0/node_modules/@tanstack/pacer/dist/batcher.js
function getDefaultBatcherState() {
	return {
		executionCount: 0,
		isEmpty: true,
		isPending: false,
		totalItemsProcessed: 0,
		items: [],
		size: 0,
		status: "idle"
	};
}
var defaultOptions$2 = {
	getShouldExecute: () => false,
	maxSize: Infinity,
	started: true,
	wait: Infinity
};
/**
* A class that collects items and processes them in batches.
*
* Batching is a technique for grouping multiple operations together to be processed as a single unit.
* This synchronous version is lighter weight and often all you need - upgrade to AsyncBatcher when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
*
* The Batcher provides a flexible way to implement batching with configurable:
* - Maximum batch size (number of items per batch)
* - Time-based batching (process after X milliseconds)
* - Custom batch processing logic via getShouldExecute
* - Event callbacks for monitoring batch operations
*
* State Management:
* - Uses TanStack Store for reactive state management
* - Use `initialState` to provide initial state values when creating the batcher
* - Use `onExecute` callback to react to batch execution and implement custom logic
* - Use `onItemsChange` callback to react to items being added or removed from the batcher
* - The state includes batch execution count, total items processed, items, and running status
* - State can be accessed via `batcher.store.state` when using the class directly
* - When using framework adapters (React/Solid), state is accessed from `batcher.state`
*
* @example
* ```ts
* const batcher = new Batcher<number>(
*   (items) => console.log('Processing batch:', items),
*   {
*     maxSize: 5,
*     wait: 2000,
*     onExecute: (batch, batcher) => console.log('Batch executed:', batch)
*   }
* );
*
* batcher.addItem(1);
* batcher.addItem(2);
* // After 2 seconds or when 5 items are added, whichever comes first,
* // the batch will be processed
* // batcher.flush() // manually trigger a batch
* ```
*/
var Batcher = class {
	#timeoutId;
	constructor(fn, initialOptions) {
		this.fn = fn;
		this.store = new Store(getDefaultBatcherState());
		this.#timeoutId = null;
		this.setOptions = (newOptions) => {
			this.options = {
				...this.options,
				...newOptions
			};
		};
		this.#setState = (newState) => {
			this.store.setState((state) => {
				const combinedState = {
					...state,
					...newState
				};
				const { isPending, items } = combinedState;
				const size = items.length;
				const isEmpty = size === 0;
				return {
					...combinedState,
					isEmpty,
					size,
					status: isPending ? "pending" : "idle"
				};
			});
			emitChange("Batcher", this);
		};
		this.#getWait = () => {
			return parseFunctionOrValue(this.options.wait, this);
		};
		this.addItem = (item) => {
			this.#setState({
				items: [...this.store.state.items, item],
				isPending: this.options.wait !== Infinity
			});
			this.options.onItemsChange?.(this);
			if (this.store.state.items.length >= this.options.maxSize || this.options.getShouldExecute(this.store.state.items, this)) this.#execute();
			else if (this.options.wait !== Infinity) {
				this.#clearTimeout();
				this.#timeoutId = setTimeout(() => this.#execute(), this.#getWait());
			}
		};
		this.#execute = () => {
			if (this.store.state.items.length === 0) return;
			const batch = this.peekAllItems();
			this.clear();
			this.options.onItemsChange?.(this);
			this.fn(batch);
			this.#setState({
				executionCount: this.store.state.executionCount + 1,
				totalItemsProcessed: this.store.state.totalItemsProcessed + batch.length
			});
			this.options.onExecute?.(batch, this);
		};
		this.flush = () => {
			this.#clearTimeout();
			this.#execute();
		};
		this.peekAllItems = () => {
			return [...this.store.state.items];
		};
		this.#clearTimeout = () => {
			if (this.#timeoutId) {
				clearTimeout(this.#timeoutId);
				this.#timeoutId = null;
			}
		};
		this.clear = () => {
			this.#setState({
				items: [],
				isPending: false
			});
		};
		this.cancel = () => {
			this.#clearTimeout();
			this.#setState({ isPending: false });
		};
		this.reset = () => {
			this.#setState(getDefaultBatcherState());
			this.options.onItemsChange?.(this);
		};
		this.key = initialOptions.key;
		this.options = {
			...defaultOptions$2,
			...initialOptions
		};
		this.#setState(this.options.initialState ?? {});
		if (this.key) pacerEventClient.on("d-Batcher", (event) => {
			if (event.payload.key !== this.key) return;
			this.#setState(event.payload.store.state);
			this.setOptions(event.payload.options);
		});
	}
	#setState;
	#getWait;
	/**
	* Processes the current batch of items.
	* This method will automatically be triggered if the batcher is running and any of these conditions are met:
	* - The number of items reaches batchSize
	* - The wait duration has elapsed
	* - The getShouldExecute function returns true upon adding an item
	*
	* You can also call this method manually to process the current batch at any time.
	*/
	#execute;
	#clearTimeout;
};
//#endregion
//#region node_modules/.pnpm/@tanstack+pacer@0.21.0/node_modules/@tanstack/pacer/dist/debouncer.js
function getDefaultDebouncerState() {
	return {
		canLeadingExecute: true,
		executionCount: 0,
		isPending: false,
		lastArgs: void 0,
		status: "idle",
		maybeExecuteCount: 0
	};
}
var defaultOptions$1 = {
	enabled: true,
	leading: false,
	trailing: true,
	wait: 0
};
/**
* A class that creates a debounced function.
*
* Debouncing ensures that a function is only executed after a certain amount of time has passed
* since its last invocation. This is useful for handling frequent events like window resizing,
* scroll events, or input changes where you want to limit the rate of execution.
* This synchronous version is lighter weight and often all you need - upgrade to AsyncDebouncer when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
*
* The debounced function can be configured to execute either at the start of the delay period
* (leading edge) or at the end (trailing edge, default). Each new call during the wait period
* will reset the timer.
*
* State Management:
* - Uses TanStack Store for reactive state management
* - Use `initialState` to provide initial state values when creating the debouncer
* - Use `onExecute` callback to react to function execution and implement custom logic
* - The state includes canLeadingExecute, execution count, and isPending status
* - State can be accessed via `debouncer.store.state` when using the class directly
* - When using framework adapters (React/Solid), state is accessed from `debouncer.state`
*
* @example
* ```ts
* const debouncer = new Debouncer((value: string) => {
*   saveToDatabase(value);
* }, { wait: 500 });
*
* // Will only save after 500ms of no new input
* inputElement.addEventListener('input', () => {
*   debouncer.maybeExecute(inputElement.value);
* });
* ```
*/
var Debouncer = class {
	#timeoutId;
	constructor(fn, initialOptions) {
		this.fn = fn;
		this.store = new Store(getDefaultDebouncerState());
		this.setOptions = (newOptions) => {
			this.options = {
				...this.options,
				...newOptions
			};
			if (!this.#getEnabled()) this.cancel();
		};
		this.#setState = (newState) => {
			this.store.setState((state) => {
				const combinedState = {
					...state,
					...newState
				};
				const { isPending } = combinedState;
				return {
					...combinedState,
					status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
				};
			});
			emitChange("Debouncer", this);
		};
		this.#getEnabled = () => {
			return !!parseFunctionOrValue(this.options.enabled, this);
		};
		this.#getWait = () => {
			return parseFunctionOrValue(this.options.wait, this);
		};
		this.maybeExecute = (...args) => {
			if (!this.#getEnabled()) return void 0;
			this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
			let _didLeadingExecute = false;
			if (this.options.leading && this.store.state.canLeadingExecute) {
				this.#setState({ canLeadingExecute: false });
				_didLeadingExecute = true;
				this.#execute(...args);
			}
			if (this.options.trailing) this.#setState({
				isPending: true,
				lastArgs: args
			});
			if (this.#timeoutId) clearTimeout(this.#timeoutId);
			this.#timeoutId = setTimeout(() => {
				this.#setState({ canLeadingExecute: true });
				if (this.options.trailing && !_didLeadingExecute) this.#execute(...args);
			}, this.#getWait());
		};
		this.#execute = (...args) => {
			if (!this.#getEnabled()) return void 0;
			this.fn(...args);
			this.#setState({
				executionCount: this.store.state.executionCount + 1,
				isPending: false,
				lastArgs: void 0
			});
			this.options.onExecute?.(args, this);
		};
		this.flush = () => {
			if (this.store.state.isPending && this.store.state.lastArgs) {
				this.#clearTimeout();
				this.#execute(...this.store.state.lastArgs);
			}
		};
		this.#clearTimeout = () => {
			if (this.#timeoutId) {
				clearTimeout(this.#timeoutId);
				this.#timeoutId = void 0;
			}
		};
		this.cancel = () => {
			this.#clearTimeout();
			this.#setState({
				canLeadingExecute: true,
				isPending: false
			});
		};
		this.reset = () => {
			this.#setState(getDefaultDebouncerState());
		};
		this.key = initialOptions.key;
		this.options = {
			...defaultOptions$1,
			...initialOptions
		};
		this.#setState(this.options.initialState ?? {});
		if (this.key) pacerEventClient.on("d-Debouncer", (event) => {
			if (event.payload.key !== this.key) return;
			this.#setState(event.payload.store.state);
			this.setOptions(event.payload.options);
		});
	}
	#setState;
	/**
	* Returns the current enabled state of the debouncer
	*/
	#getEnabled;
	/**
	* Returns the current wait time in milliseconds
	*/
	#getWait;
	#execute;
	#clearTimeout;
};
//#endregion
//#region node_modules/.pnpm/@tanstack+pacer@0.21.0/node_modules/@tanstack/pacer/dist/throttler.js
function getDefaultThrottlerState() {
	return {
		executionCount: 0,
		isPending: false,
		lastArgs: void 0,
		lastExecutionTime: 0,
		nextExecutionTime: 0,
		status: "idle",
		maybeExecuteCount: 0
	};
}
var defaultOptions = {
	enabled: true,
	leading: true,
	trailing: true,
	wait: 0
};
/**
* A class that creates a throttled function.
*
* Throttling ensures a function is called at most once within a specified time window.
* Unlike debouncing which waits for a pause in calls, throttling guarantees consistent
* execution timing regardless of call frequency.
* This synchronous version is lighter weight and often all you need - upgrade to AsyncThrottler when you need promises, retry support, abort/cancel capabilities, or advanced error handling.
*
* Supports both leading and trailing edge execution:
* - Leading: Execute immediately on first call (default: true)
* - Trailing: Execute after wait period if called during throttle (default: true)
*
* For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
*
* State Management:
* - Uses TanStack Store for reactive state management
* - Use `initialState` to provide initial state values when creating the throttler
* - Use `onExecute` callback to react to function execution and implement custom logic
* - The state includes execution count, last execution time, pending status, and more
* - State can be accessed via `throttler.store.state` when using the class directly
* - When using framework adapters (React/Solid), state is accessed from `throttler.state`
*
* @example
* ```ts
* const throttler = new Throttler(
*   (id: string) => api.getData(id),
*   { wait: 1000 } // Execute at most once per second
* );
*
* // First call executes immediately
* throttler.maybeExecute('123');
*
* // Subsequent calls within 1000ms are throttled
* throttler.maybeExecute('123'); // Throttled
* ```
*/
var Throttler = class {
	#timeoutId;
	constructor(fn, initialOptions) {
		this.fn = fn;
		this.store = new Store(getDefaultThrottlerState());
		this.setOptions = (newOptions) => {
			this.options = {
				...this.options,
				...newOptions
			};
			if (!this.#getEnabled()) this.cancel();
		};
		this.#setState = (newState) => {
			this.store.setState((state) => {
				const combinedState = {
					...state,
					...newState
				};
				const { isPending } = combinedState;
				return {
					...combinedState,
					status: !this.#getEnabled() ? "disabled" : isPending ? "pending" : "idle"
				};
			});
			emitChange("Throttler", this);
		};
		this.#getEnabled = () => {
			return !!parseFunctionOrValue(this.options.enabled, this);
		};
		this.#getWait = () => {
			return parseFunctionOrValue(this.options.wait, this);
		};
		this.maybeExecute = (...args) => {
			this.#setState({ maybeExecuteCount: this.store.state.maybeExecuteCount + 1 });
			const now = Date.now();
			const timeSinceLastExecution = now - this.store.state.lastExecutionTime;
			const wait = this.#getWait();
			if (this.options.leading && timeSinceLastExecution >= wait) this.#execute(...args);
			else {
				this.#setState({ lastArgs: args });
				if (!this.#timeoutId && this.options.trailing) {
					const timeoutDuration = wait - (this.store.state.lastExecutionTime ? now - this.store.state.lastExecutionTime : 0);
					this.#setState({ isPending: true });
					this.#timeoutId = setTimeout(() => {
						const { lastArgs } = this.store.state;
						if (lastArgs !== void 0) this.#execute(...lastArgs);
					}, timeoutDuration);
				}
			}
		};
		this.#execute = (...args) => {
			if (!this.#getEnabled()) return;
			this.fn(...args);
			const lastExecutionTime = Date.now();
			const nextExecutionTime = lastExecutionTime + this.#getWait();
			this.#clearTimeout();
			this.#setState({
				executionCount: this.store.state.executionCount + 1,
				lastExecutionTime,
				nextExecutionTime,
				isPending: false,
				lastArgs: void 0
			});
			this.options.onExecute?.(args, this);
			setTimeout(() => {
				if (!this.store.state.isPending) this.#setState({ nextExecutionTime: void 0 });
			}, this.#getWait());
		};
		this.flush = () => {
			if (this.store.state.isPending && this.store.state.lastArgs) this.#execute(...this.store.state.lastArgs);
		};
		this.#clearTimeout = () => {
			if (this.#timeoutId) {
				clearTimeout(this.#timeoutId);
				this.#timeoutId = void 0;
			}
		};
		this.cancel = () => {
			this.#clearTimeout();
			this.#setState({
				lastArgs: void 0,
				isPending: false
			});
		};
		this.reset = () => {
			this.#setState(getDefaultThrottlerState());
		};
		this.key = initialOptions.key;
		this.options = {
			...defaultOptions,
			...initialOptions
		};
		this.#setState(this.options.initialState ?? {});
		if (this.key) pacerEventClient.on("d-Throttler", (event) => {
			if (event.payload.key !== this.key) return;
			this.#setState(event.payload.store.state);
			this.setOptions(event.payload.options);
		});
	}
	#setState;
	#getEnabled;
	#getWait;
	#execute;
	#clearTimeout;
};
//#endregion
export { AsyncDebouncer as i, Debouncer as n, Batcher as r, Throttler as t };
