timeout-flow 0.0.19 → 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/ADDITIONAL_TERMS.md +122 -122
- package/LICENSE +694 -694
- package/README.md +475 -307
- package/dist/timeout-flow.min.js +1 -1
- package/package.json +79 -68
- package/robots.txt +79 -79
- package/src/AfterTimer.js +81 -81
- package/src/EveryTimer.js +208 -208
- package/src/TimeoutFlow.js +400 -400
- package/src/TimerBase.js +137 -132
- package/src/abort.js +87 -75
- package/src/after.js +32 -32
- package/src/debounce.js +105 -105
- package/src/every.js +34 -34
- package/src/index.js +24 -23
- package/src/now.js +22 -22
- package/src/parseDuration.js +43 -46
- package/src/raf/ReadMe-Raf.md +94 -94
- package/src/raf/afterRaf.js +203 -203
- package/src/raf/debounceRaf.js +126 -126
- package/src/raf/everyRaf.js +314 -316
- package/src/raf/index.js +27 -27
- package/src/raf/throttleRaf.js +181 -181
- package/src/raf/waitForRaf.js +100 -100
- package/src/resolveDelayAndFn.js +65 -89
- package/src/retry.js +205 -164
- package/src/sleep.js +58 -0
- package/src/throttle.js +141 -141
- package/src/waitFor.js +99 -77
- package/types/TimerBase.d.ts +2 -2
- package/types/abort.d.ts +9 -0
- package/types/index.d.ts +1 -0
- package/types/raf/waitForRaf.d.ts +1 -1
- package/types/resolveDelayAndFn.d.ts +1 -15
- package/types/retry.d.ts +57 -18
- package/types/sleep.d.ts +29 -0
- package/types/waitFor.d.ts +19 -8
package/src/throttle.js
CHANGED
|
@@ -1,142 +1,142 @@
|
|
|
1
|
-
// ./src/throttle.js
|
|
2
|
-
|
|
3
|
-
import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
|
|
4
|
-
import { pendingAbort } from './abort.js';
|
|
5
|
-
import { now } from './now.js'
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* @typedef {((...args: any[]) => void) & {
|
|
10
|
-
* cancel: () => void,
|
|
11
|
-
* flush: () => void
|
|
12
|
-
* }} ThrottledFunction
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Creates a throttled version of a function.
|
|
17
|
-
* Executes immediately, throttles further calls, optional trailing execution.
|
|
18
|
-
*
|
|
19
|
-
* Preferred:
|
|
20
|
-
* - throttle(fn, delay, [options])
|
|
21
|
-
*
|
|
22
|
-
* Also supported:
|
|
23
|
-
* - throttle(delay, fn, [options]) // legacy/alt ordering
|
|
24
|
-
*
|
|
25
|
-
* Notes:
|
|
26
|
-
* - Uses performance.now() (via `now()`) for elapsed timing.
|
|
27
|
-
* - If trailing is enabled, uses the latest arguments/context seen during the wait.
|
|
28
|
-
* - `.cancel()` clears any pending trailing invocation.
|
|
29
|
-
* - `.flush()` immediately invokes a pending trailing call (if scheduled).
|
|
30
|
-
* - Optional AbortSignal: abort cancels any pending trailing invocation.
|
|
31
|
-
*
|
|
32
|
-
* @param {Function|string|number} a
|
|
33
|
-
* @param {Function|string|number|Object} b
|
|
34
|
-
* @param {Object} [c]
|
|
35
|
-
* @param {boolean} [c.trailing=true]
|
|
36
|
-
* @param {AbortSignal} [c.signal]
|
|
37
|
-
* @returns {ThrottledFunction}
|
|
38
|
-
*/
|
|
39
|
-
export function throttle(a, b, c) {
|
|
40
|
-
// Require an explicit delay by passing `undefined` as defaultDelay.
|
|
41
|
-
const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
|
|
42
|
-
|
|
43
|
-
const signal = options?.signal;
|
|
44
|
-
const trailing = options?.trailing ?? true;
|
|
45
|
-
|
|
46
|
-
const waitWindow = Math.max(0, delay);
|
|
47
|
-
|
|
48
|
-
let lastCallTime = -Infinity;
|
|
49
|
-
let timeoutId = 0;
|
|
50
|
-
|
|
51
|
-
/** @type {any[] | null} */
|
|
52
|
-
let lastArgs = null;
|
|
53
|
-
/** @type {any | null} */
|
|
54
|
-
let lastThis = null;
|
|
55
|
-
|
|
56
|
-
const abort = pendingAbort(signal, () => cancel());
|
|
57
|
-
|
|
58
|
-
const invoke = () => {
|
|
59
|
-
if (!lastArgs) return;
|
|
60
|
-
|
|
61
|
-
const args = lastArgs;
|
|
62
|
-
const ctx = lastThis;
|
|
63
|
-
|
|
64
|
-
// clear first (re-entrancy safe + GC friendly)
|
|
65
|
-
lastArgs = null;
|
|
66
|
-
lastThis = null;
|
|
67
|
-
|
|
68
|
-
abort.remove();
|
|
69
|
-
fn.apply(ctx, args);
|
|
70
|
-
};
|
|
71
|
-
|
|
72
|
-
const cancel = () => {
|
|
73
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
74
|
-
timeoutId = 0;
|
|
75
|
-
|
|
76
|
-
lastArgs = null;
|
|
77
|
-
lastThis = null;
|
|
78
|
-
|
|
79
|
-
abort.remove();
|
|
80
|
-
};
|
|
81
|
-
|
|
82
|
-
/** @param {number} wait */
|
|
83
|
-
const scheduleTrailing = (wait) => {
|
|
84
|
-
abort.add();
|
|
85
|
-
|
|
86
|
-
timeoutId = setTimeout(() => {
|
|
87
|
-
timeoutId = 0;
|
|
88
|
-
lastCallTime = now();
|
|
89
|
-
invoke();
|
|
90
|
-
}, wait);
|
|
91
|
-
};
|
|
92
|
-
|
|
93
|
-
/** @type {any} */
|
|
94
|
-
const throttled = function (...args) {
|
|
95
|
-
if (signal?.aborted) return;
|
|
96
|
-
|
|
97
|
-
const currentTime = now();
|
|
98
|
-
const timeSinceLast = currentTime - lastCallTime;
|
|
99
|
-
|
|
100
|
-
lastArgs = args;
|
|
101
|
-
lastThis = this;
|
|
102
|
-
|
|
103
|
-
if (timeSinceLast >= waitWindow) {
|
|
104
|
-
// Leading edge: run now
|
|
105
|
-
lastCallTime = currentTime;
|
|
106
|
-
|
|
107
|
-
// Clear any pending trailing call (and listener)
|
|
108
|
-
if (timeoutId) {
|
|
109
|
-
clearTimeout(timeoutId);
|
|
110
|
-
timeoutId = 0;
|
|
111
|
-
abort.remove();
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
invoke();
|
|
115
|
-
return;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
if (!trailing) return;
|
|
119
|
-
|
|
120
|
-
// Trailing edge: schedule once, keep latest args
|
|
121
|
-
if (!timeoutId) {
|
|
122
|
-
const wait = Math.max(0, waitWindow - timeSinceLast);
|
|
123
|
-
scheduleTrailing(wait);
|
|
124
|
-
}
|
|
125
|
-
};
|
|
126
|
-
|
|
127
|
-
throttled.cancel = cancel;
|
|
128
|
-
|
|
129
|
-
throttled.flush = () => {
|
|
130
|
-
if (!timeoutId) return;
|
|
131
|
-
clearTimeout(timeoutId);
|
|
132
|
-
timeoutId = 0;
|
|
133
|
-
|
|
134
|
-
lastCallTime = now();
|
|
135
|
-
invoke();
|
|
136
|
-
};
|
|
137
|
-
|
|
138
|
-
// If already aborted at creation time, ensure clean slate.
|
|
139
|
-
if (signal?.aborted) cancel();
|
|
140
|
-
|
|
141
|
-
return throttled;
|
|
1
|
+
// ./src/throttle.js
|
|
2
|
+
|
|
3
|
+
import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
|
|
4
|
+
import { pendingAbort } from './abort.js';
|
|
5
|
+
import { now } from './now.js'
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @typedef {((...args: any[]) => void) & {
|
|
10
|
+
* cancel: () => void,
|
|
11
|
+
* flush: () => void
|
|
12
|
+
* }} ThrottledFunction
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Creates a throttled version of a function.
|
|
17
|
+
* Executes immediately, throttles further calls, optional trailing execution.
|
|
18
|
+
*
|
|
19
|
+
* Preferred:
|
|
20
|
+
* - throttle(fn, delay, [options])
|
|
21
|
+
*
|
|
22
|
+
* Also supported:
|
|
23
|
+
* - throttle(delay, fn, [options]) // legacy/alt ordering
|
|
24
|
+
*
|
|
25
|
+
* Notes:
|
|
26
|
+
* - Uses performance.now() (via `now()`) for elapsed timing.
|
|
27
|
+
* - If trailing is enabled, uses the latest arguments/context seen during the wait.
|
|
28
|
+
* - `.cancel()` clears any pending trailing invocation.
|
|
29
|
+
* - `.flush()` immediately invokes a pending trailing call (if scheduled).
|
|
30
|
+
* - Optional AbortSignal: abort cancels any pending trailing invocation.
|
|
31
|
+
*
|
|
32
|
+
* @param {Function|string|number} a
|
|
33
|
+
* @param {Function|string|number|Object} b
|
|
34
|
+
* @param {Object} [c]
|
|
35
|
+
* @param {boolean} [c.trailing=true]
|
|
36
|
+
* @param {AbortSignal} [c.signal]
|
|
37
|
+
* @returns {ThrottledFunction}
|
|
38
|
+
*/
|
|
39
|
+
export function throttle(a, b, c) {
|
|
40
|
+
// Require an explicit delay by passing `undefined` as defaultDelay.
|
|
41
|
+
const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
|
|
42
|
+
|
|
43
|
+
const signal = options?.signal;
|
|
44
|
+
const trailing = options?.trailing ?? true;
|
|
45
|
+
|
|
46
|
+
const waitWindow = Math.max(0, delay);
|
|
47
|
+
|
|
48
|
+
let lastCallTime = -Infinity;
|
|
49
|
+
let timeoutId = 0;
|
|
50
|
+
|
|
51
|
+
/** @type {any[] | null} */
|
|
52
|
+
let lastArgs = null;
|
|
53
|
+
/** @type {any | null} */
|
|
54
|
+
let lastThis = null;
|
|
55
|
+
|
|
56
|
+
const abort = pendingAbort(signal, () => cancel());
|
|
57
|
+
|
|
58
|
+
const invoke = () => {
|
|
59
|
+
if (!lastArgs) return;
|
|
60
|
+
|
|
61
|
+
const args = lastArgs;
|
|
62
|
+
const ctx = lastThis;
|
|
63
|
+
|
|
64
|
+
// clear first (re-entrancy safe + GC friendly)
|
|
65
|
+
lastArgs = null;
|
|
66
|
+
lastThis = null;
|
|
67
|
+
|
|
68
|
+
abort.remove();
|
|
69
|
+
fn.apply(ctx, args);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const cancel = () => {
|
|
73
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
74
|
+
timeoutId = 0;
|
|
75
|
+
|
|
76
|
+
lastArgs = null;
|
|
77
|
+
lastThis = null;
|
|
78
|
+
|
|
79
|
+
abort.remove();
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** @param {number} wait */
|
|
83
|
+
const scheduleTrailing = (wait) => {
|
|
84
|
+
abort.add();
|
|
85
|
+
|
|
86
|
+
timeoutId = setTimeout(() => {
|
|
87
|
+
timeoutId = 0;
|
|
88
|
+
lastCallTime = now();
|
|
89
|
+
invoke();
|
|
90
|
+
}, wait);
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/** @type {any} */
|
|
94
|
+
const throttled = function (...args) {
|
|
95
|
+
if (signal?.aborted) return;
|
|
96
|
+
|
|
97
|
+
const currentTime = now();
|
|
98
|
+
const timeSinceLast = currentTime - lastCallTime;
|
|
99
|
+
|
|
100
|
+
lastArgs = args;
|
|
101
|
+
lastThis = this;
|
|
102
|
+
|
|
103
|
+
if (timeSinceLast >= waitWindow) {
|
|
104
|
+
// Leading edge: run now
|
|
105
|
+
lastCallTime = currentTime;
|
|
106
|
+
|
|
107
|
+
// Clear any pending trailing call (and listener)
|
|
108
|
+
if (timeoutId) {
|
|
109
|
+
clearTimeout(timeoutId);
|
|
110
|
+
timeoutId = 0;
|
|
111
|
+
abort.remove();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
invoke();
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (!trailing) return;
|
|
119
|
+
|
|
120
|
+
// Trailing edge: schedule once, keep latest args
|
|
121
|
+
if (!timeoutId) {
|
|
122
|
+
const wait = Math.max(0, waitWindow - timeSinceLast);
|
|
123
|
+
scheduleTrailing(wait);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
throttled.cancel = cancel;
|
|
128
|
+
|
|
129
|
+
throttled.flush = () => {
|
|
130
|
+
if (!timeoutId) return;
|
|
131
|
+
clearTimeout(timeoutId);
|
|
132
|
+
timeoutId = 0;
|
|
133
|
+
|
|
134
|
+
lastCallTime = now();
|
|
135
|
+
invoke();
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
// If already aborted at creation time, ensure clean slate.
|
|
139
|
+
if (signal?.aborted) cancel();
|
|
140
|
+
|
|
141
|
+
return throttled;
|
|
142
142
|
}
|
package/src/waitFor.js
CHANGED
|
@@ -1,77 +1,99 @@
|
|
|
1
|
-
// ./src/waitFor.js
|
|
2
|
-
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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
|
-
return;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
1
|
+
// ./src/waitFor.js
|
|
2
|
+
|
|
3
|
+
import { attachAbort, abortReason } from './abort.js';
|
|
4
|
+
import { toDelay } from './sleep.js';
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Waits for a condition to become truthy, polling at intervals.
|
|
9
|
+
*
|
|
10
|
+
* Timing model:
|
|
11
|
+
* - With `immediate: false` (default) the first check runs after `interval`.
|
|
12
|
+
* - The next check is scheduled `interval` after the previous one finishes,
|
|
13
|
+
* so async conditions never overlap.
|
|
14
|
+
* - `timeout` is measured from the call and enforced by its own timer, so it
|
|
15
|
+
* is not rounded up to the next poll. At the deadline a sync condition gets
|
|
16
|
+
* one final check (success at exactly `timeout` counts, like `>=`); an async
|
|
17
|
+
* check still pending at the deadline is abandoned and the promise rejects.
|
|
18
|
+
*
|
|
19
|
+
* @template T
|
|
20
|
+
* @param {() => T | Promise<T>} condition - sync or async; truthy when satisfied
|
|
21
|
+
* @param {Object} [options] - optional polling control
|
|
22
|
+
* @param {string|number} [options.interval='250ms'] - delay between checks
|
|
23
|
+
* @param {string|number} [options.timeout] - max wait time; rejects with an
|
|
24
|
+
* Error named 'TimeoutError' (message 'waitFor timed out')
|
|
25
|
+
* @param {boolean} [options.immediate=false] - If true, evaluate condition immediately
|
|
26
|
+
* @param {AbortSignal} [options.signal] - rejects with `signal.reason` on abort
|
|
27
|
+
* @returns {Promise<T>} resolves with the condition's truthy value
|
|
28
|
+
*/
|
|
29
|
+
export function waitFor(condition, { interval = '250ms', timeout, immediate = false, signal } = {}) {
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
if (signal?.aborted) {
|
|
32
|
+
reject(abortReason(signal));
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const intervalMs = toDelay(interval);
|
|
37
|
+
const timeoutMs = timeout != null ? toDelay(timeout) : null;
|
|
38
|
+
|
|
39
|
+
let done = false;
|
|
40
|
+
let pending = false;
|
|
41
|
+
let poller = 0;
|
|
42
|
+
let deadline = 0;
|
|
43
|
+
|
|
44
|
+
const finish = (settle, value) => {
|
|
45
|
+
if (done) return;
|
|
46
|
+
done = true;
|
|
47
|
+
clearTimeout(poller);
|
|
48
|
+
clearTimeout(deadline);
|
|
49
|
+
cleanupAbort();
|
|
50
|
+
settle(value);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const cleanupAbort = attachAbort(signal, () => finish(reject, abortReason(signal)));
|
|
54
|
+
|
|
55
|
+
const check = async () => {
|
|
56
|
+
let value;
|
|
57
|
+
pending = true;
|
|
58
|
+
try {
|
|
59
|
+
value = await condition();
|
|
60
|
+
} catch (err) {
|
|
61
|
+
finish(reject, err);
|
|
62
|
+
return;
|
|
63
|
+
} finally {
|
|
64
|
+
pending = false;
|
|
65
|
+
}
|
|
66
|
+
if (done) return;
|
|
67
|
+
if (value) finish(resolve, value);
|
|
68
|
+
else poller = setTimeout(check, intervalMs);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
if (immediate) check();
|
|
72
|
+
else poller = setTimeout(check, intervalMs);
|
|
73
|
+
|
|
74
|
+
if (!done && timeoutMs != null) {
|
|
75
|
+
deadline = setTimeout(() => {
|
|
76
|
+
if (!pending) {
|
|
77
|
+
try {
|
|
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
|
+
}
|
|
88
|
+
} catch (err) {
|
|
89
|
+
finish(reject, err);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const err = new Error('waitFor timed out');
|
|
94
|
+
err.name = 'TimeoutError';
|
|
95
|
+
finish(reject, err);
|
|
96
|
+
}, timeoutMs);
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
}
|
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
|
@@ -21,6 +21,15 @@ export function pendingAbort(signal: AbortSignal | null | undefined, onAbort: ()
|
|
|
21
21
|
remove: () => void;
|
|
22
22
|
reset: () => void;
|
|
23
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;
|
|
24
33
|
/**
|
|
25
34
|
* Standardized AbortError factory.
|
|
26
35
|
* Works in browsers and Node runtimes that may not have DOMException.
|
package/types/index.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ export { throttle } from "./throttle.js";
|
|
|
4
4
|
export { debounce } from "./debounce.js";
|
|
5
5
|
export { after } from "./after.js";
|
|
6
6
|
export { every } from "./every.js";
|
|
7
|
+
export { sleep } from "./sleep.js";
|
|
7
8
|
export { waitFor } from "./waitFor.js";
|
|
8
9
|
export { retry } from "./retry.js";
|
|
9
10
|
export { afterRaf, everyRaf, debounceRaf, throttleRaf, waitForRaf } from "./raf/index.js";
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* @param {Function} condition - Function returning truthy when complete
|
|
9
9
|
* @param {Object} [options]
|
|
10
10
|
* @param {string|number} [options.timeout] - Optional max time to wait
|
|
11
|
-
* @param {AbortSignal} [options.signal] - Optional AbortSignal
|
|
11
|
+
* @param {AbortSignal} [options.signal] - Optional AbortSignal; rejects with `signal.reason`
|
|
12
12
|
* @param {boolean} [options.immediate=false] - If true, evaluate condition immediately before first frame
|
|
13
13
|
* @returns {Promise<void>} Resolves when condition is met, rejects on timeout/abort
|
|
14
14
|
*/
|
|
@@ -1,18 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Resolves flexible (fn, delay) or (delay, fn) inputs.
|
|
3
|
-
*
|
|
4
|
-
* NOTE: This helper is intentionally strict:
|
|
5
|
-
* - It requires an explicit delay (2-arg form).
|
|
6
|
-
* - Use `resolveDelayFnOptions()` for overloads that allow `(fn, options)` or default delays.
|
|
7
|
-
*
|
|
8
|
-
* @param {Function|string|number} a - function or duration
|
|
9
|
-
* @param {Function|string|number} b - function or duration
|
|
10
|
-
* @returns {{ fn: Function, delay: number }}
|
|
11
|
-
*/
|
|
12
|
-
export function resolveDelayAndFn(a: Function | string | number, b: Function | string | number): {
|
|
13
|
-
fn: Function;
|
|
14
|
-
delay: number;
|
|
15
|
-
};
|
|
16
1
|
/**
|
|
17
2
|
* Resolves flexible overloads and returns `{ fn, delay, options }`.
|
|
18
3
|
*
|
|
@@ -36,3 +21,4 @@ export function resolveDelayFnOptions<O extends Record<string, any>>(a: Function
|
|
|
36
21
|
delay: number;
|
|
37
22
|
options: O;
|
|
38
23
|
};
|
|
24
|
+
export function isPlainOptions(v: any): boolean;
|
package/types/retry.d.ts
CHANGED
|
@@ -1,31 +1,70 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Retries a
|
|
2
|
+
* Retries a (possibly async) function with delays between attempts.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Attempt numbers are 0-based everywhere (`fn`, hooks, predicates).
|
|
5
|
+
*
|
|
6
|
+
* Outcome:
|
|
7
|
+
* - Resolves with the first successful result.
|
|
8
|
+
* - When retries stop (attempts exhausted, `timeout` reached, or
|
|
9
|
+
* `shouldRetry` returned false) it rejects with the last failure:
|
|
10
|
+
* the last thrown error as-is, or, when the last attempt resolved with a
|
|
11
|
+
* result rejected by `isSuccess`, a `RetryError` (`name: 'RetryError'`)
|
|
12
|
+
* carrying `.result` and `.attempts`.
|
|
13
|
+
* - On abort it rejects with `signal.reason` (an AbortError by default).
|
|
14
|
+
*
|
|
15
|
+
* @template T
|
|
16
|
+
* @param {(attempt: number) => T | Promise<T>} fn - sync or async function
|
|
5
17
|
* @param {Object} [options]
|
|
6
|
-
* @param {number} [options.attempts=3] - total attempts
|
|
7
|
-
* @param {string|number} [options.delay='500ms'] - base delay between
|
|
8
|
-
* @param {boolean} [options.backoff=false]
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* @param {
|
|
12
|
-
* @param {
|
|
13
|
-
* @param {
|
|
18
|
+
* @param {number} [options.attempts=3] - total attempts including the first (`Infinity` allowed)
|
|
19
|
+
* @param {string|number} [options.delay='500ms'] - base delay between attempts
|
|
20
|
+
* @param {boolean|'fixed'|'linear'|'exponential'} [options.backoff=false]
|
|
21
|
+
* Delay growth per retry n (0-based): fixed (false) = delay,
|
|
22
|
+
* linear = delay*(n+1), exponential (true) = delay*factor^n.
|
|
23
|
+
* @param {number} [options.factor=2] - exponential multiplier
|
|
24
|
+
* @param {string|number} [options.maxDelay] - cap for each computed delay
|
|
25
|
+
* @param {boolean|number|'full'|'equal'|'decorrelated'} [options.jitter=false] - jitter strategy.
|
|
26
|
+
* A number j in [0, 1] applies proportional �j jitter:
|
|
27
|
+
* delay * (1 + (random()*2 - 1) * j), after the maxDelay cap and then
|
|
28
|
+
* re-capped by maxDelay, clamped to >= 0 and rounded. Other numbers
|
|
29
|
+
* (or NaN) reject with a RangeError before any attempt.
|
|
30
|
+
* `delayFirst` is never jittered.
|
|
31
|
+
* @param {boolean|string|number} [options.delayFirst=false]
|
|
32
|
+
* Wait before the first attempt (`true` = `delay`, or an explicit duration).
|
|
33
|
+
* @param {string|number} [options.timeout] - overall deadline measured from the call.
|
|
34
|
+
* A retry is skipped when its wait would end past the deadline; the first
|
|
35
|
+
* attempt always runs and an in-flight attempt is never interrupted.
|
|
36
|
+
* @param {AbortSignal} [options.signal] - cancels waiting and further attempts
|
|
37
|
+
* @param {(result: T, attempt: number) => boolean | Promise<boolean>} [options.isSuccess]
|
|
38
|
+
* Treat a resolved result as a failure (and retry) when this returns false.
|
|
14
39
|
* @param {(err: any, attempt: number) => boolean | Promise<boolean>} [options.shouldRetry]
|
|
15
|
-
*
|
|
40
|
+
* Return false to stop retrying after a failure.
|
|
41
|
+
* @param {(attempt: number, elapsedMs: number) => void | Promise<void>} [options.onAttempt]
|
|
42
|
+
* Called before every attempt.
|
|
16
43
|
* @param {(err: any, attempt: number, delayMs: number) => void | Promise<void>} [options.onRetry]
|
|
17
|
-
*
|
|
18
|
-
* @
|
|
44
|
+
* Called after deciding to retry and before waiting.
|
|
45
|
+
* @param {(ms: number, options: { signal?: AbortSignal }) => Promise<void>} [options.sleep]
|
|
46
|
+
* Injectable sleep (e.g. for fake-timer tests).
|
|
47
|
+
* @param {() => number} [options.now] - injectable clock used for `timeout`
|
|
48
|
+
* @param {() => number} [options.random=Math.random] - injectable RNG for tests
|
|
49
|
+
* @returns {Promise<T>}
|
|
19
50
|
*/
|
|
20
|
-
export function retry(fn: (
|
|
51
|
+
export function retry<T>(fn: (attempt: number) => T | Promise<T>, { attempts, delay, backoff, factor, maxDelay, jitter, delayFirst, timeout, signal, isSuccess, shouldRetry, onAttempt, onRetry, sleep, now, random, }?: {
|
|
21
52
|
attempts?: number | undefined;
|
|
22
53
|
delay?: string | number | undefined;
|
|
23
|
-
backoff?: boolean | undefined;
|
|
54
|
+
backoff?: boolean | "fixed" | "exponential" | "linear" | undefined;
|
|
24
55
|
factor?: number | undefined;
|
|
25
56
|
maxDelay?: string | number | undefined;
|
|
26
|
-
jitter?: boolean | "full" | "equal" | "decorrelated" | undefined;
|
|
57
|
+
jitter?: number | boolean | "full" | "equal" | "decorrelated" | undefined;
|
|
58
|
+
delayFirst?: string | number | boolean | undefined;
|
|
59
|
+
timeout?: string | number | undefined;
|
|
27
60
|
signal?: AbortSignal | undefined;
|
|
28
|
-
|
|
61
|
+
isSuccess?: ((result: T, attempt: number) => boolean | Promise<boolean>) | undefined;
|
|
29
62
|
shouldRetry?: ((err: any, attempt: number) => boolean | Promise<boolean>) | undefined;
|
|
63
|
+
onAttempt?: ((attempt: number, elapsedMs: number) => void | Promise<void>) | undefined;
|
|
30
64
|
onRetry?: ((err: any, attempt: number, delayMs: number) => void | Promise<void>) | undefined;
|
|
31
|
-
|
|
65
|
+
sleep?: ((ms: number, options: {
|
|
66
|
+
signal?: AbortSignal;
|
|
67
|
+
}) => Promise<void>) | undefined;
|
|
68
|
+
now?: (() => number) | undefined;
|
|
69
|
+
random?: (() => number) | undefined;
|
|
70
|
+
}): Promise<T>;
|
package/types/sleep.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Normalizes a duration to a setTimeout-safe delay in ms.
|
|
3
|
+
* - Strings are parsed ("500ms", "1s", "1.5m", "1h"); invalid strings throw.
|
|
4
|
+
* - Numbers behave like setTimeout: NaN and negative values clamp to 0.
|
|
5
|
+
* - Values above setTimeout's 32-bit limit (including Infinity) are capped at
|
|
6
|
+
* 2147483647 ms (~24.8 days) instead of overflowing and firing immediately.
|
|
7
|
+
*
|
|
8
|
+
* @param {string|number|null|undefined} duration
|
|
9
|
+
* @returns {number}
|
|
10
|
+
*/
|
|
11
|
+
export function toDelay(duration: string | number | null | undefined): number;
|
|
12
|
+
/**
|
|
13
|
+
* Promise-based delay: `await sleep('500ms')`.
|
|
14
|
+
*
|
|
15
|
+
* - Accepts the same durations as the rest of TimeoutFlow ("500ms", "1s", 250).
|
|
16
|
+
* - Numbers behave like setTimeout: NaN / negative become 0; huge values
|
|
17
|
+
* (including Infinity) are capped at ~24.8 days rather than firing at once.
|
|
18
|
+
* - Invalid duration strings reject with an Error (never throw synchronously).
|
|
19
|
+
* - With `signal`, rejects with `signal.reason` (an AbortError by default)
|
|
20
|
+
* and clears its timer; an already-aborted signal rejects immediately.
|
|
21
|
+
*
|
|
22
|
+
* @param {string|number} [duration=0]
|
|
23
|
+
* @param {Object} [options]
|
|
24
|
+
* @param {AbortSignal} [options.signal]
|
|
25
|
+
* @returns {Promise<void>}
|
|
26
|
+
*/
|
|
27
|
+
export function sleep(duration?: string | number, { signal }?: {
|
|
28
|
+
signal?: AbortSignal | undefined;
|
|
29
|
+
}): Promise<void>;
|