Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@equinor/fusion-observable

Package Overview
Dependencies
Maintainers
0
Versions
73
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@equinor/fusion-observable - npm Package Compare versions

Comparing version 8.3.2 to 8.3.3

15

dist/esm/action-mapper.js

@@ -1,6 +0,15 @@

export const actionMapper = (actions, subject) => Object.entries(actions).reduce((cur, [prop, fnOrActions]) => Object.assign(cur, {
/**
* Maps action definitions to a subject {@link FlowSubject}
*
* @param actions - object of named action
* @param subject - target subject to map actions to
* @returns object of callable action which maps to provided subject
*/
export const actionMapper = (actions,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
subject) => Object.entries(actions).reduce((cur, [prop, fnOrActions]) => Object.assign(cur, {
[prop]: typeof fnOrActions === 'function'
?
? /** if value is a function, call it 🤙🏻 */
(...args) => subject.next(fnOrActions(...args))
:
: /** extract child actions */
actionMapper(fnOrActions, subject),

@@ -7,0 +16,0 @@ }), {});

@@ -0,1 +1,6 @@

/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* taken from https://github.com/reduxjs/redux-toolkit/tree/master/packages/toolkit/src
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function createAction(type, prepareAction) {

@@ -19,5 +24,26 @@ function actionCreator(...args) {

export const matchActionSuffix = (suffix) => new RegExp(`${actionSuffixDivider}${suffix}$`);
/**
* Extracts the base type from an action type string.
*
* The action type string is expected to be in the format `${baseType}${actionSuffixDivider}${actionSuffix}`,
* where `${actionSuffixDivider}` is a special character that separates the base type from the action suffix.
*
* This function returns the `baseType` part of the action type string.
*
* @param type - The action type string to extract the base type from.
* @returns The base type of the action type string, or `never` if the input string does not match the expected format.
*/
export function getBaseType(type) {
return type.replace(matchActionSuffix('\\w+$'), '');
}
/**
* Returns the action type of the actions created by the passed
* `createAction()`-generated action creator (arbitrary action creators
* are not supported).
*
* @param action The action creator whose action type to get.
* @returns The action type used by the action creator.
*
* @public
*/
export function getType(actionCreator) {

@@ -24,0 +50,0 @@ return `${actionCreator}`;

1

dist/esm/create-async-action.js

@@ -0,1 +1,2 @@

/* eslint-disable @typescript-eslint/no-explicit-any */
import { actionSuffixDivider, createAction, matchActionSuffix, } from './create-action';

@@ -2,0 +3,0 @@ export function createAsyncAction(type, request, success, failure) {

import { produce as createNextState, isDraft, isDraftable } from 'immer';
function freezeDraftable(val) {
// eslint-disable-next-line @typescript-eslint/no-empty-function
return isDraftable(val) ? createNextState(val, () => { }) : val;

@@ -10,2 +11,3 @@ }

const [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);
// Ensure the initial state gets frozen either way (if draftable)
let getInitialState;

@@ -32,3 +34,6 @@ if (isStateFunction(initialState)) {

if (isDraft(previousState)) {
const draft = previousState;
// If it's already a draft, we must already be inside a `createNextState` call,
// likely because this is being wrapped in `createReducer`, `createSlice`, or nested
// inside an existing draft. It's safe to just pass the draft to the mutator.
const draft = previousState; // We can assume this is already a draft
const result = caseReducer(draft, action);

@@ -41,2 +46,4 @@ if (result === undefined) {

else if (!isDraftable(previousState)) {
// If state is not draftable (ex: a primitive, such as 0), we want to directly
// return the caseReducer func and not wrap it with produce.
const result = caseReducer(previousState, action);

@@ -52,2 +59,7 @@ if (result === undefined) {

else {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// createNextState() produces an Immutable<Draft<S>> rather
// than an Immutable<S>, and TypeScript cannot find out how to reconcile
// these two types.
return createNextState(previousState, (draft) => {

@@ -71,2 +83,7 @@ return caseReducer(draft, action);

if (process.env.NODE_ENV !== 'production') {
/*
* to keep the definition by the user in line with actual behavior,
* we enforce `addCase` to always be called before calling `addMatcher`
* as matching cases take precedence over matchers
*/
if (actionMatchers.length > 0) {

@@ -88,3 +105,5 @@ throw new Error('`builder.addCase` should only be called before calling `builder.addMatcher`');

},
addMatcher(matcher, reducer) {
addMatcher(matcher,
// reducer: CaseReducer<TState, A>
reducer) {
if (process.env.NODE_ENV !== 'production') {

@@ -91,0 +110,0 @@ if (defaultCaseReducer) {

@@ -16,12 +16,32 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {

import { filterAction } from './operators';
/**
* A specialized Observable that maintains internal state, which can be mutated by dispatching actions.
* Actions are processed sequentially by a reducer function to produce new state values.
* This class extends from Observable to allow subscribers to react to state changes over time.
*/
export class FlowSubject extends Observable {
/**
* Observable stream of actions dispatched to the subject.
*/
get action$() {
return __classPrivateFieldGet(this, _FlowSubject_action, "f").asObservable();
}
/**
* The current value of state.
*/
get value() {
return __classPrivateFieldGet(this, _FlowSubject_state, "f").value;
}
/**
* Flag to indicate if the observable is closed.
*/
get closed() {
return __classPrivateFieldGet(this, _FlowSubject_state, "f").closed || __classPrivateFieldGet(this, _FlowSubject_action, "f").closed;
}
/**
* Initializes a new instance of the FlowSubject class.
*
* @param reducer A reducer with an initial state or a reducer function.
* @param initialState The initial state of the subject.
*/
constructor(reducer, initialState) {

@@ -31,3 +51,11 @@ super((subscriber) => {

});
/**
* The internal subject for actions.
* @private
*/
_FlowSubject_action.set(this, new Subject());
/**
* The internal behavior subject for state management.
* @private
*/
_FlowSubject_state.set(this, void 0);

@@ -39,5 +67,17 @@ const initial = 'getInitialState' in reducer ? reducer.getInitialState() : initialState;

}
/**
* Dispatches an action to the subject.
*
* @param action The action to dispatch.
*/
next(action) {
__classPrivateFieldGet(this, _FlowSubject_action, "f").next(action);
}
/**
* Adds an effect that listens for actions and performs side effects.
*
* @param actionTypeOrFn The type of action to listen for, an array of action types, or the effect function itself.
* @param fn The effect function to execute when the action is dispatched, if the first parameter is an action type.
* @returns A subscription to the effect.
*/
addEffect(actionTypeOrFn, fn) {

@@ -64,5 +104,19 @@ const action$ = typeof actionTypeOrFn === 'function'

}
/**
* Deprecated. Use `addFlow` instead.
*
* @deprecated use `addFlow`
*
* @param fn The flow function to execute.
* @returns A subscription to the flow.
*/
addEpic(fn) {
return this.addFlow(fn);
}
/**
* Adds a flow that listens for actions and performs side effects.
*
* @param fn The flow function to execute.
* @returns A subscription to the flow.
*/
addFlow(fn) {

@@ -80,2 +134,5 @@ const epic$ = fn(this.action$, this);

}
/**
* Unsubscribes from actions and removes subscribers.
*/
unsubscribe() {

@@ -85,2 +142,5 @@ __classPrivateFieldGet(this, _FlowSubject_action, "f").unsubscribe();

}
/**
* Finalizes the subject and completes observers.
*/
complete() {

@@ -90,2 +150,7 @@ __classPrivateFieldGet(this, _FlowSubject_action, "f").complete();

}
/**
* Clones the subject to a simple observable.
*
* @returns An observable of the state.
*/
asObservable() {

@@ -92,0 +157,0 @@ return __classPrivateFieldGet(this, _FlowSubject_state, "f").asObservable();

@@ -0,1 +1,5 @@

/**
* [[include:observable/README.MD]]
* @module
*/
export { castDraft } from 'immer';

@@ -5,2 +9,3 @@ export * from './FlowSubject';

export * from './types';
/** @deprecated use {@link FlowSubject} */
export { FlowSubject as ReactiveObservable } from './FlowSubject';

@@ -7,0 +12,0 @@ export { actionMapper } from './action-mapper';

@@ -5,5 +5,7 @@ import { map } from 'rxjs/operators';

.split('.')
.reduce((cur, attr) => cur[attr], obj);
.reduce(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(cur, attr) => cur[attr], obj);
});
export default mapProp;
//# sourceMappingURL=map-prop.js.map
import { useLayoutEffect, useState } from 'react';
/**
* Apply side effect to Reactive Subject.
*
* __IMPORTANT__ observable returned from epics must return new action or will create infinite loop
*/
export const useObservableEffect = (subject, effectOrType, effect) => {

@@ -3,0 +8,0 @@ const [type] = useState(() => (typeof effectOrType === 'string' ? effectOrType : undefined));

import { useLayoutEffect } from 'react';
/**
* Apply side effect to Reactive Subject.
*
* __IMPORTANT__ observable returned from flow must return new action or will create infinite loop
*/
export const useObservableFlow = (subject, epic) => {

@@ -8,4 +13,5 @@ useLayoutEffect(() => {

};
/** @deprecated since 8.0.3 renamed to useObservableFlow */
export const useObservableEpic = useObservableFlow;
export default useObservableFlow;
//# sourceMappingURL=useObservableFlow.js.map
import { useMemo } from 'react';
import { from } from 'rxjs';
import { useObservableState } from './useObservableState';
/**
* Convert an observable input to an observable
*/
export const useObservableInput = (input) => {
return useMemo(() => from(input), [input]);
};
/** Observe state of an observable input */
export function useObservableInputState(input, initial) {

@@ -8,0 +12,0 @@ return useObservableState(useObservableInput(input), { initial });

import { useCallback, useRef } from 'react';
import { useObservableLayoutSubscription } from './useObservableSubscription';
/**
* TODO
*/
export const useObservableRef = (subject, initial) => {

@@ -4,0 +7,0 @@ initial !== null && initial !== void 0 ? initial : (initial = subject.value);

@@ -8,2 +8,5 @@ import { useMemo } from 'react';

};
/**
* Hook for observing a property of an object
*/
export function useObservableSelector(subject, selector, compare) {

@@ -10,0 +13,0 @@ return useMemo(() => selectorFn(subject, selector, compare), [subject, selector, compare]);

import { useObservableSelector } from './useObservableSelector';
import { useObservableState } from './useObservableState';
/**
* @deprecated use useObservableState (since ^8.1)
*
* will be removed in next major
*
* ```ts
* const {value} = useObservableState(useObservableSelector(...));
* ```
*
* Hook for extracting a property of an `Observable`
* @param subject the subject to observe changes on
* @param initial initial value of the state
* @param selector the property of the subject state to observe
* @param compare **Memoize** function for comparing difference
* @returns Observable property of subject
*/
export function useObservableSelectorState(subject, selector, options) {

@@ -4,0 +20,0 @@ const selector$ = useObservableSelector(subject, selector, options === null || options === void 0 ? void 0 : options.compare);

import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useObservableLayoutSubscription } from './useObservableSubscription';
/**
* Hook for extracting state of observable.
* **note** when state changes the consumer of the hook will rerender
*
* @param subject [dep] Observable subject
* @param initial initial value
* @returns current state of observable
*/
export function useObservableState(subject, opt) {
const resolveInitial = useCallback(() => {
var _a, _b;
return (_b = (_a = opt === null || opt === void 0 ? void 0 : opt.initial) !== null && _a !== void 0 ? _a : subject.value) !== null && _b !== void 0 ? _b : undefined;
/** provided initial value */
return (_b = (_a = opt === null || opt === void 0 ? void 0 : opt.initial) !== null && _a !== void 0 ? _a :
/** use subject current value if supported */
subject.value) !== null && _b !== void 0 ? _b :
/** nothing to resolve */
undefined;
}, [subject, opt === null || opt === void 0 ? void 0 : opt.initial]);

@@ -15,2 +28,5 @@ const initialValue = useRef(resolveInitial());

}, [resolveInitial]);
/**
* when subject change, reset state
*/
useLayoutEffect(() => {

@@ -17,0 +33,0 @@ setError(null);

@@ -0,2 +1,3 @@

/* eslint-disable @typescript-eslint/no-explicit-any */
export {};
//# sourceMappingURL=ts-helpers.js.map

@@ -1,2 +0,3 @@

export const version = '8.3.2';
// Generated by genversion.
export const version = '8.3.3';
//# sourceMappingURL=version.js.map
import { ActionCreator, ActionDefinitions, ActionTypes } from './types/actions';
/** flat map ActionDefinitions */
export type ActionCalls<T extends ActionDefinitions> = {
[K in keyof T]: T[K] extends ActionCreator ? (...args: Parameters<T[K]>) => void : never;
};
/**
* Maps action definitions to a subject {@link FlowSubject}
*
* @param actions - object of named action
* @param subject - target subject to map actions to
* @returns object of callable action which maps to provided subject
*/
export declare const actionMapper: <T extends ActionDefinitions>(actions: T, subject: {

@@ -6,0 +14,0 @@ next: (action: ActionTypes<T>) => void;

@@ -0,3 +1,15 @@

/**
* taken from https://github.com/reduxjs/redux-toolkit/tree/master/packages/toolkit/src
*/
import { Action, PayloadAction } from './types/actions';
import { IfMaybeUndefined, IfVoid, IsAny, IsUnknownOrNonInferrable } from './types/ts-helpers';
/**
* A "prepare" method to be used as the second parameter of `createAction`.
* Takes any number of arguments and returns a Flux Standard Action without
* type (will be added later) that *must* contain a payload (might be undefined).
*
* taken from https://github.com/reduxjs/redux-toolkit/tree/master/packages/toolkit/src
*
* @public
*/
export type PrepareAction<P> = ((...args: any[]) => {

@@ -16,2 +28,6 @@ payload: P;

});
/**
* Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
*
*/
export type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {

@@ -22,2 +38,7 @@ error: infer E;

} ? M : never> : void;
/**
* Basic type for all action creators.
*
* @inheritdoc {redux#ActionCreator}
*/
export interface BaseActionCreator<P, T extends string = string, M = never, E = never> {

@@ -27,19 +48,118 @@ type: T;

}
/**
* An action creator that takes multiple arguments that are passed
* to a `PrepareAction` method to create the final Action.
* @typeParam Args arguments for the action creator function
* @typeParam P `payload` type
* @typeParam T `type` name
* @typeParam E optional `error` type
* @typeParam M optional `meta` type
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {
/**
* Calling this {@link redux#ActionCreator} with `Args` will return
* an Action with a payload of type `P` and (depending on the `PrepareAction`
* method used) a `meta`- and `error` property of types `M` and `E` respectively.
*/
(...args: Args): PayloadAction<P, T, M, E>;
}
/**
* An action creator of type `T` that takes an optional payload of type `P`.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload of `P`.
* Calling it without an argument will return a PayloadAction with a payload of `undefined`.
*/
(payload?: P): PayloadAction<P, T>;
}
/**
* An action creator of type `T` that takes no payload.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {
/**
* Calling this {@link redux#ActionCreator} will
* return a {@link PayloadAction} of type `T` with a payload of `undefined`
*/
(): PayloadAction<undefined, T>;
}
/**
* An action creator of type `T` that requires a payload of type P.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload of `P`
*/
(payload: P): PayloadAction<P, T>;
}
/**
* An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload
* of exactly the type of the argument.
*/
<PT>(payload: PT): PayloadAction<PT, T>;
}
/**
* An action creator that produces actions with a `payload` attribute.
*
* @typeParam P the `payload` type
* @typeParam T the `type` of the resulting action
* @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
*
* @public
*/
export type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>, IsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>, IfVoid<P, ActionCreatorWithoutPayload<T>, IfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>, ActionCreatorWithPayload<P, T>>>>>>;
/**
* A utility function to create an action creator for the given action type
* string. The action creator accepts a single argument, which will be included
* in the action object as a field called payload. The action creator function
* will also have its toString() overridden so that it returns the action type,
* allowing it to be used in reducer logic that is looking for that action type.
*
* @param type The action type to use for created actions.
* @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
* If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
*
* @public
*/
export declare function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;
/**
* A utility function to create an action creator for the given action type
* string. The action creator accepts a single argument, which will be included
* in the action object as a field called payload. The action creator function
* will also have its toString() overridden so that it returns the action type,
* allowing it to be used in reducer logic that is looking for that action type.
*
* @param type The action type to use for created actions.
* @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
* If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
*
* @public
*/
export declare function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;

@@ -49,5 +169,26 @@ export declare const actionSuffixDivider = "::";

type BaseType<T extends string> = T extends `${infer A}${typeof actionSuffixDivider}${infer R}` ? A : never;
/**
* Extracts the base type from an action type string.
*
* The action type string is expected to be in the format `${baseType}${actionSuffixDivider}${actionSuffix}`,
* where `${actionSuffixDivider}` is a special character that separates the base type from the action suffix.
*
* This function returns the `baseType` part of the action type string.
*
* @param type - The action type string to extract the base type from.
* @returns The base type of the action type string, or `never` if the input string does not match the expected format.
*/
export declare function getBaseType<T extends string>(type: T): BaseType<T>;
/**
* Returns the action type of the actions created by the passed
* `createAction()`-generated action creator (arbitrary action creators
* are not supported).
*
* @param action The action creator whose action type to get.
* @returns The action type used by the action creator.
*
* @public
*/
export declare function getType<T extends string>(actionCreator: PayloadActionCreator<any, T>): T;
type IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends (...args: any[]) => any ? True : False;
export {};

@@ -15,2 +15,2 @@ import { PayloadActionCreator } from './create-action';

export declare const isFailureAction: <A extends AnyAction>(action: A) => action is ActionWithSuffix<A, "failure">;
export declare const isCompleteAction: <A extends AnyAction>(action: A) => action is ActionWithSuffix<A, "failure" | "success">;
export declare const isCompleteAction: <A extends AnyAction>(action: A) => action is ActionWithSuffix<A, "success" | "failure">;

@@ -19,8 +19,67 @@ import type { Draft } from 'immer';

};
/**
* A utility function that allows defining a reducer as a mapping from action
* type to *case reducer* functions that handle these action types. The
* reducer's initial state is passed as the first argument.
*
* @remarks
* The body of every case reducer is implicitly wrapped with a call to
* `produce()` from the [immer](https://github.com/mweststrate/immer) library.
* This means that rather than returning a new state object, you can also
* mutate the passed-in state object directly; these mutations will then be
* automatically and efficiently translated into copies, giving you both
* convenience and immutability.
*
* @overloadSummary
* This overload accepts a callback function that receives a `builder` object as its argument.
* That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
* called to define what actions this reducer will handle.
*
* @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
* @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
* case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
*
* @public
*/
export declare function createReducer<S extends NotFunction, A extends Action = AnyAction>(initialState: S | (() => S), builderCallback: (builder: ActionReducerMapBuilder<S, A>) => void): ReducerWithInitialState<S, A>;
/**
* A builder for an action <-> reducer map.
*
* @public
*/
export interface ActionReducerMapBuilder<State, Actions extends AnyAction = AnyAction> {
/**
* Adds a case reducer to handle a single exact action type.
* @remarks
* All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
* @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
* @param reducer - The actual case reducer function.
*/
addCase<ActionCreator extends TypedActionCreator<ActionType<Actions>>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State, Actions>;
/**
* Adds a case reducer to handle a single exact action type.
* @remarks
* All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
* @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
* @param reducer - The actual case reducer function.
*/
addCase<Type extends Actions['type'], A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State, Actions>;
/**
* Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.
* @remarks
* If multiple matcher reducers match, all of them will be executed in the order
* they were defined in - even if a case reducer already matched.
* All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.
* @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates)
* function
* @param reducer - The actual case reducer function.
*
*/
addMatcher<TAction extends Actions = Actions>(matcher: (action: Actions) => action is TAction, reducer: CaseReducer<State, TAction extends AnyAction ? TAction : TAction & AnyAction>): Omit<ActionReducerMapBuilder<State, Actions>, 'addCase'>;
addMatcher<TAction extends Actions = Actions>(matcher: (action: Actions) => boolean, reducer: CaseReducer<State, TAction extends AnyAction ? TAction : TAction & AnyAction>): Omit<ActionReducerMapBuilder<State, Actions>, 'addCase'>;
/**
* Adds a "default case" reducer that is executed if no case reducer and no matcher
* reducer was executed for this action.
* @param reducer - The fallback "default case" reducer function.
*/
addDefaultCase(reducer: CaseReducer<State, AnyAction>): void;

@@ -27,0 +86,0 @@ }

@@ -6,19 +6,92 @@ import { Reducer } from 'react';

import type { ReducerWithInitialState } from './types/reducers';
/**
* A specialized Observable that maintains internal state, which can be mutated by dispatching actions.
* Actions are processed sequentially by a reducer function to produce new state values.
* This class extends from Observable to allow subscribers to react to state changes over time.
*/
export declare class FlowSubject<S, A extends Action = Action> extends Observable<S> {
#private;
/**
* Observable stream of actions dispatched to the subject.
*/
get action$(): Observable<A>;
/**
* The current value of state.
*/
get value(): S;
/**
* Flag to indicate if the observable is closed.
*/
get closed(): boolean;
/**
* Initializes a new instance of the FlowSubject class.
*
* @param reducer A reducer with an initial state or a reducer function.
* @param initialState The initial state of the subject.
*/
constructor(reducer: ReducerWithInitialState<S, A> | Reducer<S, A>, initialState?: S);
/**
* Resets the state to the initial value.
*/
reset: VoidFunction;
/**
* Dispatches an action to the subject.
*
* @param action The action to dispatch.
*/
next(action: A): void;
/**
* Adds an effect that listens for actions and performs side effects.
*
* @param fn The effect function to execute.
* @returns A subscription to the effect.
*/
addEffect(fn: Effect<A, S>): Subscription;
/**
* Adds an effect that listens for a specific action type and performs side effects.
*
* @param actionType The type of action to listen for.
* @param cb The effect function to execute when the action is dispatched.
* @returns A subscription to the effect.
*/
addEffect<TType extends ActionType<A>>(actionType: TType, cb: Effect<ExtractAction<A, NoInfer<TType>>, S>): Subscription;
/**
* Adds an effect that listens for an array of action types and performs side effects.
*
* @param actionType The array of action types to listen for.
* @param cb The effect function to execute when one of the actions is dispatched.
* @returns A subscription to the effect.
*/
addEffect<TType extends ActionType<A>>(actionType: Array<TType>, cb: Effect<ExtractAction<A, NoInfer<TType>>, S>): Subscription;
/**
* Deprecated. Use `addFlow` instead.
*
* @deprecated use `addFlow`
*
* @param fn The flow function to execute.
* @returns A subscription to the flow.
*/
addEpic(fn: Flow<A, S>): Subscription;
/**
* Adds a flow that listens for actions and performs side effects.
*
* @param fn The flow function to execute.
* @returns A subscription to the flow.
*/
addFlow(fn: Flow<A, S>): Subscription;
/**
* Unsubscribes from actions and removes subscribers.
*/
unsubscribe(): void;
/**
* Finalizes the subject and completes observers.
*/
complete(): void;
/**
* Clones the subject to a simple observable.
*
* @returns An observable of the state.
*/
asObservable(): Observable<S>;
}
export default FlowSubject;

@@ -0,1 +1,5 @@

/**
* [[include:observable/README.MD]]
* @module
*/
export { castDraft } from 'immer';

@@ -5,2 +9,3 @@ export * from './FlowSubject';

export * from './types';
/** @deprecated use {@link FlowSubject} */
export { FlowSubject as ReactiveObservable } from './FlowSubject';

@@ -7,0 +12,0 @@ export { actionMapper, type ActionCalls } from './action-mapper';

import type { OperatorFunction } from 'rxjs';
import { Action, ActionType, ExtractAction } from '../types';
export declare const filterAction: <TAction extends Action, TType extends string = ActionType<TAction>>(...types: TType[]) => OperatorFunction<TAction, ExtractAction<TAction, TType>>;
import { Action, ActionType, ExtractAction, TypeConstant } from '../types';
export declare const filterAction: <TAction extends Action, TType extends TypeConstant = ActionType<TAction>>(...types: TType[]) => OperatorFunction<TAction, ExtractAction<TAction, TType>>;
export default filterAction;

@@ -9,3 +9,8 @@ import { FlowSubject } from '../FlowSubject';

}
/**
* Apply side effect to Reactive Subject.
*
* __IMPORTANT__ observable returned from epics must return new action or will create infinite loop
*/
export declare const useObservableEffect: <S, A extends Action = Action, TType extends ActionType<A> = ActionType<A>>(subject: FlowSubject<S, A>, effectOrType: Effect<A, S> | TType, effect?: Effect<ExtractAction<A, TType>, S>) => void;
export default useObservableEffect;
import { FlowSubject } from '../FlowSubject';
import { Action, Flow } from '../types';
/**
* Apply side effect to Reactive Subject.
*
* __IMPORTANT__ observable returned from flow must return new action or will create infinite loop
*/
export declare const useObservableFlow: <S, A extends Action = Action>(subject: FlowSubject<S, A>, epic: Flow<A, S>) => void;
/** @deprecated since 8.0.3 renamed to useObservableFlow */
export declare const useObservableEpic: <S, A extends Action = Action>(subject: FlowSubject<S, A>, epic: Flow<A, S>) => void;
export default useObservableFlow;
import { Observable, ObservableInput } from 'rxjs';
import { ObservableStateReturnType } from './useObservableState';
/**
* Convert an observable input to an observable
*/
export declare const useObservableInput: <T>(input: ObservableInput<T>) => Observable<T>;
export declare function useObservableInputState<TType, E = unknown, TInitial extends TType | undefined = undefined>(input: ObservableInput<TType>, initial: TType): ObservableStateReturnType<TType | TInitial, E>;
import { Observable } from '../types';
/**
* TODO
*/
export declare const useObservableRef: <S>(subject: Observable<S>, initial?: S) => React.RefObject<S | undefined>;
export default useObservableRef;
import { Observable } from '../types';
import type { NestedKeys, NestedPropType } from '../types';
/**
* Pluck observable value by string path
* @param subject observable record
* @param selector string path of property
* @param compare [optional] compare values for changes
*/
export declare function useObservableSelector<TState extends Record<string, unknown>, TPath extends NestedKeys<TState>, TValue extends NestedPropType<TState, TPath>>(subject: Observable<TState>, selector: TPath, compare?: (x: TValue, y: TValue) => boolean): Observable<TValue>;
/**
* Pluck observable value by callback function
* @param subject observable
* @param selector callback function
* @param compare [optional] compare values for changes
*/
export declare function useObservableSelector<TType, TValue = unknown>(subject: Observable<TType>, selector: (state: TType) => TValue, compare?: (x: TValue, y: TValue) => boolean): Observable<TValue>;
import { Observable } from '../types';
/**
* @deprecated use useObservableState (since ^8.1)
*
* will be removed in next major
*
* ```ts
* const {value} = useObservableState(useObservableSelector(...));
* ```
*
* Hook for extracting a property of an `Observable`
* @param subject the subject to observe changes on
* @param initial initial value of the state
* @param selector the property of the subject state to observe
* @param compare **Memoize** function for comparing difference
* @returns Observable property of subject
*/
export declare function useObservableSelectorState<TType, TValue>(subject: Observable<TType>, selector: (state: TType) => TValue, options?: {

@@ -3,0 +19,0 @@ initial?: TValue;

@@ -11,6 +11,23 @@ import { Observable, StatefulObservable } from '../types';

};
/**
* use state of observable
* @param subject [dep] Observable subject
*/
export declare function useObservableState<S, TError = unknown>(subject: Observable<S>): ObservableStateReturnType<S | undefined, TError>;
/**
* use state of observable
* @param subject [dep] Observable subject
*/
export declare function useObservableState<TType, TError = unknown, TInitial extends TType | undefined = undefined>(subject: Observable<TType>, opt: ObservableStateOptions<TInitial>): ObservableStateReturnType<TType | TInitial, TError>;
/** === StatefulObservable === */
/**
* use state of observable with value property (`FlowSubject`, `BehaviorSubject`)
* @param subject [dep] Observable subject
*/
export declare function useObservableState<TType, TError = unknown>(subject: StatefulObservable<TType>): ObservableStateReturnType<TType, TError>;
/**
* use state of observable with value property (`FlowSubject`, `BehaviorSubject`)
* @param subject [dep] Observable subject
*/
export declare function useObservableState<TType, TError = unknown>(subject: StatefulObservable<TType>, options: ObservableStateOptions<TType>): ObservableStateReturnType<TType, TError>;
export default useObservableState;
import { Observable, Observer } from 'rxjs';
export declare const useObservableSubscription: <T>(observable: Observable<T>, observer?: Partial<Observer<T>> | ((value: T) => void) | undefined, teardown?: () => void) => void;
export declare const useObservableLayoutSubscription: <T>(observable: Observable<T>, observer?: Partial<Observer<T>> | ((value: T) => void) | undefined, teardown?: () => void) => void;
export declare const useObservableSubscription: <T>(observable: Observable<T>, observer?: Partial<Observer<T>> | ((value: T) => void), teardown?: () => void) => void;
export declare const useObservableLayoutSubscription: <T>(observable: Observable<T>, observer?: Partial<Observer<T>> | ((value: T) => void), teardown?: () => void) => void;
export type TypeConstant = string;
/**
* Represents an action with a type property of type `T extends TypeConstant`.
* This type is commonly used in state management patterns like Redux to represent
* the actions that can be dispatched to update the application state.
*/
export type Action<T extends TypeConstant = TypeConstant> = {
type: T;
};
/**
* An Action type which accepts any other properties.
* This is mainly for the use of the `Reducer` type.
* This is not part of `Action` itself to prevent types that extend `Action` from
* having an index signature.
*/
export interface AnyAction extends Action {
[extraProps: string]: any;
}
/**
* A function that creates an action of type `T extends Action = AnyAction`.
* The function can accept any number of arguments, which will be used to construct the action object.
*
* @param args - The arguments used to construct the action object.
* @returns An action of type `T`.
*/
export type ActionCreator<T extends Action = AnyAction> = (...args: any[]) => T;
/**
* Represents an asynchronous action creator function that can dispatch both a success and failure action.
*
* The `success` property is a required action creator that will be dispatched upon successful completion of the asynchronous operation.
* The `failure` property is an optional action creator that will be dispatched if the asynchronous operation fails.
*/
export type AsyncActionCreator = ActionCreator & {

@@ -13,4 +37,29 @@ success: ActionCreator;

};
/**
* Utility type that represents the possible action types for an asynchronous action creator.
*
* If the provided `AsyncActionCreator` type has a `failure` property that is an `ActionCreator`,
* the resulting type will be a union of the return types of the `AsyncActionCreator`, the `success`
* action creator, and the `failure` action creator.
*
* If the provided `AsyncActionCreator` type does not have a `failure` property that is an
* `ActionCreator`, the resulting type will be a union of the return types of the `AsyncActionCreator`
* and the `success` action creator.
*
* @template T - The type of the `AsyncActionCreator`.
*/
export type AsyncActionTypes<T> = T extends AsyncActionCreator ? T['failure'] extends ActionCreator ? ReturnType<T> | ReturnType<T['success']> | ReturnType<T['failure']> : ReturnType<T> | ReturnType<T['success']> : never;
/**
* Utility type that extracts the return type of an `ActionCreator` function, or returns the input type `T` if it is already an `AnyAction`.
* This is useful for ensuring the correct action type is used in reducers and other action-handling code.
*
* @template T - The action creator function or action type to extract the return type from.
* @returns The return type of the `ActionCreator` function, or the input type `T` if it is already an `AnyAction`.
*/
export type ActionInstance<T> = T extends ActionCreator ? ReturnType<T> : T extends AnyAction ? T : never;
/**
* Represents a map of action instances for a given set of action creators.
*
* @template T - The input type, which can be a record of action creators, or any other type.
*/
export type ActionInstanceMap<T> = T extends Record<string, ActionCreator> ? {

@@ -21,5 +70,24 @@ [K in keyof T]: T[K] extends AsyncActionCreator ? AsyncActionTypes<T[K]> : ActionInstance<T[K]>;

};
/**
* Utility type that recursively extracts the `ActionTypes` from a given object type `T`.
*
* This type is useful for creating a union of all possible action types from a given set of actions.
*
* @param T - The object type to extract `ActionTypes` from.
* @returns The union of all `ActionTypes` from the given object type `T`.
*/
export type ActionTypes<T> = T extends Record<string, ActionCreator> ? ActionTypes<ActionInstanceMap<T>> : T extends Record<string, Action> ? T[keyof T] : T extends Record<string, unknown> ? {
[K in keyof T]: ActionTypes<T[K]>;
}[keyof T] : never;
/**
* An action with a string type and an associated payload. This is the
* type of action returned by `createAction()` action creators.
*
* @template P The type of the action's payload.
* @template T the type used for the action type.
* @template M The type of the action's meta (optional)
* @template E The type of the action's error (optional)
*
* @public
*/
export type PayloadAction<P = void, T extends string = string, M = never, E = never> = {

@@ -33,7 +101,55 @@ payload: P;

});
/**
* Utility type that extracts the `type` property from an `Action` type.
*
* This type is useful when working with actions in a type-safe manner, as it allows you to
* get the specific type of an action without having to manually extract it.
*
* @template T - The action type or action creator to extract the `type` from.
* @returns The `type` property of the `Action` type, or `never` if the input type is not an `Action`.
*/
export type ActionType<T> = T extends ActionCreator ? ActionType<ActionInstance<T>> : T extends Action ? T['type'] : never;
/**
* Extracts the action name from the action type string.
*
* The action type string is expected to be in the format `${actionName}::${actionSuffix}`.
* This function will return the `actionName` part of the string.
*
* If the action type string does not match the expected format, the entire action type string will be returned.
*
* @param TAction - The action type.
* @returns The action name extracted from the action type string.
*/
export type ActionBaseType<TAction extends Action> = TAction extends Action ? TAction['type'] extends `${infer AName}::${infer ASuffix}` ? AName : TAction['type'] : never;
/**
* Utility type that extracts the payload type from an `ActionInstance` type.
* If the `ActionInstance` extends `PayloadAction<any>`, the payload type is extracted.
* Otherwise, `never` is returned.
*
* This is useful for working with actions that have payloads, as it allows you to
* easily access the payload type without having to manually extract it.
*
* @template T - The `ActionInstance` type.
* @returns The payload type of the `ActionInstance`, or `never` if it does not extend `PayloadAction<any>`.
*/
export type ActionPayloadType<T> = ActionInstance<T> extends PayloadAction<any> ? ActionInstance<T>['payload'] : never;
/**
* Extracts an action type from a given action object type.
*
* This utility type is useful when you have a union of action objects, and you want to extract the action type for a specific action object.
*
* @template TAction - The action object type.
* @template TType - The action type constant. If not provided, it will be inferred from the `TAction` type.
* @returns The extracted action type.
*/
export type ExtractAction<TAction extends Action, TType extends TypeConstant = ActionType<TAction>> = Extract<TAction, Action<TType>>;
/**
* Utility type to extract action with a suffix from action type.
* The action type string is expected to be in the format `${actionName}::${actionSuffix}`.
*
* @template TAction - The action type to check.
* @template Suffix - The required suffix for the action type.
* @returns The original action type if it has the required suffix, or `never` if it does not.
*/
export type ActionWithSuffix<TAction extends Action, Suffix extends string> = TAction extends Action ? TAction['type'] extends `${infer AName}::${infer ASuffix}` ? ASuffix extends Suffix ? TAction : never : never : never;
export type ActionDefinitions = Record<string, ActionCreator>;

@@ -7,2 +7,3 @@ import { Observable } from 'rxjs';

export type { NestedKeys, NestedPropType } from './ts-helpers';
/** @deprecated use {@link Flow} */
export { Flow as Epic } from './flow';

@@ -9,0 +10,0 @@ export type ObservableType<T> = T extends Observable<infer U> ? U : never;

@@ -0,6 +1,30 @@

/**
* return True if T is `any`, otherwise return False
* taken from https://github.com/joonhocho/tsdef
*
*/
export type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;
/**
* return True if T is `unknown`, otherwise return False
* taken from https://github.com/joonhocho/tsdef
*
*/
export type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;
/**
*/
export type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;
/**
*/
export type IfVoid<P, True, False> = [void] extends [P] ? True : False;
/**
*/
export type IsUnknownOrNonInferrable<T, True, False> = IsUnknown<T, True, False>;
/**
* Helper type. Passes T out again, but boxes it in a way that it cannot
* "widen" the type by accident if it is a generic that should be inferred
* from elsewhere.
*
* ref https://github.com/Microsoft/TypeScript/issues/14829#issuecomment-322267089
*
*/
export type NoInfer<T> = [T][T extends any ? 0 : never];

@@ -7,0 +31,0 @@ export interface TypeGuard<T> {

@@ -1,1 +0,1 @@

export declare const version = "8.3.2";
export declare const version = "8.3.3";
{
"name": "@equinor/fusion-observable",
"version": "8.3.2",
"version": "8.3.3",
"description": "WIP",

@@ -59,3 +59,3 @@ "keywords": [

"rxjs": "^7.8.1",
"uuid": "^9.0.1"
"uuid": "^10.0.0"
},

@@ -66,7 +66,7 @@ "devDependencies": {

"@types/react": "^18.2.50",
"@types/uuid": "^9.0.8",
"@types/uuid": "^10.0.0",
"happy-dom": "^14.7.1",
"react": "^18.2.0",
"typescript": "^5.4.2",
"vitest": "^1.6.0"
"typescript": "^5.5.3",
"vitest": "^2.0.1"
},

@@ -73,0 +73,0 @@ "peerDependencies": {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc