timeout-flow 0.0.19 → 0.0.20

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.
@@ -1,401 +1,401 @@
1
- // ./src/TimeoutFlow.js
2
-
3
- import { after } from './after.js';
4
- import { every } from './every.js';
5
- import { pendingAbort } from './abort.js';
6
-
7
- /**
8
- * Creates a fluent scheduler.
9
- * Returns a chainable timeline.
10
- *
11
- * @param {Object} [options]
12
- * @param {AbortSignal} [options.signal] - Optional AbortSignal to auto-cancel the flow
13
- */
14
- export function flow({ signal } = {}) {
15
- const steps = [];
16
- const labelMap = new Map();
17
-
18
- let currentIndex = 0;
19
-
20
- let started = false;
21
- let isPaused = false;
22
- let isCancelled = false;
23
- let isFinished = false;
24
-
25
- let loopEnabled = false;
26
- let loopLimit = Infinity;
27
- let loopCount = 0;
28
-
29
- /** @type {Function | null} */
30
- let onFinishCallback = null;
31
- /** @type {Function | null} */
32
- let onErrorCallback = null;
33
-
34
- let jumpTarget = null;
35
-
36
- /** @type {Array<() => boolean>} */
37
- let conditionStack = [];
38
-
39
- let skipMode = false;
40
-
41
- let whileCondition = null;
42
- let doWhileCondition = null;
43
-
44
- /** @type {any} */
45
- let runner;
46
-
47
- // Abort wiring is per-run (so we don't retain references forever)
48
- const abort = pendingAbort(signal, () => runner.cancel());
49
-
50
- const clearController = (step) => {
51
- if (!step) return;
52
- if (step.controller) step.controller = null;
53
- };
54
-
55
- const cleanupCurrentController = () => {
56
- const step = steps[currentIndex];
57
- step?.controller?.cancel?.();
58
- if (step) step.controller = null;
59
- };
60
-
61
- const finishFlow = () => {
62
- if (isFinished || isCancelled) return;
63
-
64
- started = false;
65
- isPaused = false;
66
- isFinished = true;
67
-
68
- cleanupCurrentController();
69
- abort.remove();
70
-
71
- onFinishCallback?.();
72
- };
73
-
74
- const cancelFlow = () => {
75
- if (isCancelled) return;
76
-
77
- started = false;
78
- isPaused = false;
79
- isFinished = false;
80
- isCancelled = true;
81
-
82
- cleanupCurrentController();
83
- abort.remove();
84
- };
85
-
86
- const handleError = (err, step) => {
87
- // best hygiene: cancel current controller so nothing leaks
88
- cancelFlow();
89
-
90
- if (onErrorCallback) {
91
- try {
92
- onErrorCallback(err, {
93
- step,
94
- index: currentIndex,
95
- });
96
- } catch (_) {
97
- // If the error handler itself throws, fall through to rethrow original.
98
- }
99
- return;
100
- }
101
-
102
- // No handler: preserve existing behavior (throw)
103
- throw err;
104
- };
105
-
106
- const safeCall = (fn, stepForContext) => {
107
- try {
108
- return fn();
109
- } catch (err) {
110
- handleError(err, stepForContext);
111
- return undefined;
112
- }
113
- };
114
-
115
- const incrementStep = (step) => {
116
- clearController(step);
117
- currentIndex += 1;
118
- queueMicrotask(executeNext);
119
- };
120
-
121
- function executeNext() {
122
- if (isCancelled || isPaused || isFinished) return;
123
- if (signal?.aborted) {
124
- cancelFlow();
125
- return;
126
- }
127
-
128
- // Jump handling
129
- if (jumpTarget) {
130
- const targetIndex = labelMap.get(jumpTarget);
131
- if (typeof targetIndex === 'number') {
132
- currentIndex = targetIndex;
133
- } else {
134
- // treat as a flow error
135
- safeCall(() => {
136
- throw new Error(`Label "${jumpTarget}" not found`);
137
- }, steps[currentIndex]);
138
- return;
139
- }
140
- jumpTarget = null;
141
- }
142
-
143
- // Handle if/unless conditions (applies to the next step only)
144
- if (conditionStack.length > 0) {
145
- const predicate = conditionStack.shift();
146
- const shouldRun = safeCall(predicate, steps[currentIndex]);
147
- if (!shouldRun) skipMode = true;
148
- }
149
-
150
- // Skip mode: keep skipping until we hit a label (or end)
151
- if (skipMode) {
152
- const next = steps[currentIndex];
153
- if (!next || next.type === 'label') {
154
- skipMode = false;
155
- } else {
156
- return incrementStep(next);
157
- }
158
- }
159
-
160
- const step = steps[currentIndex];
161
-
162
- // End of timeline
163
- if (!step || currentIndex >= steps.length) {
164
- if (loopEnabled && ++loopCount < loopLimit) {
165
- currentIndex = 0;
166
- executeNext();
167
- } else {
168
- finishFlow(); // ✅ only natural completion calls onFinish
169
- }
170
- return;
171
- }
172
-
173
- if (step.type === 'label') {
174
- return incrementStep(step);
175
- }
176
-
177
- if (step.type === 'after') {
178
- step.controller = after(
179
- () => safeCall(step.fn, step),
180
- step.duration,
181
- { signal, onFinish: () => incrementStep(step) }
182
- );
183
- return;
184
- }
185
-
186
- if (step.type === 'every') {
187
-
188
- // No ticks will ever fire => advance immediately.
189
- if (!(step.times > 0) && step.times !== Infinity) {
190
- return incrementStep(step);
191
- }
192
-
193
- let count = 0;
194
- const ctrl = every(
195
- () => {
196
- if (isPaused || isCancelled || isFinished) return;
197
- if (signal?.aborted) {
198
- cancelFlow();
199
- return;
200
- }
201
-
202
- // Pre-run while guard
203
- if (step.whileCondition && !safeCall(step.whileCondition, step)) {
204
- ctrl.cancel();
205
- return incrementStep(step);
206
- }
207
-
208
- safeCall(() => step.fn(count++), step);
209
-
210
- // Post-run doWhile guard
211
- if (step.doWhileCondition && !safeCall(step.doWhileCondition, step)) {
212
- ctrl.cancel();
213
- return incrementStep(step);
214
- }
215
-
216
- if (count >= step.times) {
217
- ctrl.cancel();
218
- return incrementStep(step);
219
- }
220
- },
221
- step.duration,
222
- { max: step.times, signal }
223
- );
224
-
225
- step.controller = ctrl;
226
- }
227
- }
228
-
229
- runner = {
230
- after(duration, fn) {
231
- steps.push({ type: 'after', duration, fn, controller: null });
232
- return runner;
233
- },
234
-
235
- every(duration, fn, timesOrOptions = Infinity) {
236
- const raw =
237
- typeof timesOrOptions === 'number'
238
- ? timesOrOptions
239
- : timesOrOptions?.max ?? Infinity;
240
-
241
- const times =
242
- raw === Infinity ? Infinity : Math.max(0, raw | 0); // int >= 0
243
-
244
- steps.push({
245
- type: 'every',
246
- duration,
247
- fn,
248
- times,
249
- whileCondition,
250
- doWhileCondition,
251
- controller: null,
252
- });
253
-
254
- whileCondition = null;
255
- doWhileCondition = null;
256
- return runner;
257
- },
258
-
259
- loop(n = true) {
260
- loopEnabled = true;
261
- loopLimit = n === true ? Infinity : n;
262
- return runner;
263
- },
264
-
265
- onFinish(cb) {
266
- onFinishCallback = cb;
267
- return runner;
268
- },
269
-
270
- onError(cb) {
271
- onErrorCallback = cb;
272
- return runner;
273
- },
274
-
275
- start() {
276
- // restart hygiene: cancel any active controller from a previous run
277
- cleanupCurrentController();
278
-
279
- isCancelled = false;
280
- isFinished = false;
281
- isPaused = false;
282
- started = true;
283
-
284
- currentIndex = 0;
285
- loopCount = 0;
286
-
287
- // Abort wiring is per-run
288
- abort.reset();
289
- if (!signal?.aborted) abort.add();
290
-
291
- if (signal?.aborted) {
292
- cancelFlow(); // no-op start if already aborted
293
- return runner;
294
- }
295
-
296
- executeNext();
297
- return runner;
298
- },
299
-
300
- pause() {
301
- if (isPaused || isCancelled || isFinished) return;
302
- isPaused = true;
303
- steps[currentIndex]?.controller?.pause?.();
304
- },
305
-
306
- resume() {
307
- if (!isPaused || isCancelled || isFinished) return;
308
- if (signal?.aborted) {
309
- cancelFlow();
310
- return;
311
- }
312
- isPaused = false;
313
- steps[currentIndex]?.controller?.resume?.();
314
- },
315
-
316
- cancel() {
317
- cancelFlow(); // ✅ never calls onFinish
318
- },
319
-
320
- reset() {
321
- cancelFlow();
322
-
323
- steps.length = 0;
324
- labelMap.clear();
325
-
326
- currentIndex = 0;
327
- loopCount = 0;
328
-
329
- onFinishCallback = null;
330
- onErrorCallback = null;
331
-
332
- jumpTarget = null;
333
- conditionStack = [];
334
- skipMode = false;
335
-
336
- whileCondition = null;
337
- doWhileCondition = null;
338
-
339
- // allow reuse after reset (fresh state)
340
- started = false;
341
- isPaused = false;
342
- isCancelled = false;
343
- isFinished = false;
344
-
345
- return runner;
346
- },
347
-
348
- label(name) {
349
- labelMap.set(name, steps.length); // point to next step index
350
- steps.push({ type: 'label', name, controller: null });
351
- return runner;
352
- },
353
-
354
- jumpTo(name) {
355
- jumpTarget = name;
356
- return runner;
357
- },
358
-
359
- if(predicate) {
360
- conditionStack.push(() =>
361
- typeof predicate === 'function' ? !!predicate() : !!predicate
362
- );
363
- return runner;
364
- },
365
-
366
- unless(predicate) {
367
- conditionStack.push(() =>
368
- typeof predicate === 'function' ? !predicate() : !predicate
369
- );
370
- return runner;
371
- },
372
-
373
- while(predicate) {
374
- whileCondition = () =>
375
- typeof predicate === 'function' ? !!predicate() : !!predicate;
376
- return runner;
377
- },
378
-
379
- doWhile(predicate) {
380
- doWhileCondition = () =>
381
- typeof predicate === 'function' ? !!predicate() : !!predicate;
382
- return runner;
383
- },
384
-
385
- // unified lifecycle surface
386
- get isRunning() {
387
- return started && !isPaused && !isCancelled && !isFinished;
388
- },
389
- get isPaused() {
390
- return isPaused;
391
- },
392
- get isCancelled() {
393
- return isCancelled;
394
- },
395
- get isFinished() {
396
- return isFinished;
397
- },
398
- };
399
-
400
- return runner;
1
+ // ./src/TimeoutFlow.js
2
+
3
+ import { after } from './after.js';
4
+ import { every } from './every.js';
5
+ import { pendingAbort } from './abort.js';
6
+
7
+ /**
8
+ * Creates a fluent scheduler.
9
+ * Returns a chainable timeline.
10
+ *
11
+ * @param {Object} [options]
12
+ * @param {AbortSignal} [options.signal] - Optional AbortSignal to auto-cancel the flow
13
+ */
14
+ export function flow({ signal } = {}) {
15
+ const steps = [];
16
+ const labelMap = new Map();
17
+
18
+ let currentIndex = 0;
19
+
20
+ let started = false;
21
+ let isPaused = false;
22
+ let isCancelled = false;
23
+ let isFinished = false;
24
+
25
+ let loopEnabled = false;
26
+ let loopLimit = Infinity;
27
+ let loopCount = 0;
28
+
29
+ /** @type {Function | null} */
30
+ let onFinishCallback = null;
31
+ /** @type {Function | null} */
32
+ let onErrorCallback = null;
33
+
34
+ let jumpTarget = null;
35
+
36
+ /** @type {Array<() => boolean>} */
37
+ let conditionStack = [];
38
+
39
+ let skipMode = false;
40
+
41
+ let whileCondition = null;
42
+ let doWhileCondition = null;
43
+
44
+ /** @type {any} */
45
+ let runner;
46
+
47
+ // Abort wiring is per-run (so we don't retain references forever)
48
+ const abort = pendingAbort(signal, () => runner.cancel());
49
+
50
+ const clearController = (step) => {
51
+ if (!step) return;
52
+ if (step.controller) step.controller = null;
53
+ };
54
+
55
+ const cleanupCurrentController = () => {
56
+ const step = steps[currentIndex];
57
+ step?.controller?.cancel?.();
58
+ if (step) step.controller = null;
59
+ };
60
+
61
+ const finishFlow = () => {
62
+ if (isFinished || isCancelled) return;
63
+
64
+ started = false;
65
+ isPaused = false;
66
+ isFinished = true;
67
+
68
+ cleanupCurrentController();
69
+ abort.remove();
70
+
71
+ onFinishCallback?.();
72
+ };
73
+
74
+ const cancelFlow = () => {
75
+ if (isCancelled) return;
76
+
77
+ started = false;
78
+ isPaused = false;
79
+ isFinished = false;
80
+ isCancelled = true;
81
+
82
+ cleanupCurrentController();
83
+ abort.remove();
84
+ };
85
+
86
+ const handleError = (err, step) => {
87
+ // best hygiene: cancel current controller so nothing leaks
88
+ cancelFlow();
89
+
90
+ if (onErrorCallback) {
91
+ try {
92
+ onErrorCallback(err, {
93
+ step,
94
+ index: currentIndex,
95
+ });
96
+ } catch (_) {
97
+ // If the error handler itself throws, fall through to rethrow original.
98
+ }
99
+ return;
100
+ }
101
+
102
+ // No handler: preserve existing behavior (throw)
103
+ throw err;
104
+ };
105
+
106
+ const safeCall = (fn, stepForContext) => {
107
+ try {
108
+ return fn();
109
+ } catch (err) {
110
+ handleError(err, stepForContext);
111
+ return undefined;
112
+ }
113
+ };
114
+
115
+ const incrementStep = (step) => {
116
+ clearController(step);
117
+ currentIndex += 1;
118
+ queueMicrotask(executeNext);
119
+ };
120
+
121
+ function executeNext() {
122
+ if (isCancelled || isPaused || isFinished) return;
123
+ if (signal?.aborted) {
124
+ cancelFlow();
125
+ return;
126
+ }
127
+
128
+ // Jump handling
129
+ if (jumpTarget) {
130
+ const targetIndex = labelMap.get(jumpTarget);
131
+ if (typeof targetIndex === 'number') {
132
+ currentIndex = targetIndex;
133
+ } else {
134
+ // treat as a flow error
135
+ safeCall(() => {
136
+ throw new Error(`Label "${jumpTarget}" not found`);
137
+ }, steps[currentIndex]);
138
+ return;
139
+ }
140
+ jumpTarget = null;
141
+ }
142
+
143
+ // Handle if/unless conditions (applies to the next step only)
144
+ if (conditionStack.length > 0) {
145
+ const predicate = conditionStack.shift();
146
+ const shouldRun = safeCall(predicate, steps[currentIndex]);
147
+ if (!shouldRun) skipMode = true;
148
+ }
149
+
150
+ // Skip mode: keep skipping until we hit a label (or end)
151
+ if (skipMode) {
152
+ const next = steps[currentIndex];
153
+ if (!next || next.type === 'label') {
154
+ skipMode = false;
155
+ } else {
156
+ return incrementStep(next);
157
+ }
158
+ }
159
+
160
+ const step = steps[currentIndex];
161
+
162
+ // End of timeline
163
+ if (!step || currentIndex >= steps.length) {
164
+ if (loopEnabled && ++loopCount < loopLimit) {
165
+ currentIndex = 0;
166
+ executeNext();
167
+ } else {
168
+ finishFlow(); // ✅ only natural completion calls onFinish
169
+ }
170
+ return;
171
+ }
172
+
173
+ if (step.type === 'label') {
174
+ return incrementStep(step);
175
+ }
176
+
177
+ if (step.type === 'after') {
178
+ step.controller = after(
179
+ () => safeCall(step.fn, step),
180
+ step.duration,
181
+ { signal, onFinish: () => incrementStep(step) }
182
+ );
183
+ return;
184
+ }
185
+
186
+ if (step.type === 'every') {
187
+
188
+ // No ticks will ever fire => advance immediately.
189
+ if (!(step.times > 0) && step.times !== Infinity) {
190
+ return incrementStep(step);
191
+ }
192
+
193
+ let count = 0;
194
+ const ctrl = every(
195
+ () => {
196
+ if (isPaused || isCancelled || isFinished) return;
197
+ if (signal?.aborted) {
198
+ cancelFlow();
199
+ return;
200
+ }
201
+
202
+ // Pre-run while guard
203
+ if (step.whileCondition && !safeCall(step.whileCondition, step)) {
204
+ ctrl.cancel();
205
+ return incrementStep(step);
206
+ }
207
+
208
+ safeCall(() => step.fn(count++), step);
209
+
210
+ // Post-run doWhile guard
211
+ if (step.doWhileCondition && !safeCall(step.doWhileCondition, step)) {
212
+ ctrl.cancel();
213
+ return incrementStep(step);
214
+ }
215
+
216
+ if (count >= step.times) {
217
+ ctrl.cancel();
218
+ return incrementStep(step);
219
+ }
220
+ },
221
+ step.duration,
222
+ { max: step.times, signal }
223
+ );
224
+
225
+ step.controller = ctrl;
226
+ }
227
+ }
228
+
229
+ runner = {
230
+ after(duration, fn) {
231
+ steps.push({ type: 'after', duration, fn, controller: null });
232
+ return runner;
233
+ },
234
+
235
+ every(duration, fn, timesOrOptions = Infinity) {
236
+ const raw =
237
+ typeof timesOrOptions === 'number'
238
+ ? timesOrOptions
239
+ : timesOrOptions?.max ?? Infinity;
240
+
241
+ const times =
242
+ raw === Infinity ? Infinity : Math.max(0, raw | 0); // int >= 0
243
+
244
+ steps.push({
245
+ type: 'every',
246
+ duration,
247
+ fn,
248
+ times,
249
+ whileCondition,
250
+ doWhileCondition,
251
+ controller: null,
252
+ });
253
+
254
+ whileCondition = null;
255
+ doWhileCondition = null;
256
+ return runner;
257
+ },
258
+
259
+ loop(n = true) {
260
+ loopEnabled = true;
261
+ loopLimit = n === true ? Infinity : n;
262
+ return runner;
263
+ },
264
+
265
+ onFinish(cb) {
266
+ onFinishCallback = cb;
267
+ return runner;
268
+ },
269
+
270
+ onError(cb) {
271
+ onErrorCallback = cb;
272
+ return runner;
273
+ },
274
+
275
+ start() {
276
+ // restart hygiene: cancel any active controller from a previous run
277
+ cleanupCurrentController();
278
+
279
+ isCancelled = false;
280
+ isFinished = false;
281
+ isPaused = false;
282
+ started = true;
283
+
284
+ currentIndex = 0;
285
+ loopCount = 0;
286
+
287
+ // Abort wiring is per-run
288
+ abort.reset();
289
+ if (!signal?.aborted) abort.add();
290
+
291
+ if (signal?.aborted) {
292
+ cancelFlow(); // no-op start if already aborted
293
+ return runner;
294
+ }
295
+
296
+ executeNext();
297
+ return runner;
298
+ },
299
+
300
+ pause() {
301
+ if (isPaused || isCancelled || isFinished) return;
302
+ isPaused = true;
303
+ steps[currentIndex]?.controller?.pause?.();
304
+ },
305
+
306
+ resume() {
307
+ if (!isPaused || isCancelled || isFinished) return;
308
+ if (signal?.aborted) {
309
+ cancelFlow();
310
+ return;
311
+ }
312
+ isPaused = false;
313
+ steps[currentIndex]?.controller?.resume?.();
314
+ },
315
+
316
+ cancel() {
317
+ cancelFlow(); // ✅ never calls onFinish
318
+ },
319
+
320
+ reset() {
321
+ cancelFlow();
322
+
323
+ steps.length = 0;
324
+ labelMap.clear();
325
+
326
+ currentIndex = 0;
327
+ loopCount = 0;
328
+
329
+ onFinishCallback = null;
330
+ onErrorCallback = null;
331
+
332
+ jumpTarget = null;
333
+ conditionStack = [];
334
+ skipMode = false;
335
+
336
+ whileCondition = null;
337
+ doWhileCondition = null;
338
+
339
+ // allow reuse after reset (fresh state)
340
+ started = false;
341
+ isPaused = false;
342
+ isCancelled = false;
343
+ isFinished = false;
344
+
345
+ return runner;
346
+ },
347
+
348
+ label(name) {
349
+ labelMap.set(name, steps.length); // point to next step index
350
+ steps.push({ type: 'label', name, controller: null });
351
+ return runner;
352
+ },
353
+
354
+ jumpTo(name) {
355
+ jumpTarget = name;
356
+ return runner;
357
+ },
358
+
359
+ if(predicate) {
360
+ conditionStack.push(() =>
361
+ typeof predicate === 'function' ? !!predicate() : !!predicate
362
+ );
363
+ return runner;
364
+ },
365
+
366
+ unless(predicate) {
367
+ conditionStack.push(() =>
368
+ typeof predicate === 'function' ? !predicate() : !predicate
369
+ );
370
+ return runner;
371
+ },
372
+
373
+ while(predicate) {
374
+ whileCondition = () =>
375
+ typeof predicate === 'function' ? !!predicate() : !!predicate;
376
+ return runner;
377
+ },
378
+
379
+ doWhile(predicate) {
380
+ doWhileCondition = () =>
381
+ typeof predicate === 'function' ? !!predicate() : !!predicate;
382
+ return runner;
383
+ },
384
+
385
+ // unified lifecycle surface
386
+ get isRunning() {
387
+ return started && !isPaused && !isCancelled && !isFinished;
388
+ },
389
+ get isPaused() {
390
+ return isPaused;
391
+ },
392
+ get isCancelled() {
393
+ return isCancelled;
394
+ },
395
+ get isFinished() {
396
+ return isFinished;
397
+ },
398
+ };
399
+
400
+ return runner;
401
401
  }