unwrapped 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/error.ts","../../src/core/result.ts","../../src/core/asyncResult.ts","../../src/core/cache.ts"],"sourcesContent":["export class ErrorBase {\n code: string;\n message?: string | undefined;\n thrownError?: any;\n\n constructor(code: string, message?: string, thrownError?: any, log: boolean = true) {\n this.code = code;\n this.message = message;\n this.thrownError = thrownError;\n\n if (log) {\n this.logError();\n }\n }\n\n toString(): string {\n return `Error ${this.code}: ${this.message ?? ''}`;\n }\n\n logError(): void {\n console.error(this.toString(), this.thrownError);\n }\n}","import { ErrorBase } from \"./error\";\n\nexport type ResultState<T, E = ErrorBase> =\n | { status: 'success'; value: T }\n | { status: 'error'; error: E };\n\n\nexport class Result<T, E = ErrorBase> {\n private _state: ResultState<T, E>;\n\n constructor(state: ResultState<T, E>) {\n this._state = state;\n }\n\n get state() {\n return this._state;\n }\n\n static ok<T, E = ErrorBase>(value: T): Result<T, E> {\n return new Result({ status: 'success', value });\n }\n\n static err<E>(error: E): Result<never, E> {\n return new Result({ status: 'error', error });\n }\n\n static errTag(code: string, message?: string): Result<never, ErrorBase> {\n return Result.err(new ErrorBase(code, message));\n }\n\n unwrapOrNull(): T | null {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return null;\n }\n\n unwrapOrThrow(): T {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n throw new Error('Tried to unwrap a Result that is not successful');\n }\n\n unwrapOr<O>(defaultValue: O): T | O {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return defaultValue;\n }\n\n isSuccess(): boolean {\n return this._state.status === 'success';\n }\n\n isError(): boolean {\n return this._state.status === 'error';\n }\n\n static tryPromise<T, E>(promise: Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>> {\n return promise\n .then((value) => Result.ok<T, E>(value))\n .catch((error) => Result.err(errorMapper(error)));\n }\n\n static tryFunction<T, E extends ErrorBase = ErrorBase>(fn: () => Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>> {\n return Result.tryPromise(fn(), errorMapper);\n }\n\n chain<O, E2>(fn: (input: T) => ResultState<O, E | E2>): Result<O, E | E2> {\n if (this._state.status === 'success') {\n return new Result<O, E | E2>(fn(this._state.value));\n }\n return Result.err<E>(this._state.error);\n }\n\n *[Symbol.iterator](): Generator<Result<T, E>, T, any> {\n yield this;\n\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return undefined as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static run<T, E>(generator: () => Generator<Result<any, E>, T, any>): Result<T, E> {\n const iterator = generator();\n let result = iterator.next();\n\n while (!result.done) {\n const yielded = result.value;\n if (yielded._state.status === 'error') {\n return Result.err(yielded._state.error);\n }\n result = iterator.next(yielded._state.value);\n }\n\n return Result.ok(result.value);\n }\n}\n","import type { ErrorBase } from \"./error\";\nimport { Result, type ResultState } from \"./result\";\n\nexport type AsyncResultState<T, E> =\n | { status: 'idle' }\n | { status: 'loading'; promise: Promise<Result<T, E>> }\n | ResultState<T, E>;\n\nexport type ChainFunction<I, O, E> = (input: I) => Result<O, E> | Promise<Result<O, E>>;\nexport type FlatChainFunction<I, O, E> = (input: I) => AsyncResult<O, E>;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AsyncResultListener<T, E> = (result: AsyncResult<T, E>) => any;\n\nexport class AsyncResult<T, E = ErrorBase> {\n private _state: AsyncResultState<T, E>;\n private _listeners: Set<AsyncResultListener<T, E>> = new Set();\n\n constructor(state?: AsyncResultState<T, E>) {\n this._state = state || { status: 'idle' };\n }\n\n get state() {\n return this._state;\n }\n\n private set state(newState: AsyncResultState<T, E>) {\n this._state = newState;\n this._listeners.forEach((listener) => listener(this));\n }\n\n static ok<T>(value: T): AsyncResult<T, never> {\n return new AsyncResult<T, never>({ status: 'success', value });\n }\n\n static err<E>(error: E): AsyncResult<never, E> {\n return new AsyncResult<never, E>({ status: 'error', error });\n }\n\n isSuccess() {\n return this._state.status === 'success';\n }\n\n isError() {\n return this._state.status === 'error';\n }\n\n isLoading() {\n return this._state.status === 'loading';\n }\n\n listen(listener: AsyncResultListener<T, E>, immediate = true) {\n this._listeners.add(listener);\n if (immediate) {\n listener(this);\n }\n\n return () => {\n this._listeners.delete(listener);\n };\n }\n\n listenUntilSettled(listener: AsyncResultListener<T, E>, immediate = true) {\n const unsub = this.listen((result) => {\n listener(result);\n if (result.state.status === 'success' || result.state.status === 'error') {\n unsub();\n }\n }, immediate);\n\n return unsub;\n }\n\n setState(newState: AsyncResultState<T, E>) {\n this.state = newState;\n }\n\n copyOnceSettled(other: AsyncResult<T, E>) {\n this.updateFromResultPromise(other.toResultPromise());\n }\n\n update(newState: AsyncResultState<T, E>) {\n this.state = newState;\n }\n\n updateToValue(value: T) {\n this.state = { status: 'success', value };\n }\n\n updateToError(error: E) {\n this.state = { status: 'error', error };\n }\n\n updateFromResultPromise(promise: Promise<Result<T, E>>) {\n this.state = { status: 'loading', promise };\n promise\n .then((res) => {\n this.state = res.state;\n })\n .catch((error) => {\n this.state = { status: 'error', error };\n });\n }\n\n static fromResultPromise<T, E>(promise: Promise<Result<T, E>>): AsyncResult<T, E> {\n const result = new AsyncResult<T, E>();\n result.updateFromResultPromise(promise);\n return result;\n }\n\n updateFromValuePromise(promise: Promise<T>) {\n const resultStatePromise = async (): Promise<Result<T, E>> => {\n try {\n const value = await promise;\n return Result.ok(value);\n } catch (error) {\n return Result.err(error as E);\n }\n };\n this.updateFromResultPromise(resultStatePromise());\n }\n\n static fromValuePromise<T, E>(promise: Promise<T>): AsyncResult<T, E> {\n const result = new AsyncResult<T, E>();\n result.updateFromValuePromise(promise);\n return result;\n }\n\n async waitForSettled(): Promise<AsyncResult<T, E>> {\n if (this._state.status === 'loading') {\n try {\n const value = await this._state.promise;\n this._state = value.state;\n } catch (error) {\n this._state = { status: 'error', error: error as E };\n }\n }\n return this;\n }\n\n async waitForSettledResult(): Promise<Result<T, E>> {\n const settled = await this.waitForSettled();\n if (settled.state.status === 'idle' || settled.state.status === 'loading') {\n throw new Error('Cannot convert idle or loading AsyncResult to ResultState');\n }\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n return Result.ok(settled.state.value);\n }\n\n async toResultPromise(): Promise<Result<T, E>> {\n if (this._state.status === 'idle') {\n throw new Error('Cannot convert idle AsyncResult to ResultState');\n }\n if (this._state.status === 'loading') {\n try {\n const value = await this._state.promise;\n this._state = value.state;\n } catch (error) {\n this._state = { status: 'error', error: error as E };\n }\n }\n return new Result(this._state);\n }\n\n async toValuePromiseThrow(): Promise<T> {\n const settled = await this.waitForSettled();\n return settled.unwrapOrThrow();\n }\n\n async toValueOrNullPromise(): Promise<T | null> {\n const settled = await this.waitForSettled();\n return settled.unwrapOrNull();\n }\n\n unwrapOrNull(): T | null {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return null;\n }\n\n async unwrapOrNullOnceSettled(): Promise<T | null> {\n return (await this.waitForSettled()).unwrapOrNull();\n }\n\n unwrapOrThrow(): T {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n throw new Error('Tried to unwrap an AsyncResult that is not successful');\n }\n\n async unwrapOrThrowOnceSettled(): Promise<T> {\n return (await this.waitForSettled()).unwrapOrThrow();\n }\n\n chain<O, E2>(fn: ChainFunction<T, O, E | E2>): AsyncResult<O, E | E2> {\n const newResultBuilder = async (): Promise<Result<O, E | E2>> => {\n const settled = await this.waitForSettled();\n if (settled.state.status === 'loading' || settled.state.status === 'idle') {\n throw new Error('Unexpected state after waitForSettled'); // TODO handle this case properly\n }\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n\n return fn(settled.state.value);\n };\n\n return AsyncResult.fromResultPromise<O, E | E2>(newResultBuilder());\n }\n\n flatChain<O, E2>(fn: FlatChainFunction<T, O, E | E2>): AsyncResult<O, E | E2> {\n const newResultBuilder = async (): Promise<Result<O, E | E2>> => {\n const settled = await this.waitForSettledResult();\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n\n const nextAsyncResult = fn(settled.state.value);\n const nextSettled = await nextAsyncResult.waitForSettledResult();\n return nextSettled;\n }\n\n return AsyncResult.fromResultPromise<O, E | E2>(newResultBuilder());\n }\n\n // pipeParallel PipeFunction[] -> AsyncResult<T, E>[]\n // pipeParallelAndCollapse PipeFunction[] -> AsyncResult<T[], E>\n\n mirror(other: AsyncResult<T, E>) {\n return other.listen((newState) => {\n this.setState(newState.state);\n }, true);\n }\n\n mirrorUntilSettled(other: AsyncResult<T, E>) {\n return other.listenUntilSettled((newState) => {\n this.setState(newState.state);\n }, true);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static ensureAvailable<R extends readonly AsyncResult<any, any>[]>(results: R): AsyncResult<{ [K in keyof R]: R[K] extends AsyncResult<infer T, any> ? T : never }, R[number] extends AsyncResult<any, infer E> ? E : never> {\n if (results.length === 0) {\n // empty case — TS infers void tuple, so handle gracefully\n return AsyncResult.ok(undefined as never);\n }\n\n const promise = Promise.all(results.map((r) => r.waitForSettled())).then(\n (settledResults) => {\n for (const res of settledResults) {\n if (res.state.status === 'error') {\n return Result.err(res.state.error);\n }\n }\n\n const values = settledResults.map((r) => r.unwrapOrNull()!) as {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof R]: R[K] extends AsyncResult<infer T, any>\n ? T\n : never;\n };\n\n return Result.ok(values);\n }\n );\n\n return AsyncResult.fromResultPromise(promise);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n *[Symbol.iterator](): Generator<AsyncResult<T, E>, T, any> {\n yield this;\n\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return undefined as T;\n }\n\n private static _runGeneratorProcessor<T, E>(iterator: Generator<AsyncResult<any, any>, T, any>): () => Promise<Result<T, E>> {\n return async (): Promise<Result<T, E>> => {\n let result = iterator.next();\n\n while (!result.done) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const yielded = result.value as AsyncResult<any, E>;\n const settled = await yielded.waitForSettledResult();\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n result = iterator.next(settled.state.value);\n }\n\n return Result.ok(result.value);\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static run<T, E = ErrorBase>(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>): AsyncResult<T, E> {\n const iterator = generatorFunc();\n return AsyncResult.fromResultPromise<T, E>(AsyncResult._runGeneratorProcessor<T, E>(iterator)());\n }\n\n runInPlace(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>) {\n const iterator = generatorFunc();\n this.updateFromResultPromise(AsyncResult._runGeneratorProcessor<T, E>(iterator)());\n }\n}\n","import { AsyncResult, type AsyncResultState, type ChainFunction } from \"./asyncResult\";\nimport type { ErrorBase } from \"./error\";\n\ntype KeyedAsyncCacheRefetchOptions = {\n policy: 'refetch' | 'if-error' | 'no-refetch';\n};\n\ntype CacheItem<P, V, E> = {\n result: AsyncResult<V, E>;\n fetcherParams: P;\n};\n\nconst _defaultRefetchOptions: KeyedAsyncCacheRefetchOptions = { policy: 'no-refetch' };\n\nfunction defaultParamsToKey<P>(params: P): string {\n if (typeof params === 'object') {\n return JSON.stringify(params);\n }\n return String(params);\n}\n\nexport class KeyedAsyncCache<P, V, E = ErrorBase> {\n private _cache: Map<string, CacheItem<P, V, E>> = new Map();\n private _fetcher: ChainFunction<P, V, E>;\n private _paramsToKey: (params: P) => string;\n\n constructor(fetcher: ChainFunction<P, V, E>, paramsToKey: (params: P) => string = defaultParamsToKey) {\n this._fetcher = fetcher;\n this._paramsToKey = paramsToKey;\n }\n\n private makeCacheItem(result: AsyncResult<V, E>, fetcherParams: P): CacheItem<P, V, E> {\n return { result, fetcherParams };\n }\n\n private shouldRefetch(existingResult: CacheItem<P, V, E>, refetch: KeyedAsyncCacheRefetchOptions): boolean {\n if (refetch.policy === 'refetch') {\n return true;\n }\n if (refetch.policy === 'if-error') {\n return existingResult.result.state.status === 'error';\n }\n return false;\n }\n\n get(params: P, refetch: KeyedAsyncCacheRefetchOptions = _defaultRefetchOptions): AsyncResult<V, E> {\n const key = this._paramsToKey(params);\n if (this._cache.has(key)) {\n const cacheItem = this._cache.get(key)!;\n if (!this.shouldRefetch(cacheItem, refetch)) {\n return cacheItem.result;\n } else {\n cacheItem.result.updateFromResultPromise(Promise.resolve(this._fetcher(cacheItem.fetcherParams)));\n return cacheItem.result;\n }\n }\n\n const asyncResult = AsyncResult.fromResultPromise(Promise.resolve(this._fetcher(params)));\n this._cache.set(key, this.makeCacheItem(asyncResult, params));\n return asyncResult;\n }\n\n async getSettledState(params: P, refetch: KeyedAsyncCacheRefetchOptions = _defaultRefetchOptions): Promise<AsyncResultState<V, E>> {\n const asyncResult = this.get(params, refetch);\n await asyncResult.waitForSettled();\n return asyncResult.state;\n }\n\n anyLoading(): boolean {\n for (const cacheItem of this._cache.values()) {\n if (cacheItem.result.isLoading()) {\n return true;\n }\n }\n return false;\n }\n\n clear() {\n this._cache.clear();\n }\n}\n"],"mappings":";AAAO,IAAM,YAAN,MAAgB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,MAAc,SAAkB,aAAmB,MAAe,MAAM;AAClF,SAAK,OAAO;AACZ,SAAK,UAAU;AACf,SAAK,cAAc;AAEnB,QAAI,KAAK;AACP,WAAK,SAAS;AAAA,IAChB;AAAA,EACF;AAAA,EAEA,WAAmB;AACjB,WAAO,SAAS,KAAK,IAAI,KAAK,KAAK,WAAW,EAAE;AAAA,EAClD;AAAA,EAEA,WAAiB;AACf,YAAQ,MAAM,KAAK,SAAS,GAAG,KAAK,WAAW;AAAA,EACjD;AACF;;;ACfO,IAAM,SAAN,MAAM,QAAyB;AAAA,EAC5B;AAAA,EAER,YAAY,OAA0B;AACpC,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,IAAI,QAAQ;AACV,WAAO,KAAK;AAAA,EACd;AAA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AAO,GAAG;AAC3C,eAAO,UAAU;AAAA,MACnB,OAAO;AACL,kBAAU,OAAO,wBAAwB,QAAQ,QAAQ,KAAK,SAAS,UAAU,aAAa,CAAC,CAAC;AAChG,eAAO,UAAU;AAAA,MACnB;AAAA,IACF;AAEA,UAAM,cAAc,YAAY,kBAAkB,QAAQ,QAAQ,KAAK,SAAS,MAAM,CAAC,CAAC;AACxF,SAAK,OAAO,IAAI,KAAK,KAAK,cAAc,aAAa,MAAM,CAAC;AAC5D,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,gBAAgB,QAAW,UAAyC,wBAAyD;AACjI,UAAM,cAAc,KAAK,IAAI,QAAQ,OAAO;AAC5C,UAAM,YAAY,eAAe;AACjC,WAAO,YAAY;AAAA,EACrB;AAAA,EAEA,aAAsB;AACpB,eAAW,aAAa,KAAK,OAAO,OAAO,GAAG;AAC5C,UAAI,UAAU,OAAO,UAAU,GAAG;AAChC,eAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EAEA,QAAQ;AACN,SAAK,OAAO,MAAM;AAAA,EACpB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/core/error.ts","../../src/core/result.ts","../../src/core/asyncResult.ts","../../src/core/cache.ts"],"sourcesContent":["/**\n * Base class for error handling, providing structured error information and logging.\n * @class ErrorBase\n * @property {string} code - The error code.\n * @property {string | undefined} message - The error message (optional).\n * @property {unknown} thrownError - The original error object, if any (optional).\n * \n * @constructor\n * @param {string} code - The error code.\n * @param {string} [message] - The error message.\n * @param {unknown} [thrownError] - The original error object, if any.\n * @param {boolean} [log=true] - Whether to log the error upon creation.\n */\nexport class ErrorBase {\n code: string;\n message?: string | undefined;\n thrownError?: unknown;\n\n constructor(code: string, message?: string, thrownError?: unknown, log: boolean = true) {\n this.code = code;\n this.message = message;\n this.thrownError = thrownError;\n\n if (log) {\n this.logError();\n }\n }\n\n /**\n * Converts the error to a string representation, on the format \"Error {code}: {message}\".\n * @returns a string representation of the error\n */\n toString(): string {\n return `Error ${this.code}: ${this.message ?? ''}`;\n }\n\n /**\n * Logs the error to the console, uses console.error and ErrorBase.toString() internally.\n * Logs thrownError if it was provided on creation.\n */\n logError(): void {\n if (this.thrownError) {\n console.error(this.toString(), this.thrownError);\n } else {\n console.error(this.toString());\n }\n }\n}\n","import { ErrorBase } from \"./error\";\n\n/**\n * Type representing the state of a Result, either success with a value of type T,\n * or error with an error of type E (defaulting to ErrorBase).\n */\nexport type ResultState<T, E extends ErrorBase = ErrorBase> =\n | { status: 'success'; value: T }\n | { status: 'error'; error: E };\n\n/**\n * Class representing the result of an operation that can either succeed with a value of type T,\n * or fail with an error of type E (defaulting to ErrorBase).\n * Provides methods for unwrapping the result, chaining operations, and handling errors.\n * @class Result\n * @template T - The type of the successful result value.\n * @template E - The type of the error, extending ErrorBase (default is ErrorBase).\n */\nexport class Result<T, E extends ErrorBase = ErrorBase> {\n private _state: ResultState<T, E>;\n\n /**\n * Creates a new Result instance with the given state.\n * @param state the state of the created Result\n */\n constructor(state: ResultState<T, E>) {\n this._state = state;\n }\n\n /** Returns the internal state of the Result. */\n get state() {\n return this._state;\n }\n\n /**\n * Checks if the Result is successful.\n * @returns whether or not the result is successful\n */\n isSuccess(): boolean {\n return this._state.status === 'success';\n }\n\n /**\n * Checks if the Result is an error.\n * @returns whether or not the result is an error\n */\n isError(): boolean {\n return this._state.status === 'error';\n }\n\n /**\n * Creates a successful Result with the given value.\n * @param value the result of the successful operation\n * @returns a successful Result\n */\n static ok<T, E extends ErrorBase = ErrorBase>(value: T): Result<T, E> {\n return new Result({ status: 'success', value });\n }\n\n /**\n * Creates an error Result with the given error.\n * @param error the error of the failed operation\n * @returns an error Result\n */\n static err<E extends ErrorBase = ErrorBase>(error: E): Result<never, E> {\n return new Result({ status: 'error', error });\n }\n\n /**\n * Creates an error Result (containing an ErrorBase) with the given error code and optional message.\n * @param code the error code\n * @param message an optional error message\n * @returns an error Result\n */\n static errTag(code: string, message?: string, thrownError?: unknown): Result<never, ErrorBase> {\n return Result.err(new ErrorBase(code, message, thrownError));\n }\n\n /**\n * Returns the successful value (if the Result is successful) or null (if it is an error).\n * @returns either the successful value or null\n */\n unwrapOrNull(): T | null {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return null;\n }\n\n /**\n * Returns the successful value (if the Result is successful) or throws an error (if it is an error).\n * @returns the successful value\n * @throws an normal JS Error if the result is not successful\n */\n unwrapOrThrow(): T {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n throw new Error('Tried to unwrap a Result that is not successful');\n }\n\n /**\n * Returns the successful value (if the Result is successful) or a default value (if it is an error).\n * @param defaultValue the default value to return if the Result is an error\n * @returns either the successful value or the default value\n */\n unwrapOr<O>(defaultValue: O): T | O {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return defaultValue;\n }\n\n /**\n * Transforms a Promise of a successful value into a Promise of a Result,\n * catching any thrown errors and mapping them using the provided errorMapper function.\n * @param promise the promise to execute\n * @param errorMapper a function that maps a thrown error to a Result error\n * @returns a Promise resolving to a Result containing either the successful value or the mapped error\n */\n static tryPromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>> {\n return promise\n .then((value) => Result.ok<T, E>(value))\n .catch((error) => Result.err(errorMapper(error)));\n }\n\n /**\n * Executes an asynchronous function and transforms its result into a Result,\n * catching any thrown errors and mapping them using the provided errorMapper function.\n * Same as Result.tryPromise(fn(), errorMapper).\n * @param fn the asynchronous function to execute\n * @param errorMapper a function that maps a thrown error to a Result error\n * @returns a Promise resolving to a Result containing either the successful value or the mapped error\n */\n static tryFunction<T, E extends ErrorBase = ErrorBase>(fn: () => Promise<T>, errorMapper: (error: unknown) => E): Promise<Result<T, E>> {\n return Result.tryPromise(fn(), errorMapper);\n }\n\n /**\n * Chains the current Result with another operation that returns a ResultState.\n * If the current Result is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * @param fn a function taking as input the successful value of the result, and returning a ResultState describing the result of its own operation\n * @returns a new Result that has either the successful value of the operation, or either the error of the current result or the error returned by fn\n */\n chain<O, E2 extends ErrorBase = ErrorBase>(fn: (input: T) => ResultState<O, E | E2>): Result<O, E | E2> {\n if (this._state.status === 'success') {\n return new Result<O, E | E2>(fn(this._state.value));\n }\n return Result.err<E>(this._state.error);\n }\n\n /**\n * Chains the current Result with another operation that returns a Result.\n * If the current Result is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * Same as chain, but the function returns a Result directly instead of a ResultState.\n * @param fn a function taking as input the successful value of the result, and returning a Result describing the result of its own operation\n * @returns a new Result that has either the successful value of the operation, or either the error of the current result or the error returned by fn\n */\n flatChain<O, E2 extends ErrorBase = ErrorBase>(fn: (input: T) => Result<O, E | E2>): Result<O, E | E2> {\n if (this._state.status === 'success') {\n return fn(this._state.value);\n }\n return Result.err<E>(this._state.error);\n }\n\n /**\n * @yields the current Result, and if it is successful, returns its value.\n * This allows using Result instances in generator functions to simplify error handling and propagation.\n * @example\n * function* example(): Generator<Result<number>, number, any> {\n * const result1 = yield* Result.ok(5);\n * const result2 = yield* Result.ok(10);\n * return result1 + result2;\n * }\n */\n *[Symbol.iterator](): Generator<Result<T, E>, T, any> {\n yield this;\n\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return undefined as T;\n }\n\n /**\n * Runs a generator function that yields Result instances, propagating errors automatically.\n * If any yielded Result is an error, the execution stops and the error is returned.\n * If all yielded Results are successful, returns a successful Result with the final returned value.\n * \n * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.\n * Think of it as \"async/await\" but for Result handling in generator functions.\n * \n * @param generator a generator function that yields Result instances\n * @returns a Result containing either the final successful value or the first encountered error\n * \n * @example\n * const result = Result.run(function* () {\n * const value1 = yield* Result.ok(5);\n * const value2 = yield* Result.ok(10);\n * return value1 + value2;\n * });\n */\n static run<T, E extends ErrorBase = ErrorBase>(generator: () => Generator<Result<any, E>, T, any>): Result<T, E> {\n const iterator = generator();\n let result = iterator.next();\n\n while (!result.done) {\n const yielded = result.value;\n if (yielded._state.status === 'error') {\n return Result.err(yielded._state.error);\n }\n result = iterator.next(yielded._state.value);\n }\n\n return Result.ok(result.value);\n }\n}\n","import { ErrorBase } from \"./error\";\nimport { Result, type ResultState } from \"./result\";\n\n/**\n * Type representing the state of an AsyncResult.\n * It can be 'idle', 'loading' with a promise, or a settled ResultState (success or error).\n */\nexport type AsyncResultState<T, E extends ErrorBase = ErrorBase> =\n | { status: 'idle' }\n | { status: 'loading'; promise: Promise<Result<T, E>> }\n | ResultState<T, E>;\n\n\n/**\n * An Action is a function returning a Promise of a Result.\n */\nexport type Action<T,E extends ErrorBase = ErrorBase> = () => Promise<Result<T, E>>;\n\n/**\n * A LazyAction is an object containing a trigger function to start the action, and the AsyncResult representing the action's state.\n */\nexport type LazyAction<T, E extends ErrorBase = ErrorBase> = {\n trigger: () => void;\n result: AsyncResult<T, E>;\n};\n\n/**\n * A ChainStep is a function that takes an arbitrary input and returns a Result or a Promise of a Result.\n * It takes an input of type I and returns either a Result<O, E> or a Promise<Result<O, E>>.\n * \n * Used for chaining operations on AsyncResult.\n */\nexport type ChainStep<I, O, E extends ErrorBase = ErrorBase> = (input: I) => Result<O, E> | Promise<Result<O, E>>;\n\n/**\n * A FlatChainStep is a function that takes an arbitrary input and returns an AsyncResult.\n * It takes an input of type I and returns an AsyncResult<O, E>.\n * \n * Used for flat-chaining operations on AsyncResult.\n */\nexport type FlatChainStep<I, O, E extends ErrorBase = ErrorBase> = (input: I) => AsyncResult<O, E>;\n\n/**\n * Type representing a generator function that yields AsyncResult instances and returns a final value of type T.\n * \n * Used for running generators with AsyncResult.run().\n */\nexport type AsyncResultGenerator<T> = Generator<AsyncResult<any, any>, T, any>;\n\n/**\n * Type representing a listener function for AsyncResult state changes.\n */\nexport type AsyncResultListener<T, E extends ErrorBase = ErrorBase> = (result: AsyncResult<T, E>) => any;\n\n/**\n * Class representing the asynchronous result of an operation that can be idle, loading, successful, or failed.\n * Provides methods for listening to state changes, updating state, chaining operations, and converting to and from promises.\n * @class AsyncResult\n * @template T - The type of the successful result value.\n * @template E - The type of the error, extending ErrorBase (default is ErrorBase).\n */\nexport class AsyncResult<T, E extends ErrorBase = ErrorBase> {\n private _state: AsyncResultState<T, E>;\n private _listeners: Set<AsyncResultListener<T, E>> = new Set();\n\n constructor(state?: AsyncResultState<T, E>) {\n this._state = state || { status: 'idle' };\n }\n\n\n\n // === Getting current state ===\n\n /**\n * Returns the internal state of the AsyncResult.\n */\n get state() {\n return this._state;\n }\n\n /**\n * Checks if the AsyncResult is successful.\n * @returns whether or not the result is successful\n */\n isSuccess() {\n return this._state.status === 'success';\n }\n\n /**\n * Checks if the AsyncResult is an error.\n * @returns whether or not the result is an error\n */\n isError() {\n return this._state.status === 'error';\n }\n\n /**\n * Checks if the AsyncResult is idle.\n * @returns whether or not the result is idle\n */\n isIdle() {\n return this._state.status === 'idle';\n }\n\n /**\n * Checks if the AsyncResult is loading.\n * @returns whether or not the result is loading\n */\n isLoading() {\n return this._state.status === 'loading';\n }\n\n\n\n // === Unwrapping values ===\n\n /**\n * Returns the successful value if the AsyncResult is in a success state, otherwise returns null.\n * @returns the successful value or null\n */\n unwrapOrNull(): T | null {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return null;\n }\n\n /**\n * Returns the successful value if the AsyncResult is in a success state, otherwise throws an error.\n * @returns the successful value\n * @throws an normal JS Error if the result is not successful\n */\n unwrapOrThrow(): T {\n if (this._state.status === 'success') {\n return this._state.value;\n }\n throw new Error('Tried to unwrap an AsyncResult that is not successful');\n }\n\n\n\n // === Creating/updating from settled values ===\n\n private set state(newState: AsyncResultState<T, E>) {\n this._state = newState;\n this._listeners.forEach((listener) => listener(this));\n }\n\n private setState(newState: AsyncResultState<T, E>) {\n this.state = newState;\n }\n\n /**\n * Creates a successful AsyncResult with the given value.\n * @param value the result of the successful operation\n * @returns a successful AsyncResult\n */\n static ok<T>(value: T): AsyncResult<T, never> {\n return new AsyncResult<T, never>({ status: 'success', value });\n }\n\n /**\n * Creates an error AsyncResult with the given error.\n * @param error the error of the failed operation\n * @returns an error AsyncResult\n */\n static err<E extends ErrorBase = ErrorBase>(error: E): AsyncResult<never, E> {\n return new AsyncResult<never, E>({ status: 'error', error });\n }\n\n /**\n * Creates an error AsyncResult with a new ErrorBase constructed from the given parameters.\n * @param code the error code\n * @param message the error message (optional)\n * @param thrownError the original error object, if any (optional)\n * @param log whether to log the error upon creation (default is true)\n * @returns an error AsyncResult\n */\n static errTag(code: string, message?: string, thrownError?: unknown, log: boolean = true): AsyncResult<never, ErrorBase> {\n const error = new ErrorBase(code, message, thrownError, log);\n return AsyncResult.err(error);\n }\n\n /**\n * Updates the AsyncResult to a successful state with the given value.\n * Like AsyncResult.ok, but in place.\n * @param value the successful value\n */\n updateFromValue(value: T) {\n this.state = { status: 'success', value };\n return this;\n }\n\n /**\n * Updates the AsyncResult to an error state with the given error.\n * Like AsyncResult.err, but in place.\n * @param error the error\n */\n updateFromError(error: E) {\n this.state = { status: 'error', error };\n return this;\n }\n\n\n\n // === Creating/updating from promises ===\n\n /**\n * Creates an AsyncResult from a promise that resolves to a value.\n * The AsyncResult is initially in a loading state, and updates to a successful state once the promise resolves.\n * If the promise rejects, the AsyncResult is updated to an error state with the caught error.\n * \n * Like AsyncResult.fromResultPromise, but for promise that only resolves to a successful value and not a Result.\n * \n * @param promise the promise that resolves to a value\n * @returns an AsyncResult representing the state of the promise\n */\n static fromValuePromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<T>): AsyncResult<T, E> {\n const result = new AsyncResult<T, E>();\n result.updateFromValuePromise(promise);\n return result;\n }\n\n /**\n * Updates the AsyncResult to a loading state with the given promise.\n * The AsyncResult is initially in a loading state, and updates to a successful state once the promise resolves.\n * If the promise rejects, the AsyncResult is updated to an error state with the caught error.\n * \n * Like AsyncResult.fromValuePromise, but in place.\n * \n * @param promise the promise that resolves to a value\n */\n updateFromValuePromise(promise: Promise<T>) {\n const resultStatePromise = async (): Promise<Result<T, E>> => {\n try {\n const value = await promise;\n return Result.ok(value);\n } catch (error) {\n return Result.err(error as E);\n }\n };\n return this.updateFromResultPromise(resultStatePromise());\n }\n\n\n // === Waiting for settled state and get result ===\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading.\n * @returns itself once settled\n */\n async waitForSettled(): Promise<AsyncResult<T, E>> {\n if (this._state.status === 'loading') {\n try {\n const value = await this._state.promise;\n this._state = value.state;\n } catch (error) {\n this._state = { status: 'error', error: error as E };\n }\n }\n return this;\n }\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns a Result representing the settled state.\n * @returns a Result representing the settled state\n */\n async toResultPromise(): Promise<Result<T, E>> {\n const settled = await this.waitForSettled();\n if (settled.state.status === 'idle' || settled.state.status === 'loading') {\n throw new Error('Cannot convert idle or loading AsyncResult to ResultState');\n }\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n return Result.ok(settled.state.value);\n }\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns the successful value or throws an error.\n * @returns the successful value\n * @throws an normal JS Error if the result is not successful\n */\n async toValueOrThrowPromise(): Promise<T> {\n const settled = await this.waitForSettled();\n return settled.unwrapOrThrow();\n }\n\n /**\n * Waits for the AsyncResult to settle (either success or error) if it is currently loading, and returns the successful value or null.\n * @returns either the successful value or null\n */\n async toValueOrNullPromise(): Promise<T | null> {\n const settled = await this.waitForSettled();\n return settled.unwrapOrNull();\n }\n\n /**\n * Creates an AsyncResult from a promise that resolves to a Result.\n * The AsyncResult is initially in a loading state, and updates to the settled state once the promise resolves.\n * If the promise rejects, the AsyncResult is updated to an error state with a default ErrorBase.\n * \n * @param promise the promise that resolves to a Result\n * @returns an AsyncResult representing the state of the promise\n */\n static fromResultPromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<Result<T, E>>): AsyncResult<T, E> {\n const result = new AsyncResult<T, E>();\n result.updateFromResultPromise(promise);\n return result;\n }\n\n /**\n * Updates the AsyncResult to a loading state with the given promise.\n * The promise must produce a Result once settled (meaning it should return the error in the result when possible).\n * If the promise rejects, the AsyncResult is updated to an error state with a default ErrorBase.\n * \n * Like AsyncResult.fromResultPromise, but in place.\n * \n * @param promise the promise that resolves to a Result\n */\n updateFromResultPromise(promise: Promise<Result<T, E>>) {\n this.state = { status: 'loading', promise };\n promise\n .then((res) => {\n this.state = res.state;\n })\n .catch((error) => {\n this.updateFromError(new ErrorBase('defect_on_updateFromResultPromise', 'The promise provided to AsyncResult rejected', error) as E);\n });\n return this;\n }\n\n\n // === Listeners ===\n\n /**\n * Adds a listener that is called whenever the AsyncResult state changes.\n * @param listener the listener function to add\n * @param immediate whether to call the listener immediately with the current state (default is true)\n * @returns a function to remove the listener\n */\n listen(listener: AsyncResultListener<T, E>, immediate = true) {\n this._listeners.add(listener);\n if (immediate) {\n listener(this);\n }\n\n return () => {\n this._listeners.delete(listener);\n };\n }\n\n /**\n * Adds a listener that is called whenever the AsyncResult state changes, and automatically unsubscribes once it is settled (success or error).\n * @param listener the listener function to add\n * @param immediate whether to call the listener immediately with the current state (default is true)\n * @returns a function to remove the listener\n */\n listenUntilSettled(listener: AsyncResultListener<T, E>, immediate = true) {\n const unsub = this.listen((result) => {\n listener(result);\n if (result.state.status === 'success' || result.state.status === 'error') {\n unsub();\n }\n }, immediate);\n\n return unsub;\n }\n\n // === Mirroring ===\n\n /**\n * Mirrors the state of another AsyncResult into this one.\n * Whenever the other AsyncResult changes state, this AsyncResult is updated to match.\n * @param other the AsyncResult to mirror\n * @returns a function to stop mirroring\n */\n mirror(other: AsyncResult<T, E>) {\n return other.listen((newState) => {\n this.setState(newState.state);\n }, true);\n }\n\n /**\n * Mirrors the state of another AsyncResult into this one, until the other AsyncResult is settled (success or error).\n * Whenever the other AsyncResult changes state, this AsyncResult is updated to match, until the other AsyncResult is settled.\n * @param other the AsyncResult to mirror\n * @returns a function to stop mirroring\n */\n mirrorUntilSettled(other: AsyncResult<T, E>) {\n return other.listenUntilSettled((newState) => {\n this.setState(newState.state);\n }, true);\n }\n\n\n // === Actions ===\n\n /**\n * Creates a LazyAction that can be triggered to run the given Action.\n * @param action the Action to run when triggered\n * @returns an object containing the trigger function and the associated AsyncResult\n */\n static makeLazyAction<T, E extends ErrorBase = ErrorBase>(action: Action<T, E>): LazyAction<T, E> {\n const result = new AsyncResult<T, E>();\n const trigger = () => {\n result.updateFromResultPromise(action());\n };\n\n return { trigger, result };\n }\n\n // === Chaining ===\n\n /**\n * Chains the current AsyncResult with another operation that returns a Result or a Promise of a Result.\n * \n * If the current AsyncResult is loading, waits for it to settle first, then applies the provided function to its value.\n * If the current AsyncResult is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * \n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * \n * @param fn a function taking as input the successful value of the result, and returning a Result or a Promise of a Result describing the result of its own operation\n * @returns a new AsyncResult that has either the successful value of the operation, or either the error of the current result or the error returned by fn\n */\n chain<O, E2 extends ErrorBase = ErrorBase>(fn: ChainStep<T, O, E | E2>): AsyncResult<O, E | E2> {\n const newResultBuilder = async (): Promise<Result<O, E | E2>> => {\n const settled = await this.waitForSettled();\n if (settled.state.status === 'loading' || settled.state.status === 'idle') {\n throw new Error('Unexpected state after waitForSettled'); // TODO handle this case properly\n }\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n\n return fn(settled.state.value);\n };\n\n return AsyncResult.fromResultPromise<O, E | E2>(newResultBuilder());\n }\n\n /**\n * Chains the current AsyncResult with another operation that returns an AsyncResult.\n * \n * If the current AsyncResult is loading, waits for it to settle first, then applies the provided function to its value.\n * If the current AsyncResult is successful, applies the provided function to its value.\n * Otherwise, returns the current error.\n * \n * Useful to describe a sequence of operations that can each fail, and short-circuit on the first failure.\n * \n * Like chain, but for functions returning AsyncResult instead of Result.\n * \n * @param fn a function taking as input the successful value of the result, and returning an AsyncResult describing the result of its own operation\n * @returns a new AsyncResult that has either the successful value of the operation, or either the error of the current result or the error returned by fn\n */\n flatChain<O, E2 extends ErrorBase = ErrorBase>(fn: FlatChainStep<T, O, E | E2>): AsyncResult<O, E | E2> {\n const newResultBuilder = async (): Promise<Result<O, E | E2>> => {\n const settled = await this.toResultPromise();\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n\n const nextAsyncResult = fn(settled.state.value);\n const nextSettled = await nextAsyncResult.toResultPromise();\n return nextSettled;\n }\n\n return AsyncResult.fromResultPromise<O, E | E2>(newResultBuilder());\n }\n\n // pipeParallel PipeFunction[] -> AsyncResult<T, E>[]\n // pipeParallelAndCollapse PipeFunction[] -> AsyncResult<T[], E>\n\n /**\n * Ensures that all provided AsyncResults are successful.\n * If all are successful, returns an AsyncResult containing an array of their values.\n * If any AsyncResult is an error, returns an AsyncResult with the first encountered error.\n * @param results an array of AsyncResults to check\n * @returns an AsyncResult containing either an array of successful values or the first encountered error\n */\n static ensureAvailable<R extends readonly AsyncResult<any, any>[]>(results: R): AsyncResult<{ [K in keyof R]: R[K] extends AsyncResult<infer T, any> ? T : never }, R[number] extends AsyncResult<any, infer E> ? E : never> {\n if (results.length === 0) {\n // empty case — TS infers void tuple, so handle gracefully\n return AsyncResult.ok(undefined as never);\n }\n\n const promise = Promise.all(results.map((r) => r.waitForSettled())).then(\n (settledResults) => {\n for (const res of settledResults) {\n if (res.state.status === 'error') {\n return Result.err(res.state.error);\n }\n }\n\n const values = settledResults.map((r) => r.unwrapOrNull()!) as {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof R]: R[K] extends AsyncResult<infer T, any>\n ? T\n : never;\n };\n\n return Result.ok(values);\n }\n );\n\n return AsyncResult.fromResultPromise(promise);\n }\n\n // === Generator support ===\n\n /**\n * Yields the current AsyncResult, and if it is successful, returns its value.\n * This allows using AsyncResult instances in generator functions to simplify error handling and propagation.\n * @example\n * function* example(): Generator<AsyncResult<number>, number, any> {\n * const result1 = yield* AsyncResult.ok(5);\n * const result2 = yield* AsyncResult.ok(10);\n * return result1 + result2;\n * }\n */\n *[Symbol.iterator](): Generator<AsyncResult<T, E>, T, any> {\n yield this;\n\n if (this._state.status === 'success') {\n return this._state.value;\n }\n return undefined as T;\n }\n\n private static _runGeneratorProcessor<T, E extends ErrorBase>(iterator: AsyncResultGenerator<T>): () => Promise<Result<T, E>> {\n return async (): Promise<Result<T, E>> => {\n let result = iterator.next();\n\n while (!result.done) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const yielded = result.value as AsyncResult<any, E>;\n const settled = await yielded.toResultPromise();\n if (settled.state.status === 'error') {\n return Result.err(settled.state.error);\n }\n result = iterator.next(settled.state.value);\n }\n\n return Result.ok(result.value);\n }\n }\n\n /**\n * Runs a generator function that yields AsyncResult instances, propagating errors automatically.\n * If any yielded AsyncResult is an error, the execution stops and the error is returned.\n * If all yielded AsyncResults are successful, returns a successful AsyncResult with the final returned value.\n * \n * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.\n * Think of it as \"async/await\" but for AsyncResult handling in generator functions.\n * \n * @param generatorFunc a generator function that yields AsyncResult instances\n * @returns a AsyncResult containing either the final successful value or the first encountered error\n * \n * @example\n * const result = AsyncResult.run(function* () {\n * const value1 = yield* AsyncResult.ok(5);\n * const value2 = yield* AsyncResult.ok(10);\n * return value1 + value2;\n * }\n */\n static run<T, E extends ErrorBase = ErrorBase>(generatorFunc: () => AsyncResultGenerator<T>): AsyncResult<T, E> {\n const iterator = generatorFunc();\n return AsyncResult.fromResultPromise<T, E>(AsyncResult._runGeneratorProcessor<T, E>(iterator)());\n }\n\n\n /**\n * Runs a generator function that yields AsyncResult instances, propagating errors automatically, and updates this AsyncResult in place.\n * If any yielded AsyncResult is an error, the execution stops and this AsyncResult is updated to that error.\n * If all yielded AsyncResults are successful, this AsyncResult is updated to a successful state with the final returned value.\n * \n * This serves the same purpose as chain/flatChain, but allows for a more linear and readable style of coding.\n * Think of it as \"async/await\" but for AsyncResult handling in generator functions.\n * \n * @param generatorFunc a generator function that yields AsyncResult instances\n */\n runInPlace(generatorFunc: () => AsyncResultGenerator<T>) {\n const iterator = generatorFunc();\n return this.updateFromResultPromise(AsyncResult._runGeneratorProcessor<T, E>(iterator)());\n }\n\n\n // === Debuging ===\n\n\n log(name?: string) {\n const time = (new Date()).toTimeString().slice(0, 7);\n console.log(`${name ?? \"<Anonymous AsyncResult>\"} ; State at ${time} :`, this.state);\n }\n\n debug(name?: string) {\n return this.listen((r) => r.log(name));\n }\n}\n","import { AsyncResult, type AsyncResultState, type ChainStep } from \"./asyncResult\";\nimport type { ErrorBase } from \"./error\";\n\ntype KeyedAsyncCacheRefetchOptions = {\n policy: 'refetch' | 'if-error' | 'no-refetch';\n};\n\ntype CacheItem<P, V, E extends ErrorBase = ErrorBase> = {\n result: AsyncResult<V, E>;\n fetcherParams: P;\n valid: boolean;\n lastFetched?: number;\n ttl?: number;\n};\n\nconst _defaultRefetchOptions: KeyedAsyncCacheRefetchOptions = { policy: 'no-refetch' };\n\nfunction defaultParamsToKey<P>(params: P): string {\n if (typeof params === 'object') {\n return JSON.stringify(params);\n }\n return String(params);\n}\n\n/**\n * A cache for asynchronous operations that maps parameter sets to their corresponding AsyncResult.\n * Supports automatic refetching based on specified policies.\n * \n * @template P - The type of the parameters used to fetch values.\n * @template V - The type of the values being fetched.\n * @template E - The type of the error, extending ErrorBase (default is ErrorBase).\n */\nexport class KeyedAsyncCache<P, V, E extends ErrorBase = ErrorBase> {\n private _cache: Map<string, CacheItem<P, V, E>> = new Map();\n private _fetcher: ChainStep<P, V, E>;\n private _paramsToKey: (params: P) => string;\n private _cacheTTL?: number;\n\n /**\n * Creates a new KeyedAsyncCache instance.\n * @param fetcher the function used to fetch values based on parameters\n * @param paramsToKey a function that converts parameters to a unique string key (default uses JSON.stringify for objects)\n * @param cacheTTL optional time-to-live for cache entries in milliseconds\n */\n constructor(fetcher: ChainStep<P, V, E>, paramsToKey: (params: P) => string = defaultParamsToKey, cacheTTL: number = Infinity) {\n this._fetcher = fetcher;\n this._paramsToKey = paramsToKey;\n this._cacheTTL = cacheTTL;\n }\n\n private makeCacheItem(result: AsyncResult<V, E>, fetcherParams: P, ttl?: number | undefined): CacheItem<P, V, E> {\n return {\n result,\n fetcherParams,\n ttl: ttl ?? this._cacheTTL,\n valid: true,\n };\n }\n\n private shouldRefetch(existingResult: CacheItem<P, V, E>, refetch: KeyedAsyncCacheRefetchOptions): boolean {\n if (!existingResult.valid) {\n return true;\n }\n if (refetch.policy === 'refetch') {\n return true;\n }\n if (refetch.policy === 'if-error') {\n return existingResult.result.state.status === 'error';\n }\n if (existingResult.ttl !== undefined && existingResult.lastFetched !== undefined) {\n const now = Date.now();\n if (now - existingResult.lastFetched > existingResult.ttl) {\n return true;\n }\n }\n return false;\n }\n\n private updateOrCreateCacheItemFromParams(params: P, cacheItem?: CacheItem<P, V, E>) {\n const promise = Promise.resolve(this._fetcher(params));\n let result = cacheItem?.result.updateFromResultPromise(promise) ?? AsyncResult.fromResultPromise(promise);\n cacheItem = cacheItem ?? this.makeCacheItem(result, params);\n \n promise.then(() => {\n cacheItem.lastFetched = Date.now();\n });\n\n return cacheItem;\n }\n\n /**\n * Gets the AsyncResult for the given parameters, fetching it if not cached or if refetching is required.\n * @param params the parameters to fetch the value\n * @param refetch options determining whether to refetch the value\n * @returns the AsyncResult corresponding to the given parameters\n */\n get(params: P, refetch: KeyedAsyncCacheRefetchOptions = _defaultRefetchOptions): AsyncResult<V, E> {\n const key = this._paramsToKey(params);\n if (this._cache.has(key)) {\n const cacheItem = this._cache.get(key)!;\n if (!this.shouldRefetch(cacheItem, refetch)) {\n return cacheItem.result;\n } else {\n this.updateOrCreateCacheItemFromParams(params, cacheItem);\n return cacheItem.result;\n }\n }\n \n const cacheItem = this.updateOrCreateCacheItemFromParams(params);\n this._cache.set(key, cacheItem);\n return cacheItem.result;\n }\n\n /**\n * Gets the settled state of the AsyncResult for the given parameters, fetching it if not cached or if refetching is required.\n * Waits for the AsyncResult to settle before returning its state.\n * @param params the parameters to fetch the value\n * @param refetch options determining whether to refetch the value\n * @returns a promise resolving to the settled state of the AsyncResult\n */\n async getSettledState(params: P, refetch: KeyedAsyncCacheRefetchOptions = _defaultRefetchOptions): Promise<AsyncResultState<V, E>> {\n const asyncResult = this.get(params, refetch);\n await asyncResult.waitForSettled();\n return asyncResult.state;\n }\n\n /**\n * Checks if any cached AsyncResult is currently loading.\n * @returns whether any cached AsyncResult is loading\n */\n anyLoading(): boolean {\n for (const cacheItem of this._cache.values()) {\n if (cacheItem.result.isLoading()) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Clears the entire cache.\n */\n clear() {\n this._cache.clear();\n }\n\n /**\n * Invalidates the cache entry for the given key.\n * @param key the key of the cache entry to invalidate\n */\n invalidateKey(key: string) {\n if (this._cache.has(key)) {\n const cacheItem = this._cache.get(key)!;\n cacheItem.valid = false;\n }\n }\n\n /**\n * Invalidates the cache entry for the given parameters.\n * @param params the parameters of the cache entry to invalidate\n */\n invalidateParams(params: P) {\n const key = this._paramsToKey(params);\n this.invalidateKey(key);\n }\n\n /**\n * Invalidates all cache entries.\n */\n invalidateAll() {\n for (const cacheItem of this._cache.values()) {\n cacheItem.valid = false;\n }\n }\n}\n"],"mappings":";AAaO,IAAM,YAAN,MAAgB;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,MAAc,SAAkB,aAAuB,MAAe,MAAM;AACpF,SAAK,OAAO;AACZ,SAAK,UAAU;AACf,SAAK,cAAc;AAEnB,QAAI,KAAK;AACL,WAAK,SAAS;AAAA,IAClB;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAmB;AACf,WAAO,SAAS,KAAK,IAAI,KAAK,KAAK,WAAW,EAAE;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAiB;AACb,QAAI,KAAK,aAAa;AAClB,cAAQ,MAAM,KAAK,SAAS,GAAG,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U,GAAG;AAC9B,eAAO;AAAA,MACX;AAAA,IACJ;AACA,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA,EAKA,QAAQ;AACJ,SAAK,OAAO,MAAM;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,cAAc,KAAa;AACvB,QAAI,KAAK,OAAO,IAAI,GAAG,GAAG;AACtB,YAAM,YAAY,KAAK,OAAO,IAAI,GAAG;AACrC,gBAAU,QAAQ;AAAA,IACtB;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAAiB,QAAW;AACxB,UAAM,MAAM,KAAK,aAAa,MAAM;AACpC,SAAK,cAAc,GAAG;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAgB;AACZ,eAAW,aAAa,KAAK,OAAO,OAAO,GAAG;AAC1C,gBAAU,QAAQ;AAAA,IACtB;AAAA,EACJ;AACJ;","names":["cacheItem"]}
@@ -1,34 +1,107 @@
1
1
  import * as vue from 'vue';
2
2
  import { Ref, WatchSource, VNode } from 'vue';
3
- import { AsyncResult, FlatChainFunction, Result } from 'unwrapped/core';
3
+ import { ErrorBase, AsyncResult, Result, FlatChainStep, Action, AsyncResultGenerator } from 'unwrapped/core';
4
4
 
5
- declare function useAsyncResultRef<T, E>(asyncResult: AsyncResult<T, E>): Ref<AsyncResult<T, E>, AsyncResult<T, E>>;
6
- declare function useReactiveResult<T, E, Inputs>(source: WatchSource<Inputs>, pipe: FlatChainFunction<Inputs, T, E>, options?: {
5
+ interface ReactiveProcessOptions {
7
6
  immediate: boolean;
8
- }): Ref<AsyncResult<T, E>>;
9
- declare function useAsyncResultRefFromPromise<T, E>(promise: Promise<Result<T, E>>): Ref<AsyncResult<T, E>, AsyncResult<T, E>>;
10
- type Action<T, E> = () => Promise<Result<T, E>>;
11
- declare function useImmediateAction<T, E>(action: Action<T, E>): Ref<AsyncResult<T, E>>;
12
- interface LazyActionReturn<T, E> {
7
+ }
8
+ /**
9
+ * Makes a ref to the given AsyncResult. Whenever the state of the AsyncResult changes,
10
+ * the ref gets retriggered, making those changes visible to Vue's reactivity system.
11
+ *
12
+ * @param asyncResult the result to make reactive
13
+ * @returns the ref to the result
14
+ */
15
+ declare function useAsyncResultRef<T, E extends ErrorBase = ErrorBase>(asyncResult: AsyncResult<T, E>): Ref<AsyncResult<T, E>, AsyncResult<T, E>>;
16
+ /**
17
+ * Creates an AsyncResult ref from a promise returning a Result.
18
+ * @param promise the promise returning a Result
19
+ * @returns the ref to the AsyncResult
20
+ */
21
+ declare function useAsyncResultRefFromPromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<Result<T, E>>): Ref<AsyncResult<T, E>, AsyncResult<T, E>>;
22
+ /**
23
+ * Watches a source, gives it as inputs to the function provided, and updates the result contained in the ref accordingly.
24
+ *
25
+ * @param source the inputs to react to
26
+ * @param pipe the function to run when the inputs change
27
+ * @param options optional settings
28
+ * @returns ref to the result
29
+ */
30
+ declare function useReactiveChain<Inputs, T, E extends ErrorBase = ErrorBase>(source: WatchSource<Inputs>, pipe: FlatChainStep<Inputs, T, E>, options?: ReactiveProcessOptions): Ref<AsyncResult<T, E>>;
31
+ /**
32
+ * The return type of useLazyAction.
33
+ */
34
+ interface LazyActionRef<T, E extends ErrorBase = ErrorBase> {
13
35
  resultRef: Ref<AsyncResult<T, E>>;
14
36
  trigger: () => void;
15
37
  }
16
- declare function useLazyAction<T, E>(action: Action<T, E>): LazyActionReturn<T, E>;
17
- declare function useReactiveAction<I, O, E>(input: I | Ref<I> | (() => I), pipe: FlatChainFunction<I, O, E>, options?: {
18
- immediate: boolean;
19
- }): Ref<AsyncResult<O, E>>;
20
- declare function useGenerator<T>(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>): Ref<AsyncResult<T, any>>;
21
- declare function useLazyGenerator<T>(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>): {
38
+ /**
39
+ * Executes an action immediately and returns a ref to the AsyncResult representing the action's state.
40
+ *
41
+ * Same as useAsyncResultRefFromPromise(action()).
42
+ *
43
+ * @param action the action to execute immediately
44
+ * @returns a ref to the AsyncResult representing the action's state
45
+ */
46
+ declare function useAction<T, E extends ErrorBase = ErrorBase>(action: Action<T, E>): Ref<AsyncResult<T, E>>;
47
+ /**
48
+ * Creates a lazy action that can be triggered manually.
49
+ *
50
+ * Same as AsyncResult.makeLazyAction(action), but the AsyncResult is wrapped in a ref for Vue reactivity.
51
+ *
52
+ * @param action the action to execute when triggered
53
+ * @returns an object containing a ref to the AsyncResult and a trigger function
54
+ */
55
+ declare function useLazyAction<T, E extends ErrorBase = ErrorBase>(action: Action<T, E>): LazyActionRef<T, E>;
56
+ /**
57
+ * Runs a generator function immediately and returns a ref to the AsyncResult representing the generator's state.
58
+ * @param generatorFunc the generator function to run immediately
59
+ * @returns a ref to the AsyncResult representing the generator's state
60
+ */
61
+ declare function useGenerator<T>(generatorFunc: () => AsyncResultGenerator<T>): Ref<AsyncResult<T, any>>;
62
+ /**
63
+ * Creates a lazy generator that can be triggered manually.
64
+ *
65
+ * @param generatorFunc the generator function to run when triggered
66
+ * @returns an object containing a ref to the AsyncResult and a trigger function
67
+ */
68
+ declare function useLazyGenerator<T>(generatorFunc: () => AsyncResultGenerator<T>): {
22
69
  resultRef: Ref<AsyncResult<T, any>>;
23
70
  trigger: () => void;
24
71
  };
25
- declare function useReactiveGenerator<T, E, Inputs>(source: WatchSource<Inputs>, generatorFunc: (args: Inputs) => Generator<AsyncResult<any, any>, T, any>, options?: {
26
- immediate: boolean;
27
- }): Ref<AsyncResult<T, E>>;
72
+ /**
73
+ * Watches a source, gives it as inputs to the generator function provided, and updates the result contained in the ref accordingly.
74
+ *
75
+ * @param source the inputs to react to
76
+ * @param generatorFunc the generator function to run when the inputs change
77
+ * @param options optional settings
78
+ * @returns ref to the result
79
+ */
80
+ declare function useReactiveGenerator<Inputs, T, E extends ErrorBase = ErrorBase>(source: WatchSource<Inputs>, generatorFunc: (args: Inputs) => AsyncResultGenerator<T>, options?: ReactiveProcessOptions): Ref<AsyncResult<T, E>>;
28
81
 
82
+ /**
83
+ * A Vue component that displays different content based on the state of an AsyncResult.
84
+ * It supports slots for 'loading', 'error', 'success' (default), and 'idle' states.
85
+ *
86
+ * @example
87
+ * <AsyncResultLoader :result="myAsyncResult">
88
+ * <template #loading>
89
+ * <div>Loading data...</div>
90
+ * </template>
91
+ * <template #error="{ error }">
92
+ * <div>Error occurred: {{ error.message }}</div>
93
+ * </template>
94
+ * <template #default="{ value }">
95
+ * <div>Data loaded: {{ value }}</div>
96
+ * </template>
97
+ * <template #idle>
98
+ * <div>Waiting to start...</div>
99
+ * </template>
100
+ * </AsyncResultLoader>
101
+ */
29
102
  declare const AsyncResultLoader: vue.DefineComponent<vue.ExtractPropTypes<{
30
103
  result: {
31
- type: () => AsyncResult<unknown, unknown>;
104
+ type: () => AsyncResult<unknown>;
32
105
  required: true;
33
106
  };
34
107
  }>, () => VNode<vue.RendererNode, vue.RendererElement, {
@@ -37,17 +110,25 @@ declare const AsyncResultLoader: vue.DefineComponent<vue.ExtractPropTypes<{
37
110
  [key: string]: any;
38
111
  }>[] | null, {}, {}, {}, vue.ComponentOptionsMixin, vue.ComponentOptionsMixin, {}, string, vue.PublicProps, Readonly<vue.ExtractPropTypes<{
39
112
  result: {
40
- type: () => AsyncResult<unknown, unknown>;
113
+ type: () => AsyncResult<unknown>;
41
114
  required: true;
42
115
  };
43
116
  }>> & Readonly<{}>, {}, {}, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
44
- interface CustomSlots<E> {
117
+ interface CustomSlots<E extends ErrorBase = ErrorBase> {
45
118
  loading?: () => VNode;
46
119
  error?: (props: {
47
120
  error: E;
48
121
  }) => VNode;
49
122
  }
50
- declare function buildCustomAsyncResultLoader<T, E>(slots: CustomSlots<E>): vue.DefineComponent<vue.ExtractPropTypes<{
123
+ /**
124
+ * Builds a custom AsyncResultLoader component with predefined slots for loading and error states.
125
+ *
126
+ * Useful for creating reusable components with consistent loading and error handling UI (eg. framework-specific spinners, etc...).
127
+ *
128
+ * @param slots the custom slots for loading and error states
129
+ * @returns a Vue component that uses the provided slots
130
+ */
131
+ declare function buildCustomAsyncResultLoader<T, E extends ErrorBase = ErrorBase>(slots: CustomSlots<E>): vue.DefineComponent<vue.ExtractPropTypes<{
51
132
  result: {
52
133
  type: () => AsyncResult<T, E>;
53
134
  required: true;
@@ -61,4 +142,4 @@ declare function buildCustomAsyncResultLoader<T, E>(slots: CustomSlots<E>): vue.
61
142
  };
62
143
  }>> & Readonly<{}>, {}, {}, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
63
144
 
64
- export { type Action, AsyncResultLoader, type LazyActionReturn, buildCustomAsyncResultLoader, useAsyncResultRef, useAsyncResultRefFromPromise, useGenerator, useImmediateAction, useLazyAction, useLazyGenerator, useReactiveAction, useReactiveGenerator, useReactiveResult };
145
+ export { AsyncResultLoader, type LazyActionRef, buildCustomAsyncResultLoader, useAction, useAsyncResultRef, useAsyncResultRefFromPromise, useGenerator, useLazyAction, useLazyGenerator, useReactiveChain, useReactiveGenerator };
@@ -1,34 +1,107 @@
1
1
  import * as vue from 'vue';
2
2
  import { Ref, WatchSource, VNode } from 'vue';
3
- import { AsyncResult, FlatChainFunction, Result } from 'unwrapped/core';
3
+ import { ErrorBase, AsyncResult, Result, FlatChainStep, Action, AsyncResultGenerator } from 'unwrapped/core';
4
4
 
5
- declare function useAsyncResultRef<T, E>(asyncResult: AsyncResult<T, E>): Ref<AsyncResult<T, E>, AsyncResult<T, E>>;
6
- declare function useReactiveResult<T, E, Inputs>(source: WatchSource<Inputs>, pipe: FlatChainFunction<Inputs, T, E>, options?: {
5
+ interface ReactiveProcessOptions {
7
6
  immediate: boolean;
8
- }): Ref<AsyncResult<T, E>>;
9
- declare function useAsyncResultRefFromPromise<T, E>(promise: Promise<Result<T, E>>): Ref<AsyncResult<T, E>, AsyncResult<T, E>>;
10
- type Action<T, E> = () => Promise<Result<T, E>>;
11
- declare function useImmediateAction<T, E>(action: Action<T, E>): Ref<AsyncResult<T, E>>;
12
- interface LazyActionReturn<T, E> {
7
+ }
8
+ /**
9
+ * Makes a ref to the given AsyncResult. Whenever the state of the AsyncResult changes,
10
+ * the ref gets retriggered, making those changes visible to Vue's reactivity system.
11
+ *
12
+ * @param asyncResult the result to make reactive
13
+ * @returns the ref to the result
14
+ */
15
+ declare function useAsyncResultRef<T, E extends ErrorBase = ErrorBase>(asyncResult: AsyncResult<T, E>): Ref<AsyncResult<T, E>, AsyncResult<T, E>>;
16
+ /**
17
+ * Creates an AsyncResult ref from a promise returning a Result.
18
+ * @param promise the promise returning a Result
19
+ * @returns the ref to the AsyncResult
20
+ */
21
+ declare function useAsyncResultRefFromPromise<T, E extends ErrorBase = ErrorBase>(promise: Promise<Result<T, E>>): Ref<AsyncResult<T, E>, AsyncResult<T, E>>;
22
+ /**
23
+ * Watches a source, gives it as inputs to the function provided, and updates the result contained in the ref accordingly.
24
+ *
25
+ * @param source the inputs to react to
26
+ * @param pipe the function to run when the inputs change
27
+ * @param options optional settings
28
+ * @returns ref to the result
29
+ */
30
+ declare function useReactiveChain<Inputs, T, E extends ErrorBase = ErrorBase>(source: WatchSource<Inputs>, pipe: FlatChainStep<Inputs, T, E>, options?: ReactiveProcessOptions): Ref<AsyncResult<T, E>>;
31
+ /**
32
+ * The return type of useLazyAction.
33
+ */
34
+ interface LazyActionRef<T, E extends ErrorBase = ErrorBase> {
13
35
  resultRef: Ref<AsyncResult<T, E>>;
14
36
  trigger: () => void;
15
37
  }
16
- declare function useLazyAction<T, E>(action: Action<T, E>): LazyActionReturn<T, E>;
17
- declare function useReactiveAction<I, O, E>(input: I | Ref<I> | (() => I), pipe: FlatChainFunction<I, O, E>, options?: {
18
- immediate: boolean;
19
- }): Ref<AsyncResult<O, E>>;
20
- declare function useGenerator<T>(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>): Ref<AsyncResult<T, any>>;
21
- declare function useLazyGenerator<T>(generatorFunc: () => Generator<AsyncResult<any, any>, T, any>): {
38
+ /**
39
+ * Executes an action immediately and returns a ref to the AsyncResult representing the action's state.
40
+ *
41
+ * Same as useAsyncResultRefFromPromise(action()).
42
+ *
43
+ * @param action the action to execute immediately
44
+ * @returns a ref to the AsyncResult representing the action's state
45
+ */
46
+ declare function useAction<T, E extends ErrorBase = ErrorBase>(action: Action<T, E>): Ref<AsyncResult<T, E>>;
47
+ /**
48
+ * Creates a lazy action that can be triggered manually.
49
+ *
50
+ * Same as AsyncResult.makeLazyAction(action), but the AsyncResult is wrapped in a ref for Vue reactivity.
51
+ *
52
+ * @param action the action to execute when triggered
53
+ * @returns an object containing a ref to the AsyncResult and a trigger function
54
+ */
55
+ declare function useLazyAction<T, E extends ErrorBase = ErrorBase>(action: Action<T, E>): LazyActionRef<T, E>;
56
+ /**
57
+ * Runs a generator function immediately and returns a ref to the AsyncResult representing the generator's state.
58
+ * @param generatorFunc the generator function to run immediately
59
+ * @returns a ref to the AsyncResult representing the generator's state
60
+ */
61
+ declare function useGenerator<T>(generatorFunc: () => AsyncResultGenerator<T>): Ref<AsyncResult<T, any>>;
62
+ /**
63
+ * Creates a lazy generator that can be triggered manually.
64
+ *
65
+ * @param generatorFunc the generator function to run when triggered
66
+ * @returns an object containing a ref to the AsyncResult and a trigger function
67
+ */
68
+ declare function useLazyGenerator<T>(generatorFunc: () => AsyncResultGenerator<T>): {
22
69
  resultRef: Ref<AsyncResult<T, any>>;
23
70
  trigger: () => void;
24
71
  };
25
- declare function useReactiveGenerator<T, E, Inputs>(source: WatchSource<Inputs>, generatorFunc: (args: Inputs) => Generator<AsyncResult<any, any>, T, any>, options?: {
26
- immediate: boolean;
27
- }): Ref<AsyncResult<T, E>>;
72
+ /**
73
+ * Watches a source, gives it as inputs to the generator function provided, and updates the result contained in the ref accordingly.
74
+ *
75
+ * @param source the inputs to react to
76
+ * @param generatorFunc the generator function to run when the inputs change
77
+ * @param options optional settings
78
+ * @returns ref to the result
79
+ */
80
+ declare function useReactiveGenerator<Inputs, T, E extends ErrorBase = ErrorBase>(source: WatchSource<Inputs>, generatorFunc: (args: Inputs) => AsyncResultGenerator<T>, options?: ReactiveProcessOptions): Ref<AsyncResult<T, E>>;
28
81
 
82
+ /**
83
+ * A Vue component that displays different content based on the state of an AsyncResult.
84
+ * It supports slots for 'loading', 'error', 'success' (default), and 'idle' states.
85
+ *
86
+ * @example
87
+ * <AsyncResultLoader :result="myAsyncResult">
88
+ * <template #loading>
89
+ * <div>Loading data...</div>
90
+ * </template>
91
+ * <template #error="{ error }">
92
+ * <div>Error occurred: {{ error.message }}</div>
93
+ * </template>
94
+ * <template #default="{ value }">
95
+ * <div>Data loaded: {{ value }}</div>
96
+ * </template>
97
+ * <template #idle>
98
+ * <div>Waiting to start...</div>
99
+ * </template>
100
+ * </AsyncResultLoader>
101
+ */
29
102
  declare const AsyncResultLoader: vue.DefineComponent<vue.ExtractPropTypes<{
30
103
  result: {
31
- type: () => AsyncResult<unknown, unknown>;
104
+ type: () => AsyncResult<unknown>;
32
105
  required: true;
33
106
  };
34
107
  }>, () => VNode<vue.RendererNode, vue.RendererElement, {
@@ -37,17 +110,25 @@ declare const AsyncResultLoader: vue.DefineComponent<vue.ExtractPropTypes<{
37
110
  [key: string]: any;
38
111
  }>[] | null, {}, {}, {}, vue.ComponentOptionsMixin, vue.ComponentOptionsMixin, {}, string, vue.PublicProps, Readonly<vue.ExtractPropTypes<{
39
112
  result: {
40
- type: () => AsyncResult<unknown, unknown>;
113
+ type: () => AsyncResult<unknown>;
41
114
  required: true;
42
115
  };
43
116
  }>> & Readonly<{}>, {}, {}, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
44
- interface CustomSlots<E> {
117
+ interface CustomSlots<E extends ErrorBase = ErrorBase> {
45
118
  loading?: () => VNode;
46
119
  error?: (props: {
47
120
  error: E;
48
121
  }) => VNode;
49
122
  }
50
- declare function buildCustomAsyncResultLoader<T, E>(slots: CustomSlots<E>): vue.DefineComponent<vue.ExtractPropTypes<{
123
+ /**
124
+ * Builds a custom AsyncResultLoader component with predefined slots for loading and error states.
125
+ *
126
+ * Useful for creating reusable components with consistent loading and error handling UI (eg. framework-specific spinners, etc...).
127
+ *
128
+ * @param slots the custom slots for loading and error states
129
+ * @returns a Vue component that uses the provided slots
130
+ */
131
+ declare function buildCustomAsyncResultLoader<T, E extends ErrorBase = ErrorBase>(slots: CustomSlots<E>): vue.DefineComponent<vue.ExtractPropTypes<{
51
132
  result: {
52
133
  type: () => AsyncResult<T, E>;
53
134
  required: true;
@@ -61,4 +142,4 @@ declare function buildCustomAsyncResultLoader<T, E>(slots: CustomSlots<E>): vue.
61
142
  };
62
143
  }>> & Readonly<{}>, {}, {}, {}, {}, string, vue.ComponentProvideOptions, true, {}, any>;
63
144
 
64
- export { type Action, AsyncResultLoader, type LazyActionReturn, buildCustomAsyncResultLoader, useAsyncResultRef, useAsyncResultRefFromPromise, useGenerator, useImmediateAction, useLazyAction, useLazyGenerator, useReactiveAction, useReactiveGenerator, useReactiveResult };
145
+ export { AsyncResultLoader, type LazyActionRef, buildCustomAsyncResultLoader, useAction, useAsyncResultRef, useAsyncResultRefFromPromise, useGenerator, useLazyAction, useLazyGenerator, useReactiveChain, useReactiveGenerator };
package/dist/vue/index.js CHANGED
@@ -22,15 +22,14 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  AsyncResultLoader: () => AsyncResultLoader,
24
24
  buildCustomAsyncResultLoader: () => buildCustomAsyncResultLoader,
25
+ useAction: () => useAction,
25
26
  useAsyncResultRef: () => useAsyncResultRef,
26
27
  useAsyncResultRefFromPromise: () => useAsyncResultRefFromPromise,
27
28
  useGenerator: () => useGenerator,
28
- useImmediateAction: () => useImmediateAction,
29
29
  useLazyAction: () => useLazyAction,
30
30
  useLazyGenerator: () => useLazyGenerator,
31
- useReactiveAction: () => useReactiveAction,
32
- useReactiveGenerator: () => useReactiveGenerator,
33
- useReactiveResult: () => useReactiveResult
31
+ useReactiveChain: () => useReactiveChain,
32
+ useReactiveGenerator: () => useReactiveGenerator
34
33
  });
35
34
  module.exports = __toCommonJS(index_exports);
36
35
 
@@ -47,7 +46,10 @@ function useAsyncResultRef(asyncResult) {
47
46
  });
48
47
  return state;
49
48
  }
50
- function useReactiveResult(source, pipe, options = { immediate: true }) {
49
+ function useAsyncResultRefFromPromise(promise) {
50
+ return useAsyncResultRef(import_core.AsyncResult.fromResultPromise(promise));
51
+ }
52
+ function useReactiveChain(source, pipe, options = { immediate: true }) {
51
53
  const result = new import_core.AsyncResult();
52
54
  const resultRef = useAsyncResultRef(result);
53
55
  let unsub = null;
@@ -60,36 +62,13 @@ function useReactiveResult(source, pipe, options = { immediate: true }) {
60
62
  });
61
63
  return resultRef;
62
64
  }
63
- function useAsyncResultRefFromPromise(promise) {
64
- return useAsyncResultRef(import_core.AsyncResult.fromResultPromise(promise));
65
- }
66
- function useImmediateAction(action) {
65
+ function useAction(action) {
67
66
  return useAsyncResultRefFromPromise(action());
68
67
  }
69
68
  function useLazyAction(action) {
70
- const result = new import_core.AsyncResult();
71
- const resultRef = useAsyncResultRef(result);
72
- const trigger = () => {
73
- result.updateFromResultPromise(action());
74
- };
75
- return { resultRef, trigger };
76
- }
77
- function useReactiveAction(input, pipe, options = { immediate: true }) {
78
- const source = typeof input === "function" ? (0, import_vue.computed)(input) : (0, import_vue.toRef)(input);
79
- const outputRef = (0, import_vue.ref)(new import_core.AsyncResult());
80
- let unsub = null;
81
- (0, import_vue.watch)(source, () => {
82
- unsub?.();
83
- const newOutput = pipe(source.value);
84
- unsub = newOutput.listen((newState) => {
85
- outputRef.value.setState(newState.state);
86
- (0, import_vue.triggerRef)(outputRef);
87
- });
88
- }, { immediate: options.immediate });
89
- (0, import_vue.onUnmounted)(() => {
90
- unsub?.();
91
- });
92
- return outputRef;
69
+ const lazyAction = import_core.AsyncResult.makeLazyAction(action);
70
+ const resultRef = useAsyncResultRef(lazyAction.result);
71
+ return { resultRef, trigger: lazyAction.trigger };
93
72
  }
94
73
  function useGenerator(generatorFunc) {
95
74
  const resultRef = useAsyncResultRef(import_core.AsyncResult.run(generatorFunc));
@@ -122,24 +101,17 @@ var AsyncResultLoader = (0, import_vue2.defineComponent)({
122
101
  }
123
102
  },
124
103
  setup(props, { slots }) {
125
- const state = (0, import_vue2.ref)(props.result.state);
126
- let unlisten = null;
127
- (0, import_vue2.onUnmounted)(() => {
128
- if (unlisten) unlisten();
129
- });
104
+ let resultRef = useAsyncResultRef(props.result);
130
105
  (0, import_vue2.watch)(
131
106
  () => props.result,
132
- (newResult) => {
133
- if (unlisten) unlisten();
134
- state.value = newResult.state;
135
- unlisten = newResult.listen((res) => {
136
- state.value = res.state;
137
- });
107
+ (newResult, oldResult) => {
108
+ if (newResult === oldResult) return;
109
+ resultRef = useAsyncResultRef(newResult);
138
110
  },
139
111
  { immediate: true }
140
112
  );
141
113
  return () => {
142
- const s = state.value;
114
+ const s = resultRef.value.state;
143
115
  switch (s.status) {
144
116
  case "loading":
145
117
  return slots.loading ? slots.loading() : (0, import_vue2.h)("div", { class: "loading" }, "Loading\u2026");