uneventful 0.0.1

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/dist/mod.d.ts ADDED
@@ -0,0 +1,1895 @@
1
+ /**
2
+ * Invoke a no-argument function as a microtask, using queueMicrotask or Promise.resolve().then()
3
+ *
4
+ * @category Scheduling
5
+ */
6
+ declare let defer: (cb: () => any) => void;
7
+
8
+ /**
9
+ * Resolve a {@link Request} with a value.
10
+ *
11
+ * (For a curried version, see {@link resolver}.)
12
+ *
13
+ * @category Requests and Results
14
+ */
15
+ declare function resolve<T>(request: Request<T>, val: T): void;
16
+ /**
17
+ * Reject a {@link Request} with a reason.
18
+ *
19
+ * (For a curried version, see {@link rejecter}.)
20
+ *
21
+ * @category Requests and Results
22
+ */
23
+ declare function reject(request: Request<any>, reason: any): void;
24
+ /**
25
+ * Create a callback that will resolve the given {@link Request} with a value.
26
+ *
27
+ * @category Requests and Results
28
+ */
29
+ declare function resolver<T>(request: Request<T>): (val: T) => void;
30
+ /**
31
+ * Create a callback that will reject the given {@link Request} with a reason.
32
+ *
33
+ * @category Requests and Results
34
+ */
35
+ declare function rejecter(request: Request<any>): (err: any) => void;
36
+ /**
37
+ * A function that does nothing and returns void.
38
+ *
39
+ * @category Stream Consumers
40
+ */
41
+ declare function noop(): void;
42
+ /**
43
+ * An {@link ErrorResult} that hasn't yet been "handled" (by being passed to an
44
+ * error-specific handler, converted to a promise, given to {@link markHandled},
45
+ * etc.)
46
+ *
47
+ * @category Types and Interfaces
48
+ */
49
+ type UnhandledError = {
50
+ op: "throw";
51
+ val: undefined;
52
+ err: any;
53
+ };
54
+ /**
55
+ * An {@link ErrorResult} that has been marked "handled" (by being passed to an
56
+ * error-specific handler, converted to a promise, given to {@link markHandled},
57
+ * etc.)
58
+ *
59
+ * @category Types and Interfaces
60
+ */
61
+ type HandledError = {
62
+ op: "throw";
63
+ val: null;
64
+ err: any;
65
+ };
66
+ /**
67
+ * A result passed to a job's cleanup callbacks, or supplied by its
68
+ * .{@link Job.result result}() method.
69
+ *
70
+ * You can inspect a JobResult using functions like {@link isCancel}(),
71
+ * {@link isError}(), and {@link isValue}(). {@link getResult}() can be used to
72
+ * unwrap the value or throw the error.
73
+ *
74
+ * @category Types and Interfaces
75
+ */
76
+ type JobResult<T> = ValueResult<T> | ErrorResult | CancelResult;
77
+ /**
78
+ * A {@link JobResult} that indicates the job was canceled by its creator (via
79
+ * end() or restart()).
80
+ *
81
+ * @category Types and Interfaces
82
+ */
83
+ type CancelResult = {
84
+ op: "cancel";
85
+ val: undefined;
86
+ err: undefined;
87
+ };
88
+ /**
89
+ * The {@link JobResult} used to indicate a canceled job.
90
+ *
91
+ * @category Requests and Results
92
+ */
93
+ declare const CancelResult: Readonly<CancelResult>;
94
+ /**
95
+ * A {@link JobResult} that indicates the job was ended via a return() value.
96
+ *
97
+ * @category Types and Interfaces
98
+ */
99
+ type ValueResult<T> = {
100
+ op: "next";
101
+ val: T;
102
+ err: undefined;
103
+ };
104
+ /**
105
+ * Create a {@link ValueResult} from a value
106
+ *
107
+ * @category Requests and Results
108
+ */
109
+ declare function ValueResult<T>(val: T): ValueResult<T>;
110
+ /**
111
+ * A {@link JobResult} that indicates the job was ended via a throw() or other
112
+ * error.
113
+ *
114
+ * @category Types and Interfaces
115
+ */
116
+ type ErrorResult = UnhandledError | HandledError;
117
+ /**
118
+ * Create an {@link ErrorResult} from an error
119
+ *
120
+ * @category Requests and Results
121
+ */
122
+ declare function ErrorResult(err: any): UnhandledError;
123
+ /**
124
+ * Returns true if the given result is a {@link CancelResult}.
125
+ *
126
+ * @category Requests and Results
127
+ */
128
+ declare function isCancel(res: JobResult<any> | undefined): res is CancelResult;
129
+ /**
130
+ * Returns true if the given result is a {@link ValueResult}.
131
+ *
132
+ * @category Requests and Results
133
+ */
134
+ declare function isValue<T>(res: JobResult<T> | undefined): res is ValueResult<T>;
135
+ /**
136
+ * Returns true if the given result is a {@link ErrorResult}.
137
+ *
138
+ * @category Requests and Results
139
+ */
140
+ declare function isError(res: JobResult<any> | undefined): res is ErrorResult;
141
+ /**
142
+ * Returns true if the given result is an {@link UnhandledError}.
143
+ *
144
+ * @category Requests and Results
145
+ */
146
+ declare function isUnhandled(res: JobResult<any> | undefined): res is UnhandledError;
147
+ /**
148
+ * Returns true if the given result is a {@link HandledError} (an
149
+ * {@link ErrorResult} that has been touched by {@link markHandled}).
150
+ *
151
+ * @category Requests and Results
152
+ */
153
+ declare function isHandled(res: JobResult<any> | undefined): res is HandledError;
154
+ /**
155
+ * Return the error of an {@link ErrorResult} and mark it as handled. The
156
+ * {@link ErrorResult} is mutated in-place to become a {@link HandledError}.
157
+ *
158
+ * @category Requests and Results
159
+ */
160
+ declare function markHandled(res: ErrorResult): any;
161
+ /**
162
+ * Get the return value from a {@link JobResult}, throwing an appropriate error
163
+ * if the result isn't a {@link ValueResult}.
164
+ *
165
+ * @param res The job result you want to unwrap. Must not be undefined!
166
+ *
167
+ * @returns The value if the result is a {@link ValueResult}, or a thrown error
168
+ * if it's an {@link ErrorResult}. A {@link CancelError} is thrown if the job
169
+ * was canceled, or the error in the result is thrown.
170
+ *
171
+ * If the result is an error, it is marked as handled.
172
+ *
173
+ * @category Jobs
174
+ */
175
+ declare function getResult<T>(res: JobResult<T>): T;
176
+ /**
177
+ * Fulfill a Promise from a {@link JobResult}
178
+ *
179
+ * If the result is a {@link CancelResult}, the promise is rejected with a
180
+ * {@link CancelError}. Otherwise it is resolved or rejected according to the
181
+ * state of the result.
182
+ *
183
+ * @param resolve A value-taking function (first arg to `new Promise` callback)
184
+ *
185
+ * @param reject An error-taking function (second arg to `new Promise` callback)
186
+ *
187
+ * @param res The job result you want to settle the promise with. An error will
188
+ * be thrown if it's undefined.
189
+ *
190
+ * If the result is an error, it is marked as handled.
191
+ *
192
+ * @category Requests and Results
193
+ */
194
+ declare function fulfillPromise<T>(resolve: (v: T) => void, reject: (e: any) => void, res: JobResult<T>): void;
195
+ /**
196
+ * Propagate a {@link JobResult} to another job
197
+ *
198
+ * If the result is a {@link CancelResult}, the job will throw with a
199
+ * {@link CancelError}. Otherwise it is resolved or rejected according to the
200
+ * state of the result.
201
+ *
202
+ * @param job The job to terminate. If it's already ended, nothing changes: the
203
+ * result is not propagated and the error (if any) is not marked as handled.
204
+ *
205
+ * @param res The job result you want to settle the job with. An error will be
206
+ * thrown if it's undefined. If the result is an error, it is marked as
207
+ * handled.
208
+ *
209
+ * @category Requests and Results
210
+ */
211
+ declare function propagateResult<T>(job: Job<T>, res: JobResult<T>): void;
212
+ /**
213
+ * Error thrown when waiting for a result from a job that is canceled.
214
+ *
215
+ * If you `await`, `yield *`, `.then()`, `.catch()`, {@link getResult}() or
216
+ * otherwise wait on the result of a job that is canceled, this is the type
217
+ * of error you'll get.
218
+ *
219
+ * @category Errors
220
+ */
221
+ declare class CancelError extends Error {
222
+ }
223
+
224
+ /**
225
+ * The result type returned from calls to {@link Each}.next()
226
+ *
227
+ * @category Types and Interfaces
228
+ */
229
+ type EachResult<T> = {
230
+ /** The value provided by the source being iterated */
231
+ item: T;
232
+ /**
233
+ * A suspend callback that must be `yield`-ed before the next call to the
234
+ * iterator's .next() method. (That is, you must `yield next` it exactly once
235
+ * per loop pass. See {@link each}() for more details.)
236
+ */
237
+ next: Suspend<void>;
238
+ };
239
+ /**
240
+ * The iterable returned by `yield *` {@link each}()
241
+ *
242
+ * @category Types and Interfaces
243
+ */
244
+ type Each<T> = IterableIterator<EachResult<T>>;
245
+ /**
246
+ * Asynchronously iterate over an event source
247
+ *
248
+ * Usage:
249
+ *
250
+ * ```ts
251
+ * for (const {item: event, next} of yield *each(mouseMove)) {
252
+ * console.log(event.clientX, event.clientY);
253
+ * yield next; // required exactly once per iteration, even/w continue!
254
+ * }
255
+ * ```
256
+ *
257
+ * each(eventSource) yield-returns an iterator of `{item, next}` pairs. The
258
+ * item is the data supplied by the event source, and `next` is a
259
+ * {@link Suspend}\<void\> that advances the iterator to the next item. It
260
+ * *must* be yielded exactly once per loop iteration. If you use `continue` to
261
+ * shortcut the loop body, you must `yield next` *before* doing so.
262
+ *
263
+ * The for-loop will end if the source ends, errors, or is canceled. The source
264
+ * is paused while the loop body is running, and resumed when the `yield next`
265
+ * happens. If events arrive anyway (e.g. because the source doesn't support
266
+ * pausing), they will be ignored unless you pipe the source through the
267
+ * {@link slack}() operator to provide a buffer. If the for-loop is exited
268
+ * early for any reason (or the iterator's `.return()` is called), the source is
269
+ * unsubscribed and the iteration ended.
270
+ *
271
+ * @category Stream Consumers
272
+ */
273
+ declare function each<T>(src: Source<T>): Yielding<Each<T>>;
274
+ /**
275
+ * An object that can be waited on with `yield *until()`.
276
+ *
277
+ * @category Types and Interfaces
278
+ */
279
+ type Waitable<T> = UntilMethod<T> | Source<T> | Promise<T> | PromiseLike<T>;
280
+ /**
281
+ * An object that can be waited on with `yield *until()`, by calling its
282
+ * "uneventful.until" method.
283
+ *
284
+ * @category Types and Interfaces
285
+ */
286
+ interface UntilMethod<T> {
287
+ "uneventful.until"(): Yielding<T>;
288
+ }
289
+ /**
290
+ * Wait for and return next value (or error) from a data source when processed
291
+ * with `yield *` within a {@link Job}.
292
+ *
293
+ * @param source A {@link Waitable} data source, which can be any of:
294
+ * - A {@link Signal} (in which case the job will resume when the value is
295
+ * truthy - perhaps immediately!)
296
+ * - A {@link Source}
297
+ * - A promise, or promise-like object with a `.then()` method
298
+ * - An object with an `"uneventful.until"` method returning a {@link Yielding}
299
+ * (in which case the result will be the the result of that method)
300
+ *
301
+ * @returns a Yieldable that when processed with `yield *` in a job, will return
302
+ * the triggered event, promise resolution, or signal value. An error is thrown
303
+ * if the promise rejects or the event stream throws or closes early, or the
304
+ * signal throws.
305
+ *
306
+ * @category Scheduling
307
+ */
308
+ declare function until<T>(source: Waitable<T>): Yielding<T>;
309
+
310
+ /**
311
+ * Error indicating a rule has attempted to write a value it indirectly
312
+ * depends on, or which has already been read by another rule in the current
313
+ * batch. (Also thrown when a cached function attempts to write a value at all,
314
+ * directly or inidirectly.)
315
+ *
316
+ * @category Errors
317
+ */
318
+ declare class WriteConflict extends Error {
319
+ }
320
+ /**
321
+ * Error indicating a rule has attempted to write a value it directly depends
322
+ * on, or a cached function has called itself, directly or indirectly.
323
+ *
324
+ * @category Errors
325
+ */
326
+ declare class CircularDependency extends Error {
327
+ }
328
+ /**
329
+ * A queue for rules to run during a particular kind of period, such as
330
+ * microtasks or animation frames. (Can only be obtained or created via
331
+ * {@link RuleScheduler.for}().)
332
+ *
333
+ * @category Signals
334
+ */
335
+ declare class RuleScheduler {
336
+ /**
337
+ * Run all pending rules on this scheduler.
338
+ *
339
+ * This is a bound method
340
+ *
341
+ * (Note: "pending" rules are ones with at least one changed ancestor
342
+ * dependency; this doesn't mean they will actually *do* anything,
343
+ * since intermediate cached() function results might end up unchanged.)
344
+ */
345
+ flush: () => void;
346
+ /**
347
+ * Create an {@link RuleScheduler} from a callback-taking function, that
348
+ * you can then use to make rules that run in a specific time frame.
349
+ *
350
+ * ```ts
351
+ * // frame.rule will now create rules that run during animation fames
352
+ * const animate = RuleScheduler.for(requestAnimationFrame).rule;
353
+ *
354
+ * animate(() => {
355
+ * // ... do stuff in an animation frame when signals used here change
356
+ * })
357
+ * ```
358
+ *
359
+ * Returns the default scheduler if no arguments are given. If called with
360
+ * the same function more than once, it returns the same scheduler instance.
361
+ *
362
+ * @param scheduleFn A single-argument scheduling function (like
363
+ * requestAnimationFrame, setImmediate, or queueMicrotask). The scheduler
364
+ * will call it from time to time with a single callback. The scheduling
365
+ * function should then arrange for that callback to be invoked *once* at
366
+ * some future point, when it is the desired time for all pending rules on
367
+ * that scheduler to run.
368
+ */
369
+ static for(scheduleFn?: (cb: () => unknown) => unknown): RuleScheduler;
370
+ protected constructor(_scheduleFn?: (cb: () => unknown) => unknown);
371
+ /**
372
+ * @inheritdoc rule tied to a specific scheduler. See {@link rule} for
373
+ * more details.
374
+ *
375
+ * @remarks The rule will only run during its matching
376
+ * {@link RuleScheduler.flush}().
377
+ *
378
+ * This is a bound method, so you can use it independently of the scheduler
379
+ * it came from.
380
+ */
381
+ rule: (fn: (stop: DisposeFn) => OptionalCleanup) => DisposeFn;
382
+ }
383
+ /**
384
+ * Subscribe a function to run every time certain values change.
385
+ *
386
+ * @remarks
387
+ * The function is run asynchronously, first after being created, then again
388
+ * after there are changes in any of the values or cached functions it read
389
+ * during its previous run.
390
+ *
391
+ * The created subscription is tied to the currently-active job (which may be
392
+ * another rule). So when that job is ended or restarted, the rule will be
393
+ * terminated automatically. You can also terminate it early by calling the
394
+ * "stop" function that is both passed to the rule function and returned by
395
+ * `rule()`.
396
+ *
397
+ * Note: this function will throw an error if called without an active job. If
398
+ * you need a standalone rule, use {@link detached}.run to wrap the
399
+ * call to rule.
400
+ *
401
+ * @param fn The function that will be run each time its dependencies change.
402
+ * The function will be run in a restarted job each time, with any resources
403
+ * used by the previous run being cleaned up. The function is passed a single
404
+ * argument: a function that can be called to terminate the rule. The function
405
+ * should return a cleanup function or void.
406
+ *
407
+ * @returns A function that can be called to terminate the rule.
408
+ *
409
+ * @category Signals
410
+ */
411
+ declare const rule: (fn: (stop: DisposeFn) => OptionalCleanup) => DisposeFn;
412
+ /**
413
+ * Synchronously run pending rules from the default scheduler.
414
+ *
415
+ * @remarks Equivalent to calling
416
+ * {@link RuleScheduler.for}(defer).{@link RuleScheduler.flush flush}().
417
+ *
418
+ * Note that you should normally only need to call this when you need
419
+ * side-effects to occur within a specific synchronous timeframe, e.g. if
420
+ * rules need to be able to cancel a synchronous event or continue an
421
+ * IndexedDB transaction. (You can also define rules to run in a specific
422
+ * timeframe by creating a {@link RuleScheduler} for them, via
423
+ * {@link RuleScheduler.for}.)
424
+ *
425
+ * @category Signals
426
+ */
427
+ declare const runRules: () => void;
428
+
429
+ interface Signal<T> {
430
+ /**
431
+ * A signal object implements the {@link Producer} interface, even if it's
432
+ * not directly recognized as one by TypeScript.
433
+ */
434
+ (sink: Sink<T>, conn?: Connection, inlet?: Inlet): typeof IsStream;
435
+ /** A signal object can be called to get its current value */
436
+ (): T;
437
+ }
438
+ /**
439
+ * An observable value, as a zero-argument callable with extra methods.
440
+ *
441
+ * Note: this class is not directly instantiable - use {@link cached}() or call
442
+ * {@link readonly |.readonly()} on an existing signal instead.
443
+ *
444
+ * @category Types and Interfaces
445
+ */
446
+ declare class Signal<T> extends Function implements UntilMethod<T> {
447
+ /** The current value */
448
+ get value(): T;
449
+ /** The current value */
450
+ valueOf(): T;
451
+ /** The current value, as a string */
452
+ toString(): string;
453
+ /** The current value */
454
+ toJSON(): T;
455
+ /** Get the signal's current value, without adding the signal as a dependency */
456
+ peek(): T;
457
+ /** Get a read-only version of this signal */
458
+ readonly(): Signal<T>;
459
+ /** New writable signal with a custom setter */
460
+ withSet(set: (v: T) => unknown): Writable<T>;
461
+ "uneventful.until"(): Yielding<T>;
462
+ protected constructor();
463
+ }
464
+ interface Writable<T> {
465
+ /** Set the current value. (Note: this is a bound method so it can be used as a callback.) */
466
+ set(val: T): void;
467
+ }
468
+ /**
469
+ * A {@link Signal} with a {@link Writable.set | .set()} method and writable
470
+ * {@link Writable.value | .value} property.
471
+ *
472
+ * Note: this class is not directly instantiable - use {@link value}() or call
473
+ * {@link Signal.withSet | .withSet()} on an existing signal instead.
474
+ *
475
+ * @category Types and Interfaces
476
+ */
477
+ declare class Writable<T> extends Signal<T> {
478
+ get value(): T;
479
+ set value(val: T);
480
+ readonly(): Signal<T>;
481
+ }
482
+ /**
483
+ * Create a {@link Writable} signal with the given inital value
484
+ *
485
+ * @category Signals
486
+ */
487
+ declare function value<T>(val?: T): Writable<T>;
488
+ /**
489
+ * Create a cached version of a function. The returned callable is also a
490
+ * {@link Signal}.
491
+ *
492
+ * Note: If the supplied function has a non-zero `.length` (i.e., it explicitly
493
+ * takes arguments), it is assumed to be a {@link Source}, and the second
494
+ * calling signature below will apply, even if TypeScript doesn't see it that
495
+ * way!)
496
+ *
497
+ * @category Signals
498
+ */
499
+ declare function cached<T>(compute: () => T): Signal<T>;
500
+ /**
501
+ * If the supplied function has a non-zero `.length` (i.e., it explicitly takes
502
+ * arguments), it is assumed to be a {@link Source}, and the second argument is
503
+ * a default value for the created signal to use as default value until the
504
+ * source produces a value.
505
+ *
506
+ * The source will be subscribed *only* while the signal is subscribed as a
507
+ * stream, or observed (directly or indirectly) by a rule. While subscribed,
508
+ * the signal will update itself with the most recent value produced by the
509
+ * source, triggering rules or events as appropriate if the value changes. When
510
+ * the signal is once again unobserved, it will revert to the supplied inital
511
+ * value.
512
+ *
513
+ * @param source A {@link Source} providing data which will become this signal's value
514
+ * @param initVal The value to use when the signal is unobserved or waiting for the
515
+ * first item from the source.
516
+ */
517
+ declare function cached<T>(source: Source<T>, initVal?: T): Signal<T>;
518
+ declare function cached<T extends Signal<any>>(signal: T): T;
519
+ /**
520
+ * Call a function without creating a dependency on any signals it reads. (Like
521
+ * {@link Signal.peek}, but for any function with any arguments.)
522
+ *
523
+ * You can also pass in any arguments the function takes, and the function's
524
+ * return value is returned.
525
+ *
526
+ * @returns The result of calling `fn(..args)`
527
+ *
528
+ * @category Signals
529
+ */
530
+ declare function noDeps<F extends PlainFunction>(fn: F, ...args: Parameters<F>): ReturnType<F>;
531
+ /**
532
+ * Arrange for the current signal or rule to recalculate on demand
533
+ *
534
+ * This lets you interop with systems that have a way to query a value and
535
+ * subscribe to changes to it, but not directly produce a signal. (Such as
536
+ * querying the DOM state and using a MutationObserver.)
537
+ *
538
+ * By calling this with a {@link Source} or {@link RecalcSource}, you arrange
539
+ * for it to be subscribed, if and when the call occurs in a rule or a cached
540
+ * function that's in use by a rule (directly or indirectly). When the source
541
+ * emits a value, the signal machinery will invalidate the caching of the
542
+ * function or rule, forcing a recalculation and subsequent rule reruns, if
543
+ * applicable.
544
+ *
545
+ * Note: you should generally only call the 1-argument version of this function
546
+ * with "static" sources - i.e. ones that won't change on every call. Otherwise,
547
+ * you will end up creating new signals each time, subscribing and unsubscribing
548
+ * on every call to recalcWhen().
549
+ *
550
+ * If the source needs to reference some object, it's best to use the 2-argument
551
+ * version (i.e. `changesWhen(someObj, factory)`, where `factory` is a function
552
+ * that takes `someObj` and returns a suitable {@link RecalcSource}.)
553
+ *
554
+ * @remarks
555
+ * recalcWhen is specifically designed so that using it does not pull in any
556
+ * part of Uneventful's signals framework, in the event a program doesn't
557
+ * already use it. This means you can use it in library code to provide signal
558
+ * compatibility, without adding bundle bloat to code that doesn't use signals.
559
+ *
560
+ * @category Signals
561
+ */
562
+ declare function recalcWhen(src: RecalcSource): void;
563
+ /**
564
+ * Two-argument variant of recalcWhen
565
+ *
566
+ * In certain circumstances, you may wish to use recalcWhen with a source
567
+ * related to some object. You could call recalcWhen with a closure, but that
568
+ * would create and discard signals on every call. So this 2-argument version
569
+ * lets you avoid that by allowing the use of an arbitrary object as a key,
570
+ * along with a factory function to turn the key into a {@link RecalcSource}.
571
+ *
572
+ * @param key an object to be used as a key
573
+ *
574
+ * @param factory a function that will be called with the key to obtain a
575
+ * {@link RecalcSource}. Note that this factory function must also be a static
576
+ * function, not a closure, or the same memory thrash issue will occur.
577
+ */
578
+ declare function recalcWhen<T extends WeakKey>(key: T, factory: (key: T) => RecalcSource): void;
579
+
580
+ /**
581
+ * A backpressure controller: returns true if downstream is ready to accept
582
+ * data.
583
+ *
584
+ * @param cb (optional) - a callback to run when the downstream consumer wishes
585
+ * to resume event production (i.e., when a sink calls
586
+ * {@link Throttle.resume}()). The callback is automatically unregistered when
587
+ * invoked, so the producer must re-register it after each call if it wishes to
588
+ * keep being called.
589
+ *
590
+ * @category Types and Interfaces
591
+ */
592
+ type Backpressure = (cb?: () => any) => boolean;
593
+ /**
594
+ * Create a backpressure control function for the given connection
595
+ *
596
+ * @category Stream Producers
597
+ */
598
+ declare function backpressure(inlet?: Inlet): Backpressure;
599
+ /**
600
+ * Control backpressure for listening streams. This interface is the API
601
+ * internal to the implementation of {@link backpressure}(). Unless you're
602
+ * implementing a backpressurable stream yourself, see the {@link Throttle}
603
+ * interface instead.
604
+ *
605
+ * @category Types and Interfaces
606
+ */
607
+ interface Inlet {
608
+ /** Is the main connection open? (i.e. is the creating job not closed yet?) */
609
+ isOpen(): boolean;
610
+ /** Is the conduit currently ready to receive data? */
611
+ isReady(): boolean;
612
+ /**
613
+ * Register a callback to produce more data when the inlet is resumed
614
+ * (The callback is unregistered if the supplied job ends.)
615
+ */
616
+ onReady(cb: () => any, job: Job): this;
617
+ }
618
+ /**
619
+ * Control backpressure for listening streams
620
+ *
621
+ * Obtain instances via {@link throttle}(), then pass them into the appropriate
622
+ * stream-consuming API. (e.g. {@link connect}).
623
+ *
624
+ * @category Types and Interfaces
625
+ */
626
+ interface Throttle extends Inlet {
627
+ /** Set inlet status to "paused". */
628
+ pause(): void;
629
+ /**
630
+ * Un-pause, and iterate backpressure-able sources' onReady callbacks to
631
+ * resume sending immediately. (i.e., synchronously!)
632
+ */
633
+ resume(): void;
634
+ }
635
+ /**
636
+ * A Connection is a job that returns void when the connected stream ends
637
+ * itself. If the stream doesn't end itself (e.g. it's an event listener), the
638
+ * job will never return, and only end with a cancel or throw.
639
+ *
640
+ * @category Types and Interfaces
641
+ */
642
+ type Connection = Job<void>;
643
+ /**
644
+ * A Producer is a function that can be called to arrange for data to be
645
+ * produced and sent to a {@link Sink} function for consumption, until the
646
+ * associated {@link Connection} is closed (either by the source or the sink,
647
+ * e.g. if the sink doesn't want more data or the source has no more to send).
648
+ *
649
+ * If the source is a backpressurable stream, it can use the (optional) supplied
650
+ * inlet (usually a {@link throttle}()) to rate-limit its output.
651
+ *
652
+ * A producer function *must* return the special {@link IsStream} value, so
653
+ * TypeScript can tell what functions are usable as sources. (Otherwise any
654
+ * void function with no arguments would appear to be usable as a source!)
655
+ *
656
+ * @category Types and Interfaces
657
+ */
658
+ type Producer<T> = (sink: Sink<T>, conn?: Connection, inlet?: Throttle | Inlet) => typeof IsStream;
659
+ /**
660
+ * A Source is either a {@link Producer} or a {@link Signal}. (Signals actually
661
+ * implement the {@link Producer} interface as an overload, but TypeScript gets
662
+ * confused about that sometimes, so we generally declare our stream *inputs* as
663
+ * `Source<T>` and our stream *outputs* as {@link Producer}, so that TypeScript
664
+ * knows what's what.
665
+ *
666
+ * @category Types and Interfaces
667
+ */
668
+ type Source<T> = Producer<T> | Signal<T> | Writable<T>;
669
+ /**
670
+ * A specially-typed string used to verify that a function supports uneventful's
671
+ * streaming protocol. Return it from a function to implement the
672
+ * {@link Source} type.
673
+ *
674
+ * @category Types and Interfaces
675
+ */
676
+ declare const IsStream: "uneventful/is-stream";
677
+ /**
678
+ * A `Sink` is a function that receives data from a {@link Source}.
679
+ *
680
+ * @category Types and Interfaces
681
+ */
682
+ type Sink<T> = (val: T) => void;
683
+ /**
684
+ * A `Transformer` is a function that takes one source and returns another,
685
+ * possibly one that produces data of a different type. Most operator functions
686
+ * return a transformer, allowing them to be combined via {@link pipe}().
687
+ *
688
+ * @category Types and Interfaces
689
+ */
690
+ type Transformer<T, V = T> = (input: Source<T>) => Producer<V>;
691
+ /**
692
+ * Subscribe a sink to a source, returning a nested job. (Shorthand for
693
+ * {@link getJob}().{@link Job.connect connect}(...).)
694
+ *
695
+ * @param src An event source or finite data stream
696
+ * @param sink A callback that will receive the events
697
+ * @param inlet Optional - a {@link throttle}() to control backpressure
698
+ *
699
+ * @returns A job that can be aborted to end the subscription, and which will
700
+ * end naturally (with a void return or error) if the stream ends itself.
701
+ *
702
+ * @category Stream Consumers
703
+ */
704
+ declare function connect<T>(src: Source<T>, sink: Sink<T>, inlet?: Throttle | Inlet): Connection;
705
+ /**
706
+ * Create a backpressure controller for a stream. Pass it to one or more
707
+ * sources you're connecting to, and if they support backpressure they'll
708
+ * respond when you call its .pause() and .resume() methods.
709
+ *
710
+ * @param job - Optional: a job that controls readiness. (The throttle will
711
+ * pause indefinitely when the job ends.) Defaults to the currently-active job,
712
+ * but unlike most such defaults, it won't throw if no job is active.
713
+ *
714
+ * @category Stream Consumers
715
+ */
716
+ declare function throttle(job?: Job): Throttle;
717
+ /**
718
+ * Pipe a stream (or anything else) through a series of single-argument
719
+ * functions/operators
720
+ *
721
+ * e.g. the following creates a stream that outputs 4 and then 6:
722
+ *
723
+ * ```ts
724
+ * pipe(fromIterable([1,2,3,4]), skip(1), take(2), map(x => x*2))
725
+ * ```
726
+ *
727
+ * The first argument to pipe() can be any value, but all other arguments must
728
+ * be functions. The value is passed to the first function, and then the result
729
+ * is passed to the next function in turn, until all provided functions have
730
+ * been called with the result of the previous function. The return value is
731
+ * the last result, or the original value if no functions were given.
732
+ *
733
+ * The underlying implementation of pipe() works with any number of arguments,
734
+ * but due to TypeScript limitations we only have typing defined for a max of 9
735
+ * functions (10 arguments total). If you need more than 9 functions, you can
736
+ * stack some of them with {@link compose}(), e.g.:
737
+ *
738
+ * ```typescript
739
+ * pipe(
740
+ * aStream,
741
+ * compose(op1, op2, ...),
742
+ * compose(op10, op11, ...),
743
+ * compose(op19, ...),
744
+ * ...
745
+ * )
746
+ * ```
747
+ *
748
+ * @category Stream Operators
749
+ */
750
+ declare function pipe<A, B, C, D, E, F, G, H, I, J>(input: A, ...fns: Chain9<A, J, B, C, D, E, F, G, H, I>): J;
751
+ declare function pipe<A, B, C, D, E, F, G, H, I>(input: A, ...fns: Chain8<A, I, B, C, D, E, F, G, H>): I;
752
+ declare function pipe<A, B, C, D, E, F, G, H>(input: A, ...fns: Chain7<A, H, B, C, D, E, F, G>): H;
753
+ declare function pipe<A, B, C, D, E, F, G>(input: A, ...fns: Chain6<A, G, B, C, D, E, F>): G;
754
+ declare function pipe<A, B, C, D, E, F>(input: A, ...fns: Chain5<A, F, B, C, D, E>): F;
755
+ declare function pipe<A, B, C, D, E>(input: A, ...fns: Chain4<A, E, B, C, D>): E;
756
+ declare function pipe<A, B, C, D>(input: A, ...fns: Chain3<A, D, B, C>): D;
757
+ declare function pipe<A, B, C>(input: A, ...fns: Chain2<A, C, B>): C;
758
+ declare function pipe<A, B>(input: A, ...fns: Chain1<A, B>): B;
759
+ declare function pipe<A>(input: A): A;
760
+ declare function pipe(input: any, ...fns: Array<(v: any) => any>): any;
761
+ /**
762
+ * Compose a series of single-argument functions/operators in application order.
763
+ * (This is basically a deferred version of {@link pipe}().) For example:
764
+ *
765
+ * ```ts
766
+ * const func = compose(skip(1), take(2), map(x => x*2));
767
+ * const stream_4_6 = func(fromIterable([1,2,3,4])); // stream that outputs 4, 6
768
+ * ```
769
+ *
770
+ * As with `pipe()`, the declared typings only support composing up to 9
771
+ * functions at once; if you need more you'll need to nest calls to `compose()`
772
+ * (i.e. passing the result of a `compose()` as an argument to another
773
+ * `compose()` call.)
774
+ *
775
+ * @returns A function taking the same type as the first input function,
776
+ * returning the same type as the last input function.
777
+ *
778
+ * @category Stream Operators
779
+ */
780
+ declare function compose<A, B, C, D, E, F, G, H, I, J>(...fns: Chain9<A, J, B, C, D, E, F, G, H, I>): (a: A) => J;
781
+ declare function compose<A, B, C, D, E, F, G, H, I>(...fns: Chain8<A, I, B, C, D, E, F, G, H>): (a: A) => I;
782
+ declare function compose<A, B, C, D, E, F, G, H>(...fns: Chain7<A, H, B, C, D, E, F, G>): (a: A) => H;
783
+ declare function compose<A, B, C, D, E, F, G>(...fns: Chain6<A, G, B, C, D, E, F>): (a: A) => G;
784
+ declare function compose<A, B, C, D, E, F>(...fns: Chain5<A, F, B, C, D, E>): (a: A) => F;
785
+ declare function compose<A, B, C, D, E>(...fns: Chain4<A, E, B, C, D>): (a: A) => E;
786
+ declare function compose<A, B, C, D>(...fns: Chain3<A, D, B, C>): (a: A) => D;
787
+ declare function compose<A, B, C>(...fns: Chain2<A, C, B>): (a: A) => C;
788
+ declare function compose<A, B>(...fns: Chain1<A, B>): (a: A) => B;
789
+ declare function compose<A>(): (a: A) => A;
790
+ type Chain1<A, R> = [(v: A) => R];
791
+ type Chain2<A, R, B> = [...Chain1<A, B>, ...Chain1<B, R>];
792
+ type Chain3<A, R, B, C> = [...Chain1<A, B>, ...Chain2<B, R, C>];
793
+ type Chain4<A, R, B, C, D> = [...Chain1<A, B>, ...Chain3<B, R, C, D>];
794
+ type Chain5<A, R, B, C, D, E> = [...Chain1<A, B>, ...Chain4<B, R, C, D, E>];
795
+ type Chain6<A, R, B, C, D, E, F> = [...Chain1<A, B>, ...Chain5<B, R, C, D, E, F>];
796
+ type Chain7<A, R, B, C, D, E, F, G> = [...Chain1<A, B>, ...Chain6<B, R, C, D, E, F, G>];
797
+ type Chain8<A, R, B, C, D, E, F, G, H> = [...Chain1<A, B>, ...Chain7<B, R, C, D, E, F, G, H>];
798
+ type Chain9<A, R, B, C, D, E, F, G, H, I> = [...Chain1<A, B>, ...Chain8<B, R, C, D, E, F, G, H, I>];
799
+ /**
800
+ * Pass subscriber into a stream (or any arguments into any other function).
801
+ *
802
+ * This utility is mainly here for uses like:
803
+ *
804
+ * - `pipe(src, into(sink))`,
805
+ * - `pipe(src, into(sink, conn))`,
806
+ * - `pipe(src, into(restarting(sink)))`, etc.
807
+ *
808
+ * but can also be used for argument currying generally.
809
+ *
810
+ * @param args The arguments to pass to the stream (or other function)
811
+ *
812
+ * @returns a function that takes another function and calls it with the given args.
813
+ *
814
+ * @category Stream Consumers
815
+ */
816
+ declare function into<In extends any[], Out>(...args: In): (src: (...args: In) => Out) => Out;
817
+
818
+ /**
819
+ * An undefined or null value
820
+ *
821
+ * @category Types and Interfaces
822
+ */
823
+ type Nothing = undefined | null | void;
824
+ /**
825
+ * A function without a `this`
826
+ *
827
+ * @category Types and Interfaces
828
+ */
829
+ type PlainFunction = (this: void, ...args: any[]) => any;
830
+ /**
831
+ * Any function
832
+ *
833
+ * @category Types and Interfaces
834
+ */
835
+ type AnyFunction = (...args: any[]) => any;
836
+ /**
837
+ * A cleanup function is a callback invoked when a job is ended or restarted.
838
+ * It receives a result that indicates whether the job ended itself with a return
839
+ * value or error, or was canceled/restarted by its creator.
840
+ *
841
+ * @category Types and Interfaces
842
+ */
843
+ type CleanupFn<T = any> = (res: JobResult<T>) => unknown;
844
+ /**
845
+ * A function that can be called to dispose of something or unsubscribe
846
+ * something. It's called without arguments and returns void.
847
+ *
848
+ * @category Types and Interfaces
849
+ */
850
+ type DisposeFn = () => void;
851
+ /**
852
+ * An optional cleanup parameter or return.
853
+ *
854
+ * @category Types and Interfaces
855
+ */
856
+ type OptionalCleanup<T = any> = CleanupFn<T> | Nothing;
857
+ /**
858
+ * An asynchronous start function is called immediately in the new job and must
859
+ * return a {@link StartObj}, such as a job, generator, or promise. If a job or
860
+ * promise is returned, it will be awaited and its result used to asynchronously
861
+ * set the result of the returned job.
862
+ *
863
+ * If a generator is returned, it will be run asynchronously, in the context of
864
+ * the newly-started job. Any result it returns or error it throws will be
865
+ * treated as the result of the job. If the job is canceled, the iterator's
866
+ * `.return()` method will be called to abort it (thereby running any
867
+ * try-finally clauses in the generator), and the result of the call will be
868
+ * otherwise ignored.
869
+ *
870
+ * @template T The type the job will end up returning
871
+ * @template This The type of `this` the function accepts, if using two-argument
872
+ * start(). Defaults to void (for one-argument start()).
873
+ *
874
+ * @category Types and Interfaces
875
+ */
876
+ type AsyncStart<T, This = void> = (this: This, job: Job<T>) => StartObj<T>;
877
+ /**
878
+ * A synchronous start function returns void. It runs immediately and gets
879
+ * passed the newly created job as its first argument.
880
+ *
881
+ * @template T The type the job will end up returning
882
+ * @template This The type of `this` the function accepts, if using two-argument
883
+ * start(). Defaults to void (for one-argument start()).
884
+ *
885
+ * @category Types and Interfaces
886
+ */
887
+ type SyncStart<T, This = void> = (this: This, job: Job<T>) => void;
888
+ /**
889
+ * A synchronous or asynchronous initializing function for use with the
890
+ * {@link start}() function or a job's {@link Job.start .start}() method.
891
+ *
892
+ * @template T The type the job will end up returning
893
+ * @template This The type of `this` the function accepts, if using two-argument
894
+ * start(). Defaults to void (for one-argument start()).
895
+ *
896
+ * @category Types and Interfaces
897
+ */
898
+ type StartFn<T, This = void> = AsyncStart<T, This> | SyncStart<T, This>;
899
+ /**
900
+ * An object that can be passed as a single argument to {@link start}() or a
901
+ * job's {@link Job.start .start}() method, such as a job, generator, or
902
+ * promise.
903
+ *
904
+ * @category Types and Interfaces
905
+ */
906
+ type StartObj<T> = Yielding<T> | Promise<T> | PromiseLike<T>;
907
+ /**
908
+ * A cancellable asynchronous operation with automatic resource cleanup.
909
+ *
910
+ * You can add cleanup callbacks to a job via {@link must}() or its
911
+ * .{@link must}() method. When the job is ended or canceled, the callbacks
912
+ * are (synchronously) run in reverse order -- a bit like a delayed and
913
+ * distributed collection of `finally` blocks.
914
+ *
915
+ * Jobs implement the Promise interface (then, catch, and finally) so they can
916
+ * be passed to Promise-using APIs or awaited by async functions. They also
917
+ * implement {@link Yielding}, so you can await their results from a
918
+ * {@link start}() using `yield *`. They also have
919
+ * {@link Job.return \.return()} and {@link Job.throw \.throw()} methods so
920
+ * you can end a job with a result or error.
921
+ *
922
+ * Most jobs, however, are not intended to produce results, and are merely
923
+ * canceled (using {@link Job.end \.end()} or
924
+ * {@link Job.restart \.restart()}).
925
+ *
926
+ * Jobs can be created and accessed using {@link start}(),
927
+ * {@link detached}.start(), {@link makeJob}(), and {@link getJob}().
928
+ *
929
+ * @category Types and Interfaces
930
+ */
931
+ interface Job<T = any> extends Yielding<T>, Promise<T> {
932
+ /**
933
+ * The result of the job (canceled, returned value, or error), or
934
+ * undefined if the job isn't finished.
935
+ *
936
+ * @category Obtaining Results
937
+ */
938
+ result(): JobResult<T> | undefined;
939
+ /**
940
+ * Add a cleanup callback to be run when the job is ended or restarted.
941
+ * (Non-function values are ignored.) If the job has already ended, the
942
+ * callback will be invoked asynchronously in the next microtask. Cleanup
943
+ * functions are run in LIFO order, after any {@link Job.release}()
944
+ * callbacks (including those of the job's children), but before any
945
+ * {@link Job.do}() callbacks are run for the same job.
946
+ *
947
+ * Generally speaking, this method is used within a job to arrange for used
948
+ * resources to be cleaned up or to undo other state that was only supposed
949
+ * to be active while the job was running.
950
+ *
951
+ * @category Resource Tracking
952
+ */
953
+ must(cleanup?: OptionalCleanup<T>): this;
954
+ /**
955
+ * Create a mutual-cleanup link with a resource that might be stopped or
956
+ * terminated in some way before the job ends. (Like a child process, a
957
+ * server connection, etc.)
958
+ *
959
+ * If a job uses a lot of such resources, using {@link Job.must} callbacks
960
+ * to trigger each one would result in an ever growing number of callbacks
961
+ * (and uncollectable reference to the no-longer-usable resources). So this
962
+ * method lets you *remove* a cleanup function when it's no longer needed:
963
+ * when the resource is closed or finished, invoking the callback returned
964
+ * by this method will remove the cleanup callback from the job, allowing
965
+ * the resource to be freed before the job ends, without accumulating an
966
+ * endless number of callbacks in the job. (Uneventful also uses this
967
+ * mechanism internally to link child jobs to their parents.)
968
+ *
969
+ * In order to ensure that all such "child" jobs, resources, and activities
970
+ * are marked as canceled *before* any side effects (such as events,
971
+ * callbacks or I/O operations) can occur, Uneventful prioritizes *all*
972
+ * release callbacks to run before *any* other callbacks of any kind. since
973
+ * release callbacks are used for child jobs, this means that the entire job
974
+ * subtree is notified immediately of cancellation, before any other actions
975
+ * are taken. This ensures that no "stray" operations can continue, unaware
976
+ * that their job is canceled.
977
+ *
978
+ * This means, however, that release callbacks must do **only** simple
979
+ * actions that **can't** result in arbitrary code being synchronously run.
980
+ * (Some safe examples would be setting flags, cancelling event
981
+ * subscriptions, removing things from internal queues, etc.) Synchronously
982
+ * triggering events or other callbacks, however, runs the risk of that code
983
+ * doing things it wouldn't have done if it knew its job were canceled.
984
+ *
985
+ * Note that if you still need such actions to happen, your release callback
986
+ * can always add a new {@link Job.must}() or {@link Job.do}() callback at
987
+ * that point, and the callback will then get done during a later phase of
988
+ * job cleanup, without losing the benefits of the mutual-cleanup process.
989
+ *
990
+ * @param cleanup A cleanup callback. It will receive a {@link JobResult},
991
+ * and its return value is ignored.
992
+ *
993
+ * @returns A callback that should be used to remove the passed-in cleanup
994
+ * callback from the job, if the resource is disposed of before the job
995
+ * ends.
996
+ *
997
+ * @category Resource Tracking
998
+ */
999
+ release(cleanup: CleanupFn<T>): DisposeFn;
1000
+ /**
1001
+ * Start a nested job using the given function (or {@link Yielding},
1002
+ * promise, etc.). (Like {@link start}(), but using a specific job as the
1003
+ * parent, rather than whatever job is active. Zero, one, and two arguments
1004
+ * are supported, just as with start().)
1005
+ *
1006
+ * @category Execution Control
1007
+ */
1008
+ start<T>(init?: StartFn<T> | StartObj<T>): Job<T>;
1009
+ start<T, This>(thisArg: This, fn: StartFn<T, This>): Job<T>;
1010
+ /**
1011
+ * Start a nested job that will end when the given stream does
1012
+ *
1013
+ * This is basically shorthand for `start<void>(job => void src(sink, job,
1014
+ * inlet))` -- i.e. a quick way to subscribe to a finite and/or pausable stream.
1015
+ *
1016
+ * @param src An event source or finite data stream
1017
+ * @param sink A callback that will receive the events
1018
+ * @param inlet Optional - a {@link throttle}() to control backpressure
1019
+ * @returns A job that can be aborted to end the subscription, and which will
1020
+ * end naturally (with a void return or error) if the stream ends itself.
1021
+ *
1022
+ * @category Execution Control
1023
+ */
1024
+ connect<T>(src: Source<T>, sink: Sink<T>, inlet?: Throttle | Inlet): Connection;
1025
+ /**
1026
+ * Invoke a function with this job as the active one, so that calling the
1027
+ * global {@link must} function will add cleanup callbacks to it,
1028
+ * {@link getJob} will return it, etc. (Note: signal dependency tracking is
1029
+ * disabled for the duration of the call.)
1030
+ *
1031
+ * @param fn The function to call
1032
+ * @param args The arguments to call it with, if any
1033
+ * @returns The result of calling fn(...args)
1034
+ *
1035
+ * @category Execution Control
1036
+ */
1037
+ run<F extends PlainFunction>(fn: F, ...args: Parameters<F>): ReturnType<F>;
1038
+ /**
1039
+ * Wrap a function so this job will be active when it's called.
1040
+ *
1041
+ * @param fn The function to wrap
1042
+ *
1043
+ * @returns A function with the same signature(s), but will have this job
1044
+ * active when called.
1045
+ *
1046
+ * @remarks Note that if the supplied function has any custom properties,
1047
+ * they will *not* be available on the returned function at runtime, even
1048
+ * though TypeScript will act as if they are present at compile time. This
1049
+ * is because the only way to copy all overloads of a function signature is
1050
+ * to copy the exact type (as TypeScript has no way to generically say,
1051
+ * "this a function with all the same overloads, but none of the
1052
+ * properties").
1053
+ *
1054
+ * @category Execution Control
1055
+ */
1056
+ bind<F extends (...args: any[]) => any>(fn: F): F;
1057
+ /**
1058
+ * Release all resources held by the job.
1059
+ *
1060
+ * Arrange for all cleanup functions and result consumers added to the job
1061
+ * (via release, must, do, etc.) be called in the appropriate order. When
1062
+ * the call to end() returns, all child jobs will have been notified of
1063
+ * their cancellation. (But not all of their cleanups or result consumers
1064
+ * may have run yet, in the event that another job's end() is in progress
1065
+ * when this method is called.)
1066
+ *
1067
+ * If any callbacks throw exceptions, they're converted to unhandled promise
1068
+ * rejections (so that all of them will be called, even if one throws an
1069
+ * error).
1070
+ *
1071
+ * Note: this method is a bound function, so you can pass it as a callback
1072
+ * to another job, event source, etc.
1073
+ *
1074
+ * @category Execution Control
1075
+ */
1076
+ readonly end: () => void;
1077
+ /**
1078
+ * Invoke a callback with the result of a job. Similar to
1079
+ * {@link Job.must}(), except that `do` callbacks run in FIFO order after
1080
+ * all {@link Job.must}() and {@link Job.release}() callbacks are done for
1081
+ * the same job.
1082
+ *
1083
+ * These callbacks are used internally to implement promises, and should
1084
+ * generally be used when you want to perform actions based on the *result*
1085
+ * of a job. (Whereas {@link Job.must}() callbacks are intended to clean up
1086
+ * resources used by the job itself, and {@link Job.release}() callbacks are
1087
+ * used to notify other activities (such as child jobs) that they are being
1088
+ * canceled.)
1089
+ *
1090
+ * @remarks The .{@link Job.onError onError}(), .{@link Job.onError onValue}(),
1091
+ * and .{@link Job.onError onCancel}() provide shortcuts for creating `do`
1092
+ * callbacks that only run under specific end conditions.
1093
+ *
1094
+ * @category Obtaining Results
1095
+ */
1096
+ do(action: (res?: JobResult<T>) => unknown): this;
1097
+ /**
1098
+ * Invoke a callback if the job ends with an error.
1099
+ *
1100
+ * This is shorthand for a .{@link Job.do do}() callback that checks for an
1101
+ * error and marks it handled, so it uses the same relative order and runs
1102
+ * in the same group as other .do callbacks.
1103
+ *
1104
+ * @param cb A callback that will receive the error
1105
+ *
1106
+ * @category Obtaining Results
1107
+ */
1108
+ onError(cb: (err: any) => unknown): this;
1109
+ /**
1110
+ * Invoke a callback if the job ends with a return() value.
1111
+ *
1112
+ * This is shorthand for a .{@link Job.do do}() callback that checks for a
1113
+ * value result, so it uses the same relative order and runs in the same
1114
+ * group as other .do callbacks.
1115
+ *
1116
+ * @param cb A callback that will receive the value
1117
+ *
1118
+ * @category Obtaining Results
1119
+ */
1120
+ onValue(cb: (val: T) => unknown): this;
1121
+ /**
1122
+ * Invoke a callback if the job ends with an cancellation or
1123
+ * .{@link Job.restart restart}().
1124
+ *
1125
+ * This is shorthand for a .{@link Job.do do}() callback that checks for an
1126
+ * error and marks it handled, so it uses the same relative order and runs
1127
+ * in the same group as other .do callbacks.
1128
+ *
1129
+ * @param cb A callback that will receive the error
1130
+ *
1131
+ * @category Obtaining Results
1132
+ */
1133
+ onCancel(cb: () => unknown): this;
1134
+ /**
1135
+ * Restart this job - works just like .{@link Job.end end}(), except that
1136
+ * the job isn't ended, so cleanup callbacks can be added again and won't be
1137
+ * invoked until the next restart or the job is ended. Note that the job's
1138
+ * startup code will *not* be rerun: this just runs an early cleanup and
1139
+ * then "uncancels" the job, changing its {@link Job.result result}() from
1140
+ * {@link CancelResult} back to undefined. It's up to you to do any needed
1141
+ * re-initialization.
1142
+ *
1143
+ * Unlinke .{@link Job.end end}(), restart() guarantees that *all* cleanups
1144
+ * and result consumers for the target job will have completed running when
1145
+ * it returns.
1146
+ *
1147
+ * @see The {@link restarting} wrapper can be used to make a function that
1148
+ * runs over and over in the same job, restarting each time.
1149
+ *
1150
+ * @category Execution Control
1151
+ */
1152
+ restart(): this;
1153
+ /**
1154
+ * Informs a job of an unhandled error from one of its children.
1155
+ *
1156
+ * If the job has an .{@link Job.asyncCatch asyncCatch}() handler set, it
1157
+ * will be called with the error, otherwise the job will end with the
1158
+ * supplied error. If the error then isn't handled by a listener on the
1159
+ * job, the error will cascade to an asyncThrow on the job's parent, until
1160
+ * the {@link detached} job and its asyncCatch handler is reached. (Which
1161
+ * defaults to creating an unhandled promise rejection.)
1162
+ *
1163
+ * Note: application code should not normally need to call this method
1164
+ * directly, as it's automatically invoked on a job's parent if the job
1165
+ * fails with no error listeners. (That is, if a job result isn't awaited
1166
+ * by anything and has no onError handlers, and the job throws, then the
1167
+ * error is automatically asyncThrow()n to the job's parent.)
1168
+ *
1169
+ * @param err The error thrown by the child job
1170
+ *
1171
+ * @category Handling Errors
1172
+ */
1173
+ asyncThrow(err: any): this;
1174
+ /**
1175
+ * Set up a callback to receive unhandled errors from child jobs.
1176
+ *
1177
+ * Setting an async-catch handler allows you to create robust parent jobs
1178
+ * that log or report errors and restart either a single job or an entire
1179
+ * group of them, in the event that a child job malfunctions in a way that's
1180
+ * not caught elsewhere.
1181
+ *
1182
+ * @param handler Either an error-receiving callback, or null. If null,
1183
+ * asyncThrow()n errors for the job will be passed to the job's throw()
1184
+ * method instead. If a callback is given, it's called with `this` bound to
1185
+ * the relevant job instance.
1186
+ *
1187
+ * @category Handling Errors
1188
+ */
1189
+ asyncCatch(handler: ((this: Job, err: any) => unknown) | null): this;
1190
+ /**
1191
+ * End the job with a thrown error, passing an {@link ErrorResult} to the
1192
+ * cleanup callbacks. (Throws an error if the job is already ended or is
1193
+ * currently restarting.) Provides the same execution and ordering
1194
+ * guarantees as .{@link Job.end end}().
1195
+ *
1196
+ * Note: since this immediately ends the job with an error, it should only
1197
+ * be called by the job when it is no longer able to continue. If you want
1198
+ * to notify a job about an error in a *different* job, you may want to use
1199
+ * .{@link Job.asyncThrow asyncThrow}() instead.
1200
+ *
1201
+ * @category Producing Results
1202
+ */
1203
+ throw(err: any): this;
1204
+ /**
1205
+ * End the job with a return value, passing a {@link ValueResult} to the
1206
+ * cleanup callbacks. (Throws an error if the job is already ended or is
1207
+ * currently restarting.) Provides the same execution and ordering
1208
+ * guarantees as .{@link Job.end end}().
1209
+ *
1210
+ * @category Producing Results
1211
+ */
1212
+ return(val: T): this;
1213
+ }
1214
+ /**
1215
+ * A pausable computation that ultimately produces a value of type T.
1216
+ *
1217
+ * An item of this type can be used to either create a job of type T, or awaited
1218
+ * in a job via `yield *` to obtain the value.
1219
+ *
1220
+ * Any generator function that ultimately returns a value, implicitly returns a
1221
+ * Yielding of that type, but it's best to *explicitly* declare this so that
1222
+ * TypeScript can properly type check your yield expressions. (e.g. `function
1223
+ * *(): Yielding<number> {}` for a generator function that ultimately returns a
1224
+ * number.)
1225
+ *
1226
+ * Generator functions implementing this type should only ever `yield *` to
1227
+ * things that are of Yielding type, such as a {@link Job}, {@link to}() or
1228
+ * other generators declared Yielding.
1229
+ *
1230
+ * @yields {@link Suspend}\<any>
1231
+ * @returns T
1232
+ *
1233
+ *
1234
+ * @category Types and Interfaces
1235
+ */
1236
+ type Yielding<T> = {
1237
+ /**
1238
+ * An iterator suitable for use with `yield *` (in a job generator) to
1239
+ * obtain a result.
1240
+ *
1241
+ * @category Obtaining Results
1242
+ */
1243
+ [Symbol.iterator](): JobIterator<T>;
1244
+ };
1245
+ /**
1246
+ * An iterator yielding {@link Suspend} callbacks. (An implementation detail of
1247
+ * the {@link Yielding} type.)
1248
+ *
1249
+ * @category Types and Interfaces
1250
+ */
1251
+ type JobIterator<T> = Generator<Suspend<any>, T, any>;
1252
+ /**
1253
+ * An asynchronous operation that can be waited on by a {@link Job}.
1254
+ *
1255
+ * When a {@link JobIterator} yields a Suspend, the job invokes it with a
1256
+ * {@link Request}. The Suspend function should arrange for the request to be
1257
+ * settled (via {@link resolve} or {@link reject}).
1258
+ *
1259
+ * Note: If the request is not settled, **the job will be suspended until
1260
+ * cancelled by outside forces**. (Such as its enclosing job ending, or
1261
+ * explicit throw()/return() calls on the job instance.)
1262
+ *
1263
+ * Also note that any subjobs the Suspend function creates (or cleanup callbacks
1264
+ * it registers) **will not be called until the *calling* job ends**. So any
1265
+ * resources that won't be needed once the job is resumed should be explicitly
1266
+ * disposed of -- in which case you should probably just `yield *` to a
1267
+ * {@link start}(), instead of yielding a Suspend!
1268
+ *
1269
+ * @category Types and Interfaces
1270
+ */
1271
+ type Suspend<T> = (request: Request<T>) => void;
1272
+ /**
1273
+ * A request for a value (or error) to be returned asynchronously.
1274
+ *
1275
+ * A request is like the inverse of a Promise: instead of waiting for it to
1276
+ * settle, you settle it by passing it to {@link resolve}() or {@link reject}().
1277
+ * Like a promise, it can only be settled once: resolving or rejecting it after
1278
+ * it's already resolved or rejected has no effect.
1279
+ *
1280
+ * Settling a request will cause the requesting job (or other code) to resume
1281
+ * immediately, running up to its next suspension or termination. (Unless it's
1282
+ * settled while the requesting job is already on the call stack, in which case
1283
+ * the job will be resumed later.)
1284
+ *
1285
+ * (Note: do not call a Request directly, unless you want your code to maybe
1286
+ * break in future. Use resolve or reject (or {@link resolver}() or
1287
+ * {@link rejecter}()), as 1) they'll shield you from future changes to this
1288
+ * protocol and 2) they have better type checking anyway.)
1289
+ *
1290
+ * @category Types and Interfaces
1291
+ */
1292
+ interface Request<T> {
1293
+ (op: "next", val: T, err?: any): void;
1294
+ (op: "throw", val: undefined | null, err: any): void;
1295
+ (op: "next" | "throw", val?: T | undefined | null, err?: any): void;
1296
+ }
1297
+ /**
1298
+ * A subscribable function used to trigger signal recalculations
1299
+ *
1300
+ * It must accept a callback, and should arrange (via {@link must}()) to
1301
+ * unsubscribe when its calling job ends. Once subscribed, it should
1302
+ * invoke the callback to trigger recalculation of the signal(s) that
1303
+ * were targeted via {@link recalcWhen}.
1304
+ *
1305
+ * @category Types and Interfaces
1306
+ */
1307
+ type RecalcSource = ((cb: () => void) => unknown);
1308
+
1309
+ /**
1310
+ * Is the given value a function?
1311
+ *
1312
+ * @category Types and Interfaces
1313
+ */
1314
+ declare function isFunction(f: any): f is Function;
1315
+ /**
1316
+ * Return the currently-active Job, or throw an error if none is active.
1317
+ *
1318
+ * (You can check if a job is active first using {@link isJobActive}().)
1319
+ *
1320
+ * @category Jobs
1321
+ */
1322
+ declare function getJob<T = unknown>(): Job<T>;
1323
+ /**
1324
+ * Obtain a native promise for a job
1325
+ *
1326
+ * While jobs have the same interface as native promises, there are occasionally
1327
+ * reasons to just use one directly. (Like when Uneventful uses this function
1328
+ * to implement jobs' promise methods!)
1329
+ *
1330
+ * @param job Optional: the job to get a native promise for. If none is given,
1331
+ * the active job is used.
1332
+ *
1333
+ * @returns A {@link Promise} that resolves or rejects according to whether the
1334
+ * job returns or throws. If the job is canceled, the promise is rejected with
1335
+ * a {@link CancelError}.
1336
+ *
1337
+ * @category Jobs
1338
+ */
1339
+ declare function nativePromise<T>(job?: Job<T>): Promise<T>;
1340
+ /**
1341
+ * Return a new {@link Job}. If *either* a parent parameter or stop function
1342
+ * are given, the new job is linked to the parent.
1343
+ *
1344
+ * @param parent The parent job to which the new job should be attached.
1345
+ * Defaults to the currently-active job if none given (assuming a stop
1346
+ * parameter is provided).
1347
+ *
1348
+ * @param stop The function to call to destroy the nested job. Defaults to the
1349
+ * {@link Job.end} method of the new job if none is given (assuming a parent
1350
+ * parameter is provided).
1351
+ *
1352
+ * @returns A new job. The job is linked/nested if any arguments are given,
1353
+ * or a detached (parentless) job otherwise.
1354
+ *
1355
+ * @category Jobs
1356
+ */
1357
+ declare const makeJob: <T, R = unknown>(parent?: Job<R>, stop?: CleanupFn<R>) => Job<T>;
1358
+ /**
1359
+ * A special {@link Job} with no parents, that can be used to create standalone
1360
+ * jobs. detached.start() returns a new detached job, detached.run() can be
1361
+ * used to run code that expects to create a child job, and detached.bind() can
1362
+ * wrap a function to work without a parent job.
1363
+ *
1364
+ * (Note that in all cases, a child job of `detached` *must* be stopped
1365
+ * explicitly, or it may "run" forever, never running its cleanup callbacks.)
1366
+ *
1367
+ * The detached job has a few special features and limitations:
1368
+ *
1369
+ * - It can't be ended, thrown, return()ed, etc. -- you'll get an error
1370
+ *
1371
+ * - It can't have any cleanup functions added: no do, must, onError, etc., and
1372
+ * thus also can't have any native promise, abort signal, etc. used. You can
1373
+ * call its release() method, but nothing will actually be registered and the
1374
+ * returned callback is a no-op.
1375
+ *
1376
+ * - Unhandled errors from jobs without parents (and errors from *any* job's
1377
+ * cleanup functions) are sent to the detached job for handling. This means
1378
+ * whatever you set as the detached job's .{@link Job.asyncCatch asyncCatch}()
1379
+ * handler will receive them. (Its default is Promise.reject, causing an
1380
+ * unhandled promise rejection.)
1381
+ *
1382
+ * @category Jobs
1383
+ */
1384
+ declare const detached: Job<unknown>;
1385
+
1386
+ /**
1387
+ * Convert a promise to something you can `yield *to()` in a job
1388
+ *
1389
+ * Much like `await valueOrPromiseLike` in an async function, using `yield
1390
+ * *to(valueOrPromiseLike)` in a {@link Job}'s generator function will return
1391
+ * the value or the result of the promise/promise-like object.
1392
+ *
1393
+ * @category Scheduling
1394
+ */
1395
+ declare function to<T>(p: Promise<T> | PromiseLike<T> | T): Yielding<T>;
1396
+ /**
1397
+ * Pause the job for the specified time in ms, e.g. `yield *sleep(1000)` to wait
1398
+ * one second.
1399
+ *
1400
+ * @category Scheduling
1401
+ */
1402
+ declare function sleep(ms: number): Yielding<void>;
1403
+
1404
+ /**
1405
+ * A function that emits events, with a .source they're emitted from
1406
+ *
1407
+ * Created using {@link emitter}.
1408
+ *
1409
+ * @category Types and Interfaces
1410
+ */
1411
+ interface Emitter<T> {
1412
+ /** Call the emitter to emit events on its .source */
1413
+ (val: T): void;
1414
+ /** An event source that receives the events */
1415
+ source: Producer<T>;
1416
+ /** Close all current subscribers' connections */
1417
+ end: () => void;
1418
+ /** Close all current subscribers' connections with an error */
1419
+ throw: (e: any) => void;
1420
+ }
1421
+ /**
1422
+ * Create an event source and a function to emit events on it
1423
+ *
1424
+ * (Note: you must specify the event type (e.g. `emitter<number>()`), since
1425
+ * there's nothing else to infer it from.)
1426
+ *
1427
+ * @returns A function that emits events, with a .source property they're
1428
+ * emitted on.
1429
+ *
1430
+ * @category Stream Producers
1431
+ */
1432
+ declare function emitter<T>(): Emitter<T>;
1433
+ /**
1434
+ * A stream that immediately closes
1435
+ *
1436
+ * @category Stream Producers
1437
+ */
1438
+ declare function empty(): Producer<never>;
1439
+ /**
1440
+ * Convert an async iterable to an event source
1441
+ *
1442
+ * Each time the resulting source is subscribed to, it will emit an event for
1443
+ * each item output by the iterator, then end the stream. Pause/resume is
1444
+ * supported.
1445
+ *
1446
+ * @category Stream Producers
1447
+ */
1448
+ declare function fromAsyncIterable<T>(iterable: AsyncIterable<T>): Producer<T>;
1449
+ /**
1450
+ * Create an event source from an element, window, or other event target
1451
+ *
1452
+ * You can manually override the expected event type using a type parameter,
1453
+ * e.g. `fromDomEvent<CustomEvent>(someTarget, "custom-event")`.
1454
+ *
1455
+ * @param target an HTMLElement, Window, Document, or other EventTarget.
1456
+ * @param type the name of the event to add a listener for
1457
+ * @param options a boolean capture option, or an object of event listener
1458
+ * options
1459
+ * @returns a source that can be subscribed or piped, issuing events from the
1460
+ * target of the specified type.
1461
+ *
1462
+ * @category Stream Producers
1463
+ */
1464
+ declare function fromDomEvent<T extends HTMLElement, K extends keyof HTMLElementEventMap>(target: T, type: K, options?: boolean | AddEventListenerOptions): Producer<HTMLElementEventMap[K]>;
1465
+ declare function fromDomEvent<T extends Window, K extends keyof WindowEventMap>(target: T, type: K, options?: boolean | AddEventListenerOptions): Producer<WindowEventMap[K]>;
1466
+ declare function fromDomEvent<T extends Document, K extends keyof DocumentEventMap>(target: T, type: K, options?: boolean | AddEventListenerOptions): Producer<DocumentEventMap[K]>;
1467
+ declare function fromDomEvent<T extends Event>(target: EventTarget, type: string, options?: boolean | AddEventListenerOptions): Producer<T>;
1468
+ /**
1469
+ * Convert an iterable to a synchronous event source
1470
+ *
1471
+ * Each time the resulting source is subscribed to, it will emit an event for
1472
+ * each item in the iterator, then close the conduit. Pause/resume is
1473
+ * supported.
1474
+ *
1475
+ * @category Stream Producers
1476
+ */
1477
+ declare function fromIterable<T>(iterable: Iterable<T>): Producer<T>;
1478
+ /**
1479
+ * Convert a Promise to an event source
1480
+ *
1481
+ * Each time the resulting source is subscribed to, it will emit an event for
1482
+ * the result of the promise, then close the conduit. (Unless the promise is
1483
+ * rejected, in which case the conduit throws and closes each time the source is
1484
+ * subscribed.) Non-native promises and non-promise values are converted using
1485
+ * Promise.resolve().
1486
+ *
1487
+ * @category Stream Producers
1488
+ */
1489
+ declare function fromPromise<T>(promise: Promise<T> | PromiseLike<T> | T): Producer<T>;
1490
+ /**
1491
+ * Create an event source from an arbitrary subscribe/unsubscribe function
1492
+ *
1493
+ * The supplied "subscribe" function will be passed a 1-argument callback and
1494
+ * must return an unsubscribe function. The callback should be called with
1495
+ * events of the appropriate type, and the unsubscribe function will be called
1496
+ * when the connection is closed.
1497
+ *
1498
+ * (Note: it's okay if the act of subscribing causes an immediate callback, as
1499
+ * the subscribe function will be called in a separate microtask.)
1500
+ *
1501
+ * @category Stream Producers
1502
+ */
1503
+ declare function fromSubscribe<T>(subscribe: (cb: (val: T) => void) => DisposeFn): Producer<T>;
1504
+ /**
1505
+ * Create a source that emits a single given value
1506
+ *
1507
+ * @category Stream Producers
1508
+ */
1509
+ declare function fromValue<T>(val: T): Producer<T>;
1510
+ /**
1511
+ * Create an event source that issues a number every `ms` milliseconds (starting
1512
+ * with 0 after the first interval passes).
1513
+ *
1514
+ * @category Stream Producers
1515
+ */
1516
+ declare function interval(ms: number): Producer<number>;
1517
+ /**
1518
+ * Create a dynamic source that is created each time it's subscribed
1519
+ *
1520
+ * @param factory A function returning a source of the desired type. It will be
1521
+ * called whenever the lazy() stream is subscribed, and its result subscribed to.
1522
+ *
1523
+ * @returns A stream of the same type as the factory function returns
1524
+ *
1525
+ * @category Stream Producers
1526
+ */
1527
+ declare function lazy<T>(factory: () => Source<T>): Producer<T>;
1528
+ /**
1529
+ * An {@link Emitter} with a ready() method, that only supports a single active
1530
+ * subscriber. (Useful for testing stream operators and sinks.)
1531
+ *
1532
+ * Created using {@link mockSource}().
1533
+ *
1534
+ * @category Types and Interfaces
1535
+ */
1536
+ interface MockSource<T> extends Emitter<T> {
1537
+ ready: Backpressure;
1538
+ }
1539
+ /**
1540
+ * Like {@link emitter}, but with a ready() backpressure method. It also only
1541
+ * supports a single active subscriber. (Useful for testing stream operators
1542
+ * and sinks.)
1543
+ *
1544
+ * @category Stream Producers
1545
+ */
1546
+ declare function mockSource<T>(): MockSource<T>;
1547
+ /**
1548
+ * A stream that never emits or closes
1549
+ *
1550
+ * @category Stream Producers
1551
+ */
1552
+ declare function never(): Producer<never>;
1553
+ /**
1554
+ * Wrap a source to allow multiple subscribers to the same underlying stream
1555
+ *
1556
+ * The input source will be susbcribed when the output has at least one
1557
+ * subscriber, and unsubscribed when the output has no subscribers. The input
1558
+ * will be paused when any subscriber pauses, and will only be resumed when all
1559
+ * subscribers are unpaused. All subscribers are closed or thrown if the input
1560
+ * source closes or throws.
1561
+ *
1562
+ * (Generally speaking, you should place the share call as late in your
1563
+ * pipelines as possible, if you use it at all. It adds some overhead that is
1564
+ * wasted if the stream doesn't have multiple subscribers, and may be redundant
1565
+ * if an upstream source is already shared. It's mainly useful if there is a
1566
+ * lot of mapping, filtering, or other complicated processing taking place
1567
+ * upstream of the share, and you know for a fact there will be enough
1568
+ * subscribers to make it a bottleneck. You should probably also consider
1569
+ * putting some {@link slack}() either upstream or downstream of the share, if
1570
+ * the upstream supports backpressure.)
1571
+ *
1572
+ * @category Stream Operators
1573
+ */
1574
+ declare function share<T>(source: Source<T>): Producer<T>;
1575
+
1576
+ /**
1577
+ * Output multiple streams' contents in order (from an array/iterable of stream
1578
+ * sources)
1579
+ *
1580
+ * Streams are concatenated in order -- note that this means they need to not be
1581
+ * infinite if any subsequent streams are to be processed! The output is closed
1582
+ * when all sources are finished or if any source throws (in which case the
1583
+ * error propagates to the subscriber).
1584
+ *
1585
+ * Note: this function is just shorthand for {@link concatAll}({@link fromIterable}(*sources*)).
1586
+ *
1587
+ * @category Stream Operators
1588
+ */
1589
+ declare function concat<T>(sources: Source<T>[] | Iterable<Source<T>>): Producer<T>;
1590
+ /**
1591
+ * Flatten a source of sources by emitting their contents in series
1592
+ *
1593
+ * Streams are concatenated in order -- note that this means they need to not be
1594
+ * infinite if any subsequent streams are to be processed! The output is closed
1595
+ * when all sources are finished or if any source throws (in which case the
1596
+ * error propagates to the subscriber).
1597
+ *
1598
+ * If you want to switch to a new stream whenever a new source arrives from the
1599
+ * input stream, use {@link switchAll} instead.
1600
+ *
1601
+ * @category Stream Operators
1602
+ */
1603
+ declare function concatAll<T>(sources: Source<Source<T>>): Producer<T>;
1604
+ /**
1605
+ * Map each value of a stream to a substream, then concatenate the resulting
1606
+ * substreams
1607
+ *
1608
+ * (This is just shorthand for `compose(map(mapper), concatAll)`.)
1609
+ *
1610
+ * If you want to switch to a new stream whenever a new event arrives on the
1611
+ * input stream, use {@link switchMap} instead.
1612
+ *
1613
+ * @category Stream Operators
1614
+ */
1615
+ declare function concatMap<T, R>(mapper: (v: T, idx: number) => Source<R>): Transformer<T, R>;
1616
+ /**
1617
+ * Create a subset of a stream, based on a filter function (like Array.filter)
1618
+ *
1619
+ * The filter function receives the current index (zero-based) as well as the
1620
+ * current value. If it returns truth, the value will be passed to the output,
1621
+ * otherwise it will be skipped.
1622
+ *
1623
+ * If the filter function is typed as a Typescript type guard (i.e. as returning
1624
+ * `v is SomeType`), then the resulting source will be typed as
1625
+ * Source<SomeType>.
1626
+ *
1627
+ * @category Stream Operators
1628
+ */
1629
+ declare function filter<T, R extends T>(filter: (v: T, idx: number) => v is R): Transformer<T, R>;
1630
+ declare function filter<T>(filter: (v: T, idx: number) => boolean): Transformer<T>;
1631
+ /**
1632
+ * Replace each value in a stream using a function (like Array.map)
1633
+ *
1634
+ * The mapping function receives the current index (zero-based) as well as the
1635
+ * current value.
1636
+ *
1637
+ * @category Stream Operators
1638
+ */
1639
+ declare function map<T, R>(mapper: (v: T, idx: number) => R): Transformer<T, R>;
1640
+ /**
1641
+ * Create an event source by merging an array or iterable of event sources.
1642
+ *
1643
+ * The resulting source issues events whenever any of the input sources do, and
1644
+ * closes once they all do (or throws if any of them do).
1645
+ *
1646
+ * @category Stream Operators
1647
+ */
1648
+ declare function merge<T>(sources: Source<T>[] | Iterable<Source<T>>): Producer<T>;
1649
+ /**
1650
+ * Create an event source by merging sources from a stream of event sources
1651
+ *
1652
+ * The resulting source issues events whenever any of the input sources do, and
1653
+ * closes once they all do (or throws if any of them do).
1654
+ *
1655
+ * @category Stream Operators
1656
+ */
1657
+ declare function mergeAll<T>(sources: Source<Source<T>>): Producer<T>;
1658
+ /**
1659
+ * Create an event source by merging sources created by mapping events to sources
1660
+ *
1661
+ * The resulting source issues events whenever any of the input sources do, and
1662
+ * closes once they all do (or throws if any of them do).
1663
+ *
1664
+ * (Note: this is just shorthand for `compose(map(mapper), mergeAll)`.)
1665
+ *
1666
+ * @category Stream Operators
1667
+ */
1668
+ declare function mergeMap<T, R>(mapper: (v: T, idx: number) => Source<R>): Transformer<T, R>;
1669
+ /**
1670
+ * Skip the first N items from a source
1671
+ *
1672
+ * (Equivalent to {@link skipWhile}() with a function that checks the index is < n.)
1673
+ *
1674
+ * @category Stream Operators
1675
+ */
1676
+ declare function skip<T>(n: number): Transformer<T>;
1677
+ /**
1678
+ * Skip items from a stream until another source produces a value.
1679
+ *
1680
+ * If the notifier closes without producing a value, the output will
1681
+ * be empty. If the notifier throws, so will the output.
1682
+ *
1683
+ * @category Stream Operators
1684
+ */
1685
+ declare function skipUntil<T>(notifier: Source<any>): Transformer<T>;
1686
+ /**
1687
+ * Skip items from a stream until a given condition is false, then output all
1688
+ * remaining items. The condition function is not called again once it returns
1689
+ * false.
1690
+ *
1691
+ * @category Stream Operators
1692
+ */
1693
+ declare function skipWhile<T>(condition: (v: T, index: number) => boolean): Transformer<T>;
1694
+ /**
1695
+ * Add job control and buffering to a stream
1696
+ *
1697
+ * This lets you block events from a stream that can't be paused, or allow for
1698
+ * some slack for a source that can sometimes get ahead of its sink.
1699
+ *
1700
+ * @param size The number of items to buffer when the sink is busy (i.e., the
1701
+ * sink is running or the connection is paused). If positive, the most recent N
1702
+ * items are kept (a "sliding" buffer), and if negative, the oldest N item are
1703
+ * kept (a "dropping" buffer). If zero, no items are buffered, and items are
1704
+ * dropped if received while the sink is busy.
1705
+ *
1706
+ * @param dropped Optional: a callback that will receive items when they are
1707
+ * dropped. (Useful for testing, performance instrumentation, error logging,
1708
+ * etc.)
1709
+ *
1710
+ * @category Stream Operators
1711
+ */
1712
+ declare function slack<T>(size: number, dropped?: Sink<T>): Transformer<T>;
1713
+ /**
1714
+ * Flatten a source of sources by emitting their contents until a new one
1715
+ * arrives.
1716
+ *
1717
+ * As each source arrives from the input stream, its values are sent to the
1718
+ * output, closing the previous one (if any). The output is closed when both
1719
+ * the input stream and the most-recently-arrived stream are finished. Errors
1720
+ * propagate to the output if any stream throws.
1721
+ *
1722
+ * (If you want to send *all* the values of each stream to the output without
1723
+ * stopping, input stream, use {@link concatAll} or {@link mergeAll} instead.)
1724
+ *
1725
+ * @category Stream Operators
1726
+ */
1727
+ declare function switchAll<T>(sources: Source<Source<T>>): Producer<T>;
1728
+ /**
1729
+ * Map each value of a stream to a substream, then output the resulting
1730
+ * substreams until a new value arrives.
1731
+ *
1732
+ * (This is just shorthand for `compose(map(mapper),`{@link switchAll `switchAll)`}.)
1733
+ *
1734
+ * (If you want to send *all* the values of each stream to the output without
1735
+ * stopping, input stream, use {@link concatMap} or {@link mergeMap} instead.)
1736
+ *
1737
+ * @category Stream Operators
1738
+ */
1739
+ declare function switchMap<T, R>(mapper: (v: T, idx: number) => Source<R>): Transformer<T, R>;
1740
+ /**
1741
+ * Take the first N items from a source
1742
+ *
1743
+ * (Equivalent to {@link takeWhile}() with a function that checks the index is < n.)
1744
+ *
1745
+ * @category Stream Operators
1746
+ */
1747
+ declare function take<T>(n: number): Transformer<T>;
1748
+ /**
1749
+ * Take items from a source until another source produces a value.
1750
+ *
1751
+ * If the notifier closes without producing a value, this will output all
1752
+ * elements of the input. But if the notifier throws, so will the output.
1753
+ *
1754
+ * @category Stream Operators
1755
+ */
1756
+ declare function takeUntil<T>(notifier: Source<any>): Transformer<T>;
1757
+ /**
1758
+ * Take items from a stream until a given condition is false, then close the
1759
+ * output. The condition function is not called again after it returns false.
1760
+ *
1761
+ * If the condition function is typed as a Typescript type guard (i.e. as
1762
+ * returning `v is SomeType`), then the resulting source will be typed as
1763
+ * Source<SomeType>.
1764
+ *
1765
+ * @category Stream Operators
1766
+ */
1767
+ declare function takeWhile<T, R extends T>(condition: (v: T, idx: number) => v is R): Transformer<T, R>;
1768
+ declare function takeWhile<T>(condition: (v: T, idx: number) => boolean): Transformer<T>;
1769
+
1770
+ /**
1771
+ * Add a cleanup function to the active job. Non-function values are ignored.
1772
+ * Equivalent to {@link getJob}().{@link Job.must must}() -- see
1773
+ * {@link Job.must}() for more details.
1774
+ *
1775
+ * @category Jobs
1776
+ */
1777
+ declare function must<T>(cleanup?: OptionalCleanup<T>): Job<T>;
1778
+ /**
1779
+ * Start a nested job within the currently-active job. (Shorthand for
1780
+ * {@link getJob}().{@link Job.start start}(...).)
1781
+ *
1782
+ * This function can be called with zero, one, or two arguments:
1783
+ *
1784
+ * - When called with zero arguments, the new job is returned without any other
1785
+ * initialization.
1786
+ *
1787
+ * - When called with one argument that's a function (either a {@link SyncStart}
1788
+ * or {@link AsyncStart}): the function is run inside the new job and receives
1789
+ * it as an argument. It can return a {@link Yielding} iterator (such as a
1790
+ * generator or job), a promise, or void. A returned iterator or promise will
1791
+ * be treated as if the method was called with that to begin with; a returned
1792
+ * job will be awaited and its result transferred to the new job
1793
+ * asynchronously.
1794
+ *
1795
+ * - When called with one argument that's a {@link Yielding} iterator (such as a
1796
+ * generator or an existing job): it's attached to the new job and executed
1797
+ * asynchronously. (Starting in the next available microtask.)
1798
+ *
1799
+ * - When called with one argument that's a Promise, it's converted to a job
1800
+ * that will end when the promise settles. The resulting job is returned.
1801
+ *
1802
+ * - When called with two arguments -- a "this" object and a function -- it
1803
+ * works the same as one argument that's a function, except the function is
1804
+ * bound to the supplied "this" before being called.
1805
+ *
1806
+ * This last signature is needed because you can't make generator arrows in JS
1807
+ * yet: if you want to start() a generator function bound to the current
1808
+ * `this`, you'll want to use `.start(this, function*() { ...whatever })`.
1809
+ *
1810
+ * (Note, however, that TypeScript and/or VSCode may require that you give
1811
+ * such a function an explicit `this` parameter (e.g. `.start(this, function
1812
+ * *(this) {...}));`) in order to correctly infer types inside a generator
1813
+ * function.)
1814
+ *
1815
+ * In any of the above cases, if a supplied function throws an error when
1816
+ * starting, the new job will be ended, and the error synchronously re-thrown.
1817
+ *
1818
+ * @returns the created {@link Job}
1819
+ *
1820
+ * @category Jobs
1821
+ */
1822
+ declare function start<T>(init?: StartFn<T> | StartObj<T>): Job<T>;
1823
+ /**
1824
+ * The two-argument variant of start() allows you to pass a "this" object that
1825
+ * will be bound to the initialization function. (It's mostly useful for
1826
+ * generator functions, since generator arrows aren't a thing yet.)
1827
+ */
1828
+ declare function start<T, This>(thisArg: This, fn: StartFn<T, This>): Job<T>;
1829
+ /**
1830
+ * Is there a currently active job? (i.e., can you safely use {@link must}(),
1831
+ * or {@link getJob}() right now?)
1832
+ *
1833
+ * @category Jobs
1834
+ */
1835
+ declare function isJobActive(): boolean;
1836
+ /**
1837
+ * Set the cancellation timeout for a job.
1838
+ *
1839
+ * When the timeout is reached, the job is canceled (throwing
1840
+ * {@link CancelError} to any waiting promises or jobs), unless a new timeout
1841
+ * is set before then. You may set a new timeout value for a job as many times
1842
+ * as desired. A timeout value of zero disables the timeout. Timers are
1843
+ * disposed of if the job is canceled or restarted.
1844
+ *
1845
+ * @param ms Optional: Number of milliseconds after which the job will be
1846
+ * canceled. Defaults to zero if not given.
1847
+ *
1848
+ * @param job Optional: the job to apply the timeout to. If none is given, the
1849
+ * active job is used.
1850
+ *
1851
+ * @returns the job to which the timeout was added or removed.
1852
+ *
1853
+ * @category Scheduling
1854
+ */
1855
+ declare function timeout<T>(ms: number, job?: Job<T>): Job<T>;
1856
+ /**
1857
+ * Get an AbortSignal that aborts when the job ends or is restarted.
1858
+ *
1859
+ * @param job Optional: the job to get an AbortSignal for. If none is given,
1860
+ * the active job is used.
1861
+ *
1862
+ * @returns the AbortSignal
1863
+ *
1864
+ * @category Jobs
1865
+ */
1866
+ declare function abortSignal(job?: Job): AbortSignal;
1867
+ /**
1868
+ * Wrap a function in a {@link Job} that restarts each time the resulting
1869
+ * function is called, thereby canceling any nested jobs and cleaning up any
1870
+ * resources used by previous calls. (This can be useful for such things as
1871
+ * canceling an in-progress search when the user types more text in a field.)
1872
+ *
1873
+ * The restarting job will be ended when the job that invoked `restarting()`
1874
+ * is finished, canceled, or restarted. Calling the wrapped function after its
1875
+ * job has ended will result in an error. You can wrap any function any number
1876
+ * of times: each call to `restarting()` creates a new, distinct "restarting
1877
+ * job" and function wrapper to go with it.
1878
+ *
1879
+ * @param task (Optional) The function to be wrapped. This can be any function:
1880
+ * the returned wrapper function will match its call signature exactly, including
1881
+ * overloads. (So for example you could wrap the {@link start} API via
1882
+ * `restarting(start)`, to create a function you can pass job-start functions to.
1883
+ * When called, the function would cancel any outstanding job from a previous
1884
+ * call, and start the new one in its place.)
1885
+ *
1886
+ * @returns A function of identical type to the input function. If no input
1887
+ * function was given, the returned function will just take one argument (a
1888
+ * zero-argument function optionally returning a {@link CleanupFn}).
1889
+ *
1890
+ * @category Jobs
1891
+ */
1892
+ declare function restarting<F extends AnyFunction>(task: F): F;
1893
+ declare function restarting(): (task: () => OptionalCleanup<never>) => void;
1894
+
1895
+ export { type AnyFunction, type AsyncStart, type Backpressure, CancelError, CancelResult, CircularDependency, type CleanupFn, type Connection, type DisposeFn, type Each, type EachResult, type Emitter, ErrorResult, type HandledError, type Inlet, IsStream, type Job, type JobIterator, type JobResult, type MockSource, type Nothing, type OptionalCleanup, type PlainFunction, type Producer, type RecalcSource, type Request, RuleScheduler, Signal, type Sink, type Source, type StartFn, type StartObj, type Suspend, type SyncStart, type Throttle, type Transformer, type UnhandledError, type UntilMethod, ValueResult, type Waitable, Writable, WriteConflict, type Yielding, abortSignal, backpressure, cached, compose, concat, concatAll, concatMap, connect, defer, detached, each, emitter, empty, filter, fromAsyncIterable, fromDomEvent, fromIterable, fromPromise, fromSubscribe, fromValue, fulfillPromise, getJob, getResult, interval, into, isCancel, isError, isFunction, isHandled, isJobActive, isUnhandled, isValue, lazy, makeJob, map, markHandled, merge, mergeAll, mergeMap, mockSource, must, nativePromise, never, noDeps, noop, pipe, propagateResult, recalcWhen, reject, rejecter, resolve, resolver, restarting, rule, runRules, share, skip, skipUntil, skipWhile, slack, sleep, start, switchAll, switchMap, take, takeUntil, takeWhile, throttle, timeout, to, until, value };