timeout-flow 0.0.20 → 0.1.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 +32 -10
- package/dist/timeout-flow.min.js +1 -1
- package/package.json +79 -74
- package/src/TimerBase.js +5 -1
- package/src/parseDuration.js +0 -3
- package/src/raf/everyRaf.js +3 -5
- package/src/raf/throttleRaf.js +1 -1
- package/src/resolveDelayAndFn.js +1 -25
- package/src/waitFor.js +11 -8
- package/types/TimerBase.d.ts +2 -2
- package/types/abort.d.ts +40 -40
- package/types/index.d.ts +10 -10
- package/types/raf/waitForRaf.d.ts +19 -19
- package/types/resolveDelayAndFn.d.ts +1 -15
- package/types/retry.d.ts +70 -70
- package/types/sleep.d.ts +29 -29
- package/types/waitFor.d.ts +28 -28
- package/src/context-js.bat +0 -58
- package/src/context.txt +0 -2709
package/README.md
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
# timeout-flow
|
|
2
2
|
|
|
3
|
-
[](https://www.npmjs.com/package/timeout-flow)
|
|
3
|
+
[](https://www.npmjs.com/package/timeout-flow)
|
|
4
|
+
[](https://www.npmjs.com/package/timeout-flow)
|
|
5
|
+
[](https://github.com/iWhatty/timeout-flow/blob/main/LICENSE)
|
|
6
|
+
[](https://github.com/iWhatty/timeout-flow)
|
|
7
|
+
[](https://www.npmjs.com/package/timeout-flow)
|
|
9
8
|
|
|
10
9
|
Fluent, human-readable time control for JavaScript. A modern, composable upgrade to `setTimeout` and `setInterval` with chaining, conditional logic, pause/resume control, retries, and RAF utilities.
|
|
11
10
|
|
|
@@ -52,6 +51,13 @@ ctrl.cancel();
|
|
|
52
51
|
|
|
53
52
|
## API
|
|
54
53
|
|
|
54
|
+
### `parseDuration(input)`
|
|
55
|
+
|
|
56
|
+
Convert a finite number of milliseconds or a duration string to milliseconds.
|
|
57
|
+
Strings support `ms`, `s`, `m`, and `h`, decimal values, case-insensitive units,
|
|
58
|
+
and surrounding whitespace. Invalid strings and non-finite numbers throw.
|
|
59
|
+
Negative numbers are accepted; negative strings are not.
|
|
60
|
+
|
|
55
61
|
### `after(duration, fn, options?)`
|
|
56
62
|
|
|
57
63
|
Run once after a delay.
|
|
@@ -283,9 +289,9 @@ Timing model:
|
|
|
283
289
|
`waitForRaf()` checks once per animation frame and measures `timeout` from the
|
|
284
290
|
first frame's timestamp (RAF time), timing out once `elapsed >= timeout`.
|
|
285
291
|
|
|
286
|
-
### `flow()`
|
|
292
|
+
### `flow(options?)`
|
|
287
293
|
|
|
288
|
-
Build declarative time flows.
|
|
294
|
+
Build declarative time flows. Accepts `{ signal }` for cancellation.
|
|
289
295
|
|
|
290
296
|
```js
|
|
291
297
|
import { flow } from 'timeout-flow';
|
|
@@ -322,6 +328,16 @@ onScroll.cancel();
|
|
|
322
328
|
onScroll.flush();
|
|
323
329
|
```
|
|
324
330
|
|
|
331
|
+
The RAF timers and debounce accept both `(duration, fn, options?)` and
|
|
332
|
+
`(fn, duration, options?)`; `debounceRaf(fn, options?)` defaults to 0 ms.
|
|
333
|
+
`everyRaf` accepts `max` and `runImmediately`. `throttleRaf(fn, frameSkip?, options?)`
|
|
334
|
+
runs after `frameSkip + 1` frames, using the latest arguments by default;
|
|
335
|
+
`{ trailing: false }` keeps the first call instead. RAF debounce and throttle
|
|
336
|
+
provide `cancel()` and `flush()`. `waitForRaf(condition, { timeout, signal, immediate })`
|
|
337
|
+
requires a synchronous condition and resolves with `undefined`, not its value.
|
|
338
|
+
RAF utilities require a browser RAF implementation or a polyfill.
|
|
339
|
+
`afterRaf` with a zero or negative duration invokes its callback synchronously.
|
|
340
|
+
|
|
325
341
|
### Controllers
|
|
326
342
|
|
|
327
343
|
Most time-based primitives return a controller object:
|
|
@@ -332,13 +348,17 @@ const ctrl = after('1s', () => console.log('done'));
|
|
|
332
348
|
ctrl.pause();
|
|
333
349
|
ctrl.resume();
|
|
334
350
|
ctrl.cancel();
|
|
335
|
-
ctrl.reset
|
|
351
|
+
ctrl.reset();
|
|
336
352
|
|
|
337
353
|
console.log(ctrl.isRunning);
|
|
338
354
|
console.log(ctrl.isPaused);
|
|
339
355
|
console.log(ctrl.isFinished);
|
|
340
356
|
```
|
|
341
357
|
|
|
358
|
+
`reset()` stops the controller without restarting it; `every()` and `everyRaf()`
|
|
359
|
+
also accept `reset(true)` to restart. After `after().reset()`, call `resume()`
|
|
360
|
+
to run again.
|
|
361
|
+
|
|
342
362
|
Shared by `after()`, `every()`, `afterRaf()`, `everyRaf()`. All controllers are pause-safe (paused time does not count), cancel-safe, monotonic-time based, and `AbortSignal`-aware where supported.
|
|
343
363
|
|
|
344
364
|
### AbortSignal support
|
|
@@ -363,6 +383,7 @@ If already aborted at creation time, no work is scheduled.
|
|
|
363
383
|
|
|
364
384
|
```js
|
|
365
385
|
import {
|
|
386
|
+
parseDuration,
|
|
366
387
|
after,
|
|
367
388
|
every,
|
|
368
389
|
debounce,
|
|
@@ -420,7 +441,7 @@ Measured for a single `after()` call in a typical browser bundler (esbuild, mini
|
|
|
420
441
|
| 0.0.19 default (`import { after } from 'timeout-flow'`) | 1199 bytes |
|
|
421
442
|
| 0.0.19 subpath (`import { after } from 'timeout-flow/after'`) | 1199 bytes |
|
|
422
443
|
|
|
423
|
-
For unbundled `<script type="module">` consumption of the full kit, use the **`timeout-flow/min`** subpath, which points at the pre-built minified
|
|
444
|
+
For unbundled `<script type="module">` consumption of the full kit, use the **`timeout-flow/min`** subpath, which points at the pre-built minified ESM bundle.
|
|
424
445
|
|
|
425
446
|
### Clean signatures
|
|
426
447
|
|
|
@@ -433,6 +454,7 @@ after(done, '1s');
|
|
|
433
454
|
```
|
|
434
455
|
|
|
435
456
|
This applies to `after()`, `every()`, `debounce()`, `throttle()`. Use whichever reads best in your codebase.
|
|
457
|
+
The function-first form also accepts `(fn, options?)`, defaulting the delay to 0 ms.
|
|
436
458
|
|
|
437
459
|
### Philosophy
|
|
438
460
|
|
package/dist/timeout-flow.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// TimeoutFlow - Fluent timer + RAF control library
|
|
2
|
-
function P(e){if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`Expected a finite number of ms, got: ${e}`);return e}if(typeof e!="string")throw new TypeError(`Expected a duration string or number, got ${typeof e}`);let n=e.toLowerCase().trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);if(!n)throw new Error(`Invalid duration format: "${e}". Expected formats like "500ms", "2s", "1.5m", or "1h".`);let i=Number(n[1]);if(!Number.isFinite(i))throw new TypeError(`Invalid duration value: "${n[1]}"`);let s=n[2];switch(s){case"ms":return i;case"s":return i*1e3;case"m":return i*6e4;case"h":return i*36e5;default:throw new Error(`Unsupported duration unit: "${s}"`)}}var k;typeof performance<"u"&&typeof performance.now=="function"?k=()=>performance.now():k=()=>Date.now();var B=class{#s;#o=null;#e;#n=null;#t=!1;#r=!1;#i=!1;constructor(r){this.#s=P(r),this.#e=this.#s}get isRunning(){return this.#t}get isPaused(){return this.#r}get isFinished(){return this.#i}pause(){if(!this.#t)return;clearTimeout(this.#n),this.#n=null;let r=k()-this.#o;this.#e=Math.max(0,this.#e-r),this.#t=!1,this.#r=!0}resume(r,n=null){if(this.#i||this.#t)return;let i=n??this.#e;if(!Number.isFinite(i))return;let s=Math.max(0,i);this.#e=s,this.#o=k(),this.#t=!0,this.#r=!1,this.#n=setTimeout(()=>{this.#n=null,this.#t=!1,this.#r=!1,this.#i=!0,this.#e=0,r?.()},s)}cancel(){this.#n&&clearTimeout(this.#n),this.#n=null,this.#t=!1,this.#r=!1,this.#i=!0,this.#e=0}reset(){this.#n&&clearTimeout(this.#n),this.#n=null,this.#o=null,this.#e=this.#s,this.#t=!1,this.#r=!1,this.#i=!1}};var Q;typeof DOMException<"u"?Q=(e="Aborted")=>new DOMException(e,"AbortError"):Q=(e="Aborted")=>{let r=new Error(e);return r.name="AbortError",r};function L(e,r){return e?e.aborted?(r(),()=>{}):(e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)):()=>{}}function N(e,r){let n=null;return{add(){n||(n=L(e,r))},remove(){n&&(n(),n=null)},reset(){n&&n(),n=null}}}function $(e){return e?.reason??Q()}var X=class extends B{#s=null;#o=null;#e=()=>{};constructor(r,n,{onFinish:i,signal:s}={}){super(r),this.#s=s??null,this.#o=()=>this.cancel(),this.#n(),!this.isFinished&&this.resume(()=>{this.#t(),n?.(),i?.()})}#n(){if(!(!this.#s||!this.#o)){if(this.#s.aborted){super.cancel(),this.#t();return}this.#e=L(this.#s,this.#o)}}#t(){this.#e(),this.#e=()=>{},this.#o=null}cancel(){this.isFinished||(this.#t(),super.cancel())}reset(){this.#e(),this.#e=()=>{},this.#o=()=>this.cancel(),super.reset(),this.#n()}};var V=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function _(e,r,n,i=0){let s,l,a;if(typeof e=="function"?(s=e,V(r)?(l=i,a=r):(l=r,a=V(n)?n:{})):(l=e,s=r,a=V(n)?n:{}),typeof s!="function")throw new TypeError(`Expected a function as one argument, got: ${typeof s}`);let u=l??i;if(u==null)throw new TypeError("Expected a duration (string/number) for delay");let o=P(u);return{fn:s,delay:o,options:a}}function Z(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,void 0);return new X(s,i,l)}var Y=class{#s;#o;#e;#n=0;#t=!1;#r=null;#i=null;#l=()=>{};constructor(r,n,{max:i=1/0,runImmediately:s=!1,signal:l}={}){if(this.#s=P(r),this.#o=n,this.#e=i,this.#i=l??null,!(this.#e>0)&&this.#e!==1/0){this.#t=!0,this.#l();return}if(this.#i?.aborted){this.#t=!0,this.#l();return}this.#l=L(this.#i,()=>this.cancel()),s?this.#f():this.#u()}get count(){return this.#n}get isRunning(){return!this.#t&&!!this.#r&&this.#r.isRunning}get isPaused(){return!this.#t&&!!this.#r&&this.#r.isPaused}get isFinished(){return this.#t}#a=()=>{this.#r?.cancel(),this.#r=null,this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null};#f=()=>{if(!this.#t){if(this.#i?.aborted){this.#a();return}if(this.#n>=this.#e){this.#a();return}if(this.#o?.(this.#n++),this.#n>=this.#e){this.#a();return}this.#u()}};#u(){if(!this.#t){if(this.#i?.aborted){this.#a();return}this.#r=new B(this.#s),this.#r.resume(this.#f)}}pause(){this.#t||this.#r?.pause()}resume(){if(!this.#t){if(this.#i?.aborted){this.#a();return}if(this.#n>=this.#e){this.#a();return}if(this.#r){this.#r.isPaused?this.#r.resume(this.#f):this.#r.isRunning||this.#u();return}this.#u()}}cancel(){this.#t||this.#a()}reset(r=!1){if(this.#r?.cancel(),this.#r=null,this.#n=0,this.#t=!1,this.#i?.aborted){this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null;return}if(r){if(!(this.#e>0)&&this.#e!==1/0){this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null;return}this.#u()}}};function j(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,void 0);return new Y(s,i,l)}function ht({signal:e}={}){let r=[],n=new Map,i=0,s=!1,l=!1,a=!1,u=!1,o=!1,f=1/0,d=0,w=null,p=null,h=null,y=[],m=!1,x=null,b=null,c,g=N(e,()=>c.cancel()),R=t=>{t&&t.controller&&(t.controller=null)},F=()=>{let t=r[i];t?.controller?.cancel?.(),t&&(t.controller=null)},E=()=>{u||a||(s=!1,l=!1,u=!0,F(),g.remove(),w?.())},I=()=>{a||(s=!1,l=!1,u=!1,a=!0,F(),g.remove())},T=(t,A)=>{if(I(),p){try{p(t,{step:A,index:i})}catch{}return}throw t},D=(t,A)=>{try{return t()}catch(v){T(v,A);return}},C=t=>{R(t),i+=1,queueMicrotask(M)};function M(){if(a||l||u)return;if(e?.aborted){I();return}if(h){let A=n.get(h);if(typeof A=="number")i=A;else{D(()=>{throw new Error(`Label "${h}" not found`)},r[i]);return}h=null}if(y.length>0){let A=y.shift();D(A,r[i])||(m=!0)}if(m){let A=r[i];if(!A||A.type==="label")m=!1;else return C(A)}let t=r[i];if(!t||i>=r.length){o&&++d<f?(i=0,M()):E();return}if(t.type==="label")return C(t);if(t.type==="after"){t.controller=Z(()=>D(t.fn,t),t.duration,{signal:e,onFinish:()=>C(t)});return}if(t.type==="every"){if(!(t.times>0)&&t.times!==1/0)return C(t);let A=0,v=j(()=>{if(!(l||a||u)){if(e?.aborted){I();return}if(t.whileCondition&&!D(t.whileCondition,t)||(D(()=>t.fn(A++),t),t.doWhileCondition&&!D(t.doWhileCondition,t))||A>=t.times)return v.cancel(),C(t)}},t.duration,{max:t.times,signal:e});t.controller=v}}return c={after(t,A){return r.push({type:"after",duration:t,fn:A,controller:null}),c},every(t,A,v=1/0){let q=typeof v=="number"?v:v?.max??1/0,W=q===1/0?1/0:Math.max(0,q|0);return r.push({type:"every",duration:t,fn:A,times:W,whileCondition:x,doWhileCondition:b,controller:null}),x=null,b=null,c},loop(t=!0){return o=!0,f=t===!0?1/0:t,c},onFinish(t){return w=t,c},onError(t){return p=t,c},start(){return F(),a=!1,u=!1,l=!1,s=!0,i=0,d=0,g.reset(),e?.aborted||g.add(),e?.aborted?(I(),c):(M(),c)},pause(){l||a||u||(l=!0,r[i]?.controller?.pause?.())},resume(){if(!(!l||a||u)){if(e?.aborted){I();return}l=!1,r[i]?.controller?.resume?.()}},cancel(){I()},reset(){return I(),r.length=0,n.clear(),i=0,d=0,w=null,p=null,h=null,y=[],m=!1,x=null,b=null,s=!1,l=!1,a=!1,u=!1,c},label(t){return n.set(t,r.length),r.push({type:"label",name:t,controller:null}),c},jumpTo(t){return h=t,c},if(t){return y.push(()=>typeof t=="function"?!!t():!!t),c},unless(t){return y.push(()=>typeof t=="function"?!t():!t),c},while(t){return x=()=>typeof t=="function"?!!t():!!t,c},doWhile(t){return b=()=>typeof t=="function"?!!t():!!t,c},get isRunning(){return s&&!l&&!a&&!u},get isPaused(){return l},get isCancelled(){return a},get isFinished(){return u}},c}function mt(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,void 0),a=l?.signal,u=l?.trailing??!0,o=Math.max(0,s),f=-1/0,d=0,w=null,p=null,h=N(a,()=>m()),y=()=>{if(!w)return;let c=w,g=p;w=null,p=null,h.remove(),i.apply(g,c)},m=()=>{d&&clearTimeout(d),d=0,w=null,p=null,h.remove()},x=c=>{h.add(),d=setTimeout(()=>{d=0,f=k(),y()},c)},b=function(...c){if(a?.aborted)return;let g=k(),R=g-f;if(w=c,p=this,R>=o){f=g,d&&(clearTimeout(d),d=0,h.remove()),y();return}if(u&&!d){let F=Math.max(0,o-R);x(F)}};return b.cancel=m,b.flush=()=>{d&&(clearTimeout(d),d=0,f=k(),y())},a?.aborted&&m(),b}function pt(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,0),a=l?.signal,u=Math.max(0,s),o=0,f=null,d=null,w=N(a,()=>h()),p=()=>{if(!f)return;let m=f,x=d;f=null,d=null,w.remove(),i.apply(x,m)},h=()=>{o&&clearTimeout(o),o=0,f=null,d=null,w.remove()},y=function(...m){a?.aborted||(f=m,d=this,o&&clearTimeout(o),w.add(),o=setTimeout(()=>{o=0,p()},u))};return y.cancel=h,y.flush=()=>{o&&(clearTimeout(o),o=0,p())},a?.aborted&&h(),y}var dt=2147483647;function S(e){if(e==null)return 0;let r=typeof e=="number"?e:P(e);return r>0?Math.min(r,dt):0}function tt(e=0,{signal:r}={}){return new Promise((n,i)=>{let s=S(e);if(r?.aborted){i($(r));return}let l=L(r,()=>{clearTimeout(a),i($(r))}),a=setTimeout(()=>{l(),n()},s)})}function yt(e,{interval:r="250ms",timeout:n,immediate:i=!1,signal:s}={}){return new Promise((l,a)=>{if(s?.aborted){a($(s));return}let u=S(r),o=n!=null?S(n):null,f=!1,d=!1,w=0,p=0,h=(x,b)=>{f||(f=!0,clearTimeout(w),clearTimeout(p),y(),x(b))},y=L(s,()=>h(a,$(s))),m=async()=>{let x;d=!0;try{x=await e()}catch(b){h(a,b);return}finally{d=!1}f||(x?h(l,x):w=setTimeout(m,u))};i?m():w=setTimeout(m,u),o!=null&&(p=setTimeout(()=>{if(!d){let b;try{b=e()}catch(c){h(a,c);return}if(b&&typeof b.then!="function"){h(l,b);return}}let x=new Error("waitFor timed out");x.name="TimeoutError",h(a,x)},o))})}async function bt(e,{attempts:r=3,delay:n="500ms",backoff:i=!1,factor:s=2,maxDelay:l,jitter:a=!1,delayFirst:u=!1,timeout:o,signal:f,isSuccess:d,shouldRetry:w,onAttempt:p,onRetry:h,sleep:y=tt,now:m=k,random:x=Math.random}={}){if(typeof e!="function")throw new TypeError("retry: fn must be a function");let b=r===1/0?1/0:Math.max(1,r|0),c=()=>{if(f?.aborted)throw $(f)};if(c(),typeof a=="number"&&!(a>=0&&a<=1))throw new RangeError(`retry: numeric jitter must be within [0, 1], got: ${a}`);let g=P(n),R=l!=null?P(l):1/0,F=o!=null?P(o):1/0,E=i===!0?"exponential":i||"fixed",I=m(),T=()=>m()-I,D=async M=>{await y(M,{signal:f}),c()};u&&await D(S(u===!0?g:u));let C=Math.min(g,R);for(let M=0;;M++){c(),p&&await p(M,T());let t;try{let q=await e(M);if(!d||await d(q,M))return q;t=new et(q,M+1)}catch(q){t=q}if(M+1>=b||w&&!await w(t,M))throw t;let A=E==="exponential"?Math.pow(s,M):E==="linear"?M+1:1,v=S(Math.round(wt({expDelay:g*A,baseDelay:g,maxDelayMs:R,jitter:a,random:x,prevSleep:C})));if(C=v,T()+v>F)throw t;h&&await h(t,M,v),await D(v)}}var et=class extends Error{constructor(r,n){super(`retry: unsuccessful result after ${n} attempt(s)`),this.name="RetryError",this.result=r,this.attempts=n}};function wt({expDelay:e,baseDelay:r,maxDelayMs:n,jitter:i,random:s,prevSleep:l}){let a=Math.min(e,n);if(!i)return a;if(typeof i=="number"){let o=z(-1,1,s)*i;return Math.min(n,Math.max(0,a*(1+o)))}let u=i===!0?"full":i;if(u==="full")return Math.min(n,z(0,a,s));if(u==="equal"){let o=a/2;return Math.min(n,o+z(0,o,s))}if(u==="decorrelated"){let o=z(r,l*3,s);return Math.min(n,o)}return a}function z(e,r,n){let i=n(),s=Number.isFinite(i)?Math.min(1,Math.max(0,i)):0;return e+(r-e)*s}function nt(e,r,n,i){let s=typeof n=="function"?n:void 0,l=s?i:n,{fn:a,delay:u,options:o}=_(e,r,l,void 0),{signal:f,onFinish:d}=s?{...o,onFinish:s}:o,w=Math.max(0,u),p=0,h=w,y=null,m=!1,x=!1,b=!1,c=()=>{p&&cancelAnimationFrame(p),p=0},g=()=>{},R=()=>{g(),g=()=>{}},F=()=>{c(),m=!1,x=!1,b=!0,y=null,h=0,R()},E=()=>{F(),a?.(),d?.()},I=()=>{b||F()},T=()=>{if(R(),f?.aborted){b=!0,h=0;return}g=L(f,I)};T();let D=A=>{if(!m||b)return;if(y==null&&(y=A),A-y>=h){E();return}p=requestAnimationFrame(D)},C=()=>{if(!m||b)return;c();let A=k();if(y!=null){let v=A-y;h=Math.max(0,h-v)}y=null,m=!1,x=!0},M=()=>{if(!(b||m||!x)&&!f?.aborted){if(!(h>0)){E();return}x=!1,m=!0,y=null,p=requestAnimationFrame(D)}},t=()=>{c(),y=null,h=w,m=!1,x=!1,b=!1,T()};return b?R():h>0?(m=!0,p=requestAnimationFrame(D)):E(),{pause:C,resume:M,cancel:I,reset:t,get isRunning(){return m},get isPaused(){return x},get isFinished(){return b}}}var G=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function it(e,r,n,i,s){let l=typeof e!="function",a,u,o;l?(G(n)?o=n:G(i)?o=i:G(s)?o=s:o={},typeof n=="number"&&(a=n),typeof i=="boolean"&&(u=i),u==null&&typeof n=="boolean"&&(u=n)):o=G(n)?n:{};let{fn:f,delay:d,options:w}=_(e,r,o,void 0),p=w?.signal,h=w?.max??1/0,y=w?.runImmediately??!1,m=a??h,x=u??y,b=Math.max(0,d),c=0,g=0,R=b,F=null,E=!1,I=!1,T=!1,D=()=>{c&&cancelAnimationFrame(c),c=0},C=()=>{},M=()=>{C(),C=()=>{}},t=()=>{D(),E=!1,I=!1,T=!0,F=null,R=0,M()},A=()=>{T||t()},v=()=>{if(M(),p?.aborted){T=!0,R=0;return}C=L(p,A)};v();let q=()=>g<m,W=()=>(f?.(g++),q()?!0:(t(),!1)),H=O=>{if(!E||T)return;if(p?.aborted){t();return}if(!q()){t();return}F==null&&(F=O);let K=O-F;F=O,R-=K;let rt=Math.max(0,b);if(rt===0){R=0,W(),c=requestAnimationFrame(H);return}for(;R<=0&&!T;){if(!W())return;R+=rt}c=requestAnimationFrame(H)},J=()=>{if(!T){if(p?.aborted){t();return}if(!q()){t();return}E=!0,I=!1,F=null,c=requestAnimationFrame(H)}},ut=()=>{if(!E||T)return;D();let O=k();if(F!=null){let K=O-F;R=Math.max(0,R-K)}F=null,E=!1,I=!0},ft=()=>{if(!(T||E||!I)&&!p?.aborted){if(!q()){t();return}J()}},ct=(O=!1)=>{if(D(),g=0,R=b,F=null,E=!1,I=!1,T=!1,v(),!T){if(!(m>0)&&m!==1/0){t();return}if(O){if(x&&q()&&(W(),T))return;J()}}};return T?M():!(m>0)&&m!==1/0?t():(x&&q()&&W(),T||(R=Math.max(0,b),J())),{pause:ut,resume:ft,cancel:A,reset:ct,get isRunning(){return E},get isPaused(){return I},get isFinished(){return T},get count(){return g}}}function ot(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,0),a=Math.max(0,s),u=l?.signal,o=0,f=null,d=null,w=0,p=()=>{o&&cancelAnimationFrame(o),o=0},h=N(u,()=>y()),y=()=>{p(),f=null,d=null,w=0,h.remove()},m=()=>{if(!f)return;let c=f,g=d;f=null,d=null,h.remove(),i.apply(g,c)},x=c=>{if(!o)return;if(!f){y();return}if(c-w>=a){p(),m();return}o=requestAnimationFrame(x)},b=function(...c){u?.aborted||(f=c,d=this,w=k(),h.add(),p(),o=requestAnimationFrame(x))};return b.cancel=y,b.flush=()=>{!o||!f||(p(),m())},u?.aborted&&y(),b}var st=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function lt(e,r=0,n){if(typeof e!="function")throw new TypeError(`Expected a function, got: ${typeof e}`);let i=typeof r=="number"?r:0,s=st(r)?r:st(n)?n:{},l=s.signal,a=s.trailing??!0,u=Math.max(0,i|0),o=!1,f=0,d=null,w=null,p=u,h=N(l,()=>m()),y=()=>{o=!1,f&&cancelAnimationFrame(f),f=0,p=u,d=null,w=null,h.remove()},m=()=>{y()},x=()=>{if(!d)return;let E=d,I=w;d=null,w=null,h.remove(),e.apply(I,E)},b=()=>{o=!1,f=0,p=u,x()},c=()=>{if(o){if(l?.aborted){m();return}if(p===0){b();return}p-=1,f=requestAnimationFrame(c)}},g=()=>{if(o){if(l?.aborted){m();return}b()}},R=u===0?()=>{o=!0,h.add(),f=requestAnimationFrame(g)}:()=>{o=!0,p=u,h.add(),f=requestAnimationFrame(c)},F=function(...E){l?.aborted||((!o||a)&&(d=E,w=this),!o&&R())};return F.cancel=m,F.flush=()=>{if(o){if(l?.aborted){m();return}o=!1,f&&cancelAnimationFrame(f),f=0,p=u,x()}},l?.aborted&&m(),F}function at(e,{timeout:r,signal:n,immediate:i=!1}={}){return new Promise((s,l)=>{if(typeof e!="function"){l(new TypeError(`waitForRaf: condition must be a function, got: ${typeof e}`));return}if(n?.aborted){l($(n));return}let a=r!=null?Math.max(0,P(r)):null,u=0,o=null,f=()=>{u&&cancelAnimationFrame(u),u=0,w()},w=L(n,()=>{f(),l($(n))}),p=()=>{try{return!!e()}catch(y){return f(),l(y),null}};if(i){let y=p();if(y===null)return;if(y){f(),s();return}if(a===0){f(),l(new Error("waitForRaf timed out"));return}}let h=y=>{o==null&&(o=y);let m=p();if(m!==null){if(m){f(),s();return}if(a!=null&&y-o>=a){f(),l(new Error("waitForRaf timed out"));return}u=requestAnimationFrame(h)}};u=requestAnimationFrame(h)})}function xt(){if(typeof requestAnimationFrame!="function")throw new Error("requestAnimationFrame is not available in this environment. Use the non-RAF timers (after/every/waitFor) in Node, or provide a RAF polyfill.")}var U=e=>(...r)=>(xt(),e(...r)),At=U(nt),gt=U(it),Ft=U(ot),Rt=U(lt),vt=U(at);export{Z as after,At as afterRaf,pt as debounce,Ft as debounceRaf,j as every,gt as everyRaf,ht as flow,P as parseDuration,bt as retry,tt as sleep,mt as throttle,Rt as throttleRaf,yt as waitFor,vt as waitForRaf};
|
|
2
|
+
function P(e){if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`Expected a finite number of ms, got: ${e}`);return e}if(typeof e!="string")throw new TypeError(`Expected a duration string or number, got ${typeof e}`);let n=e.toLowerCase().trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);if(!n)throw new Error(`Invalid duration format: "${e}". Expected formats like "500ms", "2s", "1.5m", or "1h".`);let i=Number(n[1]);if(!Number.isFinite(i))throw new TypeError(`Invalid duration value: "${n[1]}"`);switch(n[2]){case"ms":return i;case"s":return i*1e3;case"m":return i*6e4;case"h":return i*36e5}}var k;typeof performance<"u"&&typeof performance.now=="function"?k=()=>performance.now():k=()=>Date.now();var U=class{#l;#s=null;#e;#n=null;#r;#t=!1;#i=!1;#o=!1;constructor(r){this.#l=P(r),this.#e=this.#l}get isRunning(){return this.#t}get isPaused(){return this.#i}get isFinished(){return this.#o}pause(){if(!this.#t)return;clearTimeout(this.#n),this.#n=null;let r=k()-this.#s;this.#e=Math.max(0,this.#e-r),this.#t=!1,this.#i=!0}resume(r,n=null){if(this.#o||this.#t)return;let i=n??this.#e;if(!Number.isFinite(i))return;let s=Math.max(0,i);r??=this.#r,this.#r=r,this.#e=s,this.#s=k(),this.#t=!0,this.#i=!1,this.#n=setTimeout(()=>{this.#n=null,this.#t=!1,this.#i=!1,this.#o=!0,this.#e=0,r?.()},s)}cancel(){this.#n&&clearTimeout(this.#n),this.#n=null,this.#t=!1,this.#i=!1,this.#o=!0,this.#e=0}reset(){this.#n&&clearTimeout(this.#n),this.#n=null,this.#s=null,this.#e=this.#l,this.#t=!1,this.#i=!1,this.#o=!1}};var Q;typeof DOMException<"u"?Q=(e="Aborted")=>new DOMException(e,"AbortError"):Q=(e="Aborted")=>{let r=new Error(e);return r.name="AbortError",r};function L(e,r){return e?e.aborted?(r(),()=>{}):(e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)):()=>{}}function O(e,r){let n=null;return{add(){n||(n=L(e,r))},remove(){n&&(n(),n=null)},reset(){n&&n(),n=null}}}function $(e){return e?.reason??Q()}var Y=class extends U{#l=null;#s=null;#e=()=>{};constructor(r,n,{onFinish:i,signal:s}={}){super(r),this.#l=s??null,this.#s=()=>this.cancel(),this.#n(),!this.isFinished&&this.resume(()=>{this.#r(),n?.(),i?.()})}#n(){if(!(!this.#l||!this.#s)){if(this.#l.aborted){super.cancel(),this.#r();return}this.#e=L(this.#l,this.#s)}}#r(){this.#e(),this.#e=()=>{},this.#s=null}cancel(){this.isFinished||(this.#r(),super.cancel())}reset(){this.#e(),this.#e=()=>{},this.#s=()=>this.cancel(),super.reset(),this.#n()}};var N=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function _(e,r,n,i=0){let s,l,a;if(typeof e=="function"?(s=e,N(r)?(l=i,a=r):(l=r,a=N(n)?n:{})):(l=e,s=r,a=N(n)?n:{}),typeof s!="function")throw new TypeError(`Expected a function as one argument, got: ${typeof s}`);let u=l??i;if(u==null)throw new TypeError("Expected a duration (string/number) for delay");let o=P(u);return{fn:s,delay:o,options:a}}function V(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,void 0);return new Y(s,i,l)}var z=class{#l;#s;#e;#n=0;#r=!1;#t=null;#i=null;#o=()=>{};constructor(r,n,{max:i=1/0,runImmediately:s=!1,signal:l}={}){if(this.#l=P(r),this.#s=n,this.#e=i,this.#i=l??null,!(this.#e>0)&&this.#e!==1/0){this.#r=!0,this.#o();return}if(this.#i?.aborted){this.#r=!0,this.#o();return}this.#o=L(this.#i,()=>this.cancel()),s?this.#f():this.#u()}get count(){return this.#n}get isRunning(){return!this.#r&&!!this.#t&&this.#t.isRunning}get isPaused(){return!this.#r&&!!this.#t&&this.#t.isPaused}get isFinished(){return this.#r}#a=()=>{this.#t?.cancel(),this.#t=null,this.#r=!0,this.#o(),this.#o=()=>{},this.#i=null};#f=()=>{if(!this.#r){if(this.#i?.aborted){this.#a();return}if(this.#n>=this.#e){this.#a();return}if(this.#s?.(this.#n++),this.#n>=this.#e){this.#a();return}this.#u()}};#u(){if(!this.#r){if(this.#i?.aborted){this.#a();return}this.#t=new U(this.#l),this.#t.resume(this.#f)}}pause(){this.#r||this.#t?.pause()}resume(){if(!this.#r){if(this.#i?.aborted){this.#a();return}if(this.#n>=this.#e){this.#a();return}if(this.#t){this.#t.isPaused?this.#t.resume(this.#f):this.#t.isRunning||this.#u();return}this.#u()}}cancel(){this.#r||this.#a()}reset(r=!1){if(this.#t?.cancel(),this.#t=null,this.#n=0,this.#r=!1,this.#i?.aborted){this.#r=!0,this.#o(),this.#o=()=>{},this.#i=null;return}if(r){if(!(this.#e>0)&&this.#e!==1/0){this.#r=!0,this.#o(),this.#o=()=>{},this.#i=null;return}this.#u()}}};function Z(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,void 0);return new z(s,i,l)}function ft({signal:e}={}){let r=[],n=new Map,i=0,s=!1,l=!1,a=!1,u=!1,o=!1,f=1/0,d=0,w=null,p=null,c=null,y=[],m=!1,x=null,b=null,h,A=O(e,()=>h.cancel()),v=t=>{t&&t.controller&&(t.controller=null)},F=()=>{let t=r[i];t?.controller?.cancel?.(),t&&(t.controller=null)},M=()=>{u||a||(s=!1,l=!1,u=!0,F(),A.remove(),w?.())},I=()=>{a||(s=!1,l=!1,u=!1,a=!0,F(),A.remove())},R=(t,g)=>{if(I(),p){try{p(t,{step:g,index:i})}catch{}return}throw t},D=(t,g)=>{try{return t()}catch(T){R(T,g);return}},C=t=>{v(t),i+=1,queueMicrotask(E)};function E(){if(a||l||u)return;if(e?.aborted){I();return}if(c){let g=n.get(c);if(typeof g=="number")i=g;else{D(()=>{throw new Error(`Label "${c}" not found`)},r[i]);return}c=null}if(y.length>0){let g=y.shift();D(g,r[i])||(m=!0)}if(m){let g=r[i];if(!g||g.type==="label")m=!1;else return C(g)}let t=r[i];if(!t||i>=r.length){o&&++d<f?(i=0,E()):M();return}if(t.type==="label")return C(t);if(t.type==="after"){t.controller=V(()=>D(t.fn,t),t.duration,{signal:e,onFinish:()=>C(t)});return}if(t.type==="every"){if(!(t.times>0)&&t.times!==1/0)return C(t);let g=0,T=Z(()=>{if(!(l||a||u)){if(e?.aborted){I();return}if(t.whileCondition&&!D(t.whileCondition,t)||(D(()=>t.fn(g++),t),t.doWhileCondition&&!D(t.doWhileCondition,t))||g>=t.times)return T.cancel(),C(t)}},t.duration,{max:t.times,signal:e});t.controller=T}}return h={after(t,g){return r.push({type:"after",duration:t,fn:g,controller:null}),h},every(t,g,T=1/0){let q=typeof T=="number"?T:T?.max??1/0,B=q===1/0?1/0:Math.max(0,q|0);return r.push({type:"every",duration:t,fn:g,times:B,whileCondition:x,doWhileCondition:b,controller:null}),x=null,b=null,h},loop(t=!0){return o=!0,f=t===!0?1/0:t,h},onFinish(t){return w=t,h},onError(t){return p=t,h},start(){return F(),a=!1,u=!1,l=!1,s=!0,i=0,d=0,A.reset(),e?.aborted||A.add(),e?.aborted?(I(),h):(E(),h)},pause(){l||a||u||(l=!0,r[i]?.controller?.pause?.())},resume(){if(!(!l||a||u)){if(e?.aborted){I();return}l=!1,r[i]?.controller?.resume?.()}},cancel(){I()},reset(){return I(),r.length=0,n.clear(),i=0,d=0,w=null,p=null,c=null,y=[],m=!1,x=null,b=null,s=!1,l=!1,a=!1,u=!1,h},label(t){return n.set(t,r.length),r.push({type:"label",name:t,controller:null}),h},jumpTo(t){return c=t,h},if(t){return y.push(()=>typeof t=="function"?!!t():!!t),h},unless(t){return y.push(()=>typeof t=="function"?!t():!t),h},while(t){return x=()=>typeof t=="function"?!!t():!!t,h},doWhile(t){return b=()=>typeof t=="function"?!!t():!!t,h},get isRunning(){return s&&!l&&!a&&!u},get isPaused(){return l},get isCancelled(){return a},get isFinished(){return u}},h}function ct(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,void 0),a=l?.signal,u=l?.trailing??!0,o=Math.max(0,s),f=-1/0,d=0,w=null,p=null,c=O(a,()=>m()),y=()=>{if(!w)return;let h=w,A=p;w=null,p=null,c.remove(),i.apply(A,h)},m=()=>{d&&clearTimeout(d),d=0,w=null,p=null,c.remove()},x=h=>{c.add(),d=setTimeout(()=>{d=0,f=k(),y()},h)},b=function(...h){if(a?.aborted)return;let A=k(),v=A-f;if(w=h,p=this,v>=o){f=A,d&&(clearTimeout(d),d=0,c.remove()),y();return}if(u&&!d){let F=Math.max(0,o-v);x(F)}};return b.cancel=m,b.flush=()=>{d&&(clearTimeout(d),d=0,f=k(),y())},a?.aborted&&m(),b}function mt(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,0),a=l?.signal,u=Math.max(0,s),o=0,f=null,d=null,w=O(a,()=>c()),p=()=>{if(!f)return;let m=f,x=d;f=null,d=null,w.remove(),i.apply(x,m)},c=()=>{o&&clearTimeout(o),o=0,f=null,d=null,w.remove()},y=function(...m){a?.aborted||(f=m,d=this,o&&clearTimeout(o),w.add(),o=setTimeout(()=>{o=0,p()},u))};return y.cancel=c,y.flush=()=>{o&&(clearTimeout(o),o=0,p())},a?.aborted&&c(),y}var ht=2147483647;function W(e){if(e==null)return 0;let r=typeof e=="number"?e:P(e);return r>0?Math.min(r,ht):0}function j(e=0,{signal:r}={}){return new Promise((n,i)=>{let s=W(e);if(r?.aborted){i($(r));return}let l=L(r,()=>{clearTimeout(a),i($(r))}),a=setTimeout(()=>{l(),n()},s)})}function pt(e,{interval:r="250ms",timeout:n,immediate:i=!1,signal:s}={}){return new Promise((l,a)=>{if(s?.aborted){a($(s));return}let u=W(r),o=n!=null?W(n):null,f=!1,d=!1,w=0,p=0,c=(x,b)=>{f||(f=!0,clearTimeout(w),clearTimeout(p),y(),x(b))},y=L(s,()=>c(a,$(s))),m=async()=>{let x;d=!0;try{x=await e()}catch(b){c(a,b);return}finally{d=!1}f||(x?c(l,x):w=setTimeout(m,u))};i?m():w=setTimeout(m,u),!f&&o!=null&&(p=setTimeout(()=>{if(!d)try{let b=e();if(b){if(typeof b.then!="function"){c(l,b);return}Promise.resolve(b).catch(()=>{})}}catch(b){c(a,b);return}let x=new Error("waitFor timed out");x.name="TimeoutError",c(a,x)},o))})}async function dt(e,{attempts:r=3,delay:n="500ms",backoff:i=!1,factor:s=2,maxDelay:l,jitter:a=!1,delayFirst:u=!1,timeout:o,signal:f,isSuccess:d,shouldRetry:w,onAttempt:p,onRetry:c,sleep:y=j,now:m=k,random:x=Math.random}={}){if(typeof e!="function")throw new TypeError("retry: fn must be a function");let b=r===1/0?1/0:Math.max(1,r|0),h=()=>{if(f?.aborted)throw $(f)};if(h(),typeof a=="number"&&!(a>=0&&a<=1))throw new RangeError(`retry: numeric jitter must be within [0, 1], got: ${a}`);let A=P(n),v=l!=null?P(l):1/0,F=o!=null?P(o):1/0,M=i===!0?"exponential":i||"fixed",I=m(),R=()=>m()-I,D=async E=>{await y(E,{signal:f}),h()};u&&await D(W(u===!0?A:u));let C=Math.min(A,v);for(let E=0;;E++){h(),p&&await p(E,R());let t;try{let q=await e(E);if(!d||await d(q,E))return q;t=new tt(q,E+1)}catch(q){t=q}if(E+1>=b||w&&!await w(t,E))throw t;let g=M==="exponential"?Math.pow(s,E):M==="linear"?E+1:1,T=W(Math.round(yt({expDelay:A*g,baseDelay:A,maxDelayMs:v,jitter:a,random:x,prevSleep:C})));if(C=T,R()+T>F)throw t;c&&await c(t,E,T),await D(T)}}var tt=class extends Error{constructor(r,n){super(`retry: unsuccessful result after ${n} attempt(s)`),this.name="RetryError",this.result=r,this.attempts=n}};function yt({expDelay:e,baseDelay:r,maxDelayMs:n,jitter:i,random:s,prevSleep:l}){let a=Math.min(e,n);if(!i)return a;if(typeof i=="number"){let o=G(-1,1,s)*i;return Math.min(n,Math.max(0,a*(1+o)))}let u=i===!0?"full":i;if(u==="full")return Math.min(n,G(0,a,s));if(u==="equal"){let o=a/2;return Math.min(n,o+G(0,o,s))}if(u==="decorrelated"){let o=G(r,l*3,s);return Math.min(n,o)}return a}function G(e,r,n){let i=n(),s=Number.isFinite(i)?Math.min(1,Math.max(0,i)):0;return e+(r-e)*s}function rt(e,r,n,i){let s=typeof n=="function"?n:void 0,l=s?i:n,{fn:a,delay:u,options:o}=_(e,r,l,void 0),{signal:f,onFinish:d}=s?{...o,onFinish:s}:o,w=Math.max(0,u),p=0,c=w,y=null,m=!1,x=!1,b=!1,h=()=>{p&&cancelAnimationFrame(p),p=0},A=()=>{},v=()=>{A(),A=()=>{}},F=()=>{h(),m=!1,x=!1,b=!0,y=null,c=0,v()},M=()=>{F(),a?.(),d?.()},I=()=>{b||F()},R=()=>{if(v(),f?.aborted){b=!0,c=0;return}A=L(f,I)};R();let D=g=>{if(!m||b)return;if(y==null&&(y=g),g-y>=c){M();return}p=requestAnimationFrame(D)},C=()=>{if(!m||b)return;h();let g=k();if(y!=null){let T=g-y;c=Math.max(0,c-T)}y=null,m=!1,x=!0},E=()=>{if(!(b||m||!x)&&!f?.aborted){if(!(c>0)){M();return}x=!1,m=!0,y=null,p=requestAnimationFrame(D)}},t=()=>{h(),y=null,c=w,m=!1,x=!1,b=!1,R()};return b?v():c>0?(m=!0,p=requestAnimationFrame(D)):M(),{pause:C,resume:E,cancel:I,reset:t,get isRunning(){return m},get isPaused(){return x},get isFinished(){return b}}}function nt(e,r,n,i,s){let l=typeof e!="function",a,u,o;l?(N(n)?o=n:N(i)?o=i:N(s)?o=s:o={},typeof n=="number"&&(a=n),typeof i=="boolean"&&(u=i),u==null&&typeof n=="boolean"&&(u=n)):o=N(n)?n:{};let{fn:f,delay:d,options:w}=_(e,r,o,void 0),p=w?.signal,c=w?.max??1/0,y=w?.runImmediately??!1,m=a??c,x=u??y,b=Math.max(0,d),h=0,A=0,v=b,F=null,M=!1,I=!1,R=!1,D=()=>{h&&cancelAnimationFrame(h),h=0},C=()=>{},E=()=>{C(),C=()=>{}},t=()=>{D(),M=!1,I=!1,R=!0,F=null,v=0,E()},g=()=>{R||t()},T=()=>{if(E(),p?.aborted){R=!0,v=0;return}C=L(p,g)};T();let q=()=>A<m,B=()=>(f?.(A++),q()?M&&!R:(t(),!1)),H=S=>{if(!M||R)return;if(p?.aborted){t();return}if(!q()){t();return}F==null&&(F=S);let K=S-F;F=S,v-=K;let et=Math.max(0,b);if(et===0){v=0,B()&&(h=requestAnimationFrame(H));return}for(;v<=0&&!R;){if(!B())return;v+=et}h=requestAnimationFrame(H)},J=()=>{if(!R){if(p?.aborted){t();return}if(!q()){t();return}M=!0,I=!1,F=null,h=requestAnimationFrame(H)}},lt=()=>{if(!M||R)return;D();let S=k();if(F!=null){let K=S-F;v=Math.max(0,v-K)}F=null,M=!1,I=!0},at=()=>{if(!(R||M||!I)&&!p?.aborted){if(!q()){t();return}J()}},ut=(S=!1)=>{if(D(),A=0,v=b,F=null,M=!1,I=!1,R=!1,T(),!R){if(!(m>0)&&m!==1/0){t();return}if(S){if(x&&q()&&(B(),R))return;J()}}};return R?E():!(m>0)&&m!==1/0?t():(x&&q()&&B(),R||(v=Math.max(0,b),J())),{pause:lt,resume:at,cancel:g,reset:ut,get isRunning(){return M},get isPaused(){return I},get isFinished(){return R},get count(){return A}}}function it(e,r,n){let{fn:i,delay:s,options:l}=_(e,r,n,0),a=Math.max(0,s),u=l?.signal,o=0,f=null,d=null,w=0,p=()=>{o&&cancelAnimationFrame(o),o=0},c=O(u,()=>y()),y=()=>{p(),f=null,d=null,w=0,c.remove()},m=()=>{if(!f)return;let h=f,A=d;f=null,d=null,c.remove(),i.apply(A,h)},x=h=>{if(!o)return;if(!f){y();return}if(h-w>=a){p(),m();return}o=requestAnimationFrame(x)},b=function(...h){u?.aborted||(f=h,d=this,w=k(),c.add(),p(),o=requestAnimationFrame(x))};return b.cancel=y,b.flush=()=>{!o||!f||(p(),m())},u?.aborted&&y(),b}function ot(e,r=0,n){if(typeof e!="function")throw new TypeError(`Expected a function, got: ${typeof e}`);let i=typeof r=="number"?r:0,s=N(r)?r:N(n)?n:{},l=s.signal,a=s.trailing??!0,u=Math.max(0,i|0),o=!1,f=0,d=null,w=null,p=u,c=O(l,()=>m()),y=()=>{o=!1,f&&cancelAnimationFrame(f),f=0,p=u,d=null,w=null,c.remove()},m=()=>{y()},x=()=>{if(!d)return;let M=d,I=w;d=null,w=null,c.remove(),e.apply(I,M)},b=()=>{o=!1,f=0,p=u,x()},h=()=>{if(o){if(l?.aborted){m();return}if(p===0){b();return}p-=1,f=requestAnimationFrame(h)}},A=()=>{if(o){if(l?.aborted){m();return}b()}},v=u===0?()=>{o=!0,c.add(),f=requestAnimationFrame(A)}:()=>{o=!0,p=u,c.add(),f=requestAnimationFrame(h)},F=function(...M){l?.aborted||((!o||a)&&(d=M,w=this),!o&&v())};return F.cancel=m,F.flush=()=>{if(o){if(l?.aborted){m();return}o=!1,f&&cancelAnimationFrame(f),f=0,p=u,x()}},l?.aborted&&m(),F}function st(e,{timeout:r,signal:n,immediate:i=!1}={}){return new Promise((s,l)=>{if(typeof e!="function"){l(new TypeError(`waitForRaf: condition must be a function, got: ${typeof e}`));return}if(n?.aborted){l($(n));return}let a=r!=null?Math.max(0,P(r)):null,u=0,o=null,f=()=>{u&&cancelAnimationFrame(u),u=0,w()},w=L(n,()=>{f(),l($(n))}),p=()=>{try{return!!e()}catch(y){return f(),l(y),null}};if(i){let y=p();if(y===null)return;if(y){f(),s();return}if(a===0){f(),l(new Error("waitForRaf timed out"));return}}let c=y=>{o==null&&(o=y);let m=p();if(m!==null){if(m){f(),s();return}if(a!=null&&y-o>=a){f(),l(new Error("waitForRaf timed out"));return}u=requestAnimationFrame(c)}};u=requestAnimationFrame(c)})}function bt(){if(typeof requestAnimationFrame!="function")throw new Error("requestAnimationFrame is not available in this environment. Use the non-RAF timers (after/every/waitFor) in Node, or provide a RAF polyfill.")}var X=e=>(...r)=>(bt(),e(...r)),wt=X(rt),xt=X(nt),gt=X(it),At=X(ot),Ft=X(st);export{V as after,wt as afterRaf,mt as debounce,gt as debounceRaf,Z as every,xt as everyRaf,ft as flow,P as parseDuration,dt as retry,j as sleep,ct as throttle,At as throttleRaf,pt as waitFor,Ft as waitForRaf};
|
package/package.json
CHANGED
|
@@ -1,75 +1,80 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "timeout-flow",
|
|
3
|
-
"version": "0.0
|
|
4
|
-
"type": "module",
|
|
5
|
-
"description": "Fluent, composable, pauseable JavaScript timers and time control flows, plus RAF utilities for frame-based logic.",
|
|
6
|
-
"keywords": [
|
|
7
|
-
"timeout",
|
|
8
|
-
"interval",
|
|
9
|
-
"flow",
|
|
10
|
-
"raf",
|
|
11
|
-
"animationframe",
|
|
12
|
-
"debounce",
|
|
13
|
-
"retry",
|
|
14
|
-
"javascript",
|
|
15
|
-
"timers",
|
|
16
|
-
"throttle",
|
|
17
|
-
"asynchronous",
|
|
18
|
-
"control-flow",
|
|
19
|
-
"utilities"
|
|
20
|
-
],
|
|
21
|
-
"author": "WATT3D <WATT3D@protonmail.com>",
|
|
22
|
-
"license": "SEE LICENSE IN LICENSE",
|
|
23
|
-
"
|
|
24
|
-
|
|
25
|
-
"url": "
|
|
26
|
-
},
|
|
27
|
-
"
|
|
28
|
-
|
|
29
|
-
"
|
|
30
|
-
},
|
|
31
|
-
"
|
|
32
|
-
"
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
"./
|
|
46
|
-
"./
|
|
47
|
-
"./
|
|
48
|
-
"./
|
|
49
|
-
"./
|
|
50
|
-
"./
|
|
51
|
-
"./
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
"
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
"
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
"
|
|
67
|
-
"
|
|
68
|
-
"
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
"
|
|
72
|
-
"
|
|
73
|
-
"
|
|
74
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "timeout-flow",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Fluent, composable, pauseable JavaScript timers and time control flows, plus RAF utilities for frame-based logic.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"timeout",
|
|
8
|
+
"interval",
|
|
9
|
+
"flow",
|
|
10
|
+
"raf",
|
|
11
|
+
"animationframe",
|
|
12
|
+
"debounce",
|
|
13
|
+
"retry",
|
|
14
|
+
"javascript",
|
|
15
|
+
"timers",
|
|
16
|
+
"throttle",
|
|
17
|
+
"asynchronous",
|
|
18
|
+
"control-flow",
|
|
19
|
+
"utilities"
|
|
20
|
+
],
|
|
21
|
+
"author": "WATT3D <WATT3D@protonmail.com>",
|
|
22
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
23
|
+
"homepage": "https://github.com/iWhatty/timeout-flow#readme",
|
|
24
|
+
"bugs": {
|
|
25
|
+
"url": "https://github.com/iWhatty/timeout-flow/issues"
|
|
26
|
+
},
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://github.com/iWhatty/timeout-flow.git"
|
|
30
|
+
},
|
|
31
|
+
"sideEffects": false,
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=18"
|
|
34
|
+
},
|
|
35
|
+
"main": "./dist/timeout-flow.min.js",
|
|
36
|
+
"module": "./src/index.js",
|
|
37
|
+
"browser": "./dist/timeout-flow.min.js",
|
|
38
|
+
"exports": {
|
|
39
|
+
".": {
|
|
40
|
+
"types": "./types/index.d.ts",
|
|
41
|
+
"import": "./src/index.js",
|
|
42
|
+
"require": "./dist/timeout-flow.min.js",
|
|
43
|
+
"default": "./src/index.js"
|
|
44
|
+
},
|
|
45
|
+
"./after": "./src/after.js",
|
|
46
|
+
"./every": "./src/every.js",
|
|
47
|
+
"./debounce": "./src/debounce.js",
|
|
48
|
+
"./throttle": "./src/throttle.js",
|
|
49
|
+
"./sleep": "./src/sleep.js",
|
|
50
|
+
"./retry": "./src/retry.js",
|
|
51
|
+
"./wait-for": "./src/waitFor.js",
|
|
52
|
+
"./flow": "./src/TimeoutFlow.js",
|
|
53
|
+
"./parse-duration": "./src/parseDuration.js",
|
|
54
|
+
"./raf": "./src/raf/index.js",
|
|
55
|
+
"./min": "./dist/timeout-flow.min.js"
|
|
56
|
+
},
|
|
57
|
+
"files": [
|
|
58
|
+
"dist",
|
|
59
|
+
"src",
|
|
60
|
+
"types",
|
|
61
|
+
"robots.txt",
|
|
62
|
+
"ADDITIONAL_TERMS.md"
|
|
63
|
+
],
|
|
64
|
+
"types": "./types/index.d.ts",
|
|
65
|
+
"scripts": {
|
|
66
|
+
"dev": "serve testing",
|
|
67
|
+
"test": "node --test testing/*.test.mjs && npm run build && npm run test:node",
|
|
68
|
+
"test:unit": "node --test testing/*.test.mjs",
|
|
69
|
+
"test:node": "node testing/node-harness.mjs",
|
|
70
|
+
"build": "node build.js",
|
|
71
|
+
"types": "tsc",
|
|
72
|
+
"prepub": "npm run build && npm run types",
|
|
73
|
+
"prepublishOnly": "npm test && npm run types"
|
|
74
|
+
},
|
|
75
|
+
"devDependencies": {
|
|
76
|
+
"esbuild": "^0.25.3",
|
|
77
|
+
"serve": "^14.2.4",
|
|
78
|
+
"typescript": "^5.8.3"
|
|
79
|
+
}
|
|
75
80
|
}
|
package/src/TimerBase.js
CHANGED
|
@@ -12,6 +12,7 @@ export class TimerBase {
|
|
|
12
12
|
#startTime = null; // performance.now()
|
|
13
13
|
#remaining;
|
|
14
14
|
#timer = null;
|
|
15
|
+
#callback;
|
|
15
16
|
|
|
16
17
|
#running = false;
|
|
17
18
|
#paused = false;
|
|
@@ -68,7 +69,7 @@ export class TimerBase {
|
|
|
68
69
|
|
|
69
70
|
/**
|
|
70
71
|
* Resume the timer using the remaining time (or an override delay).
|
|
71
|
-
* @param {Function} callback - Called when time completes
|
|
72
|
+
* @param {Function} [callback] - Called when time completes; defaults to the previous callback
|
|
72
73
|
* @param {number|null} [overrideDelay=null] - Optional custom delay in ms
|
|
73
74
|
*/
|
|
74
75
|
resume(callback, overrideDelay = null) {
|
|
@@ -84,6 +85,9 @@ export class TimerBase {
|
|
|
84
85
|
// instead of silently never firing.
|
|
85
86
|
const delay = Math.max(0, rawDelay);
|
|
86
87
|
|
|
88
|
+
callback ??= this.#callback;
|
|
89
|
+
this.#callback = callback;
|
|
90
|
+
|
|
87
91
|
// Important: remaining must reflect what we actually scheduled,
|
|
88
92
|
// otherwise pause() math will be wrong when overrideDelay is used.
|
|
89
93
|
this.#remaining = delay;
|
package/src/parseDuration.js
CHANGED
|
@@ -40,8 +40,5 @@ export function parseDuration(input) {
|
|
|
40
40
|
case 's': return value * 1000;
|
|
41
41
|
case 'm': return value * 60_000;
|
|
42
42
|
case 'h': return value * 3_600_000;
|
|
43
|
-
default:
|
|
44
|
-
// Should be unreachable due to regex, but keeps function total.
|
|
45
|
-
throw new Error(`Unsupported duration unit: "${unit}"`);
|
|
46
43
|
}
|
|
47
44
|
}
|
package/src/raf/everyRaf.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
// ./raf/everyRaf.js
|
|
2
|
-
import { resolveDelayFnOptions } from '../resolveDelayAndFn.js';
|
|
2
|
+
import { resolveDelayFnOptions, isPlainOptions } from '../resolveDelayAndFn.js';
|
|
3
3
|
import { attachAbort } from '../abort.js';
|
|
4
4
|
import { now } from '../now.js';
|
|
5
5
|
|
|
6
|
-
const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
|
|
7
6
|
|
|
8
7
|
/**
|
|
9
8
|
* Repeats a function every N milliseconds using requestAnimationFrame.
|
|
@@ -153,7 +152,7 @@ export function everyRaf(a, b, c, d, e) {
|
|
|
153
152
|
finish();
|
|
154
153
|
return false;
|
|
155
154
|
}
|
|
156
|
-
return
|
|
155
|
+
return running && !finished;
|
|
157
156
|
};
|
|
158
157
|
|
|
159
158
|
const tick = (ts) => {
|
|
@@ -184,8 +183,7 @@ export function everyRaf(a, b, c, d, e) {
|
|
|
184
183
|
if (step === 0) {
|
|
185
184
|
// If interval is 0ms, treat as "once per frame"
|
|
186
185
|
remainingToNext = 0;
|
|
187
|
-
fire();
|
|
188
|
-
rafId = requestAnimationFrame(tick);
|
|
186
|
+
if (fire()) rafId = requestAnimationFrame(tick);
|
|
189
187
|
return;
|
|
190
188
|
}
|
|
191
189
|
|
package/src/raf/throttleRaf.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// ./raf/throttleRaf.js
|
|
2
2
|
import { pendingAbort } from '../abort.js';
|
|
3
|
+
import { isPlainOptions } from '../resolveDelayAndFn.js';
|
|
3
4
|
|
|
4
|
-
const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Throttles a function using `requestAnimationFrame`, with optional frame skipping.
|
package/src/resolveDelayAndFn.js
CHANGED
|
@@ -1,31 +1,7 @@
|
|
|
1
1
|
// ./src/resolveDelayAndFn.js
|
|
2
2
|
import { parseDuration } from './parseDuration.js';
|
|
3
3
|
|
|
4
|
-
const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Resolves flexible (fn, delay) or (delay, fn) inputs.
|
|
8
|
-
*
|
|
9
|
-
* NOTE: This helper is intentionally strict:
|
|
10
|
-
* - It requires an explicit delay (2-arg form).
|
|
11
|
-
* - Use `resolveDelayFnOptions()` for overloads that allow `(fn, options)` or default delays.
|
|
12
|
-
*
|
|
13
|
-
* @param {Function|string|number} a - function or duration
|
|
14
|
-
* @param {Function|string|number} b - function or duration
|
|
15
|
-
* @returns {{ fn: Function, delay: number }}
|
|
16
|
-
*/
|
|
17
|
-
export function resolveDelayAndFn(a, b) {
|
|
18
|
-
// Keep legacy semantics but delegate parsing/validation.
|
|
19
|
-
const { fn, delay } = resolveDelayFnOptions(a, b, undefined, undefined);
|
|
20
|
-
|
|
21
|
-
// If someone called resolveDelayAndFn(fn) by mistake, throw a clearer error.
|
|
22
|
-
// (parseDuration(undefined) would be a confusing failure mode.)
|
|
23
|
-
if (b == null && typeof a === 'function') {
|
|
24
|
-
throw new TypeError('Expected a delay as the second argument (e.g. debounce(fn, "250ms"))');
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
return { fn, delay };
|
|
28
|
-
}
|
|
4
|
+
export const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
|
|
29
5
|
|
|
30
6
|
/**
|
|
31
7
|
* Resolves flexible overloads and returns `{ fn, delay, options }`.
|
package/src/waitFor.js
CHANGED
|
@@ -71,21 +71,24 @@ export function waitFor(condition, { interval = '250ms', timeout, immediate = fa
|
|
|
71
71
|
if (immediate) check();
|
|
72
72
|
else poller = setTimeout(check, intervalMs);
|
|
73
73
|
|
|
74
|
-
if (timeoutMs != null) {
|
|
74
|
+
if (!done && timeoutMs != null) {
|
|
75
75
|
deadline = setTimeout(() => {
|
|
76
76
|
if (!pending) {
|
|
77
|
-
// Final check at the deadline (sync results only).
|
|
78
|
-
let value;
|
|
79
77
|
try {
|
|
80
|
-
|
|
78
|
+
// A synchronous truthy result can still succeed at the deadline.
|
|
79
|
+
const value = condition();
|
|
80
|
+
if (value) {
|
|
81
|
+
if (typeof value.then !== 'function') {
|
|
82
|
+
finish(resolve, value);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
// The timeout still wins. Observe any rejection from the final probe.
|
|
86
|
+
Promise.resolve(value).catch(() => {});
|
|
87
|
+
}
|
|
81
88
|
} catch (err) {
|
|
82
89
|
finish(reject, err);
|
|
83
90
|
return;
|
|
84
91
|
}
|
|
85
|
-
if (value && typeof value.then !== 'function') {
|
|
86
|
-
finish(resolve, value);
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
92
|
}
|
|
90
93
|
const err = new Error('waitFor timed out');
|
|
91
94
|
err.name = 'TimeoutError';
|
package/types/TimerBase.d.ts
CHANGED
|
@@ -28,10 +28,10 @@ export class TimerBase {
|
|
|
28
28
|
pause(): void;
|
|
29
29
|
/**
|
|
30
30
|
* Resume the timer using the remaining time (or an override delay).
|
|
31
|
-
* @param {Function} callback - Called when time completes
|
|
31
|
+
* @param {Function} [callback] - Called when time completes; defaults to the previous callback
|
|
32
32
|
* @param {number|null} [overrideDelay=null] - Optional custom delay in ms
|
|
33
33
|
*/
|
|
34
|
-
resume(callback
|
|
34
|
+
resume(callback?: Function, overrideDelay?: number | null): void;
|
|
35
35
|
/**
|
|
36
36
|
* Cancel the timer immediately (terminal).
|
|
37
37
|
*/
|
package/types/abort.d.ts
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Attach an AbortSignal listener and return a cleanup function.
|
|
3
|
-
* - If `signal` is missing, returns a no-op cleanup.
|
|
4
|
-
* - If already aborted, calls `onAbort()` immediately and returns a no-op cleanup.
|
|
5
|
-
*
|
|
6
|
-
* @param {AbortSignal | null | undefined} signal
|
|
7
|
-
* @param {() => void} onAbort
|
|
8
|
-
* @returns {() => void} cleanup
|
|
9
|
-
*/
|
|
10
|
-
export function attachAbort(signal: AbortSignal | null | undefined, onAbort: () => void): () => void;
|
|
11
|
-
/**
|
|
12
|
-
* Manage AbortSignal listener lifecycle for "pending work" cases.
|
|
13
|
-
* Call `add()` when work becomes pending and `remove()` when it’s resolved/canceled.
|
|
14
|
-
*
|
|
15
|
-
* @param {AbortSignal | null | undefined} signal
|
|
16
|
-
* @param {() => void} onAbort
|
|
17
|
-
* @returns {{ add: () => void, remove: () => void, reset: () => void }}
|
|
18
|
-
*/
|
|
19
|
-
export function pendingAbort(signal: AbortSignal | null | undefined, onAbort: () => void): {
|
|
20
|
-
add: () => void;
|
|
21
|
-
remove: () => void;
|
|
22
|
-
reset: () => void;
|
|
23
|
-
};
|
|
24
|
-
/**
|
|
25
|
-
* The error an aborted operation should reject with: the signal's own
|
|
26
|
-
* `reason` (what `fetch()` and other web APIs use), falling back to a
|
|
27
|
-
* standard AbortError for runtimes without `AbortSignal.reason`.
|
|
28
|
-
*
|
|
29
|
-
* @param {AbortSignal | null | undefined} signal
|
|
30
|
-
* @returns {any}
|
|
31
|
-
*/
|
|
32
|
-
export function abortReason(signal: AbortSignal | null | undefined): any;
|
|
33
|
-
/**
|
|
34
|
-
* Standardized AbortError factory.
|
|
35
|
-
* Works in browsers and Node runtimes that may not have DOMException.
|
|
36
|
-
*
|
|
37
|
-
* We resolve the best implementation once at module load time.
|
|
38
|
-
* This avoids feature detection in the hot path.
|
|
39
|
-
*/
|
|
40
|
-
export let createAbortError: any;
|
|
1
|
+
/**
|
|
2
|
+
* Attach an AbortSignal listener and return a cleanup function.
|
|
3
|
+
* - If `signal` is missing, returns a no-op cleanup.
|
|
4
|
+
* - If already aborted, calls `onAbort()` immediately and returns a no-op cleanup.
|
|
5
|
+
*
|
|
6
|
+
* @param {AbortSignal | null | undefined} signal
|
|
7
|
+
* @param {() => void} onAbort
|
|
8
|
+
* @returns {() => void} cleanup
|
|
9
|
+
*/
|
|
10
|
+
export function attachAbort(signal: AbortSignal | null | undefined, onAbort: () => void): () => void;
|
|
11
|
+
/**
|
|
12
|
+
* Manage AbortSignal listener lifecycle for "pending work" cases.
|
|
13
|
+
* Call `add()` when work becomes pending and `remove()` when it’s resolved/canceled.
|
|
14
|
+
*
|
|
15
|
+
* @param {AbortSignal | null | undefined} signal
|
|
16
|
+
* @param {() => void} onAbort
|
|
17
|
+
* @returns {{ add: () => void, remove: () => void, reset: () => void }}
|
|
18
|
+
*/
|
|
19
|
+
export function pendingAbort(signal: AbortSignal | null | undefined, onAbort: () => void): {
|
|
20
|
+
add: () => void;
|
|
21
|
+
remove: () => void;
|
|
22
|
+
reset: () => void;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* The error an aborted operation should reject with: the signal's own
|
|
26
|
+
* `reason` (what `fetch()` and other web APIs use), falling back to a
|
|
27
|
+
* standard AbortError for runtimes without `AbortSignal.reason`.
|
|
28
|
+
*
|
|
29
|
+
* @param {AbortSignal | null | undefined} signal
|
|
30
|
+
* @returns {any}
|
|
31
|
+
*/
|
|
32
|
+
export function abortReason(signal: AbortSignal | null | undefined): any;
|
|
33
|
+
/**
|
|
34
|
+
* Standardized AbortError factory.
|
|
35
|
+
* Works in browsers and Node runtimes that may not have DOMException.
|
|
36
|
+
*
|
|
37
|
+
* We resolve the best implementation once at module load time.
|
|
38
|
+
* This avoids feature detection in the hot path.
|
|
39
|
+
*/
|
|
40
|
+
export let createAbortError: any;
|
package/types/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
export { parseDuration } from "./parseDuration.js";
|
|
2
|
-
export { flow } from "./TimeoutFlow.js";
|
|
3
|
-
export { throttle } from "./throttle.js";
|
|
4
|
-
export { debounce } from "./debounce.js";
|
|
5
|
-
export { after } from "./after.js";
|
|
6
|
-
export { every } from "./every.js";
|
|
7
|
-
export { sleep } from "./sleep.js";
|
|
8
|
-
export { waitFor } from "./waitFor.js";
|
|
9
|
-
export { retry } from "./retry.js";
|
|
10
|
-
export { afterRaf, everyRaf, debounceRaf, throttleRaf, waitForRaf } from "./raf/index.js";
|
|
1
|
+
export { parseDuration } from "./parseDuration.js";
|
|
2
|
+
export { flow } from "./TimeoutFlow.js";
|
|
3
|
+
export { throttle } from "./throttle.js";
|
|
4
|
+
export { debounce } from "./debounce.js";
|
|
5
|
+
export { after } from "./after.js";
|
|
6
|
+
export { every } from "./every.js";
|
|
7
|
+
export { sleep } from "./sleep.js";
|
|
8
|
+
export { waitFor } from "./waitFor.js";
|
|
9
|
+
export { retry } from "./retry.js";
|
|
10
|
+
export { afterRaf, everyRaf, debounceRaf, throttleRaf, waitForRaf } from "./raf/index.js";
|