nanoeffects 0.4.0 → 0.5.0

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.
Files changed (53) hide show
  1. package/README.md +4 -1
  2. package/dist/{action-creator-D48fp13T.d.ts → action-creator-DOWcbXpy.d.ts} +16 -2
  3. package/dist/actions.d.ts +38 -3
  4. package/dist/actions.js +1 -1
  5. package/dist/{bus-Cho463Sq.js → bus-BAs9x7IQ.js} +1 -1
  6. package/dist/{context-DlA80GOA.js → context-CK0ZomWt.js} +1 -1
  7. package/dist/context-plugin-B0sLWOxR.d.ts +34 -0
  8. package/dist/dev.d.ts +2 -2
  9. package/dist/effects.d.ts +153 -56
  10. package/dist/effects.js +1 -1
  11. package/dist/index.d.ts +3 -2
  12. package/dist/index.js +1 -1
  13. package/dist/{module-DVX8aYlq.d.ts → module-DCJl-qfi.d.ts} +16 -2
  14. package/dist/notrace/{action-creator-D48fp13T.d.ts → action-creator-DOWcbXpy.d.ts} +16 -2
  15. package/dist/notrace/actions.d.ts +52 -3
  16. package/dist/notrace/actions.js +1 -1
  17. package/dist/notrace/{bus-B12SvxLv.js → bus-Bdk0YyFQ.js} +1 -1
  18. package/dist/notrace/{context-yAWj0BFZ.js → context-CctVmHLC.js} +1 -1
  19. package/dist/notrace/context-plugin-B0sLWOxR.d.ts +34 -0
  20. package/dist/notrace/{delay-Cgvn16oY.js → delay-B_W1tnkS.js} +1 -1
  21. package/dist/notrace/effects.d.ts +153 -56
  22. package/dist/notrace/effects.js +1 -1
  23. package/dist/notrace/index.d.ts +3 -2
  24. package/dist/notrace/index.js +1 -1
  25. package/dist/notrace/policies.d.ts +1 -1
  26. package/dist/notrace/policies.js +1 -1
  27. package/dist/notrace/redux.d.ts +18 -20
  28. package/dist/notrace/redux.js +1 -1
  29. package/dist/observable.d.ts +1 -1
  30. package/dist/policies.d.ts +1 -1
  31. package/dist/policies.js +1 -1
  32. package/dist/react.d.ts +50 -0
  33. package/dist/react.js +1 -0
  34. package/dist/redux.d.ts +18 -20
  35. package/dist/redux.js +1 -1
  36. package/dist/trace.d.ts +1 -1
  37. package/docs/README.md +7 -1
  38. package/docs/actions.md +1 -1
  39. package/docs/context.md +24 -2
  40. package/docs/effects.md +82 -5
  41. package/docs/guide.md +2 -0
  42. package/docs/migrating-from-effector.md +293 -0
  43. package/docs/migrating-from-rxjs.md +127 -0
  44. package/docs/migrating-from-saga.md +93 -0
  45. package/docs/observable.md +1 -0
  46. package/docs/package.md +12 -2
  47. package/docs/policies.md +1 -0
  48. package/docs/react.md +157 -0
  49. package/docs/stores.md +429 -40
  50. package/docs/typescript.md +153 -0
  51. package/llms-full.txt +2645 -0
  52. package/llms.txt +48 -0
  53. package/package.json +35 -6
package/README.md CHANGED
@@ -15,6 +15,8 @@ npm install nanoeffects
15
15
 
16
16
  ESM only, no dependencies, types included.
17
17
 
18
+ Want to try it first? [Open the playground](https://stackblitz.com/github/nanoeffects/nanoeffects/tree/main/examples/playground): a search box with `debounce` and `latest`, running in your browser, no install. More playgrounds (React) and recipes: [Examples](examples/README.md).
19
+
18
20
  ## Create a bus
19
21
 
20
22
  Subscribe with `on`, send with `emit`. `on` returns a function that unsubscribes.
@@ -48,6 +50,7 @@ const bus = createBus();
48
50
  bus.on(
49
51
  "search",
50
52
  latest(async (query, ctx) => {
53
+ // signal — lets latest cancel this request, not only drop its result
51
54
  const items = await api.search(query, { signal: ctx.signal });
52
55
  ctx.emit("results", items);
53
56
  }),
@@ -85,7 +88,7 @@ Start with the [Guide](docs/guide.md) (bus → policies → effects → modules)
85
88
  | Domain logic off the UI | [Actions, commands, modules](docs/actions.md) |
86
89
  | Redux / Zustand / MobX | [Stores](docs/stores.md) |
87
90
 
88
- [Full index, package entries, tracing](docs/README.md) · [Examples](examples)
91
+ [Full index, package entries, tracing](docs/README.md) · [Examples](examples/README.md)
89
92
 
90
93
  - **Tiny.** `createBus` is about 1.3 kB gzip; other entries load only when imported.
91
94
  - **Cancellation first.** Aborting a task aborts its children and drops its result.
@@ -157,6 +157,18 @@ type Context<E extends EventMap> = EventLike<E> & ContextOf<E> & {
157
157
  /** Child task: aborted with the parent; errors propagate to the parent. */
158
158
  run<P, R>(fn: Task<P, E, R>, ...args: PayloadOf<P>): Promise<Awaited<R>>;
159
159
  };
160
+ /**
161
+ * The event map of a bus, with the context fields that plugins added. Use it to
162
+ * name the types of a bus in other files: `type AppEvents = EventsOf<typeof bus>`.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * const bus = createBus<Events>().use(effectsPlugin({ race }));
167
+ * type AppEvents = EventsOf<typeof bus>;
168
+ * type AppContext = Context<AppEvents>; // has `race`
169
+ * ```
170
+ */
171
+ type EventsOf<B> = B extends Bus<infer E extends EventMap> ? E : never;
160
172
  interface Bus<E extends EventMap> {
161
173
  on: On<E>;
162
174
  /**
@@ -173,10 +185,12 @@ interface Bus<E extends EventMap> {
173
185
  */
174
186
  use<R>(plugin: (bus: Bus<E>) => R): R;
175
187
  /** `BusOptions.context` and `.trace`, and `commands`, for what makes tasks of its own, like `modulePlugin`. */
176
- readonly context?: ContextOption<E> | undefined;
188
+ readonly ctx?: ContextOption<E> | undefined;
177
189
  /** What runs the commands; `commandsPlugin` and `modulePlugin` set it. Without one a command runs its own handler. */
178
190
  commands?: Commands | undefined;
179
191
  readonly trace?: Tracer | undefined;
192
+ /** Called with every new task context to add fields to it, for what needs the task, like `effectsPlugin`. Chain to the previous one. */
193
+ addContext?: ((ctx: object) => void) | undefined;
180
194
  }
181
195
  type BusOptions<E extends EventMap> = {
182
196
  /** Tracing of every task phase; make it with `createTracer` from `nanoeffects/trace`. */
@@ -292,4 +306,4 @@ interface ActionCreator<P = void, T extends string = string, A extends unknown[]
292
306
  toString(): T;
293
307
  }
294
308
  //#endregion
295
- export { Handler as A, ContextOf as C, EventKey as D, Emittable as E, WithType as F, commandCall as I, createBus as L, Off as M, On as N, EventLike as O, WithContext as P, Tracer as R, Context as S, Emit as T, Bus as _, EffectName as a, CommandCall as b, PayloadOf as c, Trace as d, TraceEvent as f, AnyEvent as g, Action as h, WithPayload as i, HandlerRef as j, EventPayload as k, Phase as l, UnsubscribeCallback as m, Free as n, EventMap as o, TraceLogger as p, FreeActionCreator as r, Keys as s, ActionCreator as t, Task as u, BusOptions as v, ContextOption as w, Commands as x, Command as y, anyEventType as z };
309
+ export { EventsOf as A, anyEventType as B, ContextOf as C, EventKey as D, Emittable as E, WithContext as F, WithType as I, commandCall as L, HandlerRef as M, Off as N, EventLike as O, On as P, createBus as R, Context as S, Emit as T, Bus as _, EffectName as a, CommandCall as b, PayloadOf as c, Trace as d, TraceEvent as f, AnyEvent as g, Action as h, WithPayload as i, Handler as j, EventPayload as k, Phase as l, UnsubscribeCallback as m, Free as n, EventMap as o, TraceLogger as p, FreeActionCreator as r, Keys as s, ActionCreator as t, Task as u, BusOptions as v, ContextOption as w, Commands as x, Command as y, Tracer as z };
package/dist/actions.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { n as Free, o as EventMap, r as FreeActionCreator, t as ActionCreator, u as Task } from "./action-creator-D48fp13T.js";
2
- import { a as modulePlugin, c as bindHandler, i as createModule, l as commandsPlugin, n as ModuleApi, o as Binding, r as ModuleContext, s as MadeCommand, t as Module, u as createCommand } from "./module-DVX8aYlq.js";
1
+ import { D as EventKey, _ as Bus, c as PayloadOf, n as Free, o as EventMap, r as FreeActionCreator, t as ActionCreator, u as Task } from "./action-creator-DOWcbXpy.js";
2
+ import { a as modulePlugin, c as bindHandler, i as createModule, l as commandsPlugin, n as ModuleApi, o as Binding, r as ModuleContext, s as MadeCommand, t as Module, u as createCommand } from "./module-DCJl-qfi.js";
3
3
  //#region src/actions/action.d.ts
4
4
  /**
5
5
  * Creates an action creator, as in Redux Toolkit.
@@ -34,6 +34,41 @@ export declare function createAction<A extends unknown[], P, T extends string =
34
34
  payload: P;
35
35
  }): ActionCreator<P, T, A>;
36
36
  //#endregion
37
+ //#region src/actions/emitter.d.ts
38
+ /** What `emitterPlugin` adds to the bus. */
39
+ type EmitterApi<E extends EventMap> = {
40
+ /**
41
+ * Turns an action creator into a function that emits its action on this
42
+ * bus, to pass as a callback. The function takes what the creator takes.
43
+ */
44
+ emitter: {
45
+ /** A creator without a payload type: the payload comes from the event map. */
46
+ <K extends EventKey<E>>(creator: FreeActionCreator<K>): (...payload: PayloadOf<E[K]>) => void;
47
+ <P, T extends string, A extends unknown[]>(creator: ActionCreator<P, T, A>): (...args: A) => void;
48
+ };
49
+ };
50
+ /**
51
+ * Adds `bus.emitter(creator)`: a function that emits the action of `creator`
52
+ * on this bus. Use it where something wants a callback, such as the
53
+ * subscription of a state manager, instead of `(value) => bus.emit(creator(value))`.
54
+ * The creator stays a plain `createAction`, so `bus.emit(creator(value))` and
55
+ * `bus.on(creator, …)` work as before. Returns the same bus.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * import { createBus } from "nanoeffects";
60
+ * import { createAction, emitterPlugin } from "nanoeffects/actions";
61
+ *
62
+ * const bus = createBus().use(emitterPlugin());
63
+ * const nameChanged = createAction<string>("name/changed");
64
+ * const emitNameChanged = bus.emitter(nameChanged);
65
+ *
66
+ * // nanostores: the store calls it with the new value
67
+ * $name.listen(emitNameChanged);
68
+ * ```
69
+ */
70
+ export declare const emitterPlugin: () => <E extends EventMap>(bus: Bus<E>) => Bus<E> & EmitterApi<E>;
71
+ //#endregion
37
72
  //#region src/actions/job.d.ts
38
73
  type Creator = {
39
74
  (...args: never[]): {
@@ -89,4 +124,4 @@ export declare const createJob: <P = void, R = void, T extends string = string,
89
124
  fail?: F;
90
125
  }) => Job<P, R, T, S, F>;
91
126
  //#endregion
92
- export { type ActionCreator, type Binding, type FreeActionCreator, type Job, type Module, type ModuleApi, type ModuleContext, bindHandler, commandsPlugin, createCommand, createModule, modulePlugin };
127
+ export { type ActionCreator, type Binding, type EmitterApi, type FreeActionCreator, type Job, type Module, type ModuleApi, type ModuleContext, bindHandler, commandsPlugin, createCommand, createModule, modulePlugin };
package/dist/actions.js CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./onAbort-BgMfspK4.js";import{i as t,n}from"./context-DlA80GOA.js";import{t as r}from"./event-0RIBGYqS.js";import{r as i}from"./bus-Cho463Sq.js";function a(e,t){return Object.assign((...n)=>({type:e,payload:t?t(...n).payload:n[0]}),{type:e,match:t=>t.type===e,toString:()=>e})}var o=class extends Error{};const s=(e,t)=>{let n=t=>t.type===e;function r(n,r){if(typeof r==`object`){if(!t)throw new o(`No handler for command "${e}"`);return t(n,r)}return i(a,e,n)}let a=Object.assign(r,{type:e,match:n});return a},c=(e,t)=>[e,t],l=(e=[])=>t=>{let n=/* @__PURE__ */ new Map,i=(e,t)=>{let r={fn:t};return n.set(e,[...n.get(e)??[],r]),()=>{let t=(n.get(e)??[]).filter(e=>e!==r);t.length>0?n.set(e,t):n.delete(e)}};function a(e,t){if(t)return i(r(e),t);let n=e.map(([e,t])=>i(r(e),t));return()=>{for(let e of n)e()}}a(e);let o={run:(e,t,r)=>{let i=(n.get(e.type)??[]).at(-1)?.fn,a=i&&e.wrap?e.wrap(i):i??e;return Reflect.apply(a,null,[t,r])},handle:a};return t.commands=o,o},u=e=>typeof e==`string`?a(e):e,d=(e,t,n)=>{let r=e.emit;r(Reflect.apply(t,null,[n]))},f=e=>{try{return Promise.resolve(e())}catch(e){if(e instanceof o)throw e;return Promise.reject(e)}},p=(e,t,n={})=>{let r=s(e,t),a=u(n.success??`${e}/success`),o=u(n.fail??`${e}/fail`),c=(e,t,n)=>{let r=n;return f(()=>Reflect.apply(e,null,[t,n])).then(e=>(d(r,a,e),e),e=>{d(r,o,e)})},l=e=>(t,n)=>c(e,t,n);function p(t,n){return typeof n==`object`?c(r,t,n):i(m,e,t)}let m=Object.assign(p,{type:e,match:r.match,wrap:l,success:a,fail:o});return m},m=(e,t)=>({name:e,setup:t}),h=(r=[])=>i=>{let a=i.commands??l()(i),o={handle:(...e)=>{if(!a.handle)throw Error("modulePlugin: the `commands` of the bus is not a registry from `commandsPlugin()`");return Reflect.apply(a.handle,null,e)}},s=n({event:{type:`app`,payload:void 0},bus:i,tracer:i.trace}),c=n=>{let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;return{mount:a=>{let s=r.get(a);if(s)return s;let l=i.get(a.name);l&&r.get(l)?.();let u=t(n,a.name),d=u.ctx,f=c(d),p=()=>{r.delete(a),i.get(a.name)===a&&i.delete(a.name),d.abort(),u.unlink()};r.set(a,p),i.set(a.name,a);let m=(t,n)=>{let r=Reflect.apply(o.handle,null,[t,n]);return e(d,r),r},h=(...e)=>{let t=e.map(e=>typeof e==`function`?m(e,e):f.mount(e));return()=>{for(let e of t)e()}},g=(e,...t)=>{d.run(e,...t).catch(e=>{if(!d.signal.aborted)throw e})};try{a.setup(Object.assign(d,{handle:m,use:h,spawn:g}))}catch(e){throw p(),e}return p},unmount:e=>r.get(e)?.(),isMounted:e=>r.has(e)}},u=c(s.ctx);for(let e of r)u.mount(e);return{commands:a,mount:e=>(s.ctx.signal.throwIfAborted(),u.mount(e)),unmount:u.unmount,isMounted:u.isMounted,dispose:()=>s.ctx.abort()}};export{c as bindHandler,l as commandsPlugin,a as createAction,s as createCommand,p as createJob,m as createModule,h as modulePlugin};
1
+ import{t as e}from"./onAbort-BgMfspK4.js";import{i as t,n}from"./context-CK0ZomWt.js";import{t as r}from"./event-0RIBGYqS.js";import{r as i}from"./bus-BAs9x7IQ.js";function a(e,t){return Object.assign((...n)=>({type:e,payload:t?t(...n).payload:n[0]}),{type:e,match:t=>t.type===e,toString:()=>e})}var o=class extends Error{};const s=(e,t)=>{let n=t=>t.type===e;function r(n,r){if(typeof r==`object`){if(!t)throw new o(`No handler for command "${e}"`);return t(n,r)}return i(a,e,n)}let a=Object.assign(r,{type:e,match:n});return a},c=(e,t)=>[e,t],l=(e=[])=>t=>{let n=/* @__PURE__ */ new Map,i=(e,t)=>{let r={fn:t};return n.set(e,[...n.get(e)??[],r]),()=>{let t=(n.get(e)??[]).filter(e=>e!==r);t.length>0?n.set(e,t):n.delete(e)}};function a(e,t){if(t)return i(r(e),t);let n=e.map(([e,t])=>i(r(e),t));return()=>{for(let e of n)e()}}a(e);let o={run:(e,t,r)=>{let i=(n.get(e.type)??[]).at(-1)?.fn,a=i&&e.wrap?e.wrap(i):i??e;return Reflect.apply(a,null,[t,r])},handle:a};return t.commands=o,o},u=()=>e=>{function t(t){return(...n)=>{let r=t(...n);e.emit(r)}}return Object.assign(e,{emitter:t})},d=e=>typeof e==`string`?a(e):e,f=(e,t,n)=>{let r=e.emit;r(Reflect.apply(t,null,[n]))},p=e=>{try{return Promise.resolve(e())}catch(e){if(e instanceof o)throw e;return Promise.reject(e)}},m=(e,t,n={})=>{let r=s(e,t),a=d(n.success??`${e}/success`),o=d(n.fail??`${e}/fail`),c=(e,t,n)=>{let r=n;return p(()=>Reflect.apply(e,null,[t,n])).then(e=>(f(r,a,e),e),e=>{f(r,o,e)})},l=e=>(t,n)=>c(e,t,n);function u(t,n){return typeof n==`object`?c(r,t,n):i(m,e,t)}let m=Object.assign(u,{type:e,match:r.match,wrap:l,success:a,fail:o});return m},h=(e,t)=>({name:e,setup:t}),g=(r=[])=>i=>{let a=i.commands??l()(i),o={handle:(...e)=>{if(!a.handle)throw Error("modulePlugin: the `commands` of the bus is not a registry from `commandsPlugin()`");return Reflect.apply(a.handle,null,e)}},s=n({event:{type:`app`,payload:void 0},bus:i,tracer:i.trace}),c=n=>{let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;return{mount:a=>{let s=r.get(a);if(s)return s;let l=i.get(a.name);l&&r.get(l)?.();let u=t(n,a.name),d=u.ctx,f=c(d),p=()=>{r.delete(a),i.get(a.name)===a&&i.delete(a.name),d.abort(),u.unlink()};r.set(a,p),i.set(a.name,a);let m=(t,n)=>{let r=Reflect.apply(o.handle,null,[t,n]);return e(d,r),r},h=(...e)=>{let t=e.map(e=>typeof e==`function`?m(e,e):f.mount(e));return()=>{for(let e of t)e()}},g=(e,...t)=>{d.run(e,...t).catch(e=>{if(!d.signal.aborted)throw e})};try{a.setup(Object.assign(d,{handle:m,use:h,spawn:g}))}catch(e){throw p(),e}return p},unmount:e=>r.get(e)?.(),isMounted:e=>r.has(e)}},u=c(s.ctx);for(let e of r)u.mount(e);return{commands:a,mount:e=>(s.ctx.signal.throwIfAborted(),u.mount(e)),unmount:u.unmount,isMounted:u.isMounted,dispose:()=>s.ctx.abort(),createModule:h}};export{c as bindHandler,l as commandsPlugin,a as createAction,s as createCommand,m as createJob,h as createModule,u as emitterPlugin,g as modulePlugin};
@@ -1 +1 @@
1
- import{n as e}from"./onAbort-BgMfspK4.js";import{a as t,n,r}from"./context-DlA80GOA.js";import{n as i}from"./promise-CSLpzwSR.js";import{n as a,t as o}from"./event-0RIBGYqS.js";const s=`*`,c=()=>{let e={},t={},n=n=>(t[n]=void 0,e[n]??=/* @__PURE__ */ new Map,e[n]),r=(e,t)=>{let r=n(e),i=r.get(t)??0;i>1?r.set(t,i-1):t?r.delete(t):r.clear()};return{get:n=>(t[n]??=[...e[n]??[]].flatMap(([e,t])=>Array(t).fill(e)),t[n]),add:(e,t)=>{let i=n(e);return i.set(t,(i.get(t)??0)+1),()=>{r(e,t)}},remove:r,clear:()=>{for(let t of Reflect.ownKeys(e))delete e[t];for(let e of Reflect.ownKeys(t))delete t[e]}}},l=Symbol(`nanoeffects.commandCall`),u=(e,t,n)=>{let r={type:t,payload:n};return Object.defineProperty(r,l,{value:e,enumerable:!1}),r},d=e=>{if(typeof e==`function`)return e;if(typeof e==`object`&&e&&l in e)return e[l]},f=(e,t,n)=>Reflect.apply(e,null,[t,n]),p=(s={})=>{let l=c(),u=(e,t)=>l.add(o(e),t),p=(e,t)=>{let n=u(e,(e,r)=>(n(),t(e,r)));return n},m=(e,t)=>{e===void 0?l.clear():l.remove(o(e),t)},h=(t,a)=>{let{onError:o}=s,{ctx:c}=n({event:a,bus:g,tracer:s.trace,parent:{ref:r()}});if(!o){t(a.payload,c);return}let l=t=>{try{o(t,a)}catch(t){e(`onError failed`,t)}};try{let e=t(a.payload,c);i(e)&&Promise.resolve(e).catch(l)}catch(e){l(e)}},g={on:u,once:p,off:m,emit:(e,i)=>{let c=o(e),u=a(e,i),p={type:c,payload:u},m=d(e),_=[...l.get(c),...l.get(`*`)];_.length===0&&!m&&s.onUnhandled?.(p);for(let e of _)h(e,p);if(m){let{ctx:e}=n({event:p,bus:g,tracer:s.trace,parent:{ref:r()}}),i=g.commands?.run??f;return t(e,`command`,()=>i(m,u,e))}},use:e=>e(g),context:s.context,trace:s.trace};return g};export{s as i,p as n,u as r,l as t};
1
+ import{n as e}from"./onAbort-BgMfspK4.js";import{a as t,n,r}from"./context-CK0ZomWt.js";import{n as i}from"./promise-CSLpzwSR.js";import{n as a,t as o}from"./event-0RIBGYqS.js";const s=`*`,c=()=>{let e={},t={},n=n=>(t[n]=void 0,e[n]??=/* @__PURE__ */ new Map,e[n]),r=(e,t)=>{let r=n(e),i=r.get(t)??0;i>1?r.set(t,i-1):t?r.delete(t):r.clear()};return{get:n=>(t[n]??=[...e[n]??[]].flatMap(([e,t])=>Array(t).fill(e)),t[n]),add:(e,t)=>{let i=n(e);return i.set(t,(i.get(t)??0)+1),()=>{r(e,t)}},remove:r,clear:()=>{for(let t of Reflect.ownKeys(e))delete e[t];for(let e of Reflect.ownKeys(t))delete t[e]}}},l=Symbol(`nanoeffects.commandCall`),u=(e,t,n)=>{let r={type:t,payload:n};return Object.defineProperty(r,l,{value:e,enumerable:!1}),r},d=e=>{if(typeof e==`function`)return e;if(typeof e==`object`&&e&&l in e)return e[l]},f=(e,t,n)=>Reflect.apply(e,null,[t,n]),p=(s={})=>{let l=c(),u=(e,t)=>l.add(o(e),t),p=(e,t)=>{let n=u(e,(e,r)=>(n(),t(e,r)));return n},m=(e,t)=>{e===void 0?l.clear():l.remove(o(e),t)},h=(t,a)=>{let{onError:o}=s,{ctx:c}=n({event:a,bus:g,tracer:s.trace,parent:{ref:r()}});if(!o){t(a.payload,c);return}let l=t=>{try{o(t,a)}catch(t){e(`onError failed`,t)}};try{let e=t(a.payload,c);i(e)&&Promise.resolve(e).catch(l)}catch(e){l(e)}},g={on:u,once:p,off:m,emit:(e,i)=>{let c=o(e),u=a(e,i),p={type:c,payload:u},m=d(e),_=[...l.get(c),...l.get(`*`)];_.length===0&&!m&&s.onUnhandled?.(p);for(let e of _)h(e,p);if(m){let{ctx:e}=n({event:p,bus:g,tracer:s.trace,parent:{ref:r()}}),i=g.commands?.run??f;return t(e,`command`,()=>i(m,u,e))}},use:e=>e(g),ctx:s.context,trace:s.trace};return g};export{s as i,p as n,u as r,l as t};
@@ -1 +1 @@
1
- import{t as e}from"./onAbort-BgMfspK4.js";const t=t=>{let n=new AbortController;return{controller:n,unlink:e({signal:t},e=>n.abort(e))}},n=typeof __NANOEFFECTS_TRACE__>`u`||__NANOEFFECTS_TRACE__,r=/* @__PURE__ */ new WeakMap;let i;const a=()=>i,o=()=>{},s=(e,t,i,a)=>{let o=n&&r.get(e);o&&o.tracer.report(o.ref,t,i,a)},c=(e,t)=>{let i=n&&r.get(e);return i?i.tracer.settler(i.ref,t):o},l=(e,t,i)=>{let a=n&&r.get(e);return a?a.tracer.run(a.ref,t,e.signal,i):i()},u=(e,t)=>typeof e==`function`?e(t):e,d=e=>e,f=({event:a,bus:s,tracer:c,parent:p})=>{let{controller:m,unlink:h}=t(p?.signal),{signal:g}=m,_=n&&c?{tracer:c,ref:c.task(a,p?.ref)}:void 0,v=(...e)=>{if(g.aborted)return;let t=s?.emit,n=i;i=_?.ref;try{return t?.(...e)}finally{i=n}},y=(...t)=>{if(g.aborted)return o;let n=s?.on,r=n?.(...t);if(!r)return o;let i=e({signal:g},r);return()=>{i(),r()}},b=async(e,...t)=>{g.throwIfAborted();let n=t[0],r=f({event:{type:a.type,payload:n},bus:s,tracer:c,parent:{signal:g,ref:_?.ref}});try{return await l(r.ctx,`run`,()=>e(n,r.ctx))}finally{r.unlink()}},x=d({...u(s?.context,a),type:a.type,payload:a.payload,signal:g,abort:e=>m.abort(e),emit:v,on:y,off:s?.off??o,run:b});return _&&r.set(x,_),{ctx:x,unlink:h}},p=(e,t)=>{let i=n?r.get(e):void 0;return f({event:{type:t??e.type??``,payload:e.payload},bus:{emit:e.emit,on:e.on,off:e.off,context:e},tracer:i?.tracer,parent:{signal:e.signal,ref:i?.ref}})};export{l as a,p as i,f as n,s as o,a as r,c as t};
1
+ import{t as e}from"./onAbort-BgMfspK4.js";const t=t=>{let n=new AbortController;return{controller:n,unlink:e({signal:t},e=>n.abort(e))}},n=typeof __NANOEFFECTS_TRACE__>`u`||__NANOEFFECTS_TRACE__,r=/* @__PURE__ */ new WeakMap;let i;const a=()=>i,o=()=>{},s=(e,t,i,a)=>{let o=n&&r.get(e);o&&o.tracer.report(o.ref,t,i,a)},c=(e,t)=>{let i=n&&r.get(e);return i?i.tracer.settler(i.ref,t):o},l=(e,t,i)=>{let a=n&&r.get(e);return a?a.tracer.run(a.ref,t,e.signal,i):i()},u=(e,t)=>typeof e==`function`?e(t):e,d=e=>e,f=({event:a,bus:s,tracer:c,parent:p})=>{let{controller:m,unlink:h}=t(p?.signal),{signal:g}=m,_=n&&c?{tracer:c,ref:c.task(a,p?.ref)}:void 0,v=(...e)=>{if(g.aborted)return;let t=s?.emit,n=i;i=_?.ref;try{return t?.(...e)}finally{i=n}},y=(...t)=>{if(g.aborted)return o;let n=s?.on,r=n?.(...t);if(!r)return o;let i=e({signal:g},r);return()=>{i(),r()}},b=async(e,...t)=>{g.throwIfAborted();let n=t[0],r=f({event:{type:a.type,payload:n},bus:s,tracer:c,parent:{signal:g,ref:_?.ref}});try{return await l(r.ctx,`run`,()=>e(n,r.ctx))}finally{r.unlink()}},x=d({...u(s?.ctx,a),type:a.type,payload:a.payload,signal:g,abort:e=>m.abort(e),emit:v,on:y,off:s?.off??o,run:b});return s?.addContext?.(x),_&&r.set(x,_),{ctx:x,unlink:h}},p=(e,t)=>{let i=n?r.get(e):void 0;return f({event:{type:t??e.type??``,payload:e.payload},bus:{emit:e.emit,on:e.on,off:e.off,ctx:e},tracer:i?.tracer,parent:{signal:e.signal,ref:i?.ref}})};export{l as a,p as i,f as n,s as o,a as r,c as t};
@@ -0,0 +1,34 @@
1
+ import { C as ContextOf, F as WithContext, _ as Bus, o as EventMap } from "./action-creator-DOWcbXpy.js";
2
+ //#region src/core/context-plugin.d.ts
3
+ /** What a function that makes the fields of a task gets to see. */
4
+ type ContextTask = {
5
+ type: string;
6
+ payload?: unknown;
7
+ };
8
+ /**
9
+ * `unknown` when none of the `fields` is already a context field of the bus,
10
+ * else `never`: the call does not compile. Used as `bus: Bus<E> & NoClash<…>`.
11
+ */
12
+ type NoClash<Fields extends object, E extends EventMap> = [keyof Fields & keyof ContextOf<E>] extends [never] ? unknown : never;
13
+ /**
14
+ * Puts `fields` on the context of every task of the bus: a store, a client, a
15
+ * logger. The types come from the value, so the event map needs no
16
+ * `WithContext`. Returns the same bus, typed with the fields. A function gets
17
+ * `{ type, payload }` of the task and returns its fields.
18
+ *
19
+ * Several uses merge with each other, with the `context` option of `createBus`
20
+ * and with `effectsPlugin`. A name that the bus already has is a type error. The
21
+ * fields of the library (`signal`, `emit`, `run`, …) win, and a field that the
22
+ * context already has is not replaced.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * type Events = { "user/loaded": User };
27
+ *
28
+ * const bus = createBus<Events>().use(contextPlugin({ store }));
29
+ * bus.on("user/loaded", (user, { store }) => store.put(user)); // ctx.store: Store
30
+ * ```
31
+ */
32
+ declare const contextPlugin: <Fields extends object>(fields: Fields | ((task: ContextTask) => Fields)) => <E extends EventMap>(bus: Bus<E> & NoClash<Fields, E>) => Bus<E & WithContext<Fields>>;
33
+ //#endregion
34
+ export { NoClash as n, contextPlugin as r, ContextTask as t };
package/dist/dev.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as Bus, m as UnsubscribeCallback, o as EventMap } from "./action-creator-D48fp13T.js";
2
- import { n as ModuleApi } from "./module-DVX8aYlq.js";
1
+ import { _ as Bus, m as UnsubscribeCallback, o as EventMap } from "./action-creator-DOWcbXpy.js";
2
+ import { n as ModuleApi } from "./module-DCJl-qfi.js";
3
3
  //#region src/dev/types.d.ts
4
4
  /** The parts of what `modulePlugin` returned that the diagnostics report. */
5
5
  type ReportedApp<E extends EventMap> = Pick<ModuleApi<E>, "mount" | "unmount" | "isMounted">;
package/dist/effects.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { S as Context, o as EventMap, s as Keys, u as Task } from "./action-creator-D48fp13T.js";
1
+ import { F as WithContext, S as Context, _ as Bus, o as EventMap, s as Keys, u as Task } from "./action-creator-DOWcbXpy.js";
2
+ import { n as NoClash } from "./context-plugin-B0sLWOxR.js";
2
3
  //#region src/utils/delay.d.ts
3
4
  /**
4
5
  * Resolves after `ms`, or rejects early if `ctx.signal` aborts. `ms` can be a
@@ -85,6 +86,38 @@ export declare function allSettled<const T extends readonly Starter<unknown>[]>(
85
86
  signal?: AbortSignal;
86
87
  }, effects: T): Promise<{ -readonly [K in keyof T]: PromiseSettledResult<Awaited<ReturnType<T[K]>>>; }>;
87
88
  //#endregion
89
+ //#region src/effects/backoff.d.ts
90
+ type BackoffOptions = {
91
+ /** Pause before the second attempt, in ms. Default 100. */
92
+ base?: number;
93
+ /** How many times each pause is longer than the one before. Default 2. */
94
+ factor?: number;
95
+ /** Longest pause, in ms. Default `Infinity`. */
96
+ max?: number;
97
+ /**
98
+ * Use a random pause from 0 up to the computed one ("full jitter"), so
99
+ * clients that failed together do not retry together. Default `false`.
100
+ */
101
+ jitter?: boolean;
102
+ };
103
+ /**
104
+ * Builds the `delay` of `retry`: the pause grows as `base * factor ** (attempt - 1)`
105
+ * and never passes `max`. `retry` counts attempts from 1; `poll` counts calls from
106
+ * 0, so there the first pause is `base / factor`.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * bus.on(
111
+ * "load",
112
+ * retry(loadUser, {
113
+ * times: 5,
114
+ * delay: backoff({ base: 200, max: 5000, jitter: true }), // 200, 400, 800, ... up to 5 s, randomised
115
+ * }),
116
+ * );
117
+ * ```
118
+ */
119
+ export declare const backoff: (options?: BackoffOptions) => (attempt: number) => number;
120
+ //#endregion
88
121
  //#region src/effects/cancellable.d.ts
89
122
  type CancellableHandle<T> = {
90
123
  resolve: (value: T | PromiseLike<T>) => void;
@@ -118,6 +151,124 @@ export declare const cancellable: <T = void>(ctx: {
118
151
  signal: AbortSignal;
119
152
  }, executor: CancellableExecutor<T>) => Promise<T>;
120
153
  //#endregion
154
+ //#region src/effects/race.d.ts
155
+ type RaceStarter<T> = Starter<T>;
156
+ /**
157
+ * Runs all starters; first to settle wins, losers are cancelled via `ctx.abort`.
158
+ * The result holds only the winner's value, under its key or index.
159
+ *
160
+ * @example
161
+ * ```ts
162
+ * bus.on("load", async (id, ctx) => {
163
+ * const result = await race(ctx, {
164
+ * data: ({ signal }) => fetchData(id, { signal }),
165
+ * timeout: ({ signal }) => delay({ signal }, 5000),
166
+ * });
167
+ *
168
+ * if ("timeout" in result) throw new Error("timed out");
169
+ * render(result.data);
170
+ * });
171
+ * ```
172
+ */
173
+ export declare function race<T extends Record<string, RaceStarter<unknown>>>(ctx: {
174
+ signal?: AbortSignal;
175
+ }, effects: T): Promise<{ [K in keyof T]?: Awaited<ReturnType<T[K]>>; }>;
176
+ export declare function race<const T extends readonly RaceStarter<unknown>[]>(ctx: {
177
+ signal?: AbortSignal;
178
+ }, effects: T): Promise<{ -readonly [K in keyof T]?: Awaited<ReturnType<T[K]>>; }>;
179
+ //#endregion
180
+ //#region src/effects/take.d.ts
181
+ type TakeOptions<P> = {
182
+ /**
183
+ * Wait for the first payload this accepts; others are skipped. A type guard
184
+ * (`(payload): payload is T`) narrows the type of the result to `T`.
185
+ */
186
+ predicate?: (payload: P) => boolean;
187
+ /** Stop waiting when this aborts, e.g. the signal of a `race` starter. */
188
+ signal?: AbortSignal | undefined;
189
+ };
190
+ /**
191
+ * Waits for the next `event` on the bus and resolves with its payload. It sees
192
+ * only events emitted after the call, takes only one, and unsubscribes when it
193
+ * is done. If `ctx` (or `options.signal`) aborts first, it unsubscribes and
194
+ * rejects with the abort reason.
195
+ *
196
+ * @example
197
+ * ```ts
198
+ * bus.on("login", async (user, ctx) => {
199
+ * const reason = await take(ctx, "logout");
200
+ * cleanup(user, reason);
201
+ * });
202
+ *
203
+ * // wait for a matching event, but not longer than 5 s
204
+ * const done = await timeout(ctx, 5000, ({ signal }) =>
205
+ * take(ctx, "saved", { signal, predicate: (id) => id === draftId }),
206
+ * );
207
+ *
208
+ * // a type guard narrows the result: `failed` is `{ ok: false }`
209
+ * const failed = await take(ctx, "result", {
210
+ * predicate: (result): result is { ok: false } => !result.ok,
211
+ * });
212
+ * ```
213
+ */
214
+ export declare function take<E extends EventMap, K extends Keys<E>, T extends E[K]>(ctx: Context<E>, event: K, options: TakeOptions<E[K]> & {
215
+ predicate: (payload: E[K]) => payload is T;
216
+ }): Promise<T>;
217
+ export declare function take<E extends EventMap, K extends Keys<E>>(ctx: Context<E>, event: K, options?: TakeOptions<E[K]>): Promise<E[K]>;
218
+ //#endregion
219
+ //#region src/effects/plugin.d.ts
220
+ /** The effects that `effectsPlugin` can put on `ctx`. */
221
+ type Supported = {
222
+ race: typeof race;
223
+ all: typeof all;
224
+ allSettled: typeof allSettled;
225
+ take: typeof take;
226
+ delay: typeof delay;
227
+ };
228
+ type Results = Record<string, Starter<unknown>>;
229
+ type List = readonly Starter<unknown>[];
230
+ /** Each supported effect without its leading `ctx` argument. `take` knows the events of the bus. */
231
+ type Bound<E extends EventMap> = {
232
+ race: {
233
+ <T extends Results>(effects: T): Promise<{ [K in keyof T]?: Awaited<ReturnType<T[K]>>; }>;
234
+ <const T extends List>(effects: T): Promise<{ -readonly [K in keyof T]?: Awaited<ReturnType<T[K]>>; }>;
235
+ };
236
+ all: {
237
+ <T extends Results>(effects: T): Promise<{ [K in keyof T]: Awaited<ReturnType<T[K]>>; }>;
238
+ <const T extends List>(effects: T): Promise<{ -readonly [K in keyof T]: Awaited<ReturnType<T[K]>>; }>;
239
+ };
240
+ allSettled: {
241
+ <T extends Results>(effects: T): Promise<{ [K in keyof T]: PromiseSettledResult<Awaited<ReturnType<T[K]>>>; }>;
242
+ <const T extends List>(effects: T): Promise<{ -readonly [K in keyof T]: PromiseSettledResult<Awaited<ReturnType<T[K]>>>; }>;
243
+ };
244
+ take: <K extends Keys<E>>(event: K, options?: TakeOptions<E[K]>) => Promise<E[K]>;
245
+ delay: (ms: number | (() => number)) => Promise<void>;
246
+ };
247
+ type Helpers = Partial<Supported>;
248
+ type BoundOf<H extends Helpers, E extends EventMap> = { [K in keyof H & keyof Bound<E>]: Bound<E>[K]; };
249
+ /**
250
+ * Puts the effects you pass on the context of every task of the bus, bound to
251
+ * that task, so a handler can write `({ race })` instead of `race(ctx, …)`.
252
+ * The key is the name of the effect: `race`, `all`, `allSettled`, `take`,
253
+ * `delay`. Returns the same bus, typed with the new fields.
254
+ *
255
+ * @example
256
+ * ```ts
257
+ * import { createBus } from "nanoeffects";
258
+ * import { all, delay, effectsPlugin, race } from "nanoeffects/effects";
259
+ *
260
+ * const bus = createBus().use(effectsPlugin({ race, delay }));
261
+ *
262
+ * bus.on("load", async (id, { race, delay }) => {
263
+ * const result = await race({
264
+ * data: ({ signal }) => fetchData(id, { signal }),
265
+ * timeout: () => delay(5000),
266
+ * });
267
+ * });
268
+ * ```
269
+ */
270
+ export declare const effectsPlugin: <H extends Helpers>(helpers: H) => <E extends EventMap>(bus: Bus<E> & NoClash<BoundOf<H, E>, E>) => Bus<E & WithContext<BoundOf<H, E>>>;
271
+ //#endregion
121
272
  //#region src/effects/poll.d.ts
122
273
  type PollOptions = {
123
274
  /** Also call `fn` at once, not only after the first `ms`. Default `false`. */
@@ -160,32 +311,6 @@ export declare function poll(ctx: {
160
311
  signal: AbortSignal;
161
312
  }, fn: (tick: number) => unknown, ms: PollMs, options?: PollOptions): Promise<void>;
162
313
  //#endregion
163
- //#region src/effects/race.d.ts
164
- type RaceStarter<T> = Starter<T>;
165
- /**
166
- * Runs all starters; first to settle wins, losers are cancelled via `ctx.abort`.
167
- * The result holds only the winner's value, under its key or index.
168
- *
169
- * @example
170
- * ```ts
171
- * bus.on("load", async (id, ctx) => {
172
- * const result = await race(ctx, {
173
- * data: ({ signal }) => fetchData(id, { signal }),
174
- * timeout: ({ signal }) => delay({ signal }, 5000),
175
- * });
176
- *
177
- * if ("timeout" in result) throw new Error("timed out");
178
- * render(result.data);
179
- * });
180
- * ```
181
- */
182
- export declare function race<T extends Record<string, RaceStarter<unknown>>>(ctx: {
183
- signal?: AbortSignal;
184
- }, effects: T): Promise<{ [K in keyof T]?: Awaited<ReturnType<T[K]>>; }>;
185
- export declare function race<const T extends readonly RaceStarter<unknown>[]>(ctx: {
186
- signal?: AbortSignal;
187
- }, effects: T): Promise<{ -readonly [K in keyof T]?: Awaited<ReturnType<T[K]>>; }>;
188
- //#endregion
189
314
  //#region src/effects/retry.d.ts
190
315
  type RetryOptions = {
191
316
  /** Total number of attempts, the first one included. Default 3. */
@@ -226,34 +351,6 @@ export declare function retry<T>(ctx: {
226
351
  signal?: AbortSignal;
227
352
  }, fn: RetryFn<T>, options?: RetryOptions): Promise<T>;
228
353
  //#endregion
229
- //#region src/effects/take.d.ts
230
- type TakeOptions<P> = {
231
- /** Wait for the first payload this accepts; others are skipped. */
232
- predicate?: (payload: P) => boolean;
233
- /** Stop waiting when this aborts, e.g. the signal of a `race` starter. */
234
- signal?: AbortSignal | undefined;
235
- };
236
- /**
237
- * Waits for the next `event` on the bus and resolves with its payload. It sees
238
- * only events emitted after the call, takes only one, and unsubscribes when it
239
- * is done. If `ctx` (or `options.signal`) aborts first, it unsubscribes and
240
- * rejects with the abort reason.
241
- *
242
- * @example
243
- * ```ts
244
- * bus.on("login", async (user, ctx) => {
245
- * const reason = await take(ctx, "logout");
246
- * cleanup(user, reason);
247
- * });
248
- *
249
- * // wait for a matching event, but not longer than 5 s
250
- * const done = await timeout(ctx, 5000, ({ signal }) =>
251
- * take(ctx, "saved", { signal, predicate: (id) => id === draftId }),
252
- * );
253
- * ```
254
- */
255
- export declare const take: <E extends EventMap, K extends Keys<E>>(ctx: Context<E>, event: K, options?: TakeOptions<E[K]>) => Promise<E[K]>;
256
- //#endregion
257
354
  //#region src/effects/timeout.d.ts
258
355
  /**
259
356
  * Runs a function; if it takes longer than `ms`, aborts its signal and rejects
@@ -281,4 +378,4 @@ export declare function timeout<T>(ctx: {
281
378
  signal?: AbortSignal;
282
379
  }, ms: number, starter: Starter<T>): Promise<T>;
283
380
  //#endregion
284
- export type { CancellableExecutor, CancellableHandle, EffectContext, PollOptions, RaceStarter, RetryOptions, TakeOptions };
381
+ export type { BackoffOptions, CancellableExecutor, CancellableHandle, EffectContext, PollOptions, RaceStarter, RetryOptions, TakeOptions };
package/dist/effects.js CHANGED
@@ -1 +1 @@
1
- import{n as e,t}from"./onAbort-BgMfspK4.js";import{a as n,i as r,o as i,t as a}from"./context-DlA80GOA.js";import{n as o,r as s,t as c}from"./delay-CIHnOh_L.js";const l=(e,n)=>n?.signal?new Promise((r,i)=>{let a=t(n,i);e.then(r,i).finally(a)}):e,u=async(e,n,o,s)=>{n?.signal?.throwIfAborted();let{ctx:c,unlink:u}=r(n??{}),d=a(c,e);i(c,e,`start`),t(c,()=>d(`cancel`));try{let e=await l(o(c),n);return d(`done`),s?.(!1),e}catch(e){throw d(`error`,e),s?.(!0),e}finally{u()}},d=async(e,t)=>{let{ctx:i,unlink:a}=r(e);try{return await n(i,`run`,()=>t(i))}finally{a()}},f=e=>e,p=(e,t)=>n=>e(t,f(n)),m=e=>Array.isArray(e)?Array(e.length):{},h=(e,t)=>{let i=Object.entries(t).map(([t,i])=>{let a=r(e),o={signal:a.ctx.signal,abort:a.ctx.abort},s=()=>i(o);return{key:t,task:new Promise(e=>e(n(a.ctx,`run`,s))).finally(a.unlink),cancel:a.ctx.abort}});return{tasks:i.map(({key:e,task:t})=>[e,t]),cancelAll:()=>{for(let e of i)e.cancel()}}},g=(e,t,n,r,i)=>{let a=()=>{};return u(e,t,async e=>{let t=h(e,n);return a=t.cancelAll,r(t.tasks)},e=>{(e||i===`end`)&&a()})};function _(e,t){return g(`all`,e,t,async e=>{let n=await Promise.all(e.map(([,e])=>e)),r=m(t);for(let[t,[i]]of e.entries())r[i]=n[t];return r},`failure`)}const v=e=>e.then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}));function y(e,t){return g(`allSettled`,e,t,async e=>{let n=await Promise.all(e.map(([,e])=>v(e))),r=m(t);for(let[t,[i]]of e.entries())r[i]=n[t];return r},`failure`)}const b=(n,r)=>n.signal.aborted?Promise.reject(n.signal.reason):new Promise((i,a)=>{let o=[],s=`pending`,c=t=>{try{t()}catch(t){e(`cancel cleanup failed`,t)}},l=t(n,e=>{s=`cancelled`;for(let e of o.reverse())c(e);a(e)}),u=e=>(...t)=>{s===`pending`&&(s=`settled`,l(),o.length=0,e(...t))},d=e=>{s===`pending`?o.push(e):s===`cancelled`&&c(e)};try{r({resolve:u(i),reject:u(a),onCancel:d})}catch(e){u(a)(e)}}),x=(e,n,r,i)=>{if(e.signal.aborted)return Promise.resolve();let a=i.leading??!1,c=i.waitForFn??!1;return u(`poll`,e,e=>new Promise((i,l)=>{let u=0,f=null,p=()=>{f!==null&&(o(f),f=null)},m=e=>{try{f=s(h,typeof r==`function`?r(e):r)}catch(e){p(),l(e)}},h=()=>{f=null,c||m(u+1),g()},g=()=>{let t=u++;d(e,e=>n(e,t)).then(()=>{c&&!e.signal.aborted&&m(u)},e=>{p(),l(e)})};t(e,p),a?(g(),c||m(u)):m(0)})).catch(t=>{if(!e.signal.aborted)throw t})};function S(e,t,n,r={}){if(typeof e!=`object`){let r=t,i=n??{};return(t,n)=>x(n,p(r,t),e,i)}let i=t;return x(e,(e,t)=>i(t),n,r)}function C(e,t){let n=m(t);return Object.keys(t).length===0?Promise.resolve(n):g(`race`,e,t,async e=>{let[t,r]=await Promise.race(e.map(([e,t])=>t.then(t=>[e,t])));return n[t]=r,n},`end`)}const w=(e,t,n)=>typeof e==`function`?e(t,n):e,T=e=>({times:e.times??3,delay:e.delay??0,shouldRetry:e.shouldRetry??(()=>!0)}),E=(e,t,n)=>u(`retry`,e,async e=>{let{times:r,delay:i,shouldRetry:a}=T(n);for(let n=1;;n++)try{return await d(e,e=>t(e,n))}catch(t){if(e.signal.throwIfAborted(),n>=r||!a(t,n))throw t;let o=w(i,n,t);o>0&&await c(e,o)}});function D(e,t,n={}){if(typeof e==`function`){let n=e;return(e,r)=>E(r,p(n,e),t??{})}let r=t;return E(e,(e,t)=>r(t),n)}const O=(e,n,r={})=>u(`take`,e,i=>new Promise((a,o)=>{let{predicate:s}=r,c=[],l=()=>{for(let e of c)e()},u=e=>{l(),o(e)};c.push(e.on(n,e=>{(!s||s(e))&&(l(),a(e))})),c.push(t(i,u)),c.push(t({signal:r.signal},u))})),k=(e,t,i)=>u(`timeout`,e,async e=>{let a=r(e),c=s(()=>a.ctx.abort(new DOMException(`Timed out after ${t}ms`,`TimeoutError`)),t);try{return await l(Promise.resolve(n(a.ctx,`run`,()=>i(a.ctx))),a.ctx)}finally{o(c),a.unlink()}});function A(e,t,n){if(typeof e==`number`){let n=t;return(t,r)=>k(r,e,p(n,t))}let r=t,i=n;return k(e,r,e=>i({signal:e.signal,abort:e.abort}))}export{_ as all,y as allSettled,b as cancellable,c as delay,t as onAbort,S as poll,C as race,D as retry,O as take,A as timeout};
1
+ import{n as e,t}from"./onAbort-BgMfspK4.js";import{a as n,i as r,o as i,t as a}from"./context-CK0ZomWt.js";import{n as o,r as s,t as c}from"./delay-CIHnOh_L.js";const l=(e,n)=>n?.signal?new Promise((r,i)=>{let a=t(n,i);e.then(r,i).finally(a)}):e,u=async(e,n,o,s)=>{n?.signal?.throwIfAborted();let{ctx:c,unlink:u}=r(n??{}),d=a(c,e);i(c,e,`start`),t(c,()=>d(`cancel`));try{let e=await l(o(c),n);return d(`done`),s?.(!1),e}catch(e){throw d(`error`,e),s?.(!0),e}finally{u()}},d=async(e,t)=>{let{ctx:i,unlink:a}=r(e);try{return await n(i,`run`,()=>t(i))}finally{a()}},f=e=>e,p=(e,t)=>n=>e(t,f(n)),m=e=>Array.isArray(e)?Array(e.length):{},h=(e,t)=>{let i=Object.entries(t).map(([t,i])=>{let a=r(e),o={signal:a.ctx.signal,abort:a.ctx.abort},s=()=>i(o);return{key:t,task:new Promise(e=>e(n(a.ctx,`run`,s))).finally(a.unlink),cancel:a.ctx.abort}});return{tasks:i.map(({key:e,task:t})=>[e,t]),cancelAll:()=>{for(let e of i)e.cancel()}}},g=(e,t,n,r,i)=>{let a=()=>{};return u(e,t,async e=>{let t=h(e,n);return a=t.cancelAll,r(t.tasks)},e=>{(e||i===`end`)&&a()})};function _(e,t){return g(`all`,e,t,async e=>{let n=await Promise.all(e.map(([,e])=>e)),r=m(t);for(let[t,[i]]of e.entries())r[i]=n[t];return r},`failure`)}const v=e=>e.then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}));function y(e,t){return g(`allSettled`,e,t,async e=>{let n=await Promise.all(e.map(([,e])=>v(e))),r=m(t);for(let[t,[i]]of e.entries())r[i]=n[t];return r},`failure`)}const b=e=>e>0?e:0,x=(e={})=>{let t=b(e.base??100),n=e.factor??2,r=b(e.max??1/0),i=e.jitter??!1;return e=>{let a=b(Math.min(r,t*n**(e-1)));return i?Math.random()*a||0:a}},S=(n,r)=>n.signal.aborted?Promise.reject(n.signal.reason):new Promise((i,a)=>{let o=[],s=`pending`,c=t=>{try{t()}catch(t){e(`cancel cleanup failed`,t)}},l=t(n,e=>{s=`cancelled`;for(let e of o.reverse())c(e);a(e)}),u=e=>(...t)=>{s===`pending`&&(s=`settled`,l(),o.length=0,e(...t))},d=e=>{s===`pending`?o.push(e):s===`cancelled`&&c(e)};try{r({resolve:u(i),reject:u(a),onCancel:d})}catch(e){u(a)(e)}}),C=e=>t=>{let n=t.addContext,r=Object.entries(e);return t.addContext=e=>{n?.(e);for(let[t,n]of r)Object.assign(e,{[t]:(...t)=>n(e,...t)})},t},w=(e,n,r,i)=>{if(e.signal.aborted)return Promise.resolve();let a=i.leading??!1,c=i.waitForFn??!1;return u(`poll`,e,e=>new Promise((i,l)=>{let u=0,f=null,p=()=>{f!==null&&(o(f),f=null)},m=e=>{try{f=s(h,typeof r==`function`?r(e):r)}catch(e){p(),l(e)}},h=()=>{f=null,c||m(u+1),g()},g=()=>{let t=u++;d(e,e=>n(e,t)).then(()=>{c&&!e.signal.aborted&&m(u)},e=>{p(),l(e)})};t(e,p),a?(g(),c||m(u)):m(0)})).catch(t=>{if(!e.signal.aborted)throw t})};function T(e,t,n,r={}){if(typeof e!=`object`){let r=t,i=n??{};return(t,n)=>w(n,p(r,t),e,i)}let i=t;return w(e,(e,t)=>i(t),n,r)}function E(e,t){let n=m(t);return Object.keys(t).length===0?Promise.resolve(n):g(`race`,e,t,async e=>{let[t,r]=await Promise.race(e.map(([e,t])=>t.then(t=>[e,t])));return n[t]=r,n},`end`)}const D=(e,t,n)=>typeof e==`function`?e(t,n):e,O=e=>({times:e.times??3,delay:e.delay??0,shouldRetry:e.shouldRetry??(()=>!0)}),k=(e,t,n)=>u(`retry`,e,async e=>{let{times:r,delay:i,shouldRetry:a}=O(n);for(let n=1;;n++)try{return await d(e,e=>t(e,n))}catch(t){if(e.signal.throwIfAborted(),!(n<r)||!a(t,n))throw t;let o=D(i,n,t);o>0&&await c(e,o)}});function A(e,t,n={}){if(typeof e==`function`){let n=e;return(e,r)=>k(r,p(n,e),t??{})}let r=t;return k(e,(e,t)=>r(t),n)}function j(e,n,r={}){return u(`take`,e,i=>new Promise((a,o)=>{let{predicate:s}=r,c=[],l=()=>{for(let e of c)e()},u=e=>{l(),o(e)};c.push(e.on(n,e=>{(!s||s(e))&&(l(),a(e))})),c.push(t(i,u)),c.push(t({signal:r.signal},u))}))}const M=(e,t,i)=>u(`timeout`,e,async e=>{let a=r(e),c=s(()=>a.ctx.abort(new DOMException(`Timed out after ${t}ms`,`TimeoutError`)),t);try{return await l(Promise.resolve(n(a.ctx,`run`,()=>i(a.ctx))),a.ctx)}finally{o(c),a.unlink()}});function N(e,t,n){if(typeof e==`number`){let n=t;return(t,r)=>M(r,e,p(n,t))}let r=t,i=n;return M(e,r,e=>i({signal:e.signal,abort:e.abort}))}export{_ as all,y as allSettled,x as backoff,S as cancellable,c as delay,C as effectsPlugin,t as onAbort,T as poll,E as race,A as retry,j as take,N as timeout};
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- import { A as Handler, C as ContextOf, D as EventKey, E as Emittable, F as WithType, I as commandCall, L as createBus, M as Off, N as On, O as EventLike, P as WithContext, R as Tracer, S as Context, T as Emit, _ as Bus, a as EffectName, b as CommandCall, c as PayloadOf, d as Trace, f as TraceEvent, g as AnyEvent, h as Action, i as WithPayload, j as HandlerRef, k as EventPayload, l as Phase, m as UnsubscribeCallback, o as EventMap, p as TraceLogger, s as Keys, u as Task, v as BusOptions, w as ContextOption, x as Commands, y as Command, z as anyEventType } from "./action-creator-D48fp13T.js";
2
- export { type Action, type AnyEvent, type Bus, type BusOptions, type Command, type CommandCall, type Commands, type Context, type ContextOf, type ContextOption, type EffectName, type Emit, type Emittable, type EventKey, type EventLike, type EventMap, type EventPayload, type Handler, type HandlerRef, type Keys, type Off, type On, type PayloadOf, type Phase, type Task, type Trace, type TraceEvent, type TraceLogger, type Tracer, type UnsubscribeCallback, type WithContext, type WithPayload, type WithType, anyEventType, commandCall, createBus };
1
+ import { A as EventsOf, B as anyEventType, C as ContextOf, D as EventKey, E as Emittable, F as WithContext, I as WithType, L as commandCall, M as HandlerRef, N as Off, O as EventLike, P as On, R as createBus, S as Context, T as Emit, _ as Bus, a as EffectName, b as CommandCall, c as PayloadOf, d as Trace, f as TraceEvent, g as AnyEvent, h as Action, i as WithPayload, j as Handler, k as EventPayload, l as Phase, m as UnsubscribeCallback, o as EventMap, p as TraceLogger, s as Keys, u as Task, v as BusOptions, w as ContextOption, x as Commands, y as Command, z as Tracer } from "./action-creator-DOWcbXpy.js";
2
+ import { n as NoClash, r as contextPlugin, t as ContextTask } from "./context-plugin-B0sLWOxR.js";
3
+ export { type Action, type AnyEvent, type Bus, type BusOptions, type Command, type CommandCall, type Commands, type Context, type ContextOf, type ContextOption, type ContextTask, type EffectName, type Emit, type Emittable, type EventKey, type EventLike, type EventMap, type EventPayload, type EventsOf, type Handler, type HandlerRef, type Keys, type NoClash, type Off, type On, type PayloadOf, type Phase, type Task, type Trace, type TraceEvent, type TraceLogger, type Tracer, type UnsubscribeCallback, type WithContext, type WithPayload, type WithType, anyEventType, commandCall, contextPlugin, createBus };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export{i as anyEventType,t as commandCall,n as createBus}from"./bus-Cho463Sq.js";
1
+ import{i as e,n as t,t as n}from"./bus-BAs9x7IQ.js";const r=e=>typeof e==`function`,i=e=>({type:Reflect.get(e,`type`),payload:Reflect.get(e,`payload`)}),a=e=>t=>{let n=t.addContext;return t.addContext=t=>{n?.(t);let a=r(e)?e(i(t)):e;for(let[e,n]of Object.entries(a))e in t||Reflect.set(t,e,n)},t};export{e as anyEventType,n as commandCall,a as contextPlugin,t as createBus};
@@ -1,4 +1,4 @@
1
- import { S as Context, _ as Bus, c as PayloadOf, m as UnsubscribeCallback, o as EventMap, u as Task, y as Command } from "./action-creator-D48fp13T.js";
1
+ import { S as Context, _ as Bus, c as PayloadOf, m as UnsubscribeCallback, o as EventMap, u as Task, y as Command } from "./action-creator-DOWcbXpy.js";
2
2
  //#region src/actions/command.d.ts
3
3
  /** What `createCommand` returns: a command that also tells whether an action is of its type. */
4
4
  type MadeCommand<P, R, T extends string> = Command<P, R> & {
@@ -104,7 +104,10 @@ type ModuleContext<E extends EventMap = EventMap> = Context<E> & {
104
104
  * returned function undoes just this call, e.g. for what was added later from
105
105
  * a listener.
106
106
  */
107
- use(...items: Array<Module<E> | Command<never, unknown>>): UnsubscribeCallback;
107
+ use(...items: Array<Module<E> | {
108
+ readonly type: string;
109
+ (payload: never): unknown;
110
+ }>): UnsubscribeCallback;
108
111
  /**
109
112
  * Starts a background task that lives as long as the module: it is aborted
110
113
  * on unmount, and an error of it is left unhandled, as in any handler.
@@ -146,6 +149,12 @@ type ModuleApi<E extends EventMap = EventMap> = {
146
149
  isMounted(module: Module<E>): boolean;
147
150
  /** Unmounts every module; a disposed app cannot mount modules. */
148
151
  dispose(): void;
152
+ /**
153
+ * `createModule` with the event map of this bus: the module sees the context
154
+ * fields of the bus without a type argument. It returns a plain module, not
155
+ * mounted, with no link to this bus.
156
+ */
157
+ createModule(name: string, setup: (m: ModuleContext<E>) => void): Module<E>;
149
158
  };
150
159
  /**
151
160
  * The plugin that assembles an app from modules: `bus.use(modulePlugin(modules))`
@@ -171,6 +180,11 @@ type ModuleApi<E extends EventMap = EventMap> = {
171
180
  * const unmount = app.mount(orderModule); // later, e.g. after a lazy import
172
181
  * unmount(); // or app.unmount(orderModule)
173
182
  *
183
+ * // a module made from the app has the context fields of the bus, typed
184
+ * const userModule = app.createModule("user", (m) => {
185
+ * m.on("loaded", (user, { store }) => store.put(user));
186
+ * });
187
+ *
174
188
  * bus.emit(getUser, "1");
175
189
  * app.commands.handle(getUser, fakeUser); // in a test
176
190
  * app.dispose();
@@ -157,6 +157,18 @@ type Context<E extends EventMap> = EventLike<E> & ContextOf<E> & {
157
157
  /** Child task: aborted with the parent; errors propagate to the parent. */
158
158
  run<P, R>(fn: Task<P, E, R>, ...args: PayloadOf<P>): Promise<Awaited<R>>;
159
159
  };
160
+ /**
161
+ * The event map of a bus, with the context fields that plugins added. Use it to
162
+ * name the types of a bus in other files: `type AppEvents = EventsOf<typeof bus>`.
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * const bus = createBus<Events>().use(effectsPlugin({ race }));
167
+ * type AppEvents = EventsOf<typeof bus>;
168
+ * type AppContext = Context<AppEvents>; // has `race`
169
+ * ```
170
+ */
171
+ type EventsOf<B> = B extends Bus<infer E extends EventMap> ? E : never;
160
172
  interface Bus<E extends EventMap> {
161
173
  on: On<E>;
162
174
  /**
@@ -173,10 +185,12 @@ interface Bus<E extends EventMap> {
173
185
  */
174
186
  use<R>(plugin: (bus: Bus<E>) => R): R;
175
187
  /** `BusOptions.context` and `.trace`, and `commands`, for what makes tasks of its own, like `modulePlugin`. */
176
- readonly context?: ContextOption<E> | undefined;
188
+ readonly ctx?: ContextOption<E> | undefined;
177
189
  /** What runs the commands; `commandsPlugin` and `modulePlugin` set it. Without one a command runs its own handler. */
178
190
  commands?: Commands | undefined;
179
191
  readonly trace?: Tracer | undefined;
192
+ /** Called with every new task context to add fields to it, for what needs the task, like `effectsPlugin`. Chain to the previous one. */
193
+ addContext?: ((ctx: object) => void) | undefined;
180
194
  }
181
195
  type BusOptions<E extends EventMap> = {
182
196
  /** Tracing of every task phase; make it with `createTracer` from `nanoeffects/trace`. */
@@ -292,4 +306,4 @@ interface ActionCreator<P = void, T extends string = string, A extends unknown[]
292
306
  toString(): T;
293
307
  }
294
308
  //#endregion
295
- export { Handler as A, ContextOf as C, EventKey as D, Emittable as E, WithType as F, commandCall as I, createBus as L, Off as M, On as N, EventLike as O, WithContext as P, Tracer as R, Context as S, Emit as T, Bus as _, EffectName as a, CommandCall as b, PayloadOf as c, Trace as d, TraceEvent as f, AnyEvent as g, Action as h, WithPayload as i, HandlerRef as j, EventPayload as k, Phase as l, UnsubscribeCallback as m, Free as n, EventMap as o, TraceLogger as p, FreeActionCreator as r, Keys as s, ActionCreator as t, Task as u, BusOptions as v, ContextOption as w, Commands as x, Command as y, anyEventType as z };
309
+ export { EventsOf as A, anyEventType as B, ContextOf as C, EventKey as D, Emittable as E, WithContext as F, WithType as I, commandCall as L, HandlerRef as M, Off as N, EventLike as O, On as P, createBus as R, Context as S, Emit as T, Bus as _, EffectName as a, CommandCall as b, PayloadOf as c, Trace as d, TraceEvent as f, AnyEvent as g, Action as h, WithPayload as i, Handler as j, EventPayload as k, Phase as l, UnsubscribeCallback as m, Free as n, EventMap as o, TraceLogger as p, FreeActionCreator as r, Keys as s, ActionCreator as t, Task as u, BusOptions as v, ContextOption as w, Commands as x, Command as y, Tracer as z };