chain-store 0.0.3 → 0.0.5

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.
package/README.md CHANGED
@@ -1,183 +1,57 @@
1
- # chain-store
2
-
3
- **A simple event-based state manager.** It works with just two functions!
4
-
5
- ```
6
- /** Any package manager */
7
-
8
- > npm install chain-store
9
- ```
10
-
11
-
12
- ### Actions
13
-
14
- Create an action, trigger it, and subscribe or unsubscribe to updates:
15
- ```ts
16
- import { createAction } from "chain-store";
17
- import type { Action, Subscription } from "chain-store";
18
-
19
- /* Create */
20
- const setNumber: Action<number> = createAction<number>()
21
-
22
- /* Subscribe */
23
- const subscription: Subscription = setNumber.watch(console.log)
24
-
25
- /* Trigger */
26
- setNumber(42); // -> 42
27
-
28
- /* Unsubscribe */
29
- subscription.dispose();
30
- ```
31
-
32
-
33
- ### Chaining
34
- Every action can be chained with other actions using the `.map` and `.filter` methods.
35
- These methods take a callback as input. The callback returns a new value for `.map`
36
- and a boolean for `.filter`. Callbacks can be asynchronous.
37
-
38
- ```ts
39
- const asString = setNumber.map((n: number) => n.toString());
40
- const asObject = asString.map(async (s: string) => ({ value: s }));
41
- const negativeOnly = setNumber.filter((n: number) => n < 0)
42
- const squareRoot = setNumber.filter((n: number) => n >= 0).map(Math.sqrt)
43
- ```
44
-
45
-
46
- All actions in a chain are connected, and triggering any of them will trigger
47
- the others. Each action triggers in the order of chaining. Subscriptions
48
- fire after all callbacks for that action have resolved, so asynchronous callbacks
49
- will take longer to process.
50
-
51
- ```ts
52
- /* Subscribe to see the output */
53
- asString.watch(s => console.log("asString", s));
54
- asObject.watch(o => console.log("asObject", o));
55
- negativeOnly.watch(n => console.log("negativeOnly", n));
56
- squareRoot.watch(n => console.log("squareRoot", n));
57
-
58
- asObject(16); // -> "asString", "16"
59
- // -> "squareRoot", 4
60
- // -> "asObject", { value: "16" } */
61
-
62
- /* "negativeOnly" is filtered out */
63
-
64
-
65
- squareRoot(-10); // -> "asString", "-10"
66
- // -> "negativeOnly", -10
67
- // -> "asObject", { value: "-10" }
68
-
69
- /* "squareRoot" is filtered out, even though it was the original trigger */
70
- ```
71
-
72
- Of course, you can choose which actions to watch. And there’s no need to create
73
- each action separately:
74
-
75
- ```ts
76
- const chainAction = createAction<number>()
77
- .filter(n > 0)
78
- .map(n => Math.pow(n, 2))
79
- .filter(n < 1000)
80
- .map(n => `Power of two is: ${n}`)
81
- ```
82
-
83
-
84
- ### Async Actions
85
- An async action is the end of a chain. The main difference between an async action
86
- and a regular action is that an async action has `.done`, `.fail`, and `.finally` methods,
87
- which can be watched just like triggers.
88
-
89
- Create an async action by chaining an action with the `.target` method:
90
-
91
- ```ts
92
- import { createAction } from "chain-store";
93
- import type { AsyncAction } from "chain-store";
94
-
95
- const asyncAction: AsyncAction<number, { data: number }>
96
- = createAction<number>().target(async (payload: number) => ({ data: payload }))
97
-
98
- asynsAction.watch((payload: number) =>
99
- console.log("start", payload));
100
-
101
- asyncActions.done.watch((result: { data: number }, payload: number) =>
102
- console.log("done", result, payload));
103
-
104
- asyncActions.fail.watch((error: Error, payload: number) =>
105
- console.log("fail", error, payload));
106
-
107
- asyncActions.finally.watch((payload: number) =>
108
- console.log("finally", payload));
109
- ```
110
-
111
- Async actions return an `ActionPromise`. It’s like a promise, but it isn’t one.
112
- It’s useful when you need to wait for an async action to complete before doing
113
- something elsewhere in the app, outside the store.
114
-
115
- ```ts
116
- const actionPromise = asyncAction(20);
117
-
118
- actionPromise.done((result: { data: number }, payload: number) => {
119
- console.log(result, params); // -> { data: 20 }, 20, "done"
120
- console.log(actionPromise.state); // -> "done"
121
- });
122
-
123
- console.log(actionPromise.state); // -> "pending"
124
-
125
-
126
- ```
127
-
128
- **Note I:** An async action fails only if its own callback is rejected. Any other
129
- rejection earlier in the chain simply stops further execution, so no fail event
130
- occurs in that case.
131
-
132
- ### Store
133
-
134
- ```ts
135
- import { createStore, createAction } from "chain-store";
136
-
137
- type State = { name: string, age: number };
138
- const initialState: State = { name: "John", age: 30 };
139
-
140
-
141
- const changeName = createAction<string>();
142
-
143
- /* Create a store */
144
- const store = createStore<State>(initialState);
145
-
146
- /* Subscribe the store to an action */
147
- store.on(changeName, (state: State, name: string) => {
148
- return { ...state, name: name };
149
- });
150
-
151
- /* Subscribe to store changes */
152
- const subscription = store.watch((state: State) => console.log(`My name is ${state.name}`));
153
-
154
- changeName("Alex"); // -> "My name is Alex"
155
-
156
- /* Unsubscribe from store changes */
157
- subscription.dispose();
158
-
159
- /* Unsubscribe the store from the action */
160
- store.off(changeName)
161
- ```
162
-
163
- The store also works with mutable state, if needed:
164
-
165
- ```ts
166
- const setAge = createAction<number>();
167
-
168
- store.on(setAge, (state: State, age: number) => {
169
- state.age = age; /* State mutation */
170
- return state;
171
- });
172
-
173
- /* Subscribe to partial state updates */
174
- store
175
- .map((state: State) => state.age)
176
- .watch((age: number) => console.log(`Now I'm ${age}`));
177
-
178
- setAge(42); // -> "Now I'm 42"
179
-
180
- /* The store.watch() subscription won't be triggered
181
- because the state is the same object */
182
- ```
183
-
1
+ ![chain-store](https://graverok.github.io/chain-store/chain-store-light.svg)
2
+
3
+ **A simple event-based state manager!**
4
+
5
+ ```ts
6
+ import { createAction, createStore } from "chain-store";
7
+ import type { Action, ActionTarget, Store } from "chain-store";
8
+
9
+ type ExampleData = { name: string, email: string };
10
+
11
+ // Create Action:
12
+ const getData: Action<number> = createAction<number>();
13
+
14
+ // Create ActionTarget:
15
+ const fetchData: ActionTarget<number, ExampleData> = getData.target(
16
+ (id: number) => {
17
+ return fetch(`/details/?id=${ id }`).then(
18
+ res => res.json() as ExampleData
19
+ )
20
+ }
21
+
22
+ );
23
+
24
+ type State = Record<number, {
25
+ loading: boolean,
26
+ data: ExampleData | null,
27
+ error?: string
28
+ }>;
29
+
30
+ // Create Store:
31
+ const store: Store<State> = createStore<State>({})
32
+ // Subscribe to watch changes
33
+ .on(fetchData, (state: State, params: number) => ({
34
+ ...state,
35
+ [params]: { ...state[params], loading: true, error: void 0 }
36
+ }))
37
+ .on(fetchData.done, (state: State, result: ExampleData, params: number) => ({
38
+ ...state,
39
+ [params]: { data: result, loading: false, error: void 0 }
40
+ }))
41
+ .on(fetchData.fail, (state: State, error: Error, params: number) => ({
42
+ ...state,
43
+ [params]: { data: null, loading: false, error: error.name }
44
+ }));
45
+
46
+ // Trigger Action
47
+ getData(1);
48
+
49
+ // Or trigger ActionTarget if you need to execute something when it's completed.
50
+ fetchData(1)
51
+ .done((result: ExampleData, params: number) => console.log(result, params))
52
+ .fail((error: Error, params: number) => console.log(error.name, params))
53
+ .finish((params: number) => console.log(params));
54
+
55
+ ```
56
+
57
+ More info on [**github.com/graverok/chain-store**](https://github.com/graverok/chain-store)
package/dist/index.es.js CHANGED
@@ -1,165 +1,121 @@
1
- const B = () => j(), C = (n) => {
2
- const e = [], o = [];
3
- let r = {}, u = [], t = !1, s = n;
4
- const d = (c) => {
5
- var a;
6
- return (a = y(e, void 0, (h) => h[0] === c)) == null ? void 0 : a[1].dispose();
7
- }, g = {
8
- on: (c, a) => (d(c), e.push([
9
- c,
10
- c.watch((...h) => {
11
- var f;
12
- t = !0;
13
- const i = o.map(([b]) => b(s)), l = a(s, ...h);
14
- l !== s && (s = l, (f = r.emit) == null || f.call(r, s)), o.forEach(([b, w], x) => {
15
- const A = b(s);
16
- A !== (i == null ? void 0 : i[x]) && w(A);
17
- }), t = !1, u.forEach((b) => b()), u = [];
18
- })
19
- ]), g),
20
- off: (c) => (d(c), g),
21
- map: (c) => ({
22
- getState: () => c(s),
23
- watch: (a) => (o.push([c, a]), {
24
- dispose: () => {
25
- const h = () => y(
26
- o,
27
- void 0,
28
- ([i, l]) => i === c && l === a
29
- );
30
- t ? u.push(h) : h();
31
- }
32
- })
33
- }),
34
- getState: () => s,
35
- watch: S(r)
36
- };
37
- return g;
38
- }, j = (n, e, o, r) => {
39
- let u = {};
40
- const t = [], s = (c, a) => {
41
- var h;
42
- (h = u.emit) == null || h.call(u, c), t.forEach((i) => i(c, a));
43
- }, d = (c, a) => {
44
- try {
45
- if (o) return q(c, o, (h) => s(h, a));
46
- if (r)
47
- return q(
48
- c,
49
- r,
50
- (h) => h && s(c, a)
51
- );
52
- s(c, a);
53
- } catch {
54
- }
55
- };
56
- return e == null || e(d), Object.assign((c) => {
57
- (n ?? d)(c);
58
- }, {
59
- watch: S(u),
60
- map: (c) => j(n ?? d, E(t), c),
61
- filter: (c) => j(n ?? d, E(t), void 0, c),
62
- target: (c, a) => K(
63
- n ?? d,
64
- E(t),
65
- c,
66
- a
67
- )
68
- });
69
- }, K = (n, e, o, r) => {
70
- let u = {}, t = {}, s = {}, d = {};
71
- const g = [], c = async (i, l) => {
72
- var x, A, O, P, D, m;
73
- const f = o(i);
74
- if (!(f instanceof Promise)) {
75
- (x = u.emit) == null || x.call(u, i), (A = t.emit) == null || A.call(t, f, i), l == null || l.done(f, i);
76
- return;
77
- }
78
- const b = g.includes(f), w = (r == null ? void 0 : r.skipDuplicates) !== !1;
79
- !b && w && g.push(f), (!b || !w) && ((O = u.emit) == null || O.call(u, i));
80
- try {
81
- const p = await f;
82
- (!b || !w) && ((P = t.emit) == null || P.call(t, p, i)), l == null || l.done(p, i);
83
- } catch (p) {
84
- (!b || !w) && ((D = s.emit) == null || D.call(s, p, i)), l == null || l.fail(p, i);
85
- } finally {
86
- !b || !w ? (m = d.emit) == null || m.call(d, i) : window.requestAnimationFrame(() => {
87
- y(g, f);
88
- }), l == null || l.finish(i);
89
- }
90
- };
91
- return e(async (i, l) => {
92
- try {
93
- await c(i, l);
94
- } catch {
95
- }
96
- }), Object.assign((i) => {
97
- const { events: l, methods: f } = I();
98
- return n(i, l), f;
99
- }, {
100
- watch: S(u),
101
- done: { watch: S(t) },
102
- fail: { watch: S(s) },
103
- finish: { watch: S(d) }
104
- });
105
- }, q = (n, e, o) => {
106
- if (!e) return o(n);
107
- const r = e(n);
108
- if (!(r instanceof Promise)) return o(r);
109
- r.then(o).catch(() => {
110
- });
111
- }, F = ["done", "fail", "finish"], I = (n) => {
112
- const e = {}, o = n ?? {
113
- state: "pending",
114
- stored: [],
115
- set: (t) => o.state = t,
116
- controller: new z(() => o.state)
117
- }, r = F.reduce(
118
- (t, s, d) => ({
119
- ...t,
120
- [s]: (g, c) => {
121
- var a;
122
- o.stored[d] = g, d < 2 && o.set(s), (a = e[s]) == null || a.call(e, g, c);
123
- }
124
- }),
125
- {}
126
- ), u = (t, s) => ({
127
- [t]: e[t] ? void 0 : (d) => (e[t] = d, o.state !== "pending" && //@ts-expect-error
128
- d(o.stored[s], s < 2 ? o.stored[2] : void 0), I(o).methods)
129
- });
130
- return {
131
- events: r,
132
- methods: Object.assign(
133
- o.controller,
134
- F.reduce(
135
- (t, s, d) => ({
136
- ...t,
137
- ...u(s, d)
138
- }),
139
- {}
140
- )
141
- )
142
- };
143
- };
144
- class z {
145
- constructor(e) {
146
- this.getState = e;
147
- }
148
- get state() {
149
- return this.getState();
150
- }
151
- }
152
- const E = (n) => (e) => n.push(e), y = (n, e, o) => {
153
- const r = n.findIndex(o ?? ((u) => e === u));
154
- return r >= 0 ? n.splice(r, 1)[0] : void 0;
155
- }, S = (n) => (e) => {
156
- if (n != null && n.watch) return n.watch(e);
157
- const o = [], r = (t) => y(o, t), u = (t) => !o.includes(t) && o.push(t);
158
- return n.watch = (t) => (u(t), {
159
- dispose: () => r(t)
160
- }), n.emit = (...t) => o.forEach((s) => s(...t)), n.watch(e);
161
- };
162
- export {
163
- B as createAction,
164
- C as createStore
1
+ //#region src/store.ts
2
+ var e = () => n(), t = (e) => {
3
+ let t = [], n = [], r = {}, i = [], a = !1, o = e, s = (e) => l(t, void 0, (t) => t[0] === e)?.[1].dispose(), c = {
4
+ on: (e, l) => (s(e), t.push([e, e.watch((...e) => {
5
+ a = !0;
6
+ let t = n.map(([e]) => e(o)), s = l(o, ...e);
7
+ s !== o && (o = s, r.emit?.(o));
8
+ for (let e = 0; e < n.length; e++) {
9
+ let r = n[e][0](o);
10
+ r !== t[e] && n[e][1](r);
11
+ }
12
+ a = !1;
13
+ for (let e of i) e();
14
+ i = [];
15
+ })]), c),
16
+ off: (e) => (s(e), c),
17
+ map: (e) => ({
18
+ getState: () => e(o),
19
+ watch: (t) => (n.push([e, t]), { dispose: () => {
20
+ let r = () => l(n, void 0, ([n, r]) => n === e && r === t);
21
+ a ? i.push(r) : r();
22
+ } })
23
+ }),
24
+ getState: () => o,
25
+ watch: d(r)
26
+ };
27
+ return c;
28
+ }, n = (e, t, a, o) => {
29
+ let s = {}, l = [], u = (e, t, n) => {
30
+ s.emit?.(e), l.forEach((r) => t.push(() => r(e, t, n))), l.forEach(() => t.splice(0, 1)[0]());
31
+ }, f = (e, t, n) => {
32
+ try {
33
+ if (a) return i(e, a, (e) => u(e, t, n));
34
+ if (o) return i(e, o, (r) => r && u(e, t, n));
35
+ u(e, t, n);
36
+ } catch {}
37
+ };
38
+ return t?.(f), Object.assign((t) => {
39
+ (e ?? f)(t, []);
40
+ }, {
41
+ watch: d(s),
42
+ map: (t) => n(e ?? f, c(l), t),
43
+ filter: (t) => n(e ?? f, c(l), void 0, t),
44
+ target: (t, n) => r(e ?? f, c(l), t, n)
45
+ });
46
+ }, r = (e, t, n, r) => {
47
+ let i = {}, a = {}, s = {}, c = {}, f = [], p = async (e, t) => {
48
+ let o = n(e), d = t?.(m);
49
+ if (!(o instanceof Promise)) return i.emit?.(e), u(() => {
50
+ a.emit?.(o, e), d?.done(o, e);
51
+ });
52
+ let p = f.includes(o), h = r?.skipDuplicates !== !1;
53
+ !p && h && f.push(o), (!p || !h) && i.emit?.(e);
54
+ try {
55
+ let t = await o;
56
+ (!p || !h) && a.emit?.(t, e), d?.done(t, e);
57
+ } catch (t) {
58
+ (!p || !h) && s.emit?.(t, e), d?.fail(t, e);
59
+ } finally {
60
+ !p || !h ? c.emit?.(e) : u(() => l(f, o)), d?.finish(e);
61
+ }
62
+ }, m = (e, t, n) => {
63
+ try {
64
+ u(() => p(e, n));
65
+ } catch {}
66
+ };
67
+ return t(m), Object.assign((t) => {
68
+ let { events: n, methods: r } = o();
69
+ return e(t, [], (e) => e === m ? n : void 0), r;
70
+ }, {
71
+ watch: d(i),
72
+ done: { watch: d(a) },
73
+ fail: { watch: d(s) },
74
+ finish: { watch: d(c) }
75
+ });
76
+ }, i = (e, t, n) => {
77
+ if (!t) return n(e);
78
+ let r = t(e);
79
+ if (!(r instanceof Promise)) return n(r);
80
+ r.then(n).catch(() => void 0);
81
+ }, a = [
82
+ "done",
83
+ "fail",
84
+ "finish"
85
+ ], o = (e, t = {}) => {
86
+ let n = e ?? {
87
+ state: "pending",
88
+ stored: [],
89
+ set: (e) => n.state = e,
90
+ controller: new s(() => n.state)
91
+ }, r = a.reduce((e, r, i) => ({
92
+ ...e,
93
+ [r]: (...e) => {
94
+ n.stored[i] = e[0], i < 2 && n.set(r), t[r]?.(...e);
95
+ }
96
+ }), {}), i = (e, r) => ({ [e]: t[e] ? void 0 : (i) => (t[e] = i, n.state !== "pending" && i(n.stored[r], ...r < 2 ? [n.stored[2]] : []), o(n, t).methods) });
97
+ return {
98
+ events: r,
99
+ methods: Object.assign(n.controller, a.reduce((e, t, n) => ({
100
+ ...e,
101
+ ...i(t, n)
102
+ }), {}))
103
+ };
104
+ }, s = class {
105
+ getState;
106
+ constructor(e) {
107
+ this.getState = e;
108
+ }
109
+ get state() {
110
+ return this.getState();
111
+ }
112
+ }, c = (e) => (t) => e.push(t), l = (e, t, n) => {
113
+ let r = e.findIndex(n ?? ((e) => t === e));
114
+ return r >= 0 ? e.splice(r, 1)[0] : void 0;
115
+ }, u = (e) => (async () => void 0)().then(e).catch(() => void 0), d = (e) => (t) => {
116
+ if (e?.watch) return e.watch(t);
117
+ let n = [], r = (e) => l(n, e), i = (e) => !n.includes(e) && n.push(e);
118
+ return e.watch = (e) => (i(e), { dispose: () => r(e) }), e.emit = (...e) => n.forEach((t) => t(...e)), e.watch(t);
165
119
  };
120
+ //#endregion
121
+ export { e as createAction, t as createStore };
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- (function(w,y){typeof exports=="object"&&typeof module<"u"?y(exports):typeof define=="function"&&define.amd?define(["exports"],y):(w=typeof globalThis<"u"?globalThis:w||self,y(w["chain-store"]={}))})(this,function(w){"use strict";const y=()=>E(),M=n=>{const s=[],e=[];let r={},u=[],t=!1,o=n;const d=c=>{var l;return(l=x(s,void 0,a=>a[0]===c))==null?void 0:l[1].dispose()},g={on:(c,l)=>(d(c),s.push([c,c.watch((...a)=>{var h;t=!0;const i=e.map(([b])=>b(o)),f=l(o,...a);f!==o&&(o=f,(h=r.emit)==null||h.call(r,o)),e.forEach(([b,p],m)=>{const A=b(o);A!==(i==null?void 0:i[m])&&p(A)}),t=!1,u.forEach(b=>b()),u=[]})]),g),off:c=>(d(c),g),map:c=>({getState:()=>c(o),watch:l=>(e.push([c,l]),{dispose:()=>{const a=()=>x(e,void 0,([i,f])=>i===c&&f===l);t?u.push(a):a()}})}),getState:()=>o,watch:S(r)};return g},E=(n,s,e,r)=>{let u={};const t=[],o=(c,l)=>{var a;(a=u.emit)==null||a.call(u,c),t.forEach(i=>i(c,l))},d=(c,l)=>{try{if(e)return P(c,e,a=>o(a,l));if(r)return P(c,r,a=>a&&o(c,l));o(c,l)}catch{}};return s==null||s(d),Object.assign(c=>{(n??d)(c)},{watch:S(u),map:c=>E(n??d,O(t),c),filter:c=>E(n??d,O(t),void 0,c),target:(c,l)=>z(n??d,O(t),c,l)})},z=(n,s,e,r)=>{let u={},t={},o={},d={};const g=[],c=async(i,f)=>{var m,A,q,F,I,K;const h=e(i);if(!(h instanceof Promise)){(m=u.emit)==null||m.call(u,i),(A=t.emit)==null||A.call(t,h,i),f==null||f.done(h,i);return}const b=g.includes(h),p=(r==null?void 0:r.skipDuplicates)!==!1;!b&&p&&g.push(h),(!b||!p)&&((q=u.emit)==null||q.call(u,i));try{const j=await h;(!b||!p)&&((F=t.emit)==null||F.call(t,j,i)),f==null||f.done(j,i)}catch(j){(!b||!p)&&((I=o.emit)==null||I.call(o,j,i)),f==null||f.fail(j,i)}finally{!b||!p?(K=d.emit)==null||K.call(d,i):window.requestAnimationFrame(()=>{x(g,h)}),f==null||f.finish(i)}};return s(async(i,f)=>{try{await c(i,f)}catch{}}),Object.assign(i=>{const{events:f,methods:h}=D();return n(i,f),h},{watch:S(u),done:{watch:S(t)},fail:{watch:S(o)},finish:{watch:S(d)}})},P=(n,s,e)=>{if(!s)return e(n);const r=s(n);if(!(r instanceof Promise))return e(r);r.then(e).catch(()=>{})},T=["done","fail","finish"],D=n=>{const s={},e=n??{state:"pending",stored:[],set:t=>e.state=t,controller:new B(()=>e.state)},r=T.reduce((t,o,d)=>({...t,[o]:(g,c)=>{var l;e.stored[d]=g,d<2&&e.set(o),(l=s[o])==null||l.call(s,g,c)}}),{}),u=(t,o)=>({[t]:s[t]?void 0:d=>(s[t]=d,e.state!=="pending"&&d(e.stored[o],o<2?e.stored[2]:void 0),D(e).methods)});return{events:r,methods:Object.assign(e.controller,T.reduce((t,o,d)=>({...t,...u(o,d)}),{}))}};class B{constructor(s){this.getState=s}get state(){return this.getState()}}const O=n=>s=>n.push(s),x=(n,s,e)=>{const r=n.findIndex(e??(u=>s===u));return r>=0?n.splice(r,1)[0]:void 0},S=n=>s=>{if(n!=null&&n.watch)return n.watch(s);const e=[],r=t=>x(e,t),u=t=>!e.includes(t)&&e.push(t);return n.watch=t=>(u(t),{dispose:()=>r(t)}),n.emit=(...t)=>e.forEach(o=>o(...t)),n.watch(s)};w.createAction=y,w.createStore=M,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`chain-store`]={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=()=>r(),n=e=>{let t=[],n=[],r={},i=[],a=!1,o=e,s=e=>u(t,void 0,t=>t[0]===e)?.[1].dispose(),c={on:(e,l)=>(s(e),t.push([e,e.watch((...e)=>{a=!0;let t=n.map(([e])=>e(o)),s=l(o,...e);s!==o&&(o=s,r.emit?.(o));for(let e=0;e<n.length;e++){let r=n[e][0](o);r!==t[e]&&n[e][1](r)}a=!1;for(let e of i)e();i=[]})]),c),off:e=>(s(e),c),map:e=>({getState:()=>e(o),watch:t=>(n.push([e,t]),{dispose:()=>{let r=()=>u(n,void 0,([n,r])=>n===e&&r===t);a?i.push(r):r()}})}),getState:()=>o,watch:f(r)};return c},r=(e,t,n,o)=>{let s={},c=[],u=(e,t,n)=>{s.emit?.(e),c.forEach(r=>t.push(()=>r(e,t,n))),c.forEach(()=>t.splice(0,1)[0]())},d=(e,t,r)=>{try{if(n)return a(e,n,e=>u(e,t,r));if(o)return a(e,o,n=>n&&u(e,t,r));u(e,t,r)}catch{}};return t?.(d),Object.assign(t=>{(e??d)(t,[])},{watch:f(s),map:t=>r(e??d,l(c),t),filter:t=>r(e??d,l(c),void 0,t),target:(t,n)=>i(e??d,l(c),t,n)})},i=(e,t,n,r)=>{let i={},a={},o={},c={},l=[],p=async(e,t)=>{let s=n(e),f=t?.(m);if(!(s instanceof Promise))return i.emit?.(e),d(()=>{a.emit?.(s,e),f?.done(s,e)});let p=l.includes(s),h=r?.skipDuplicates!==!1;!p&&h&&l.push(s),(!p||!h)&&i.emit?.(e);try{let t=await s;(!p||!h)&&a.emit?.(t,e),f?.done(t,e)}catch(t){(!p||!h)&&o.emit?.(t,e),f?.fail(t,e)}finally{!p||!h?c.emit?.(e):d(()=>u(l,s)),f?.finish(e)}},m=(e,t,n)=>{try{d(()=>p(e,n))}catch{}};return t(m),Object.assign(t=>{let{events:n,methods:r}=s();return e(t,[],e=>e===m?n:void 0),r},{watch:f(i),done:{watch:f(a)},fail:{watch:f(o)},finish:{watch:f(c)}})},a=(e,t,n)=>{if(!t)return n(e);let r=t(e);if(!(r instanceof Promise))return n(r);r.then(n).catch(()=>void 0)},o=[`done`,`fail`,`finish`],s=(e,t={})=>{let n=e??{state:`pending`,stored:[],set:e=>n.state=e,controller:new c(()=>n.state)},r=o.reduce((e,r,i)=>({...e,[r]:(...e)=>{n.stored[i]=e[0],i<2&&n.set(r),t[r]?.(...e)}}),{}),i=(e,r)=>({[e]:t[e]?void 0:i=>(t[e]=i,n.state!==`pending`&&i(n.stored[r],...r<2?[n.stored[2]]:[]),s(n,t).methods)});return{events:r,methods:Object.assign(n.controller,o.reduce((e,t,n)=>({...e,...i(t,n)}),{}))}},c=class{getState;constructor(e){this.getState=e}get state(){return this.getState()}},l=e=>t=>e.push(t),u=(e,t,n)=>{let r=e.findIndex(n??(e=>t===e));return r>=0?e.splice(r,1)[0]:void 0},d=e=>(async()=>void 0)().then(e).catch(()=>void 0),f=e=>t=>{if(e?.watch)return e.watch(t);let n=[],r=e=>u(n,e),i=e=>!n.includes(e)&&n.push(e);return e.watch=e=>(i(e),{dispose:()=>r(e)}),e.emit=(...e)=>n.forEach(t=>t(...e)),e.watch(t)};e.createAction=t,e.createStore=n});
package/dist/store.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { Action, Store } from './types';
2
- export declare const createAction: <Input>() => Action<Input, Input>;
2
+ export declare const createAction: <Input = void>() => Action<Input, Input>;
3
3
  export declare const createStore: <State>(initialState: State) => Store<State>;
package/dist/types.d.ts CHANGED
@@ -10,7 +10,7 @@ export type ActionPromiseEvents<Params = any, Result = any, Error = any> = {
10
10
  finish: (params: Params) => void;
11
11
  };
12
12
  export type Args<Params> = Params extends Array<unknown> ? Params : [Params];
13
- export type AsyncActionOptions = {
13
+ export type ActionTargetOptions = {
14
14
  skipDuplicates?: boolean;
15
15
  };
16
16
  export type ChainFn<Input, Output> = (params: Input) => Output | Promise<Output>;
@@ -20,12 +20,12 @@ export interface Subscription {
20
20
  export interface Unit<Params> {
21
21
  watch: (watcher: (...args: Args<Params>) => void) => Subscription;
22
22
  }
23
- export interface Action<Input, Output = Input> extends ActionCall<Input>, Unit<Output> {
23
+ export interface Action<Input = void, Output = Input> extends ActionCall<Input>, Unit<Output> {
24
24
  filter: (fn: ChainFn<Output, boolean>) => Action<Input, Output>;
25
25
  map: <Mapped>(fn: ChainFn<Output, Mapped>) => Action<Input, Mapped>;
26
- target: <Result, Err = Error>(fn: ChainFn<Output, Result>) => AsyncAction<Input, Result, Output, Err>;
26
+ target: <Result, Err = Error>(fn: ChainFn<Output, Result>) => ActionTarget<Input, Result, Output, Err>;
27
27
  }
28
- export interface AsyncAction<Input, Result, Params = Input, Err = Error> extends ActionCall<Input, ActionPromise<Params, Result, Err>>, Unit<Params> {
28
+ export interface ActionTarget<Input, Result, Params = Input, Err = Error> extends ActionCall<Input, ActionPromise<Params, Result, Err>>, Unit<Params> {
29
29
  done: {
30
30
  watch: (watcher: (result: Result, params: Params) => void) => Subscription;
31
31
  };
@@ -43,6 +43,6 @@ export interface ReadStore<State> {
43
43
  export interface Store<State> extends ReadStore<State> {
44
44
  on: <T>(action: Unit<T>, f: (state: State, ...args: Args<T>) => State) => Store<State>;
45
45
  off: <T>(action: Unit<T>) => Store<State>;
46
- map: <Part>(mapper: (state: State) => Part) => ReadStore<Part>;
46
+ map: <Mapped>(mapper: (state: State) => Mapped) => ReadStore<Mapped>;
47
47
  }
48
48
  export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "chain-store",
3
3
  "description": "Simple event-based state manager",
4
- "version": "0.0.3",
4
+ "version": "0.0.5",
5
5
  "author": {
6
6
  "name": "Aleksandr Gurianov",
7
7
  "url": "http://golova.pro"
@@ -32,12 +32,14 @@
32
32
  "@types/node": "^22.8.6",
33
33
  "prettier": "^3.1.1",
34
34
  "typescript": "^5.3.3",
35
- "vite": "5.4.6",
36
- "vite-plugin-dts": "^4.0.3",
37
- "vite-tsconfig-paths": "^4.3.1"
35
+ "vite": "^8.3.4",
36
+ "vite-plugin-dts": "^5.1.2",
37
+ "vite-tsconfig-paths": "^6.1.1",
38
+ "vitest": "^5.0.4"
38
39
  },
39
40
  "scripts": {
40
- "build": "vite build"
41
+ "build": "vite build",
42
+ "test": "vitest"
41
43
  },
42
44
  "files": [
43
45
  "dist",