chain-store 0.0.2 → 0.0.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.
package/README.md CHANGED
@@ -1,183 +1,45 @@
1
- # chain-store
1
+ ![chain-store](https://graverok.github.io/chain-store/chain-store-light.svg)
2
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 in which it was chained. Subscriptions
48
- fire after all callbacks for that action have resolved, so asynchronous callbacks
49
- can make the process take longer.
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:
3
+ **A simple event-based state manager!**
90
4
 
91
5
  ```ts
92
6
  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
-
7
+ import type { Action, AsyncAction } from "chain-store";
8
+ import { DiagnosticsChannel } from "undici-types";
9
+ import { createStore } from "./store";
10
+ import Error = DiagnosticsChannel.Error;
125
11
 
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>();
12
+ type ExampleData = { name: string, email: string };
142
13
 
143
- /* Create a store */
144
- const store = createStore<State>(initialState);
14
+ // Create Action:
15
+ const getData: Action<number> = createAction<number>();
145
16
 
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>();
17
+ // Create AsyncAction:
18
+ const fetchData: AsyncAction<number, ExampleData> = getData.target(
19
+ (id: number) => fetch(`/details/?id=${ id }`).then(res => res.json() as ExampleData)
20
+ );
167
21
 
168
- store.on(setAge, (state: State, age: number) => {
169
- state.age = age; /* State mutation */
170
- return state;
171
- });
22
+ type State = Record<number, { loading: boolean, data: ExampleData | null, error?: string }>;
172
23
 
173
- /* Subscribe to partial state updates */
174
- store
175
- .map((state: State) => state.age)
176
- .watch((age: number) => console.log(`Now I'm ${age}`));
24
+ // Create Store:
25
+ const store = createStore < State >> ({})
26
+ // Subscribe to watch changes
27
+ .on(fetchData, (state: State, params: number) => ({
28
+ ...state,
29
+ [params]: { ...state[params], loading: true, error: void 0 }
30
+ }))
31
+ .on(fetchData.done, (state: State, result: ExampleData, params: number) => ({
32
+ ...state,
33
+ [params]: { data: result, loading: false, error: void 0 }
34
+ }))
35
+ .on(fetchData.fail, (state: State, error: Error, params: number) => ({
36
+ ...state,
37
+ [params]: { data: null, loading: false, error: error.name }
38
+ }));
177
39
 
178
- setAge(42); // -> "Now I'm 42"
40
+ // Trigger
41
+ getData(1); /* or fetchData(1) */
179
42
 
180
- /* The store.watch() subscription won't be triggered
181
- because the state is the same object */
182
43
  ```
183
44
 
45
+ More info on [**github.com/graverok/chain-store**](https://github.com/graverok/chain-store)
package/dist/index.es.js CHANGED
@@ -1,201 +1,129 @@
1
- const O = () => w([]), k = (c) => {
2
- const t = [], r = [], i = b();
3
- let n = [], s = !1, e = c;
4
- const a = (o) => {
5
- var l, p;
6
- const d = t.findIndex(([h]) => h === o);
7
- d >= 0 && ((p = (l = t[d]) == null ? void 0 : l[1]) == null || p.dispose(), t.splice(d, 1));
8
- }, u = {
9
- on: (o, d) => (a(o), t.push([
10
- o,
11
- o.watch((...l) => {
12
- s = !0;
13
- const p = r.map(([m]) => m(e)), h = d(e, ...l);
14
- h !== e && (e = h, i.emit("watch")(e)), r.forEach(([m, P], j) => {
15
- const y = m(e);
16
- y !== (p == null ? void 0 : p[j]) && P(y);
17
- }), s = !1, n.forEach((m) => m()), n = [];
18
- })
19
- ]), u),
20
- off: (o) => (a(o), u),
21
- map: (o) => ({
22
- getState: () => o(e),
23
- watch: (d) => (r.push([o, d]), {
24
- dispose: () => {
25
- const l = () => {
26
- const p = r.findIndex(
27
- (h) => h[0] === o && h[1] === d
28
- );
29
- p >= 0 && r.splice(p, 1);
30
- };
31
- if (s) return n.push(l);
32
- l();
33
- }
34
- })
35
- }),
36
- getState: () => e,
37
- watch: (o) => {
38
- i.init("watch").watch(o);
39
- }
40
- };
41
- return u;
42
- }, w = (c, t) => {
43
- const r = b(), i = (e) => {
44
- r.emit("watch")(e);
45
- }, n = (e) => {
46
- try {
47
- S(i, t)(e);
48
- } catch {
49
- }
50
- };
51
- return c.push(n), Object.assign((e) => {
52
- c.forEach((a) => a(e));
53
- }, {
54
- ...r.init("watch"),
55
- map: (e) => w(c, {
56
- map: t != null && t.filter || t != null && t.map ? S(e, t, !0) : e
57
- }),
58
- filter: (e) => w(c, {
59
- ...t,
60
- filter: t != null && t.filter ? x(e, t.filter) : e
61
- }),
62
- target: (e, a) => t != null && t.filter ? E(c, {
63
- map: async (u) => {
64
- const o = t != null && t.map ? await t.map(u) : u;
65
- if (!await t.filter(
66
- o
67
- )) throw new Error();
68
- return o;
69
- },
70
- target: e,
71
- options: a
72
- }) : E(c, {
73
- map: t == null ? void 0 : t.map,
74
- target: e,
75
- options: a
76
- })
77
- });
78
- }, E = (c, t) => {
79
- const r = b(), i = [], n = async (a, u) => {
80
- var p;
81
- const o = t.target(a);
82
- if (!(o instanceof Promise)) {
83
- r.emit("watch")(a), r.emit("done")(o, a), u == null || u.done(o, a);
84
- return;
85
- }
86
- const d = i.includes(o), l = ((p = t.options) == null ? void 0 : p.skipDuplicates) !== !1;
87
- !d && l && i.push(o), (!d || !l) && r.emit("watch")(a), window.requestAnimationFrame(async () => {
88
- try {
89
- const h = await o;
90
- (!d || !l) && r.emit("done")(h, a), u == null || u.done(h, a);
91
- } catch (h) {
92
- (!d || !l) && r.emit("fail")(h, a), u == null || u.fail(h, a);
93
- } finally {
94
- if (!d || !l)
95
- r.emit("finally")(a);
96
- else {
97
- const h = i.findIndex((m) => m === o);
98
- h >= 0 && i.splice(h, 1);
99
- }
100
- u == null || u.finish(a);
101
- }
102
- });
103
- }, s = async (a, u) => {
104
- if (!t.map) return await n(a, u);
105
- try {
106
- const o = await t.map(a);
107
- await n(o, u);
108
- } catch {
109
- }
110
- };
111
- return c.push(s), Object.assign((a) => {
112
- const { events: u, methods: o } = A();
113
- return c.forEach((d) => {
114
- s === d ? s(a, u) : d(a);
115
- }), o;
116
- }, {
117
- ...r.init("watch"),
118
- done: r.init("done"),
119
- fail: r.init("fail"),
120
- finish: r.init("finish")
121
- });
122
- }, x = (c, t, r) => (i) => {
123
- const n = (t == null ? void 0 : t(i)) ?? !0, s = (e) => {
124
- if (!e && r) throw new Error();
125
- return e && c(i);
126
- };
127
- return n instanceof Promise ? n.then(s) : s(n);
128
- }, S = (c, t, r) => (i) => {
129
- var s;
130
- const n = ((s = t == null ? void 0 : t.map) == null ? void 0 : s.call(t, i)) ?? i;
131
- return n instanceof Promise ? n.then(x(c, t == null ? void 0 : t.filter, r)).catch(() => {
132
- if (r) throw new Error();
133
- return !1;
134
- }) : x(c, t == null ? void 0 : t.filter, r)(n);
135
- }, A = (c) => {
136
- const t = {}, r = c ?? {
137
- state: "pending",
138
- stored: {},
139
- set: (s) => {
140
- r.state = s;
141
- },
142
- controller: new I(() => r.state)
143
- }, i = {
144
- done: (s, e) => {
145
- var a;
146
- r.stored.result = s, r.set("done"), (a = t.done) == null || a.call(t, s, e);
147
- },
148
- fail: (s, e) => {
149
- var a;
150
- r.stored.error = s, r.set("fail"), (a = t.fail) == null || a.call(t, s, e);
151
- },
152
- finish: (s) => {
153
- var e;
154
- r.stored.params = s, (e = t.finish) == null || e.call(t, s);
155
- }
156
- }, n = (s, ...e) => t[s] ? void 0 : (a) => (t[s] = a, r.state !== "pending" && a(...e.map((u) => r.stored[u])), A(r).methods);
157
- return {
158
- events: i,
159
- methods: Object.assign(r.controller, {
160
- done: n("done", "result", "params"),
161
- fail: n("fail", "error", "params"),
162
- finish: n("finish", "params")
163
- })
164
- };
165
- };
166
- class I {
167
- constructor(t) {
168
- this.getState = t;
169
- }
170
- get state() {
171
- return this.getState();
172
- }
173
- }
174
- const b = () => {
175
- const c = {}, t = (i, n) => {
176
- var s;
177
- (s = c[i]) != null && s.includes(n) && (c[i] = c[i].filter(
178
- (e) => e !== n
179
- ));
180
- }, r = (i, n) => {
181
- var s;
182
- (s = c[i]) != null && s.includes(n) || (c[i] = [...c[i] ?? [], n]);
183
- };
184
- return {
185
- init: (i) => ({
186
- watch: (n) => (r(i, n), {
187
- dispose: () => t(i, n)
188
- })
189
- }),
190
- emit: (i) => (...n) => {
191
- var s;
192
- (s = c[i]) == null || s.forEach(
193
- (e) => e(...n)
194
- );
195
- }
196
- };
197
- };
198
- export {
199
- O as createAction,
200
- k 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);
31
+ for (let r of l) t.push(() => r(e, t, n));
32
+ for (let e = 0; e < l.length; e++) t.splice(0, 1)[0]();
33
+ }, f = (e, t, n) => {
34
+ try {
35
+ if (a) return i(e, a, (e) => u(e, t, n));
36
+ if (o) return i(e, o, (r) => r && u(e, t, n));
37
+ u(e, t, n);
38
+ } catch {}
39
+ };
40
+ return t?.(f), Object.assign((t) => {
41
+ (e ?? f)(t, []);
42
+ }, {
43
+ watch: d(s),
44
+ map: (t) => n(e ?? f, c(l), t),
45
+ filter: (t) => n(e ?? f, c(l), void 0, t),
46
+ target: (t, n) => r(e ?? f, c(l), t, n)
47
+ });
48
+ }, r = (e, t, n, r) => {
49
+ let i = {}, a = {}, s = {}, c = {}, f = [], p = async (e, t) => {
50
+ let o = n(e), d = t?.(m);
51
+ if (!(o instanceof Promise)) return i.emit?.(e), u(() => {
52
+ a.emit?.(o, e), d?.done(o, e);
53
+ });
54
+ let p = f.includes(o), h = r?.skipDuplicates !== !1;
55
+ !p && h && f.push(o), (!p || !h) && i.emit?.(e);
56
+ try {
57
+ let t = await o;
58
+ (!p || !h) && a.emit?.(t, e), d?.done(t, e);
59
+ } catch (t) {
60
+ (!p || !h) && s.emit?.(t, e), d?.fail(t, e);
61
+ } finally {
62
+ !p || !h ? c.emit?.(e) : u(() => l(f, o)), d?.finish(e);
63
+ }
64
+ }, m = (e, t, n) => {
65
+ try {
66
+ u(() => p(e, n));
67
+ } catch {}
68
+ };
69
+ return t(m), Object.assign((t) => {
70
+ let { events: n, methods: r } = o();
71
+ return e(t, [], (e) => e === m ? n : void 0), r;
72
+ }, {
73
+ watch: d(i),
74
+ done: { watch: d(a) },
75
+ fail: { watch: d(s) },
76
+ finish: { watch: d(c) }
77
+ });
78
+ }, i = (e, t, n) => {
79
+ if (!t) return n(e);
80
+ let r = t(e);
81
+ if (!(r instanceof Promise)) return n(r);
82
+ r.then(n).catch(() => void 0);
83
+ }, a = [
84
+ "done",
85
+ "fail",
86
+ "finish"
87
+ ], o = (e, t = {}) => {
88
+ let n = e ?? {
89
+ state: "pending",
90
+ stored: [],
91
+ set: (e) => n.state = e,
92
+ controller: new s(() => n.state)
93
+ }, r = a.reduce((e, r, i) => ({
94
+ ...e,
95
+ [r]: (...e) => {
96
+ n.stored[i] = e[0], i < 2 && n.set(r), t[r]?.(...e);
97
+ }
98
+ }), {}), i = (e, r) => ({ [e]: t[e] ? void 0 : (i) => {
99
+ t[e] = i;
100
+ let a = [n.stored[r]];
101
+ return r < 2 && a.push(n.stored[2]), n.state !== "pending" && i(...a), o(n, t).methods;
102
+ } });
103
+ return {
104
+ events: r,
105
+ methods: Object.assign(n.controller, a.reduce((e, t, n) => ({
106
+ ...e,
107
+ ...i(t, n)
108
+ }), {}))
109
+ };
110
+ }, s = class {
111
+ getState;
112
+ constructor(e) {
113
+ this.getState = e;
114
+ }
115
+ get state() {
116
+ return this.getState();
117
+ }
118
+ }, c = (e) => (t) => e.push(t), l = (e, t, n) => {
119
+ let r = e.findIndex(n ?? ((e) => t === e));
120
+ return r >= 0 ? e.splice(r, 1)[0] : void 0;
121
+ }, u = (e) => (async () => void 0)().then(e).catch(() => void 0), d = (e) => (t) => {
122
+ if (e?.watch) return e.watch(t);
123
+ let n = [], r = (e) => l(n, e), i = (e) => !n.includes(e) && n.push(e);
124
+ return e.watch = (e) => (i(e), { dispose: () => r(e) }), e.emit = (...e) => {
125
+ for (let t of n) t(...e);
126
+ }, e.watch(t);
201
127
  };
128
+ //#endregion
129
+ export { e as createAction, t as createStore };
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- (function(m,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(m=typeof globalThis<"u"?globalThis:m||self,b(m["chain-store"]={}))})(this,function(m){"use strict";const b=()=>y([]),P=c=>{const t=[],r=[],a=S();let i=[],s=!1,e=c;const n=o=>{var l,p;const d=t.findIndex(([h])=>h===o);d>=0&&((p=(l=t[d])==null?void 0:l[1])==null||p.dispose(),t.splice(d,1))},u={on:(o,d)=>(n(o),t.push([o,o.watch((...l)=>{s=!0;const p=r.map(([w])=>w(e)),h=d(e,...l);h!==e&&(e=h,a.emit("watch")(e)),r.forEach(([w,I],T)=>{const j=w(e);j!==(p==null?void 0:p[T])&&I(j)}),s=!1,i.forEach(w=>w()),i=[]})]),u),off:o=>(n(o),u),map:o=>({getState:()=>o(e),watch:d=>(r.push([o,d]),{dispose:()=>{const l=()=>{const p=r.findIndex(h=>h[0]===o&&h[1]===d);p>=0&&r.splice(p,1)};if(s)return i.push(l);l()}})}),getState:()=>e,watch:o=>{a.init("watch").watch(o)}};return u},y=(c,t)=>{const r=S(),a=e=>{r.emit("watch")(e)},i=e=>{try{f(a,t)(e)}catch{}};return c.push(i),Object.assign(e=>{c.forEach(n=>n(e))},{...r.init("watch"),map:e=>y(c,{map:t!=null&&t.filter||t!=null&&t.map?f(e,t,!0):e}),filter:e=>y(c,{...t,filter:t!=null&&t.filter?x(e,t.filter):e}),target:(e,n)=>t!=null&&t.filter?E(c,{map:async u=>{const o=t!=null&&t.map?await t.map(u):u;if(!await t.filter(o))throw new Error;return o},target:e,options:n}):E(c,{map:t==null?void 0:t.map,target:e,options:n})})},E=(c,t)=>{const r=S(),a=[],i=async(n,u)=>{var p;const o=t.target(n);if(!(o instanceof Promise)){r.emit("watch")(n),r.emit("done")(o,n),u==null||u.done(o,n);return}const d=a.includes(o),l=((p=t.options)==null?void 0:p.skipDuplicates)!==!1;!d&&l&&a.push(o),(!d||!l)&&r.emit("watch")(n),window.requestAnimationFrame(async()=>{try{const h=await o;(!d||!l)&&r.emit("done")(h,n),u==null||u.done(h,n)}catch(h){(!d||!l)&&r.emit("fail")(h,n),u==null||u.fail(h,n)}finally{if(!d||!l)r.emit("finally")(n);else{const h=a.findIndex(w=>w===o);h>=0&&a.splice(h,1)}u==null||u.finish(n)}})},s=async(n,u)=>{if(!t.map)return await i(n,u);try{const o=await t.map(n);await i(o,u)}catch{}};return c.push(s),Object.assign(n=>{const{events:u,methods:o}=A();return c.forEach(d=>{s===d?s(n,u):d(n)}),o},{...r.init("watch"),done:r.init("done"),fail:r.init("fail"),finish:r.init("finish")})},x=(c,t,r)=>a=>{const i=(t==null?void 0:t(a))??!0,s=e=>{if(!e&&r)throw new Error;return e&&c(a)};return i instanceof Promise?i.then(s):s(i)},f=(c,t,r)=>a=>{var s;const i=((s=t==null?void 0:t.map)==null?void 0:s.call(t,a))??a;return i instanceof Promise?i.then(x(c,t==null?void 0:t.filter,r)).catch(()=>{if(r)throw new Error;return!1}):x(c,t==null?void 0:t.filter,r)(i)},A=c=>{const t={},r=c??{state:"pending",stored:{},set:s=>{r.state=s},controller:new O(()=>r.state)},a={done:(s,e)=>{var n;r.stored.result=s,r.set("done"),(n=t.done)==null||n.call(t,s,e)},fail:(s,e)=>{var n;r.stored.error=s,r.set("fail"),(n=t.fail)==null||n.call(t,s,e)},finish:s=>{var e;r.stored.params=s,(e=t.finish)==null||e.call(t,s)}},i=(s,...e)=>t[s]?void 0:n=>(t[s]=n,r.state!=="pending"&&n(...e.map(u=>r.stored[u])),A(r).methods);return{events:a,methods:Object.assign(r.controller,{done:i("done","result","params"),fail:i("fail","error","params"),finish:i("finish","params")})}};class O{constructor(t){this.getState=t}get state(){return this.getState()}}const S=()=>{const c={},t=(a,i)=>{var s;(s=c[a])!=null&&s.includes(i)&&(c[a]=c[a].filter(e=>e!==i))},r=(a,i)=>{var s;(s=c[a])!=null&&s.includes(i)||(c[a]=[...c[a]??[],i])};return{init:a=>({watch:i=>(r(a,i),{dispose:()=>t(a,i)})}),emit:a=>(...i)=>{var s;(s=c[a])==null||s.forEach(e=>e(...i))}}};m.createAction=b,m.createStore=P,Object.defineProperty(m,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);for(let r of c)t.push(()=>r(e,t,n));for(let e=0;e<c.length;e++)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;let a=[n.stored[r]];return r<2&&a.push(n.stored[2]),n.state!==`pending`&&i(...a),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)=>{for(let t of n)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
@@ -1,10 +1,10 @@
1
1
  type ActionCall<Params, Result extends unknown = void> = (params: Params) => Result;
2
- export type ActionPromise<Params, Result, Error, Methods = ActionPromiseMethods<Params, Result, Error>, Remaining extends keyof Methods = keyof Methods> = {
2
+ export type ActionPromise<Params, Result, Error, Methods = ActionPromiseEvents<Params, Result, Error>, Remaining extends keyof Methods = keyof Methods> = {
3
3
  state: "pending" | "done" | "fail";
4
4
  } & {
5
5
  [K in Remaining]: (fn: Methods[K]) => ActionPromise<Params, Result, Error, Methods, Exclude<Remaining, K>>;
6
6
  };
7
- export type ActionPromiseMethods<Params, Result, Error> = {
7
+ export type ActionPromiseEvents<Params = any, Result = any, Error = any> = {
8
8
  done: (result: Result, params: Params) => void;
9
9
  fail: (error: Error, params: Params) => void;
10
10
  finish: (params: Params) => void;
@@ -20,7 +20,7 @@ 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<Input> {
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
26
  target: <Result, Err = Error>(fn: ChainFn<Output, Result>) => AsyncAction<Input, Result, Output, Err>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "chain-store",
3
- "description": "Simple event-based state manager",
4
- "version": "0.0.2",
3
+ "description": "Simple event-based state manager!",
4
+ "version": "0.0.4",
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",