/**
* TypeScript type representation of the standard `setTimeout` function.
*
* This type is isolated in a separate file to avoid referencing the global
* `setTimeout` directly in the main bundle, which would automatically add a
* Node.js reference (`/// `) to the bundle.
*
* @remarks
* The separation is necessary because using `typeof setTimeout` in the same
* file where `setTimeout` is referenced as a variable in the module scope
* would cause TypeScript to add Node.js type references, potentially creating
* issues in non-Node environments.
* @example
* // How to use this type
* import { SetTimeout } from '@reatom/core'
*
* function setupTimer(customTimeout: SetTimeout) {
* return customTimeout(() => console.log('Timer fired'), 1000)
* }
*
* @public
* @see {@link https://github.com/reatom/reatom/issues/983} for the original issue and discussion
*/import { StandardSchemaV1 } from "@standard-schema/spec";
//#region src/setTimeout.d.ts
type SetTimeout = typeof setTimeout;
//#endregion
//#region src/utils.d.ts
/**
* Generic function type representing any function that takes any parameters and
* returns any value. Used throughout Reatom for typing function parameters and
* callbacks.
*/
interface Fn {
(...params: any[]): any;
}
/**
* Type alias for Record for brevity. Represents an object with
* string keys and values of type T.
*
* @template T - The type of values in the record (defaults to any)
*/
type Rec = Record;
/**
* Function interface for unsubscribing from subscriptions. Used consistently
* throughout Reatom for cleanup functions.
*/
interface Unsubscribe {
(): void;
}
/**
* Type representing different possible return values from observable
* subscription methods. Supports both function-based unsubscribers and objects
* with unsubscribe methods.
*/
type MaybeUnsubscribe = void | Exclude<{}, Fn> | Unsubscribe | {
unsubscribe: Unsubscribe;
};
/**
* Utility type that converts properties with undefined values to optional
* properties. Makes properties with object or null values required, while
* making other properties optional.
*
* @template T - The object type to transform
*/
type UndefinedToOptional = Partial & PickValues;
/**
* Union type of all JavaScript falsy values except for NaN. Includes: false, 0,
* empty string, null, and undefined.
*
* @see https://stackoverflow.com/a/51390763
*/
type Falsy = false | 0 | '' | null | undefined;
/**
* Removes named generics to produce a plain type representation. Preserves
* function signatures and object structure while eliminating generic parameter
* names.
*
* This is useful for presenting cleaner types in documentation and error
* messages.
*
* @template Intersection - The type to convert to a plain representation
*/
type Plain = Intersection extends ((...params: infer I) => infer O) ? ((...params: I) => O) & { [Key in keyof Intersection]: Intersection[Key] } : Intersection extends (new (...params: any[]) => any) ? Intersection : Intersection extends object ? { [Key in keyof Intersection]: Intersection[Key] } : Intersection;
/**
* Creates a shallow clone type of T. Useful for creating a new type that has
* the same shape but is a distinct type.
*
* @template T - The type to create a shallow clone of
*/
type Shallow = { [K in keyof T]: T[K] } & {};
/**
* Represents a constructor function that can be instantiated with the new
* operator.
*
* @template ReturnType - The type of object that will be created when
* instantiated
*/
interface Newable {
new (...params: any[]): ReturnType;
}
/**
* Extracts the union type of all values in an object type.
*
* @template T - The object type to extract values from
*/
type Values = T[keyof T];
/**
* Extracts keys from type T where the corresponding value does not extend type
* V.
*
* @template T - The object type to extract keys from
* @template V - The value type to exclude
*/
type OmitValuesKeys = Values<{ [K in keyof T]: T[K] extends V ? never : K }>;
/**
* Creates a type with all properties from T except those with values extending
* V.
*
* @template T - The object type to filter properties from
* @template V - The value type to exclude
*/
type OmitValues = { [K in OmitValuesKeys]: T[K] };
/**
* Extracts keys from type T where the corresponding value extends type V.
*
* @template T - The object type to extract keys from
* @template V - The value type to include
*/
type PickValuesKeys = Values<{ [K in keyof T]: T[K] extends V ? K : never }>;
/**
* Creates a type with only properties from T with values extending V.
*
* @template T - The object type to filter properties from
* @template V - The value type to include
*/
type PickValues = { [K in PickValuesKeys]: T[K] };
/**
* Flattens a function type with up to 5 overloads into a single function
* signature. This creates a union of the parameter types and return types.
*
* Useful for generic type handling of overloaded functions.
*
* @template T - The overloaded function type to flatten
*/
type Overloads = T extends {
(...params: infer Overload1Params): infer Return1;
(...params: infer Overload2Params): infer Return2;
(...params: infer Overload3Params): infer Return3;
(...params: infer Overload4Params): infer Return4;
(...params: infer Overload5Params): infer Return5;
} ? (...params: Overload1Params | Overload2Params | Overload3Params | Overload4Params | Overload5Params) => Return1 | Return2 | Return3 | Return4 | Return5 : never;
/**
* Extracts the parameters type from an overloaded function. Returns a union of
* all possible parameter tuples.
*
* @template T - The overloaded function type to extract parameters from
*/
type OverloadParameters = Parameters>;
/**
* Asserts that a value is truthy, throwing an error if it's falsy. This is a
* TypeScript type assertion function that helps with type narrowing.
*
* @param value - The value to check
* @param message - The error message to use if the assertion fails
* @param ErrorConstructor - Optional custom error constructor to use (defaults
* to Error)
* @throws {Error} Throws an error with the provided message if value is falsy
*/
declare function assert(value: unknown, message: string, ErrorConstructor?: Newable): asserts value;
/**
* No-operation function that accepts any parameters and returns undefined.
* Useful as a default callback or for stubbing functionality.
*/
declare const noop: (...params: any[]) => any;
/**
* Identity function that returns the first argument unchanged. Can accept
* additional parameters but ignores them.
*
* @template T - The type of value being passed through
* @param value - The value to return
* @returns The same value that was passed in
*/
declare const identity: (value: T, ...a: any[]) => T;
/**
* Creates a promise that resolves after the specified number of milliseconds.
* Useful for creating delays in async functions.
*
* @param ms - The number of milliseconds to sleep (defaults to 0)
* @returns A promise that resolves after the specified delay
*/
declare const sleep: (ms?: number) => Promise;
/**
* Type guard that checks if a value is an object (non-null and typeof
* 'object'). Provides advanced type narrowing to either the original object
* type or a generic object type.
*
* @template T - The type of value being checked
* @param thing - The value to check
* @returns True if the value is a non-null object, false otherwise
*/
declare const isObject: (thing: T) => thing is T extends Record ? T : Record;
/**
* Type guard that checks if a value is a plain object (a simple object literal
* or created with Object.create(null)). Verifies that the object either has no
* prototype or its prototype is Object.prototype.
*
* @param thing - The value to check
* @returns True if the value is a plain object, false otherwise
*/
declare const isRec: (thing: unknown) => thing is Record;
/**
* Performs a shallow equality comparison between two values. Handles
* primitives, objects, dates, regular expressions, arrays, maps, and sets.
*
* For iterables, compares each item in sequence for equality. For objects,
* compares direct property values but not nested objects deeply.
*
* @param a - First value to compare
* @param b - Second value to compare
* @param is - Optional comparison function to use for individual values
* (defaults to Object.is)
* @returns True if the values are shallowly equal, false otherwise
*/
declare const isShallowEqual: (a: any, b: any, is?: (value1: any, value2: any) => boolean) => any;
/**
* Performs a deep equality comparison between two values. Recursively compares
* nested objects and arrays while properly handling cyclic references.
*
* Handles primitives, objects, dates, regular expressions, arrays, maps, and
* sets. Uses a WeakMap to track visited objects to avoid infinite recursion
* with circular references.
*
* @param a - First value to compare
* @param b - Second value to compare
* @returns True if the values are deeply equal, false otherwise
*/
declare const isDeepEqual: (a: any, b: any) => any;
/**
* Type utility for merging up to four types with proper type safety. Properties
* from later types override properties from earlier types. Preserves function
* signatures from T1 if it's a function type.
*
* @template T1 - First type to merge
* @template T2 - Second type to merge, overrides T1 properties
* @template T3 - Optional third type to merge, overrides T1 and T2 properties
* @template T4 - Optional fourth type to merge, overrides T1, T2, and T3
* properties
*/
type Assign = Plain<(T1 extends ((...params: infer I) => infer O) ? (...params: I) => O : {}) & Omit & Omit & Omit & T4>;
/**
* Type-safe version of Object.assign that properly handles type merging. Unlike
* standard Object.assign typing, properties with the same name are replaced
* rather than becoming a union type.
*
* @template T1 - Type of the target object
* @template T2 - Type of the first source object
* @template T3 - Type of the optional second source object
* @template T4 - Type of the optional third source object
* @returns A new object with merged properties
*/
declare const assign: {
(a1: T1, a2: T2): Assign;
(a1: T1, a2: T2, a3?: T3): Assign;
(a1: T1, a2: T2, a3?: T3, a4?: T4): Assign;
};
/**
* Creates a new object with merged properties from all provided objects.
* Similar to Object.assign but always creates a new object rather than mutating
* the first argument.
*
* @example
* // Creates a new object: { a: 1, b: 2, c: 3 }
* const obj = merge({ a: 1 }, { b: 2 }, { c: 3 })
*
* @returns A new object with all properties from the provided objects
*/
declare const merge: typeof assign;
/**
* Type-safe version of Object.keys that preserves the key type information.
* Returns an array of keys with the correct type for the object.
*
* @template T - The object type
* @param thing - The object to get keys from
* @returns An array of the object's keys with proper typing
*/
declare const keys: {
(thing: T): Array;
};
/**
* Type-safe version of Object.entries that preserves key and value type
* information. Returns an array of key-value pairs with correct types.
*
* @template T - The object type
* @param thing - The object to get entries from
* @returns An array of [key, value] pairs with proper typing
*/
declare const entries: {
(thing: T): Array<[keyof T, T[keyof T]]>;
};
/**
* Type-safe version of Object.fromEntries that preserves key and value type
* information. Creates an object from an iterable of key-value pairs.
*
* @template K - The key type
* @template V - The value type
* @param entries - An iterable of [key, value] pairs
* @returns An object with the specified keys and values
*/
declare const fromEntries: {
(entries: Iterable): Record;
};
/**
* Creates a new object with only the specified keys from the original object.
*
* @example
* const user = { id: 1, name: 'Alice', email: 'alice@example.com' }
* const userInfo = pick(user, ['name', 'email'])
* // Result: { name: 'Alice', email: 'alice@example.com' }
*
* @template T - The source object type
* @template K - The keys to pick from the object
* @param target - The source object
* @param keys - Array of keys to include in the result
* @returns A new object containing only the specified keys and their values
*/
declare const pick: (target: T, keys: Array) => Plain>;
/**
* Creates a new object excluding the specified keys from the original object.
*
* @example
* const user = { id: 1, name: 'Alice', password: 'secret' }
* const safeUser = omit(user, ['password'])
* // Result: { id: 1, name: 'Alice' }
*
* @template T - The source object type
* @template K - The keys to omit from the object
* @param target - The source object
* @param keys - Array of keys to exclude from the result
* @returns A new object containing all keys except the specified ones
*/
declare const omit: (target: T, keys: Array) => Plain>;
/**
* Creates a deep clone of a value using JSON serialization/deserialization.
* This is a type-safe shortcut to `JSON.parse(JSON.stringify(value))`.
*
* Note: This has limitations with circular references, functions, symbols, and
* special objects like Date (converts to string). Consider using the native
* structuredClone when available.
*
* @template T - The type of value being cloned
* @param value - The value to clone
* @returns A deep clone of the input value
* @see https://developer.mozilla.org/en-US/docs/Web/API/structuredClone
*/
declare const jsonClone: (value: T) => T;
/**
* Generates a random integer between min and max (inclusive).
*
* @param min - The minimum integer value (defaults to 0)
* @param max - The maximum integer value (defaults to Number.MAX_SAFE_INTEGER -
* 1)
* @returns A random integer between min and max
*/
declare const random: (min?: number, max?: number) => number;
/**
* Replaces the default random number generator with a custom implementation.
* Useful for testing to provide deterministic "random" values.
*
* @example
* // Set up deterministic random values for testing
* const restore = mockRandom(() => 42)
* console.log(random()) // Always returns 42
* restore() // Back to normal random behavior
*
* @param fn - The custom random function to use
* @returns A restore function that reverts to the original random
* implementation when called
*/
declare const mockRandom: (fn: typeof random) => () => void;
/**
* Asserts that a value is not null or undefined. Throws a TypeError if the
* value is null or undefined. Also serves as a type guard to narrow the type to
* non-nullable.
*
* @example
* const name = nonNullable(user.name) // TypeScript knows name is not null or undefined
*
* @template T - The type of value to check
* @param value - The value to check
* @param message - Optional custom error message
* @returns The input value if it's not null or undefined
* @throws {TypeError} If the value is null or undefined
*/
declare const nonNullable: (value: T, message?: string) => NonNullable;
/**
* Converts any JavaScript value to a stable string representation. Handles
* complex data structures and edge cases that JSON.stringify cannot manage.
*
* Provides special handling for:
*
* - Circular references
* - Maps and Sets
* - Symbols
* - Functions
* - Custom class instances
* - Regular objects (with sorted keys for stability)
*
* @example
* // Handles circular references
* const obj = { name: 'test' }
* obj.self = obj
* const key = toStringKey(obj) // No infinite recursion!
*
* // Stable representation of objects (key order doesn't matter)
* toStringKey({ a: 1, b: 2 }) === toStringKey({ b: 2, a: 1 }) // true
*
* @param thing - The value to convert to a string
* @param immutable - Whether to memoize results for complex objects (defaults
* to true)
* @returns A string representation of the value
*/
declare const toStringKey: (thing: any, immutable?: boolean) => string;
/**
* Interface extending DOMException for abort-specific error handling. Used to
* represent errors triggered by AbortController signal aborts.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortController
*/
interface AbortError extends DOMException {
name: 'AbortError';
}
/**
* Converts any value to an AbortError. If the value is already an AbortError,
* it will be returned as is. Otherwise, creates a new AbortError with
* appropriate information.
*
* Handles different environments by using DOMException when available or
* falling back to regular Error with name set to 'AbortError'.
*
* @param reason - The value to convert to an AbortError
* @returns An AbortError instance
*/
declare const toAbortError: (reason: any) => AbortError;
/**
* Checks if an AbortController is aborted and throws an AbortError if it is.
* Useful for quick abort checks at the beginning of async operations.
*
* @param controller - The AbortController to check (can be undefined, null or
* void)
* @throws {AbortError} If the controller's signal is aborted
*/
declare const throwIfAborted: (controller?: void | AbortController | null | undefined) => void;
/**
* Type guard that checks if a value is an AbortError.
*
* @param thing - The value to check
* @returns True if the value is an AbortError, false otherwise
*/
declare const isAbort: (thing: any) => thing is AbortError;
/**
* Creates and throws an AbortError with the provided message. Optionally aborts
* the provided controller with the same error.
*
* @param message - The error message
* @param controller - Optional AbortController to abort
* @throws {AbortError} Always throws the created AbortError
*/
declare const throwAbort: (message?: string, controller?: AbortController) => never;
declare const setTimeout$1: SetTimeout;
/**
* Maximum safe integer value for setTimeout delay. Any timeout value larger
* than this may cause overflow issues in some browsers.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value
*/
declare const MAX_SAFE_TIMEOUT: number;
/**
* Represents a constructor function that can be instantiated with the new
* operator.
*
* @template T - The type of object that will be created when instantiated
*/
type Constructor = new (...args: any[]) => T;
/**
* Detects whether the code is running in a browser environment. Checks for the
* existence of window and document objects.
*
* @returns True if running in a browser environment, false otherwise
*/
declare const isBrowser: () => boolean;
/**
* Creates a Promise and returns it along with its resolve and reject functions.
* This utility is similar to the upcoming `Promise.withResolvers()` static
* method. It allows for manual control over a Promise's settlement from outside
* its constructor.
*
* @example
* const { promise, resolve, reject } = withResolvers()
*
* promise
* .then((value) => console.log('Resolved:', value))
* .catch((error) => console.error('Rejected:', error))
*
* // Sometime later, or in a different part of the code:
* if (Math.random() > 0.5) {
* resolve('Success!')
* } else {
* reject(new Error('Failed!'))
* }
*
* @template T - The type of the value the promise will resolve with.
* @property {Promise} promise - The created Promise.
* @property {(value: T) => void} resolve - A function to resolve the promise
* with a value of type T.
* @property {(reason?: any) => void} reject - A function to reject the promise
* with an optional reason.
* @returns An object containing the `promise`, and its `resolve` and `reject`
* functions.
*/
declare const withResolvers: () => {
promise: Promise;
resolve: (value: T) => void;
reject: (reason?: any) => void;
};
/**
* Removes the first occurrence of an item from an array in a single iteration.
* Mutates the array in place by splicing out the found element.
*
* More efficient than using `indexOf` + `splice` as it only walks the array
* once.
*
* @example
* const items = [1, 2, 3, 4]
* removeItem(items, 3) // returns true, items is now [1, 2, 4]
* removeItem(items, 5) // returns false, items unchanged
*
* @template T - The type of elements in the array
* @param array - The array to remove the item from
* @param item - The item to remove (compared using strict equality)
* @returns True if the item was found and removed, false otherwise
*/
declare const removeItem: (array: T[], item: T) => boolean;
//#endregion
//#region src/core/action.d.ts
interface ActionCall {
params: Params;
payload: Payload;
}
/** Autoclearable array of processed events */
interface ActionState extends Array> {}
/** Logic container with atom features */
interface Action extends AtomLike, Params, Payload> {
subscribe: (cb?: (payload: Payload, params: Params) => any) => Unsubscribe;
}
/** Action type that supports all overloads of the original function */
type GAction = T & Action, ReturnType>;
/**
* Type guard to check if a value is a Reatom action.
*
* This function determines whether the given value is an action by checking if
* it's an atom with non-reactive behavior (actions are non-reactive atoms).
*
* @param target - The value to check
* @returns `true` if the value is a Reatom action, `false` otherwise
*/
declare let isAction: (target: unknown) => target is Action;
/**
* Creates an extension that adds middleware to an action, wrapping only the
* call function, not the state.
*
* Unlike `withMiddleware`, which wraps the entire middleware chain (including
* the state update), `withActionMiddleware` wraps only the call function that
* gets passed to `actionMiddleware`. This allows you to decorate the action's
* execution logic without interfering with the action's state management.
*
* @example
* // Creating a retry middleware for actions
* const withRetry = (maxAttempts: number) =>
* withActionMiddleware((target) => {
* return (next, ...params) => {
* let attempts = 0
* while (attempts < maxAttempts) {
* try {
* return next(...params)
* } catch (error) {
* attempts++
* if (attempts >= maxAttempts) throw error
* }
* }
* }
* })
*
* // Using the middleware
* const fetchData = action(async () => {
* const response = await fetch('/api/data')
* return response.json()
* }).extend(withRetry(3))
*
* @template Target - The type of action the middleware will be applied to
* @param cb - A function that receives the target action and returns a
* middleware function that wraps the call
* @returns An extension that applies the middleware when used with .extend()
*/
declare let withActionMiddleware: {
(cb: (target: Action) => (next: Fn, ...params: Params) => Payload): Ext>;
};
/**
* Creates a logic and side effect container.
*
* Actions are used to encapsulate complex logic, perform side effects (like API
* calls), and orchestrate multiple state updates. Unlike atoms, actions are
* meant to be called with parameters and can return values.
*
* Actions also have atom-like features (subscribe, extend) and track their call
* history.
*
* @example
* // Create an action that fetches data and updates state
* const fetchUserData = action(async (userId: string) => {
* const response = await wrap(fetch(`/api/users/${userId}`))
* const data = await wrap(response.json())
*
* // Update state atoms with the fetched data
* userName(data.name)
* userEmail(data.email)
*
* return data // Actions can return values
* }, 'fetchUserData')
*
* // Call the action
* fetchUserData('user123')
*
* @template Params - The parameter types the action accepts
* @template Payload - The return type of the action
* @param cb - The function containing the action's logic
* @param name - Optional name for debugging purposes
* @returns An action instance that can be called with the specified parameters
*/
declare function action any>(cb: T, name?: string): GAction;
declare function action(cb: (...params: Params) => Payload, name?: string): Action;
//#endregion
//#region src/core/actions.d.ts
/**
* Type representing a set of methods converted to Reatom actions.
*
* This type maps each method in the original record to a corresponding Reatom
* action with the same parameter and return types.
*
* @template Methods - Record of functions to be converted to actions
*/
type ActionsExt> = { [K in keyof Methods]: Methods[K] extends ((...params: infer Params) => infer Payload) ? Action : never };
/**
* Extension that binds actions to an atom or action as methods.
*
* This extension adds methods to an atom or action by converting them to Reatom
* actions. Each method is converted to an action with the same name and bound
* to the target. The name of each action will be prefixed with the target's
* name for better debugging.
*
* @example
* const counter = atom(0, 'counter').extend(
* withActions({
* increment: (amount = 1) => counter((prev) => prev + amount),
* decrement: (amount = 1) => counter((prev) => prev - amount),
* reset: () => counter(0),
* }),
* )
*
* counter.increment(5) // Can now call these methods directly
* counter.reset()
*
* @example
* const counter = atom(0, 'counter').extend(
* withActions((target) => ({
* increment: (amount = 1) => target.set((prev) => prev + amount),
* decrement: (amount = 1) => target.set((prev) => prev - amount),
* reset: () => target.set(0),
* })),
* )
*
* @template Target - The atom or action being extended
* @template Methods - Record of functions to convert to actions
* @param options - Either a record of methods or a function that creates
* methods given the target
* @returns An extension that adds the methods as actions
* @throws {ReatomError} If a method name collides with an existing property on
* the target
*/
declare function withActions>(options: Methods | ((target: Target) => Methods)): (target: Target) => ActionsExt;
//#endregion
//#region src/extensions/withAbort.d.ts
interface AbortExt {
abort: Action<[reason?: any]>;
}
/**
* Extension to add abort handling to actions and computed atoms.
*
* @example
* // last-in-win: only the last request matters
* const fetchUser = action(async (id: number) => {
* const response = await wrap(fetch(`/api/user/${id}`))
* return response.json()
* }).extend(withAbort())
*
* fetchUser(1) // will be aborted
* fetchUser(2) // will be aborted
* fetchUser(3) // this one wins
*
* @example
* // first-in-win: ignore subsequent calls until the first completes
* const fetchOnce = action(async () => {
* await wrap(fetch('/api/data'))
* }).extend(withAbort('first-in-win'))
*
* fetchOnce() // runs
* fetchOnce() // ignored, returns previous promise
* fetchOnce() // ignored, returns previous promise
*
* @example
* // manual with manual abort (useful for polling/long-running tasks)
* const poll = action(async () => {
* while (true) {
* await wrap(sleep(1000))
* doSome()
* }
* }).extend(withAbort('manual'))
*
* // start
* poll()
*
* // stop
* poll.abort()
*
* @param strategy - The abort strategy to use:
*
* - `'last-in-win'` (default): Aborts previous concurrent calls when a new one
* starts
* - `'first-in-win'`: Ignores new calls while a previous one is still running
* - `'manual'`: No automatic abort, just adds the `abort` action for manual
* control
*/
declare let withAbort: (strategy?: "last-in-win" | "first-in-win" | "finally" | "manual") => AssignerExt;
//#endregion
//#region src/persist/index.d.ts
interface PersistRecord {
data: Snapshot;
id: number;
timestamp: number;
version: number | string;
/** Time stamp after which the record is cleared. */
to: number;
}
declare let isPersistRecord: (value: unknown) => value is PersistRecord;
declare function assertPersistRecord(value: unknown, storage?: string): asserts value is PersistRecord;
interface PersistStorageCacheOption {
cache?: Map;
}
type PersistCache = Map;
interface PersistStorage {
name: string;
cache: PersistCache;
get(options: Options & {
key: string;
}): null | PersistRecord | Promise>;
set(options: Options & {
key: string;
}, rec: PersistRecord): void | Promise;
clear?(options: Options & {
key: string;
}): void | Promise;
subscribe?(options: Options & {
key: string;
}, callback: (record: PersistRecord) => void): Unsubscribe;
}
interface SyncPersistStorage {
name: string;
get(options: Options & {
key: string;
}): null | PersistRecord;
set(options: Options & {
key: string;
}, rec: PersistRecord): void;
clear?(options: Options & {
key: string;
}): void;
subscribe?(options: Options & {
key: string;
}, callback: (record: PersistRecord) => void): Unsubscribe;
}
interface WithPersistOptions {
/** Key of the storage record. */
key: string;
/** Custom snapshot serializer. */
toSnapshot?: (state: State) => Snapshot;
/** Custom snapshot deserializer. */
fromSnapshot?: (snapshot: Snapshot, state?: State) => State;
/** Schema to validate and transform the snapshot. */
schema?: StandardSchemaV1;
/**
* A callback to call if the version of a stored snapshot is older than
* `version` option.
*/
migration?: (persistRecord: PersistRecord, version: number | string) => State;
/**
* Determines whether the atom is updated on storage updates.
*
* @defaultValue true
*/
subscribe?: boolean;
/**
* Number of milliseconds from the snapshot creation time after which it will
* be deleted.
*
* @defaultValue MAX_SAFE_TIMEOUT
*/
time?: number;
/**
* Version of the stored snapshot. Triggers `migration`.
*
* @defaultValue 0
*/
version?: number | string;
}
type WithRequiredPersistOptions = WithPersistOptions & Shallow, 'fromSnapshot' | 'toSnapshot'>>>;
interface WithPersist {
(options: Options & WithPersistOptions, Decode>): Ext;
(options: AtomState extends Snapshot ? ({} extends Options ? string : never) | (Options & WithPersistOptions, Decode>) : Options & WithRequiredPersistOptions, Decode>): Ext;
/**
* Atom that holds the current storage instance, useful other environments,
* like SSR or tests to provide the storage instance to the user.
*/
storageAtom: Atom>;
}
declare const reatomPersist: (storage: Omit, "cache">) => WithPersist;
declare const createMemStorage: ({
name,
mutable,
snapshot,
subscribe: subscribeOption
}: {
name: string;
mutable?: boolean;
snapshot?: Rec;
subscribe?: boolean;
}) => PersistStorage & {
snapshotAtom: Atom>;
};
//#endregion
//#region src/primitives/reatomMap.d.ts
type StateInit$1 = Map | ConstructorParameters>[0];
interface MapAtom extends AtomLike