nanoeffects 0.8.0 → 0.10.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.
- package/README.md +2 -2
- package/dist/actions.d.ts +38 -22
- package/dist/actions.js +1 -1
- package/dist/bus-CkTHUAvq.js +1 -0
- package/dist/context-COgyNlrC.js +1 -0
- package/dist/effects.js +1 -1
- package/dist/index.js +1 -1
- package/dist/lifecycle-key-8iX8RUVD.js +1 -0
- package/dist/notrace/actions.d.ts +38 -22
- package/dist/notrace/actions.js +1 -1
- package/dist/notrace/bus-BmCTo8BG.js +1 -0
- package/dist/notrace/context-yYU3_9lq.js +1 -0
- package/dist/notrace/{delay-B_W1tnkS.js → delay-BosJKFjg.js} +1 -1
- package/dist/notrace/effects.js +1 -1
- package/dist/notrace/index.js +1 -1
- package/dist/notrace/lifecycle-key-8iX8RUVD.js +1 -0
- package/dist/notrace/policies.d.ts +30 -2
- package/dist/notrace/policies.js +1 -1
- package/dist/oop.js +1 -1
- package/dist/policies.d.ts +2 -1
- package/dist/policies.js +1 -1
- package/dist/react.d.ts +33 -1
- package/dist/react.js +1 -1
- package/dist/scope.js +1 -1
- package/dist/signal.d.ts +51 -0
- package/dist/signal.js +1 -0
- package/dist/with-policy-CqUS-VWW.d.ts +30 -0
- package/dist/with-policy-DBV9dh2F.js +1 -0
- package/docs/README.md +6 -0
- package/docs/actions.md +80 -4
- package/docs/cancel-stale-requests.md +111 -0
- package/docs/debounce-and-abort.md +106 -0
- package/docs/guide.md +1 -1
- package/docs/migrating-from-effector.md +2 -2
- package/docs/migrating-from-mitt.md +97 -0
- package/docs/motivation.md +41 -0
- package/docs/observable.md +124 -10
- package/docs/package.md +4 -2
- package/docs/plugins.md +20 -0
- package/docs/policies.md +33 -0
- package/docs/prevent-double-submit.md +128 -0
- package/docs/query-libraries.md +124 -0
- package/docs/react.md +44 -0
- package/llms-full.txt +944 -24
- package/llms.txt +9 -3
- package/package.json +25 -4
- package/skills/nanoeffects/SKILL.md +52 -0
- package/dist/bus-BAs9x7IQ.js +0 -1
- package/dist/context-CK0ZomWt.js +0 -1
- package/dist/notrace/bus-Bdk0YyFQ.js +0 -1
- package/dist/notrace/context-CctVmHLC.js +0 -1
package/README.md
CHANGED
|
@@ -88,8 +88,8 @@ Start with the [Guide](docs/guide.md) (bus → policies → effects → modules)
|
|
|
88
88
|
| Domain logic off the UI | [Actions, commands, modules](docs/actions.md) |
|
|
89
89
|
| Redux / Zustand / MobX | [Stores](docs/stores.md) |
|
|
90
90
|
|
|
91
|
-
[Full index, package entries, tracing](docs/README.md) · [Examples](examples/README.md)
|
|
91
|
+
[Full index, package entries, tracing](docs/README.md) · [Examples](examples/README.md) · [Why nanoeffects exists](docs/motivation.md)
|
|
92
92
|
|
|
93
|
-
- **Tiny.** `createBus` is about 1.3 kB
|
|
93
|
+
- **Tiny.** `createBus` is about 1.4 kB gzip (1.3 kB brotli); other entries load only when imported.
|
|
94
94
|
- **Cancellation first.** Aborting a task aborts its children and drops its result.
|
|
95
95
|
- **One model** instead of hand-rolled `AbortController`, lodash debounce, and retry glue.
|
package/dist/actions.d.ts
CHANGED
|
@@ -87,55 +87,71 @@ type Creator = {
|
|
|
87
87
|
readonly type: string;
|
|
88
88
|
};
|
|
89
89
|
type Outcome = string | Creator;
|
|
90
|
-
/** What `createJob` returns: the command of the job, with its
|
|
91
|
-
type Job<P, R, T extends string, S extends Outcome, F extends Outcome
|
|
90
|
+
/** What `createJob` returns: the command of the job, with its four actions as properties. */
|
|
91
|
+
type Job<P, R, T extends string, S extends Outcome, F extends Outcome, PE extends Outcome = `${T}/pending`, CE extends Outcome = `${T}/cancel`> = MadeCommand<P, Promise<Awaited<R> | undefined>, T> & {
|
|
92
|
+
/** Made from a string with the payload of the call as its payload, or the creator that was given. */
|
|
93
|
+
readonly pending: PE extends string ? ActionCreator<P, PE> : PE;
|
|
92
94
|
/** Made from a string with the result as its payload, or the creator that was given. */
|
|
93
95
|
readonly success: S extends string ? ActionCreator<Awaited<R>, S> : S;
|
|
94
96
|
/** Made from a string with the error as its payload, or the creator that was given. */
|
|
95
97
|
readonly fail: F extends string ? ActionCreator<unknown, F> : F;
|
|
98
|
+
/** Made from a string with the abort reason as its payload, or the creator that was given. */
|
|
99
|
+
readonly cancel: CE extends string ? ActionCreator<unknown, CE> : CE;
|
|
96
100
|
};
|
|
97
101
|
/**
|
|
98
102
|
* Creates a job: a command whose outcome is sent on as actions. When the
|
|
99
|
-
* handler
|
|
100
|
-
*
|
|
101
|
-
* the
|
|
102
|
-
*
|
|
103
|
-
*
|
|
103
|
+
* handler starts, `job.pending(payload)` is emitted on the bus. When it
|
|
104
|
+
* succeeds, `job.success(result)` follows, and when it fails, `job.fail(error)`.
|
|
105
|
+
* When the task is aborted after it started, `job.cancel(reason)` follows
|
|
106
|
+
* instead. After `pending`, exactly one of the three closes the call. A job is
|
|
107
|
+
* made for the case where nobody waits for the result and the bus carries it
|
|
108
|
+
* on, like `createAsyncThunk` or an effector effect. It returns the command,
|
|
109
|
+
* with the four actions on it.
|
|
104
110
|
*
|
|
105
111
|
* A scope as the last argument, `{ cache, $effects: { race } }`, gives the handler
|
|
106
112
|
* and the listeners of the outcome those context fields; see `scopePlugin`.
|
|
107
113
|
*
|
|
108
|
-
* `success` and `
|
|
109
|
-
* creator with `createAction`, or an action creator that
|
|
110
|
-
* is used and returned as it is. A missing one is made
|
|
111
|
-
* `<type>/success
|
|
114
|
+
* `pending`, `success`, `fail` and `cancel` are a type string, from which the
|
|
115
|
+
* job makes an action creator with `createAction`, or an action creator that
|
|
116
|
+
* exists already, which is used and returned as it is. A missing one is made
|
|
117
|
+
* with the type `<type>/pending`, `<type>/success`, `<type>/fail` or
|
|
118
|
+
* `<type>/cancel`.
|
|
112
119
|
*
|
|
113
120
|
* `bus.emit(job(payload))` returns a promise of the result. An error of the
|
|
114
121
|
* handler always counts as handled: it goes to `job.fail` and the promise
|
|
115
122
|
* resolves with `undefined`; a command is the tool for a result that must reject.
|
|
116
123
|
* The actions are emitted as the task that ran the job, also for a handler bound
|
|
117
|
-
* with `commands.handle
|
|
118
|
-
*
|
|
119
|
-
*
|
|
124
|
+
* with `commands.handle`. Once the task is aborted, `success` and `fail` are
|
|
125
|
+
* skipped and `cancel` is sent when the handler settles (a handler that never
|
|
126
|
+
* settles sends nothing). A call that does not start, because a policy drops it
|
|
127
|
+
* or it is aborted while it waits in a `queue`, sends none of the four. A
|
|
128
|
+
* missing handler is not an outcome: `emit` throws `MissingHandlerError`.
|
|
129
|
+
* Calling the job builds `{ type, payload }` like a command; it does not run
|
|
130
|
+
* the handler.
|
|
120
131
|
*
|
|
121
132
|
* @example
|
|
122
133
|
* ```ts
|
|
123
|
-
* const loadUser = createJob("user/load", fetchUser
|
|
124
|
-
*
|
|
125
|
-
* fail: "user/failed",
|
|
126
|
-
* });
|
|
134
|
+
* const loadUser = createJob("user/load", fetchUser);
|
|
135
|
+
* let loading = false;
|
|
127
136
|
*
|
|
128
|
-
* bus.on(loadUser.
|
|
129
|
-
* bus.
|
|
137
|
+
* bus.on(loadUser.pending, () => { loading = true; });
|
|
138
|
+
* bus.on(loadUser.success, (user) => { loading = false; render(user); });
|
|
139
|
+
* bus.on(loadUser.fail, () => { loading = false; });
|
|
140
|
+
* bus.on(loadUser.cancel, () => { loading = false; });
|
|
141
|
+
* bus.emit(loadUser("1")); // pending now, then success, fail or cancel
|
|
130
142
|
* ```
|
|
131
143
|
*/
|
|
132
|
-
export declare const createJob: <P = void, R = void, T extends string = string, E extends EventMap = EventMap, S extends Outcome = `${T}/success`, F extends Outcome = `${T}/fail`, X extends Scope = Record<never, never>>(type: T, handler?: Task<P, Scoped<E, X>, R>, outcomes?: {
|
|
144
|
+
export declare const createJob: <P = void, R = void, T extends string = string, E extends EventMap = EventMap, S extends Outcome = `${T}/success`, F extends Outcome = `${T}/fail`, PE extends Outcome = `${T}/pending`, CE extends Outcome = `${T}/cancel`, X extends Scope = Record<never, never>>(type: T, handler?: Task<P, Scoped<E, X>, R>, outcomes?: {
|
|
145
|
+
/** Gets the payload of the call when the handler starts: a type to make an action creator of, or an action creator. */
|
|
146
|
+
pending?: PE;
|
|
133
147
|
/** Gets the result when the handler succeeds: a type to make an action creator of, or an action creator. */
|
|
134
148
|
success?: S;
|
|
135
149
|
/** Gets the error when the handler fails: a type to make an action creator of, or an action creator. */
|
|
136
150
|
fail?: F;
|
|
151
|
+
/** Gets the abort reason when the task is aborted before the handler settles: a type to make an action creator of, or an action creator. */
|
|
152
|
+
cancel?: CE;
|
|
137
153
|
},
|
|
138
154
|
/** Context values and `$effects` for the handler and for the listeners of the outcome; see `scopePlugin`. */
|
|
139
|
-
scope?: X) => CarryingCalls<Job<P, R, T, S, F>, P, Promise<Awaited<R> | undefined>, FieldsOfScope<E, X>>;
|
|
155
|
+
scope?: X) => CarryingCalls<Job<P, R, T, S, F, PE, CE>, P, Promise<Awaited<R> | undefined>, FieldsOfScope<E, X>>;
|
|
140
156
|
//#endregion
|
|
141
157
|
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{
|
|
1
|
+
import{n as e,t}from"./onAbort-BgMfspK4.js";import{i as n,n as r,s as i}from"./context-COgyNlrC.js";import{t as a}from"./event-0RIBGYqS.js";import{i as o}from"./bus-CkTHUAvq.js";import{n as s,t as c}from"./lifecycle-key-8iX8RUVD.js";import{t as l}from"./scope-key-B7l7mUS5.js";const u=(e,t)=>(t&&Object.defineProperty(e,l,{value:t}),e),d=(e,t)=>({...e,...t,$effects:{...e.$effects,...t.$effects}}),f=e=>Reflect.get(e,l);function p(e,t,n){let r=typeof t==`function`?t:void 0,i=typeof t==`function`?n:t;return Object.assign(u((...t)=>u({type:e,payload:r?r(...t).payload:t[0]},i),i),{type:e,match:t=>t.type===e,toString:()=>e})}var m=class extends Error{};function h(e,t,n){let r=t=>t.type===e;function i(r,i){if(typeof i==`object`){if(!t)throw new m(`No handler for command "${e}"`);return t(r,i)}return u(o(s,e,r),n)}let a=Object.assign(i,{type:e,match:r}),s=u(a,n);return s}const g=(e,t)=>[e,t],_=e=>typeof Reflect.get(e??{},`handle`)==`function`,v=(e=[])=>t=>{let n=t.commands;if(_(n))return n.handle(e),n;let r=/* @__PURE__ */ new Map,i=(e,t)=>{let n={fn:t};return r.set(e,[...r.get(e)??[],n]),()=>{let t=(r.get(e)??[]).filter(e=>e!==n);t.length>0?r.set(e,t):r.delete(e)}};function o(e,t){if(t)return i(a(e),t);let n=e.map(([e,t])=>i(a(e),t));return()=>{for(let e of n)e()}}o(e);let s={run:(e,t,n)=>{let i=(r.get(e.type)??[]).at(-1)?.fn,a=i&&e.wrap?e.wrap(i):i??e;return Reflect.apply(a,null,[t,n])},handle:o};return t.commands=s,s},y=()=>e=>{function t(t){return(...n)=>{let r=t(...n);e.emit(r)}}return Object.assign(e,{emitter:t})},b=e=>typeof e==`string`?p(e):e,x=(e,t,n,r)=>{let i=f(t);e.emit(Reflect.apply(t,null,[n]),r&&i?d(r,i):r)},S=(t,n,r,a)=>{let o=t;o[i]=!0;try{x(t,n,r,a)}catch(t){e(`cancel listener`,t)}o[i]=!1},C=e=>{try{return Promise.resolve(e())}catch(e){if(e instanceof m)throw e;return Promise.reject(e)}},w=(n,r,i={},a)=>{let l=h(n,r),d=e=>b(i[e]??`${n}/${e}`),f=d(`pending`),p=d(`success`),m=d(`fail`),g=d(`cancel`),_=(n,r,i,o)=>{let s=i,l=`idle`,u=()=>{},d=()=>{l=`closed`,u()},h=e=>{l===`started`&&(d(),S(s,g,e,a))},_=()=>{l===`idle`&&(l=`started`,u=t(s,h),x(s,f,r,a))},v=e=>{l===`started`&&(d(),s.signal.aborted?S(s,g,s.signal.reason,a):`error`in e?x(s,m,e.error,a):x(s,p,e.value,a))};return Reflect.set(s,c,{start:_,cancel:h,done:v,drop:()=>{l===`idle`&&(l=`closed`)}}),C(()=>(o||_(),Reflect.apply(n,null,[r,i]))).then(e=>(v({value:e}),e),t=>{if(l===`idle`)try{_()}catch(t){e(`pending listener`,t)}v({error:t})})},v=e=>{let t=Reflect.get(e,s)===!0;return(n,r)=>_(e,n,r,t)};function y(e,t){return typeof t==`object`?r?_(l,e,t,!1):Reflect.apply(l,null,[e,t]):u(o(T,n,e),a)}let w=Object.assign(y,{type:n,match:l.match,wrap:v,pending:f,success:p,fail:m,cancel:g}),T=u(w,a);return T},T=e=>typeof e==`object`&&!!e,E=e=>{if(typeof e==`string`)return e;if(T(e)||typeof e==`function`){let t=Reflect.get(e,`type`);return typeof t==`string`?t:e}return e},D=(e,t)=>{let[n,r]=e;return n===void 0||Object.is(E(n),E(t[0]))&&(r===void 0||Object.is(r,t[1]))},O=e=>{let t={on:e.on,once:e.once,off:e.off},n=[],r=!0,i=(t,n)=>Reflect.apply(t,e,n),a=(e,t)=>(...a)=>{if(!r)return i(t,a);let o={kind:e,args:a,dropped:!1};return n.push(o),()=>{o.live?o.live():o.dropped=!0}},o=e=>(...t)=>{if(!r)return i(e,t);for(let e of n)e.kind!==`off`&&D(t,e.args)&&(e.dropped=!0);n.push({kind:`off`,args:t,dropped:!1})},s=a(`on`,t.on),c=a(`once`,t.once),l=o(t.off);return e.on=s,e.once=c,e.off=l,{release:()=>{r=!1,e.on===s&&(e.on=t.on),e.once===c&&(e.once=t.once),e.off===l&&(e.off=t.off)},replay:()=>{for(let e of n.splice(0))if(!e.dropped){if(e.kind===`off`)i(t.off,e.args);else{let n=e.kind===`on`?t.on:t.once;e.live=i(n,e.args)}}}}};function k(e,t,n){return n?{name:e,setup:t,scope:n}:{name:e,setup:t}}const A=(e,t)=>n=>t?e.fitScope?.(t,n)??n:n,j=(e,t,n)=>{n&&e.applyScope?.(t,n)},M=(e,t,n)=>Array.isArray(t)?[t.map(([t,n])=>[t,e(n)]),n]:[t,e(n)],N=(e,t)=>{let n=e.on;return(...e)=>{let[r,i]=e;return Reflect.apply(n,null,[r,t(i)])}},P=e=>(t,...n)=>{e.run(t,...n).catch(t=>{if(!e.signal.aborted)throw t})},F=(e=[])=>i=>{let a=i.commands??v()(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=e=>{let r=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map;return{mount:c=>{let l=r.get(c);if(l)return l;let u=a.get(c.name);u&&r.get(u)?.();let d=n(e,c.name),f=d.ctx,p=s(f),m=()=>{r.delete(c),a.get(c.name)===c&&a.delete(c.name),f.abort(),d.unlink()};r.set(c,m),a.set(c.name,c);let h=c.scope,g=A(i,h),_=(e,n)=>{let r=Reflect.apply(o.handle,null,M(g,e,n));return t(f,r),r},v=(...e)=>{let t=e.map(e=>typeof e==`function`?_(e,e):p.mount(e));return()=>{for(let e of t)e()}},y=P(f),b=N(f,g);try{j(i,f,h),c.setup(Object.assign(f,{handle:_,use:v,spawn:y,on:b}))}catch(e){throw m(),e}return m},unmount:e=>r.get(e)?.(),isMounted:e=>r.has(e)}},c=O(i),l=i.emit,u,d=(t=!0)=>{if(u)return u;c.release(),i.emit===f&&(i.emit=l);let n=r({event:{type:`app`,payload:void 0},bus:i,tracer:i.trace});if(u={root:n,apps:s(n.ctx)},t)for(let t of e)u.apps.mount(t);return c.replay(),u},f=(...e)=>(d(),Reflect.apply(l,i,e));i.emit=f;let p={get commands(){return d(),a},mount:e=>{let{root:t,apps:n}=d();return t.ctx.signal.throwIfAborted(),n.mount(e)},unmount:e=>d().apps.unmount(e),isMounted:e=>d().apps.isMounted(e),dispose:()=>d(!1).root.ctx.abort(),createModule:k};return i.app=p,p};export{g as bindHandler,v as commandsPlugin,p as createAction,h as createCommand,w as createJob,k as createModule,y as emitterPlugin,F as modulePlugin};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./onAbort-BgMfspK4.js";import{a as t,n,r}from"./context-COgyNlrC.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(),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 a,u as i,d as n,p as r,l as t};
|
|
@@ -0,0 +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=Symbol(),r=typeof __NANOEFFECTS_TRACE__>`u`||__NANOEFFECTS_TRACE__,i=/* @__PURE__ */ new WeakMap;let a;const o=()=>a,s=()=>{},c=(e,t,n,a)=>{let o=r&&i.get(e);o&&o.tracer.report(o.ref,t,n,a)},l=(e,t)=>{let n=r&&i.get(e);return n?n.tracer.settler(n.ref,t):s},u=(e,t,n)=>{let a=r&&i.get(e);return a?a.tracer.run(a.ref,t,e.signal,n):n()},d=(e,t)=>typeof e==`function`?e(t):e,f=({event:o,bus:c,tracer:l,parent:p})=>{let{controller:m,unlink:h}=t(p?.signal),{signal:g}=m,_=r&&l?{tracer:l,ref:l.task(o,p?.ref)}:void 0,v=(...e)=>{if(g.aborted&&!x[n])return;let t=c?.emit,r=a;a=_?.ref;try{return t?.(...e)}finally{a=r}},y=(...t)=>{if(g.aborted)return s;let n=c?.on,r=n?.(...t);if(!r)return s;let i=e({signal:g},r);return()=>{i(),r()}},b=async(e,...t)=>{g.throwIfAborted();let n=t[0],r=f({event:{type:o.type,payload:n},bus:c,tracer:l,parent:{signal:g,ref:_?.ref}});try{return await u(r.ctx,`run`,()=>e(n,r.ctx))}finally{r.unlink()}},x={...d(c?.ctx,o),type:o.type,payload:o.payload,signal:g,abort:e=>m.abort(e),emit:v,on:y,off:c?.off??s,run:b};return c?.addContext?.(x),_&&i.set(x,_),{ctx:x,unlink:h}},p=(e,t)=>{let n=r?i.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:n?.tracer,parent:{signal:e.signal,ref:n?.ref}})};export{u as a,p as i,f as n,c as o,o as r,n as s,l as t};
|
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-
|
|
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-COgyNlrC.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)t in e||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.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{a as e,r as t,t as n}from"./bus-CkTHUAvq.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=Symbol(),t=Symbol();export{t as n,e as t};
|
|
@@ -204,56 +204,72 @@ type Creator = {
|
|
|
204
204
|
readonly type: string;
|
|
205
205
|
};
|
|
206
206
|
type Outcome = string | Creator;
|
|
207
|
-
/** What `createJob` returns: the command of the job, with its
|
|
208
|
-
type Job<P, R, T extends string, S extends Outcome, F extends Outcome
|
|
207
|
+
/** What `createJob` returns: the command of the job, with its four actions as properties. */
|
|
208
|
+
type Job<P, R, T extends string, S extends Outcome, F extends Outcome, PE extends Outcome = `${T}/pending`, CE extends Outcome = `${T}/cancel`> = MadeCommand<P, Promise<Awaited<R> | undefined>, T> & {
|
|
209
|
+
/** Made from a string with the payload of the call as its payload, or the creator that was given. */
|
|
210
|
+
readonly pending: PE extends string ? ActionCreator<P, PE> : PE;
|
|
209
211
|
/** Made from a string with the result as its payload, or the creator that was given. */
|
|
210
212
|
readonly success: S extends string ? ActionCreator<Awaited<R>, S> : S;
|
|
211
213
|
/** Made from a string with the error as its payload, or the creator that was given. */
|
|
212
214
|
readonly fail: F extends string ? ActionCreator<unknown, F> : F;
|
|
215
|
+
/** Made from a string with the abort reason as its payload, or the creator that was given. */
|
|
216
|
+
readonly cancel: CE extends string ? ActionCreator<unknown, CE> : CE;
|
|
213
217
|
};
|
|
214
218
|
/**
|
|
215
219
|
* Creates a job: a command whose outcome is sent on as actions. When the
|
|
216
|
-
* handler
|
|
217
|
-
*
|
|
218
|
-
* the
|
|
219
|
-
*
|
|
220
|
-
*
|
|
220
|
+
* handler starts, `job.pending(payload)` is emitted on the bus. When it
|
|
221
|
+
* succeeds, `job.success(result)` follows, and when it fails, `job.fail(error)`.
|
|
222
|
+
* When the task is aborted after it started, `job.cancel(reason)` follows
|
|
223
|
+
* instead. After `pending`, exactly one of the three closes the call. A job is
|
|
224
|
+
* made for the case where nobody waits for the result and the bus carries it
|
|
225
|
+
* on, like `createAsyncThunk` or an effector effect. It returns the command,
|
|
226
|
+
* with the four actions on it.
|
|
221
227
|
*
|
|
222
228
|
* A scope as the last argument, `{ cache, $effects: { race } }`, gives the handler
|
|
223
229
|
* and the listeners of the outcome those context fields; see `scopePlugin`.
|
|
224
230
|
*
|
|
225
|
-
* `success` and `
|
|
226
|
-
* creator with `createAction`, or an action creator that
|
|
227
|
-
* is used and returned as it is. A missing one is made
|
|
228
|
-
* `<type>/success
|
|
231
|
+
* `pending`, `success`, `fail` and `cancel` are a type string, from which the
|
|
232
|
+
* job makes an action creator with `createAction`, or an action creator that
|
|
233
|
+
* exists already, which is used and returned as it is. A missing one is made
|
|
234
|
+
* with the type `<type>/pending`, `<type>/success`, `<type>/fail` or
|
|
235
|
+
* `<type>/cancel`.
|
|
229
236
|
*
|
|
230
237
|
* `bus.emit(job(payload))` returns a promise of the result. An error of the
|
|
231
238
|
* handler always counts as handled: it goes to `job.fail` and the promise
|
|
232
239
|
* resolves with `undefined`; a command is the tool for a result that must reject.
|
|
233
240
|
* The actions are emitted as the task that ran the job, also for a handler bound
|
|
234
|
-
* with `commands.handle
|
|
235
|
-
*
|
|
236
|
-
*
|
|
241
|
+
* with `commands.handle`. Once the task is aborted, `success` and `fail` are
|
|
242
|
+
* skipped and `cancel` is sent when the handler settles (a handler that never
|
|
243
|
+
* settles sends nothing). A call that does not start, because a policy drops it
|
|
244
|
+
* or it is aborted while it waits in a `queue`, sends none of the four. A
|
|
245
|
+
* missing handler is not an outcome: `emit` throws `MissingHandlerError`.
|
|
246
|
+
* Calling the job builds `{ type, payload }` like a command; it does not run
|
|
247
|
+
* the handler.
|
|
237
248
|
*
|
|
238
249
|
* @example
|
|
239
250
|
* ```ts
|
|
240
|
-
* const loadUser = createJob("user/load", fetchUser
|
|
241
|
-
*
|
|
242
|
-
* fail: "user/failed",
|
|
243
|
-
* });
|
|
251
|
+
* const loadUser = createJob("user/load", fetchUser);
|
|
252
|
+
* let loading = false;
|
|
244
253
|
*
|
|
245
|
-
* bus.on(loadUser.
|
|
246
|
-
* bus.
|
|
254
|
+
* bus.on(loadUser.pending, () => { loading = true; });
|
|
255
|
+
* bus.on(loadUser.success, (user) => { loading = false; render(user); });
|
|
256
|
+
* bus.on(loadUser.fail, () => { loading = false; });
|
|
257
|
+
* bus.on(loadUser.cancel, () => { loading = false; });
|
|
258
|
+
* bus.emit(loadUser("1")); // pending now, then success, fail or cancel
|
|
247
259
|
* ```
|
|
248
260
|
*/
|
|
249
|
-
export declare const createJob: <P = void, R = void, T extends string = string, E extends EventMap = EventMap, S extends Outcome = `${T}/success`, F extends Outcome = `${T}/fail`, X extends Scope = Record<never, never>>(type: T, handler?: Task<P, Scoped<E, X>, R>, outcomes?: {
|
|
261
|
+
export declare const createJob: <P = void, R = void, T extends string = string, E extends EventMap = EventMap, S extends Outcome = `${T}/success`, F extends Outcome = `${T}/fail`, PE extends Outcome = `${T}/pending`, CE extends Outcome = `${T}/cancel`, X extends Scope = Record<never, never>>(type: T, handler?: Task<P, Scoped<E, X>, R>, outcomes?: {
|
|
262
|
+
/** Gets the payload of the call when the handler starts: a type to make an action creator of, or an action creator. */
|
|
263
|
+
pending?: PE;
|
|
250
264
|
/** Gets the result when the handler succeeds: a type to make an action creator of, or an action creator. */
|
|
251
265
|
success?: S;
|
|
252
266
|
/** Gets the error when the handler fails: a type to make an action creator of, or an action creator. */
|
|
253
267
|
fail?: F;
|
|
268
|
+
/** Gets the abort reason when the task is aborted before the handler settles: a type to make an action creator of, or an action creator. */
|
|
269
|
+
cancel?: CE;
|
|
254
270
|
},
|
|
255
271
|
/** Context values and `$effects` for the handler and for the listeners of the outcome; see `scopePlugin`. */
|
|
256
|
-
scope?: X) => CarryingCalls<Job<P, R, T, S, F>, P, Promise<Awaited<R> | undefined>, FieldsOfScope<E, X>>;
|
|
272
|
+
scope?: X) => CarryingCalls<Job<P, R, T, S, F, PE, CE>, P, Promise<Awaited<R> | undefined>, FieldsOfScope<E, X>>;
|
|
257
273
|
//#endregion
|
|
258
274
|
//#region src/actions/module.d.ts
|
|
259
275
|
/**
|
package/dist/notrace/actions.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{c as e,i as t,l as n,n as r,s as i}from"./context-yYU3_9lq.js";import{a,r as o}from"./bus-BmCTo8BG.js";import{n as s,t as c}from"./lifecycle-key-8iX8RUVD.js";const l=Symbol.for(`nanoeffects.scope`),u=(e,t)=>(t&&Object.defineProperty(e,l,{value:t}),e),d=(e,t)=>({...e,...t,$effects:{...e.$effects,...t.$effects}}),f=e=>Reflect.get(e,l);function p(e,t,n){let r=typeof t==`function`?t:void 0,i=typeof t==`function`?n:t;return Object.assign(u((...t)=>u({type:e,payload:r?r(...t).payload:t[0]},i),i),{type:e,match:t=>t.type===e,toString:()=>e})}var m=class extends Error{};function h(e,t,n){let r=t=>t.type===e;function i(r,i){if(typeof i==`object`){if(!t)throw new m(`No handler for command "${e}"`);return t(r,i)}return u(o(s,e,r),n)}let a=Object.assign(i,{type:e,match:r}),s=u(a,n);return s}const g=(e,t)=>[e,t],_=e=>typeof Reflect.get(e??{},`handle`)==`function`,v=(e=[])=>t=>{let n=t.commands;if(_(n))return n.handle(e),n;let r=/* @__PURE__ */ new Map,i=(e,t)=>{let n={fn:t};return r.set(e,[...r.get(e)??[],n]),()=>{let t=(r.get(e)??[]).filter(e=>e!==n);t.length>0?r.set(e,t):r.delete(e)}};function o(e,t){if(t)return i(a(e),t);let n=e.map(([e,t])=>i(a(e),t));return()=>{for(let e of n)e()}}o(e);let s={run:(e,t,n)=>{let i=(r.get(e.type)??[]).at(-1)?.fn,a=i&&e.wrap?e.wrap(i):i??e;return Reflect.apply(a,null,[t,n])},handle:o};return t.commands=s,s},y=()=>e=>{function t(t){return(...n)=>{let r=t(...n);e.emit(r)}}return Object.assign(e,{emitter:t})},b=e=>typeof e==`string`?p(e):e,x=(e,t,n,r)=>{let i=f(t);e.emit(Reflect.apply(t,null,[n]),r&&i?d(r,i):r)},S=(e,t,r,a)=>{let o=e;o[i]=!0;try{x(e,t,r,a)}catch(e){n(`cancel listener`,e)}o[i]=!1},C=e=>{try{return Promise.resolve(e())}catch(e){if(e instanceof m)throw e;return Promise.reject(e)}},w=(t,r,i={},a)=>{let l=h(t,r),d=e=>b(i[e]??`${t}/${e}`),f=d(`pending`),p=d(`success`),m=d(`fail`),g=d(`cancel`),_=(t,r,i,o)=>{let s=i,l=`idle`,u=()=>{},d=()=>{l=`closed`,u()},h=e=>{l===`started`&&(d(),S(s,g,e,a))},_=()=>{l===`idle`&&(l=`started`,u=e(s,h),x(s,f,r,a))},v=e=>{l===`started`&&(d(),s.signal.aborted?S(s,g,s.signal.reason,a):`error`in e?x(s,m,e.error,a):x(s,p,e.value,a))};return Reflect.set(s,c,{start:_,cancel:h,done:v,drop:()=>{l===`idle`&&(l=`closed`)}}),C(()=>(o||_(),Reflect.apply(t,null,[r,i]))).then(e=>(v({value:e}),e),e=>{if(l===`idle`)try{_()}catch(e){n(`pending listener`,e)}v({error:e})})},v=e=>{let t=Reflect.get(e,s)===!0;return(n,r)=>_(e,n,r,t)};function y(e,n){return typeof n==`object`?r?_(l,e,n,!1):Reflect.apply(l,null,[e,n]):u(o(T,t,e),a)}let w=Object.assign(y,{type:t,match:l.match,wrap:v,pending:f,success:p,fail:m,cancel:g}),T=u(w,a);return T},T=e=>typeof e==`object`&&!!e,E=e=>{if(typeof e==`string`)return e;if(T(e)||typeof e==`function`){let t=Reflect.get(e,`type`);return typeof t==`string`?t:e}return e},D=(e,t)=>{let[n,r]=e;return n===void 0||Object.is(E(n),E(t[0]))&&(r===void 0||Object.is(r,t[1]))},O=e=>{let t={on:e.on,once:e.once,off:e.off},n=[],r=!0,i=(t,n)=>Reflect.apply(t,e,n),a=(e,t)=>(...a)=>{if(!r)return i(t,a);let o={kind:e,args:a,dropped:!1};return n.push(o),()=>{o.live?o.live():o.dropped=!0}},o=e=>(...t)=>{if(!r)return i(e,t);for(let e of n)e.kind!==`off`&&D(t,e.args)&&(e.dropped=!0);n.push({kind:`off`,args:t,dropped:!1})},s=a(`on`,t.on),c=a(`once`,t.once),l=o(t.off);return e.on=s,e.once=c,e.off=l,{release:()=>{r=!1,e.on===s&&(e.on=t.on),e.once===c&&(e.once=t.once),e.off===l&&(e.off=t.off)},replay:()=>{for(let e of n.splice(0))if(!e.dropped){if(e.kind===`off`)i(t.off,e.args);else{let n=e.kind===`on`?t.on:t.once;e.live=i(n,e.args)}}}}};function k(e,t,n){return n?{name:e,setup:t,scope:n}:{name:e,setup:t}}const A=(e,t)=>n=>t?e.fitScope?.(t,n)??n:n,j=(e,t,n)=>{n&&e.applyScope?.(t,n)},M=(e,t,n)=>Array.isArray(t)?[t.map(([t,n])=>[t,e(n)]),n]:[t,e(n)],N=(e,t)=>{let n=e.on;return(...e)=>{let[r,i]=e;return Reflect.apply(n,null,[r,t(i)])}},P=e=>(t,...n)=>{e.run(t,...n).catch(t=>{if(!e.signal.aborted)throw t})},F=(n=[])=>i=>{let a=i.commands??v()(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=>{let r=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map;return{mount:c=>{let l=r.get(c);if(l)return l;let u=a.get(c.name);u&&r.get(u)?.();let d=t(n,c.name),f=d.ctx,p=s(f),m=()=>{r.delete(c),a.get(c.name)===c&&a.delete(c.name),f.abort(),d.unlink()};r.set(c,m),a.set(c.name,c);let h=c.scope,g=A(i,h),_=(t,n)=>{let r=Reflect.apply(o.handle,null,M(g,t,n));return e(f,r),r},v=(...e)=>{let t=e.map(e=>typeof e==`function`?_(e,e):p.mount(e));return()=>{for(let e of t)e()}},y=P(f),b=N(f,g);try{j(i,f,h),c.setup(Object.assign(f,{handle:_,use:v,spawn:y,on:b}))}catch(e){throw m(),e}return m},unmount:e=>r.get(e)?.(),isMounted:e=>r.has(e)}},c=O(i),l=i.emit,u,d=(e=!0)=>{if(u)return u;c.release(),i.emit===f&&(i.emit=l);let t=r({event:{type:`app`,payload:void 0},bus:i,tracer:i.trace});if(u={root:t,apps:s(t.ctx)},e)for(let e of n)u.apps.mount(e);return c.replay(),u},f=(...e)=>(d(),Reflect.apply(l,i,e));i.emit=f;let p={get commands(){return d(),a},mount:e=>{let{root:t,apps:n}=d();return t.ctx.signal.throwIfAborted(),n.mount(e)},unmount:e=>d().apps.unmount(e),isMounted:e=>d().apps.isMounted(e),dispose:()=>d(!1).root.ctx.abort(),createModule:k};return i.app=p,p};export{g as bindHandler,v as commandsPlugin,p as createAction,h as createCommand,w as createJob,k as createModule,y as emitterPlugin,F as modulePlugin};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,l as t,n,r}from"./context-yYU3_9lq.js";import{n as i}from"./promise-CSLpzwSR.js";const a=e=>typeof e==`string`?e:e.type,o=(e,t)=>typeof e==`object`?e.payload:t,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(),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(a(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(a(e),t)},h=(e,a)=>{let{onError:o}=s,{ctx:c}=n({event:a,bus:g,tracer:s.trace,parent:{ref:r()}});if(!o){e(a.payload,c);return}let l=e=>{try{o(e,a)}catch(e){t(`onError failed`,e)}};try{let t=e(a.payload,c);i(t)&&Promise.resolve(t).catch(l)}catch(e){l(e)}},g={on:u,once:p,off:m,emit:(t,i)=>{let c=a(t),u=o(t,i),p={type:c,payload:u},m=d(t),_=[...l.get(c),...l.get(`*`)];_.length===0&&!m&&s.onUnhandled?.(p);for(let e of _)h(e,p);if(m){let{ctx:t}=n({event:p,bus:g,tracer:s.trace,parent:{ref:r()}}),i=g.commands?.run??f;return e(t,`command`,()=>i(m,u,t))}},use:e=>e(g),ctx:s.context,trace:s.trace};return g};export{a,s as i,p as n,u as r,l as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=(e,t)=>{globalThis.console?.error(`[nanoeffects] ${e}`,t)},t=()=>{},n=/* @__PURE__ */ new WeakMap,r=t=>{let r=n.get(t);if(r)return r;let i=/* @__PURE__ */ new Set;return n.set(t,i),t.addEventListener(`abort`,()=>{let n=[...i];i.clear();for(let{fn:r}of n)try{r(t.reason)}catch(t){e(`abort callback failed`,t)}},{once:!0}),i},i=(e,n)=>{let{signal:i}=e;if(!i)return t;if(i.aborted)return n(i.reason),t;let a=r(i),o={fn:n};return a.add(o),()=>{a.delete(o)}},a=e=>{let t=new AbortController;return{controller:t,unlink:i({signal:e},e=>t.abort(e))}},o=Symbol();let s;const c=()=>s,l=()=>{},u=(e,t,n,r)=>{},d=(e,t)=>l,f=(e,t,n)=>n(),p=(e,t)=>typeof e==`function`?e(t):e,m=({event:e,bus:t,tracer:n,parent:r})=>{let{controller:c,unlink:u}=a(r?.signal),{signal:d}=c,h=(...e)=>{if(d.aborted&&!v[o])return;let n=t?.emit,r=s;s=void 0;try{return n?.(...e)}finally{s=r}},g=(...e)=>{if(d.aborted)return l;let n=t?.on,r=n?.(...e);if(!r)return l;let a=i({signal:d},r);return()=>{a(),r()}},_=async(r,...i)=>{d.throwIfAborted();let a=i[0],o=m({event:{type:e.type,payload:a},bus:t,tracer:n,parent:{signal:d,ref:void 0}});try{return await f(o.ctx,`run`,()=>r(a,o.ctx))}finally{o.unlink()}},v={...p(t?.ctx,e),type:e.type,payload:e.payload,signal:d,abort:e=>c.abort(e),emit:h,on:g,off:t?.off??l,run:_};return t?.addContext?.(v),{ctx:v,unlink:u}},h=(e,t)=>m({event:{type:t??e.type??``,payload:e.payload},bus:{emit:e.emit,on:e.on,off:e.off,ctx:e},tracer:void 0,parent:{signal:e.signal,ref:void 0}});export{f as a,i as c,h as i,e as l,m as n,u as o,c as r,o as s,d as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{c as e}from"./context-yYU3_9lq.js";const t=2**31-1,n=(e,n)=>{let r={id:null};if(n===1/0)return r;let i=n=>{r.id=setTimeout(()=>{n>t?i(n-t):(r.id=null,e())},Math.min(n,t))};return i(n>0?n:0),r},r=e=>{e.id!==null&&(clearTimeout(e.id),e.id=null)},i=(t,i)=>new Promise((a,o)=>{let s=n(()=>{c(),a()},typeof i==`function`?i():i),c=e(t,e=>{r(s),o(e)})});export{r as n,n as r,i as t};
|
package/dist/notrace/effects.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,c as t,i as n,
|
|
1
|
+
import{a as e,c as t,i as n,l as r,o as i,t as a}from"./context-yYU3_9lq.js";import{n as o,r as s,t as c}from"./delay-BosJKFjg.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,r,o,s)=>{r?.signal?.throwIfAborted();let{ctx:c,unlink:u}=n(r??{}),d=a(c,e);i(c,e,`start`),t(c,()=>d(`cancel`));try{let e=await l(o(c),r);return d(`done`),s?.(!1),e}catch(e){throw d(`error`,e),s?.(!0),e}finally{u()}},d=async(t,r)=>{let{ctx:i,unlink:a}=n(t);try{return await e(i,`run`,()=>r(i))}finally{a()}},f=e=>e,p=(e,t)=>n=>e(t,f(n)),m=e=>Array.isArray(e)?Array(e.length):{},h=(t,r)=>{let i=Object.entries(r).map(([r,i])=>{let a=n(t),o={signal:a.ctx.signal,abort:a.ctx.abort},s=()=>i(o);return{key:r,task:new Promise(t=>t(e(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=(e,n)=>e.signal.aborted?Promise.reject(e.signal.reason):new Promise((i,a)=>{let o=[],s=`pending`,c=e=>{try{e()}catch(e){r(`cancel cleanup failed`,e)}},l=t(e,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{n({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)t in e||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=(t,r,i)=>u(`timeout`,t,async t=>{let a=n(t),c=s(()=>a.ctx.abort(new DOMException(`Timed out after ${r}ms`,`TimeoutError`)),r);try{return await l(Promise.resolve(e(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/notrace/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,n as t,t as n}from"./bus-
|
|
1
|
+
import{i as e,n as t,t as n}from"./bus-BmCTo8BG.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=Symbol(),t=Symbol();export{t as n,e as t};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { H as Task, R as EventMap } from "./action-creator-DHAEgwuh.js";
|
|
1
|
+
import { B as PayloadOf, H as Task, R as EventMap } from "./action-creator-DHAEgwuh.js";
|
|
2
2
|
//#region src/policies/keyed.d.ts
|
|
3
3
|
/** Options shared by every policy that can keep its state per key. */
|
|
4
4
|
type KeyOption<P> = {
|
|
@@ -168,4 +168,32 @@ type ThrottleOptions<P = never> = KeyOption<P> & {
|
|
|
168
168
|
*/
|
|
169
169
|
export declare const throttle: <P, E extends EventMap, R>(ms: number, fn: Task<P, E, R>, options?: ThrottleOptions<P>) => Task<P, E, R | Promise<R | undefined> | undefined>;
|
|
170
170
|
//#endregion
|
|
171
|
-
|
|
171
|
+
//#region src/policies/with-policy.d.ts
|
|
172
|
+
/** What `withPolicy` returns: the task as a plain function that can be cancelled. */
|
|
173
|
+
type PolicyFunction<P, R> = {
|
|
174
|
+
(...args: PayloadOf<P>): Promise<Awaited<R> | undefined>;
|
|
175
|
+
/** Aborts every call that has not finished. Calls made after it work as before. */
|
|
176
|
+
cancel: (reason?: unknown) => void;
|
|
177
|
+
/** Same as `cancel`; present where `Symbol.dispose` exists, for `using`. */
|
|
178
|
+
[Symbol.dispose]?: () => void;
|
|
179
|
+
};
|
|
180
|
+
/**
|
|
181
|
+
* Makes a policy (or any task) a plain function that needs no bus and no
|
|
182
|
+
* context. The returned function keeps the state of the policy between calls,
|
|
183
|
+
* so a debounced one waits across calls. `cancel()` aborts what is pending or
|
|
184
|
+
* running; calls after it work again. The callback keeps the `(payload, ctx)`
|
|
185
|
+
* shape; `ctx.signal`, `ctx.abort` and `ctx.run` work, `ctx.emit` and `ctx.on`
|
|
186
|
+
* do nothing because there is no bus.
|
|
187
|
+
*
|
|
188
|
+
* @example
|
|
189
|
+
* ```ts
|
|
190
|
+
* const onChange = withPolicy(debounce(300, (query: string) => search(query)));
|
|
191
|
+
*
|
|
192
|
+
* onChange("re");
|
|
193
|
+
* onChange("redux"); // only this one runs, 300 ms after it
|
|
194
|
+
* onChange.cancel(); // or nothing runs at all
|
|
195
|
+
* ```
|
|
196
|
+
*/
|
|
197
|
+
export declare const withPolicy: <P, R>(task: Task<P, EventMap, R>) => PolicyFunction<P, R>;
|
|
198
|
+
//#endregion
|
|
199
|
+
export type { DebounceOptions, LatestOptions, LeadingOptions, PolicyFunction, QueueOptions, ThrottleOptions };
|
package/dist/notrace/policies.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,
|
|
1
|
+
import{a as e,c as t,i as n,n as r,o as i,t as a}from"./context-yYU3_9lq.js";import{n as o,r as s,t as c}from"./delay-BosJKFjg.js";import{n as l,t as u}from"./promise-CSLpzwSR.js";import{n as d,t as f}from"./lifecycle-key-8iX8RUVD.js";const p=e=>Reflect.get(e,f),m=e=>{p(e)?.start()},h=(t,n,r)=>(m(t),e(t,n,r)),g=(e,t)=>{i(e,t,`drop`),p(e)?.drop()},_=(e,t)=>{p(e)?.done(t)},v=(e,t,n)=>{let r=p(e);t?r?.cancel(n):r?.drop()},y=e=>(Reflect.set(e,d,!0),e),b=()=>{},x=(e,t)=>{let n=/* @__PURE__ */ new Map;return(r,i)=>{let a=e(r),o=n.get(a);if(!o){let e=t(()=>{n.get(a)===e&&n.delete(a)});o=e,n.set(a,e)}return o(r,i)}},S=(e,t)=>y(e?x(e,t):t(b)),C=(e,t={})=>S(t.key,t=>w(`latest`,(t,n,r)=>(r(),e(t,n)),t)),w=(e,r,o=b)=>{let s=null;return(c,u)=>{if(s?.abort(),u.signal.aborted)return;let{ctx:d,unlink:f}=n(u);s=d;let p=a(d,e),h=!1,g=()=>{d.signal.aborted||(h=!0,m(d),i(d,e,`start`))};t(d,e=>{v(d,h,e),p(h?`cancel`:`drop`)});let _=()=>{f(),s===d&&(s=null,o())},y=e=>{if(!d.signal.aborted)return p(h?`done`:`drop`),e};try{let e=r(c,d,g);return l(e)?Promise.resolve(e).then(y,e=>{if(!d.signal.aborted)throw p(`error`,e),e}).finally(_):(_(),y(e))}catch(e){if(_(),d.signal.aborted)return;throw p(`error`,e),e}}},T=(e,t,n={})=>S(n.key,r=>D(e,t,n,r)),E=(e,t,n,r)=>{let i=r!==b,a=null,c=null;return(l,u)=>{if(u.signal.aborted)return;let d=Date.now(),f=a===null||d-a>=e||d-a<0;return a=d,c!==null&&o(c),c=i?s(r,e):null,n&&f?Promise.resolve(h(u,`debounce`,()=>t(l,u))):(g(u,`debounce`),Promise.resolve(void 0))}},D=(e,n,r,i)=>{let a=r.leading??!1,o=r.trailing??!0;if(!o)return E(e,n,a,i);let s=!1,l=0,u=w(`debounce`,([r,i],a,u)=>{let d=l;return t(a,()=>{l===d&&(s=!1)}),c(a,e).then(()=>{if(s=!1,o&&!i)return u(),n(r,a)})},i);return(e,t)=>{if(t.signal.aborted)return;let r=a&&!s;s=!0,l++;let i=u([e,r],t);return r?Promise.resolve(h(t,`debounce`,()=>n(e,t))):i}},O=(e,n={})=>S(n.key,n=>{let r=null;return(i,a)=>{if(a.signal.aborted)return;if(r){g(a,`leading`);return}let o={};r=o;let s=()=>{c(),r===o&&(r=null,n())},c=t(a,s);try{return u(h(a,`leading`,()=>e(i,a)),s)}catch(e){throw s(),e}}}),k=(e,t={})=>S(t.key,n=>A(e,t,n)),A=(e,n,r)=>{let i=n.concurrency??1,a=n.limit??1/0,o=[],s=0,c=()=>{for(;s<i;){let e=o.shift();if(!e)return;e.start()}};return(l,u)=>new Promise((d,f)=>{if(u.signal.aborted){d(void 0);return}let p=b,m=()=>{p(),g(u,`queue`),d(void 0)},v=()=>{if(p(),u.signal.aborted){m();return}s++;let n=!0,i=()=>{n&&(n=!1,s--,c(),s===0&&o.length===0&&r())},a=t(u,()=>{i(),d(void 0)}),g;try{g=Promise.resolve(h(u,`queue`,()=>e(l,u)))}catch(e){g=Promise.reject(e)}let v=()=>{a(),i()};g.then(e=>{_(u,{value:e}),v(),d(u.signal.aborted?void 0:e)},e=>{_(u,{error:e}),v(),u.signal.aborted?d(void 0):f(e)})};if(s<i){v();return}if(o.length>=a){if(n.overflow!==`drop-old`||a<=0){m();return}o.shift()?.drop()}let y={start:v,drop:m};o.push(y),p=t(u,()=>{let e=o.indexOf(y);e>=0&&o.splice(e,1),m()})})},j=(e,t,n={})=>S(n.key,r=>M(e,t,n,r)),M=(e,t,n,r)=>{let i=n.leading??!0,a=n.trailing??!0,c=r!==b,l=null,u=0,d=null,f=null,p=null,m=!1,_=t=>l===null||t-l>=e||t-l<0||t-u>=e,v=e=>g(e,`throttle`),y=()=>{let e=p;p=null,e&&(v(e.ctx),e.resolve())},x=(e,t)=>(y(),new Promise((n,r)=>{p={payload:e,ctx:t,resolve:n,reject:r}})),S=(e,n,r)=>{y(),u=r,m=!0;try{return h(n,`throttle`,()=>t(e,n))}finally{m=!1}},C=()=>{c&&(f=s(w,e))},w=()=>{if(f=null,!c||d!==null||p)return;let t=Date.now(),n=Math.max(e-(t-(l??-1/0)),e-(t-u));n<=0?r():f=s(w,n)},T=e=>{d=null;let t=p;if(a&&t&&!t.ctx.signal.aborted){p=null;try{t.resolve(S(t.payload,t.ctx,e))}catch(e){t.reject(e)}}else y();w()},E=()=>{let t=Date.now();_(t)?T(t):d=s(E,Math.min(e-(t-(l??t)),e-(t-u)))},D=()=>{f!==null&&(o(f),f=null)},O=(e,t)=>{if(!a)v(t);else return x(e,t)},k=(e,t,n,r)=>{if(!r)v(t);else if(u=n,C(),!i)v(t);else return S(e,t,n)},A=(t,n,r,a)=>a&&d!==null?(o(d),d=s(E,e),S(t,n,r)):d===null&&(d=s(E,e),a&&(u=r,i))?S(t,n,r):O(t,n);return(e,t)=>{if(t.signal.aborted)return;let n=Date.now(),r=!m&&_(n);return l=n,D(),a?A(e,t,n,r):k(e,t,n,r)}},N=Reflect.get(Symbol,`dispose`),P=e=>{let t=new AbortController,n=async(...n)=>{let i=n[0],{ctx:a,unlink:o}=r({event:{type:`withPolicy`,payload:i},parent:{signal:t.signal}});try{return await e(i,a)}finally{o()}},i=e=>{t.abort(e),t=new AbortController},a=Object.assign(n,{cancel:i});return N&&Reflect.set(a,N,()=>i()),a};export{T as debounce,C as latest,O as leading,k as queue,j as throttle,P as withPolicy};
|
package/dist/oop.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as e}from"./bus-CkTHUAvq.js";const t=/* @__PURE__ */ new WeakMap,n=e=>typeof e==`function`,r=e=>Reflect.ownKeys(e).flatMap(t=>{let r=Reflect.getOwnPropertyDescriptor(e,t)?.value;return n(r)?[{key:t,value:r}]:[]}),i=/* @__PURE__ */ new WeakMap,a=e=>{let n=i.get(e);if(n)return n;let a=/* @__PURE__ */ new Set,o=[];for(let n=e;n&&n!==Object.prototype;n=Reflect.getPrototypeOf(n))for(let{key:e,value:i}of r(n)){if(e===`constructor`||a.has(e))continue;a.add(e);let n=t.get(i);n&&o.push({key:e,method:i,spec:n})}return i.set(e,o),o},o=/* @__PURE__ */ new WeakMap,s=e=>typeof e==`object`&&!!e||typeof e==`function`,c=e=>{let t=o.get(e);if(t)return t;let n=/* @__PURE__ */ new Set;return o.set(e,n),n},l=e=>{if(typeof e==`string`)return e;if(s(e)){let t=Reflect.get(e,`type`);return typeof t==`string`?t:e}return e},u=(e,t,n)=>Reflect.apply(Reflect.get(e,t),e,n),d=(e,t,n,r)=>{let[i,a,...o]=r,s=c(e),l={event:i,handler:a,off:()=>{}},d=u(t,n,[i,n===`once`?(e,t)=>(s.delete(l),typeof a==`function`?Reflect.apply(a,null,[e,t]):void 0):a,...o]),f=typeof d==`function`?()=>d():()=>{};return l.off=f,s.add(l),()=>{s.delete(l),f()}},f=(e,t,n)=>{let[r,i]=n,a=c(e);r===void 0&&a.clear();for(let e of[...a])Object.is(l(e.event),l(r))&&(i===void 0||e.handler===i)&&(a.delete(e),e.off());return u(t,`off`,n)},p=e=>{if(!s(e))return;let t=o.get(e);if(t){o.delete(e);for(let e of t)e.off()}},m=/* @__PURE__ */ new Set([`on`,`once`,`off`,`emit`,`ctx`,`commands`,`trace`,`addContext`,`applyScope`,`fitScope`,`app`,`use`]),h=Reflect.get(Symbol,`dispose`),g=e=>typeof e==`function`,_=(e,t,n,r)=>{n in t||Object.defineProperty(e,n,{configurable:!0,enumerable:!1,...r})},v=/* @__PURE__ */ new WeakMap,y=(e,t)=>{let n=v.get(e);if(n)return n;let r={on:(...n)=>d(e,t,`on`,n),once:(...n)=>d(e,t,`once`,n),off:(...n)=>f(e,t,n)};return v.set(e,r),r},b=(e,t)=>(...n)=>Reflect.apply(Reflect.get(e,t),e,n),x=(e,t)=>{for(let{method:n,spec:r}of a(Reflect.getPrototypeOf(e)??{})){let i=(t,r)=>Reflect.apply(n,e,[t,r]),a=r.wrap?r.wrap(i):i;d(e,t,r.once?`once`:`on`,[r.event,a])}},S=(e,t,n)=>{for(let r of[`on`,`once`,`off`])_(e,t,r,{get(){return y(this,n)[r]}});_(e,t,`emit`,{value:b(n,`emit`)});for(let[r,i]of Object.entries(n))typeof i==`function`&&!m.has(r)&&_(e,t,r,{value:b(n,r)});let r=function(){p(this)};_(e,t,`dispose`,{value:r}),h&&_(e,t,h,{value:r}),_(e,t,`bus`,{get:()=>n})},C=(e,t)=>{let n=function(...r){let i=Reflect.construct(t,r,new.target??n);return x(i,e),i};return Object.setPrototypeOf(n,t),n.prototype=Object.create(t.prototype,{constructor:{value:n,writable:!0,configurable:!0}}),Object.defineProperty(n,"name",{value:t.name,configurable:!0}),`bus`in t||Object.defineProperty(n,"bus",{value:e,configurable:!0}),S(n.prototype,t.prototype,e),n};function w(t,n){if(g(t))return C(e(),t);if(!n)throw TypeError(`extendBus: pass the class to extend`);return C(t,n)}function T(e){return t=>e?w(e,t):w(t)}const E=e=>{let[t,n,r]=e;return typeof n==`string`||typeof n==`symbol`?Reflect.get(Object(r),`value`):t},D=(e,n,r)=>((...i)=>{let a=E(i);typeof a==`function`&&t.set(a,{event:e,wrap:n,once:r})});function O(e,t){return D(e,t,!1)}function k(e,t){return D(e,t,!0)}export{O as On,k as Once,T as WithBus,p as disposeBus,w as extendBus};
|
package/dist/policies.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { B as EventMap, W as Task } from "./action-creator-BrZF6hXc.js";
|
|
2
|
+
import { n as withPolicy, t as PolicyFunction } from "./with-policy-CqUS-VWW.js";
|
|
2
3
|
//#region src/policies/keyed.d.ts
|
|
3
4
|
/** Options shared by every policy that can keep its state per key. */
|
|
4
5
|
type KeyOption<P> = {
|
|
@@ -168,4 +169,4 @@ type ThrottleOptions<P = never> = KeyOption<P> & {
|
|
|
168
169
|
*/
|
|
169
170
|
export declare const throttle: <P, E extends EventMap, R>(ms: number, fn: Task<P, E, R>, options?: ThrottleOptions<P>) => Task<P, E, R | Promise<R | undefined> | undefined>;
|
|
170
171
|
//#endregion
|
|
171
|
-
export type
|
|
172
|
+
export { type DebounceOptions, type LatestOptions, type LeadingOptions, type PolicyFunction, type QueueOptions, type ThrottleOptions, withPolicy };
|
package/dist/policies.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./onAbort-BgMfspK4.js";import{a as t,i as n,o as r,t as i}from"./context-
|
|
1
|
+
import{t as e}from"./onAbort-BgMfspK4.js";import{a as t,i as n,o as r,t as i}from"./context-COgyNlrC.js";import{n as a,r as o,t as s}from"./delay-CIHnOh_L.js";import{n as c,t as l}from"./promise-CSLpzwSR.js";import{n as u,t as d}from"./lifecycle-key-8iX8RUVD.js";import{t as f}from"./with-policy-DBV9dh2F.js";const p=e=>Reflect.get(e,d),m=e=>{p(e)?.start()},h=(e,n,r)=>(m(e),t(e,n,r)),g=(e,t)=>{r(e,t,`drop`),p(e)?.drop()},_=(e,t)=>{p(e)?.done(t)},v=(e,t,n)=>{let r=p(e);t?r?.cancel(n):r?.drop()},y=e=>(Reflect.set(e,u,!0),e),b=()=>{},x=(e,t)=>{let n=/* @__PURE__ */ new Map;return(r,i)=>{let a=e(r),o=n.get(a);if(!o){let e=t(()=>{n.get(a)===e&&n.delete(a)});o=e,n.set(a,e)}return o(r,i)}},S=(e,t)=>y(e?x(e,t):t(b)),C=(e,t={})=>S(t.key,t=>w(`latest`,(t,n,r)=>(r(),e(t,n)),t)),w=(t,a,o=b)=>{let s=null;return(l,u)=>{if(s?.abort(),u.signal.aborted)return;let{ctx:d,unlink:f}=n(u);s=d;let p=i(d,t),h=!1,g=()=>{d.signal.aborted||(h=!0,m(d),r(d,t,`start`))};e(d,e=>{v(d,h,e),p(h?`cancel`:`drop`)});let _=()=>{f(),s===d&&(s=null,o())},y=e=>{if(!d.signal.aborted)return p(h?`done`:`drop`),e};try{let e=a(l,d,g);return c(e)?Promise.resolve(e).then(y,e=>{if(!d.signal.aborted)throw p(`error`,e),e}).finally(_):(_(),y(e))}catch(e){if(_(),d.signal.aborted)return;throw p(`error`,e),e}}},T=(e,t,n={})=>S(n.key,r=>D(e,t,n,r)),E=(e,t,n,r)=>{let i=r!==b,s=null,c=null;return(l,u)=>{if(u.signal.aborted)return;let d=Date.now(),f=s===null||d-s>=e||d-s<0;return s=d,c!==null&&a(c),c=i?o(r,e):null,n&&f?Promise.resolve(h(u,`debounce`,()=>t(l,u))):(g(u,`debounce`),Promise.resolve(void 0))}},D=(t,n,r,i)=>{let a=r.leading??!1,o=r.trailing??!0;if(!o)return E(t,n,a,i);let c=!1,l=0,u=w(`debounce`,([r,i],a,u)=>{let d=l;return e(a,()=>{l===d&&(c=!1)}),s(a,t).then(()=>{if(c=!1,o&&!i)return u(),n(r,a)})},i);return(e,t)=>{if(t.signal.aborted)return;let r=a&&!c;c=!0,l++;let i=u([e,r],t);return r?Promise.resolve(h(t,`debounce`,()=>n(e,t))):i}},O=(t,n={})=>S(n.key,n=>{let r=null;return(i,a)=>{if(a.signal.aborted)return;if(r){g(a,`leading`);return}let o={};r=o;let s=()=>{c(),r===o&&(r=null,n())},c=e(a,s);try{return l(h(a,`leading`,()=>t(i,a)),s)}catch(e){throw s(),e}}}),k=(e,t={})=>S(t.key,n=>A(e,t,n)),A=(t,n,r)=>{let i=n.concurrency??1,a=n.limit??1/0,o=[],s=0,c=()=>{for(;s<i;){let e=o.shift();if(!e)return;e.start()}};return(l,u)=>new Promise((d,f)=>{if(u.signal.aborted){d(void 0);return}let p=b,m=()=>{p(),g(u,`queue`),d(void 0)},v=()=>{if(p(),u.signal.aborted){m();return}s++;let n=!0,i=()=>{n&&(n=!1,s--,c(),s===0&&o.length===0&&r())},a=e(u,()=>{i(),d(void 0)}),g;try{g=Promise.resolve(h(u,`queue`,()=>t(l,u)))}catch(e){g=Promise.reject(e)}let v=()=>{a(),i()};g.then(e=>{_(u,{value:e}),v(),d(u.signal.aborted?void 0:e)},e=>{_(u,{error:e}),v(),u.signal.aborted?d(void 0):f(e)})};if(s<i){v();return}if(o.length>=a){if(n.overflow!==`drop-old`||a<=0){m();return}o.shift()?.drop()}let y={start:v,drop:m};o.push(y),p=e(u,()=>{let e=o.indexOf(y);e>=0&&o.splice(e,1),m()})})},j=(e,t,n={})=>S(n.key,r=>M(e,t,n,r)),M=(e,t,n,r)=>{let i=n.leading??!0,s=n.trailing??!0,c=r!==b,l=null,u=0,d=null,f=null,p=null,m=!1,_=t=>l===null||t-l>=e||t-l<0||t-u>=e,v=e=>g(e,`throttle`),y=()=>{let e=p;p=null,e&&(v(e.ctx),e.resolve())},x=(e,t)=>(y(),new Promise((n,r)=>{p={payload:e,ctx:t,resolve:n,reject:r}})),S=(e,n,r)=>{y(),u=r,m=!0;try{return h(n,`throttle`,()=>t(e,n))}finally{m=!1}},C=()=>{c&&(f=o(w,e))},w=()=>{if(f=null,!c||d!==null||p)return;let t=Date.now(),n=Math.max(e-(t-(l??-1/0)),e-(t-u));n<=0?r():f=o(w,n)},T=e=>{d=null;let t=p;if(s&&t&&!t.ctx.signal.aborted){p=null;try{t.resolve(S(t.payload,t.ctx,e))}catch(e){t.reject(e)}}else y();w()},E=()=>{let t=Date.now();_(t)?T(t):d=o(E,Math.min(e-(t-(l??t)),e-(t-u)))},D=()=>{f!==null&&(a(f),f=null)},O=(e,t)=>{if(!s)v(t);else return x(e,t)},k=(e,t,n,r)=>{if(!r)v(t);else if(u=n,C(),!i)v(t);else return S(e,t,n)},A=(t,n,r,s)=>s&&d!==null?(a(d),d=o(E,e),S(t,n,r)):d===null&&(d=o(E,e),s&&(u=r,i))?S(t,n,r):O(t,n);return(e,t)=>{if(t.signal.aborted)return;let n=Date.now(),r=!m&&_(n);return l=n,D(),s?A(e,t,n,r):k(e,t,n,r)}};export{T as debounce,C as latest,O as leading,k as queue,j as throttle,f as withPolicy};
|
package/dist/react.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { B as EventMap, T as EventKey, h as Bus, r as FreeActionCreator, t as ActionCreator } from "./action-creator-BrZF6hXc.js";
|
|
1
|
+
import { B as EventMap, T as EventKey, W as Task, h as Bus, r as FreeActionCreator, t as ActionCreator } from "./action-creator-BrZF6hXc.js";
|
|
2
|
+
import { t as PolicyFunction } from "./with-policy-CqUS-VWW.js";
|
|
2
3
|
//#region src/react/plugin.d.ts
|
|
3
4
|
/** What `reactPlugin` adds to the bus. */
|
|
4
5
|
/** Tells whether two values are the same: `Object.is` unless the caller gives another. */
|
|
@@ -47,4 +48,35 @@ type ReactApi<E extends EventMap> = {
|
|
|
47
48
|
*/
|
|
48
49
|
export declare const reactPlugin: () => <E extends EventMap>(bus: Bus<E>) => Bus<E> & ReactApi<E>;
|
|
49
50
|
//#endregion
|
|
51
|
+
//#region src/react/use-policy.d.ts
|
|
52
|
+
/**
|
|
53
|
+
* A policy (`debounce`, `throttle`, `latest`, ...) as one stable function for a
|
|
54
|
+
* component. A policy made in the body of a component is made again on every
|
|
55
|
+
* render and loses its timer; made once, it keeps the callback of the first
|
|
56
|
+
* render. This hook keeps the policy across renders and calls the `callback` of
|
|
57
|
+
* the latest render, so an inline callback sees fresh props and state.
|
|
58
|
+
*
|
|
59
|
+
* `make` gets a task that runs the callback and returns the policy built around
|
|
60
|
+
* it. It runs once, and again when an item of `deps` changes: list there what
|
|
61
|
+
* `make` reads, such as the wait time. The pending calls of the old function are
|
|
62
|
+
* cancelled then, and when the component unmounts. Needs `react` 18 or newer.
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```tsx
|
|
66
|
+
* import { debounce } from "nanoeffects/policies";
|
|
67
|
+
* import { usePolicy } from "nanoeffects/react";
|
|
68
|
+
*
|
|
69
|
+
* const Search = ({ wait }: { wait: number }) => {
|
|
70
|
+
* const [results, setResults] = useState([]);
|
|
71
|
+
* const onChange = usePolicy(
|
|
72
|
+
* async (query: string) => setResults(await search(query)), // latest render's callback
|
|
73
|
+
* (task) => debounce(wait, task), // the policy, made once per wait
|
|
74
|
+
* [wait],
|
|
75
|
+
* );
|
|
76
|
+
* return <input onChange={(event) => onChange(event.target.value)} />;
|
|
77
|
+
* };
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
export declare const usePolicy: <P, R, S = R>(callback: Task<P, EventMap, R>, make: (task: Task<P, EventMap, R>) => Task<P, EventMap, S>, deps?: readonly unknown[]) => PolicyFunction<P, S>;
|
|
81
|
+
//#endregion
|
|
50
82
|
export type { ReactApi };
|
package/dist/react.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useEffect as
|
|
1
|
+
import{t as e}from"./with-policy-DBV9dh2F.js";import{useEffect as t,useMemo as n,useRef as r}from"react";const i=()=>e=>{function n(n,i,a){let o=r(i),s=r({event:n,equals:a});t(()=>{s.current={event:n,equals:a}}),t(()=>{let{event:t,equals:n}=s.current,r=n??Object.is,a=o.current;if(r(a,i))return;o.current=i;let c=typeof t==`function`?t(i):{type:t,payload:i};e.emit(c)},[i])}return Object.assign(e,{useEmitter:n})},a=(i,a,o=[])=>{let s=r(i);t(()=>{s.current=i});let c=n(()=>e(a((e,t)=>s.current(e,t))),o);return t(()=>()=>c.cancel(),[c]),c};export{i as reactPlugin,a as usePolicy};
|