-
-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathindex.d.ts
1617 lines (1482 loc) · 50.9 KB
/
index.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
export type TaskGenerator<T> = Generator<any, T, any>;
export type TaskFunction<T, Args extends any[]> = (
...args: Args
) => TaskGenerator<T>;
export type TaskFunctionArgs<T extends TaskFunction<any, any[]>> = T extends (
...args: infer A
) => TaskGenerator<any>
? A
: [];
export type TaskFunctionReturnType<T extends TaskFunction<any, any[]>> =
T extends (...args: any[]) => TaskGenerator<infer R> ? R : unknown;
export type TaskForTaskFunction<T extends TaskFunction<any, any[]>> = Task<
TaskFunctionReturnType<T>,
TaskFunctionArgs<T>
>;
export type TaskInstanceForTaskFunction<T extends TaskFunction<any, any[]>> =
TaskInstance<TaskFunctionReturnType<T>>;
export interface EncapsulatedTaskDescriptor<T, Args extends any[]> {
perform(...args: Args): TaskGenerator<T>;
}
export type EncapsulatedTaskDescriptorArgs<
T extends EncapsulatedTaskDescriptor<any, any[]>
> = T extends { perform(...args: infer A): TaskGenerator<any> } ? A : [];
export type EncapsulatedTaskDescriptorReturnType<
T extends EncapsulatedTaskDescriptor<any, any[]>
> = T extends { perform(...args: any[]): TaskGenerator<infer R> } ? R : unknown;
export type AsyncArrowTaskFunction<HostObject, T, Args extends any[]> = (
this: HostObject,
...args: Args
) => Promise<T>;
export type AsyncTaskArrowFunctionArgs<
HostObject,
T extends AsyncArrowTaskFunction<HostObject, any, any[]>
> = T extends (...args: infer A) => Promise<any> ? A : [];
export type AsyncTaskArrowFunctionReturnType<
HostObject,
T extends AsyncArrowTaskFunction<HostObject, any, any[]>
> = T extends (...args: any[]) => Promise<infer R> ? R : unknown;
export type TaskForAsyncTaskFunction<
HostObject,
T extends AsyncArrowTaskFunction<HostObject, any, any[]>
> = Task<
AsyncTaskArrowFunctionReturnType<HostObject, T>,
AsyncTaskArrowFunctionArgs<HostObject, T>
>;
export type TaskInstanceForAsyncTaskFunction<
HostObject,
T extends AsyncArrowTaskFunction<HostObject, any, any[]>
> = TaskInstance<AsyncTaskArrowFunctionReturnType<HostObject, T>>;
// eslint-disable-next-line @typescript-eslint/ban-types
export type EncapsulatedTaskState<T extends object> = Omit<
T,
'perform' | keyof TaskInstance<any>
>;
export type TaskForEncapsulatedTaskDescriptor<
T extends EncapsulatedTaskDescriptor<any, any[]>
> = EncapsulatedTask<
EncapsulatedTaskDescriptorReturnType<T>,
EncapsulatedTaskDescriptorArgs<T>,
EncapsulatedTaskState<T>
>;
export type TaskInstanceForEncapsulatedTaskDescriptor<
T extends EncapsulatedTaskDescriptor<any, any[]>
> = EncapsulatedTaskInstance<
EncapsulatedTaskDescriptorReturnType<T>,
EncapsulatedTaskState<T>
>;
interface TaskState<T extends TaskInstance<any>> {
/**
* `true` if any current task instances are running.
*/
readonly isRunning: boolean;
/**
* `true` if any future task instances are queued.
*/
readonly isQueued: boolean;
/**
* `true` if the task or task group is not in the running or queued state.
*/
readonly isIdle: boolean;
/**
* The current state of the task or task group: `"running"`, `"queued"` or `"idle"`.
*/
readonly state: 'running' | 'queued' | 'idle';
/**
* The most recently started task instance.
*/
readonly last: T | null;
/**
* The most recent task instance that is currently running.
*/
readonly lastRunning: T | null;
/**
* The most recently performed task instance.
*/
readonly lastPerformed: T | null;
/**
* The most recent task instance that succeeded.
*/
readonly lastSuccessful: T | null;
/**
* The most recently completed task instance.
*/
readonly lastComplete: T | null;
/**
* The most recent task instance that errored.
*/
readonly lastErrored: T | null;
/**
* The most recently canceled task instance.
*/
readonly lastCanceled: T | null;
/**
* The most recent task instance that is incomplete.
*/
readonly lastIncomplete: T | null;
/**
* The number of times this task or task group has been performed.
*/
readonly performCount: number;
}
interface AbstractTask<Args extends any[], T extends TaskInstance<any>>
extends TaskState<T> {
/**
* Cancels all running or queued `TaskInstance`s for this Task.
* If you're trying to cancel a specific TaskInstance (rather
* than all of the instances running under this task) call
* `.cancel()` on the specific TaskInstance.
*
* @param options.reason A descriptive reason the task was
* cancelled. Defaults to `".cancelAll() was explicitly called
* on the Task"`.
* @param options.resetState If true, will clear the task state
* (`last*` and `performCount` properties will be set to initial
* values). Defaults to false.
*/
cancelAll(options?: { reason?: string; resetState?: boolean }): Promise<void>;
/**
* Creates a new {@linkcode TaskInstance} and attempts to run it right away.
* If running this task instance would increase the task's concurrency
* to a number greater than the task's maxConcurrency, this task
* instance might be immediately canceled (dropped), or enqueued
* to run at later time, after the currently running task(s) have finished.
*
* @param args Arguments to pass to the task function.
*/
perform(...args: Args): T;
/**
* Flags the task as linked to the parent task's lifetime. Must be called
* within another task's perform function. The task will be cancelled if the
* parent task is canceled as well.
*
* ember-concurrency will indicate when this may be needed.
*/
linked(): this;
/**
* Flags the task as not linked to the parent task's lifetime. Must be called
* within another task's perform function. The task will NOT be cancelled if the
* parent task is canceled.
*
* This is useful for avoiding the so-called "self-cancel loop" for tasks.
* ember-concurrency will indicate when this may be needed.
*/
unlinked(): this;
}
/**
* The `Task` object lives on a host Ember object (e.g.
* a Component, Route, or Controller). You call the
* {@linkcode Task#perform .perform()} method on this object
* to create run individual {@linkcode TaskInstance}s,
* and at any point, you can call the {@linkcode Task#cancelAll .cancelAll()}
* method on this object to cancel all running or enqueued
* {@linkcode TaskInstance}s.
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface Task<T, Args extends any[]>
extends AbstractTask<Args, TaskInstance<T>> {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface EncapsulatedTask<
T,
Args extends any[],
// eslint-disable-next-line @typescript-eslint/ban-types
State extends object
> extends AbstractTask<Args, EncapsulatedTaskInstance<T, State>> {}
/**
* "Task Groups" provide a means for applying
* task modifiers to groups of tasks. Once a {@linkcode Task} is declared
* as part of a group task, modifiers like `drop` or `restartable`
* will no longer affect the individual `Task`. Instead those
* modifiers can be applied to the entire group.
*
* ```js
* import { task, taskGroup } from 'ember-concurrency';
*
* export default class MyController extends Controller {
* @taskGroup({ drop: true }) chores;
*
* @task({ group: 'chores' }) mowLawn = taskFn;
* @task({ group: 'chores' }) doDishes = taskFn;
* @task({ group: 'chores' }) changeDiapers = taskFn;
* }
* ```
*/
export interface TaskGroup<T> extends TaskState<TaskInstance<T>> {
/**
* Cancels all running or queued `TaskInstance`s for this task group.
* If you're trying to cancel a specific TaskInstance (rather
* than all of the instances running under this task group) call
* `.cancel()` on the specific TaskInstance.
*
* @param options.reason A descriptive reason the task group was
* cancelled. Defaults to `".cancelAll() was explicitly called
* on the Task"`.
* @param options.resetState If true, will clear the task group state
* (`last*` and `performCount` properties will be set to initial
* values). Defaults to false.
*/
cancelAll(options?: { reason?: string; resetState?: boolean }): Promise<void>;
}
/**
* A `TaskInstance` represent a single execution of a
* {@linkcode Task}. Every call to {@linkcode Task#perform} returns
* a `TaskInstance`.
*
* `TaskInstance`s are cancelable, either explicitly
* via {@linkcode TaskInstance#cancel} or {@linkcode Task#cancelAll},
* or automatically due to the host object being destroyed, or
* because concurrency policy enforced by a
* {@linkcode TaskProperty Task Modifier} canceled the task instance.
*/
export interface TaskInstance<T> extends Promise<T> {
/**
* If this TaskInstance runs to completion by returning a property
* other than a rejecting promise, this property will be set
* with that value.
*/
readonly value: T | null;
/**
* If this TaskInstance is canceled or throws an error (or yields
* a promise that rejects), this property will be set with that error.
* Otherwise, it is null.
*/
readonly error: unknown;
/**
* True if the task instance is fulfilled.
*/
readonly isSuccessful: boolean;
/**
* True if the task instance resolves to a rejection.
*/
readonly isError: boolean;
/**
* True if the task instance was canceled before it could run to completion.
*/
readonly isCanceled: boolean;
/**
* True if the task instance has started, else false.
*/
readonly hasStarted: boolean;
/**
* True if the task has run to completion.
*/
readonly isFinished: boolean;
/**
* True if the task is still running.
*/
readonly isRunning: boolean;
/**
* Describes the state that the task instance is in. Can be used for debugging,
* or potentially driving some UI state. Possible values are:
*
* - `"dropped"`: task instance was canceled before it started
* - `"canceled"`: task instance was canceled before it could finish
* - `"finished"`: task instance ran to completion (even if an exception was thrown)
* - `"running"`: task instance is currently running (returns true even if
* is paused on a yielded promise)
* - `"waiting"`: task instance hasn't begun running yet (usually
* because the task is using the {@linkcode TaskProperty#enqueue enqueue}
* task modifier)
*
* The animated timeline examples on the [Task Concurrency](/docs/task-concurrency)
* docs page make use of this property.
*/
readonly state: 'dropped' | 'canceled' | 'finished' | 'running' | 'waiting';
/**
* True if the TaskInstance was canceled before it could
* ever start running. For example, calling
* {@linkcode Task#perform .perform()} twice on a
* task with the {@linkcode TaskProperty#drop .drop} modifier applied
* will result in the second task instance being dropped.
*/
readonly isDropped: boolean;
/**
* Cancels the task instance. Has no effect if the task instance has
* already been canceled or has already finished running.
*
* @param cancelReason Defaults to `".cancel() was explicitly called"`.
*/
cancel(cancelReason?: string): Promise<void>;
/**
* Returns a promise that resolves with the value returned
* from the task's (generator) function, or rejects with
* either the exception thrown from the task function, or
* an error with a `.name` property with value `"TaskCancelation"`.
*/
then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null
): Promise<TResult1 | TResult2>;
catch<TResult = never>(
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null
): Promise<T | TResult>;
finally(onfinally?: (() => void) | null): Promise<T>;
}
// eslint-disable-next-line @typescript-eslint/ban-types
type EncapsulatedTaskInstance<T, State extends object> = TaskInstance<T> &
EncapsulatedTaskState<State>;
interface OnStateCallback<T> {
(state: TaskState<TaskInstance<any>>, taskable: T): void;
}
// This intermediate interface is necessary because
// `interface MyThing<T> extends T {}` is not allowed
interface _AbstractTaskProperty<T extends Task<any, any[]>> {
/**
* Calling `task(...).on(eventName)` configures the task to be
* automatically performed when the specified events fire. In
* this way, it behaves like
* [Ember.on](http://emberjs.com/api/classes/Ember.html#method_on).
*
* You can use `task(...).on('init')` to perform the task
* when the host object is initialized.
*
* ```js
* export default Component.extend({
* pollForUpdates: task(function * () {
* // ... this runs when the Component is first created
* // because we specified .on('init')
* }).on('init'),
*
* handleFoo: task(function * (a, b, c) {
* // this gets performed automatically if the 'foo'
* // event fires on this Component,
* // e.g., if someone called component.trigger('foo')
* }).on('foo'),
* });
* ```
*
* [See the Writing Tasks Docs for more info](/docs/writing-tasks)
*/
on(...eventNames: string[]): this;
/**
* This behaves like the {@linkcode TaskProperty#on task(...).on() modifier},
* but instead will cause the task to be canceled if any of the
* specified events fire on the parent object.
*
* [See the Live Example](/docs/examples/route-tasks/1)
*/
cancelOn(...eventNames: string[]): this;
/**
* This behaves like the {@linkcode TaskProperty#on task(...).on() modifier},
* but instead will cause the task to be performed if any of the
* specified properties on the parent object change.
*/
observes(...keys: string[]): this;
/**
* Configures the task to cancel old currently task instances
* to make room for a new one to perform. Sets default
* maxConcurrency to 1.
*
* [See the Live Example](/docs/examples/route-tasks/1)
*/
restartable(): this;
/**
* Configures the task to run task instances one-at-a-time in
* the order they were `.perform()`ed. Sets default
* maxConcurrency to 1.
*/
enqueue(): this;
/**
* Configures the task to immediately cancel (i.e. drop) any
* task instances performed when the task is already running
* at maxConcurrency. Sets default maxConcurrency to 1.
*/
drop(): this;
/**
* Configures the task to drop all but the most recently
* performed {@linkcode TaskInstance}.
*/
keepLatest(): this;
/**
* Sets the maximum number of task instances that are allowed
* to run at the same time. By default, with no task modifiers
* applied, this number is Infinity (there is no limit
* to the number of tasks that can run at the same time).
* {@linkcode TaskProperty#restartable restartable},
* {@linkcode TaskProperty#enqueue enqueue}, and
* {@linkcode TaskProperty#drop drop} set the default
* maxConcurrency to 1, but you can override this value
* to set the maximum number of concurrently running tasks
* to a number greater than 1.
*
* [See the AJAX Throttling example](/docs/examples/ajax-throttling)
*
* The example below uses a task with `maxConcurrency(3)` to limit
* the number of concurrent AJAX requests (for anyone using this task)
* to 3.
*
* ```js
* doSomeAjax: task(function * (url) {
* return fetch(url);
* }).maxConcurrency(3),
*
* elsewhere() {
* this.get('doSomeAjax').perform("http://www.example.com/json");
* },
* ```
*
* @param n The maximum number of concurrently running tasks.
*/
maxConcurrency(n: number): this;
/**
* Adds this task to a TaskGroup so that concurrency constraints
* can be shared between multiple tasks.
*
* [See the Task Group docs for more information](/docs/task-groups)
*
* @param groupPath A path to the TaskGroup property.
*/
group(groupPath: string): this;
/**
* Activates lifecycle events, allowing Evented host objects to react to task state
* changes.
*
* ```js
*
* export default Component.extend({
* uploadTask: task(function* (file) {
* // ... file upload stuff
* }).evented(),
*
* uploadedStarted: on('uploadTask:started', function(taskInstance) {
* this.analytics.track("User Photo: upload started");
* }),
* });
* ```
*/
evented(): this;
/**
* Logs lifecycle events to aid in debugging unexpected Task behavior.
* Presently only logs cancelation events and the reason for the cancelation,
* e.g. "TaskInstance 'doStuff' was canceled because the object it lives on was destroyed or unrendered"
*/
debug(): this;
/**
* Configures the task to call the passed in callback for derived state updates,
* overriding the default derived state tracking. You may call with `null` to
* completely opt-out of derived state tracking.
*
* @param {function?} callback Callback to be called. Receives an object argument with the new state.
* @instance
*/
onState(callback: OnStateCallback<T> | null): this;
}
type AbstractTaskProperty<T extends Task<any, any[]>> = T &
_AbstractTaskProperty<T>;
/**
* A {@link TaskProperty} is the Computed Property-like object returned
* from the {@linkcode task} function. You can call Task Modifier methods
* on this object to configure the behavior of the {@link Task}.
*
* See [Managing Task Concurrency](/docs/task-concurrency) for an
* overview of all the different task modifiers you can use and how
* they impact automatic cancelation / enqueueing of task instances.
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface TaskProperty<T, Args extends any[]>
extends AbstractTaskProperty<Task<T, Args>> {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface EncapsulatedTaskProperty<
T,
Args extends any[],
// eslint-disable-next-line @typescript-eslint/ban-types
State extends object
> extends AbstractTaskProperty<EncapsulatedTask<T, Args, State>> {}
export interface TaskGroupProperty<T> extends TaskGroup<T> {
/**
* Configures the task group to cancel old currently task
* instances to make room for a new one to perform. Sets
* default maxConcurrency to 1.
*
* [See the Live Example](/docs/examples/route-tasks/1)
*
* @method restartable
* @memberof TaskGroupProperty
* @instance
*/
restartable(): this;
/**
* Configures the task group to run task instances
* one-at-a-time in the order they were `.perform()`ed.
* Sets default maxConcurrency to 1.
*
* @method enqueue
* @memberof TaskGroupProperty
* @instance
*/
enqueue(): this;
/**
* Configures the task group to immediately cancel (i.e.
* drop) any task instances performed when the task group
* is already running at maxConcurrency. Sets default
* maxConcurrency to 1.
*
* @method drop
* @memberof TaskGroupProperty
* @instance
*/
drop(): this;
/**
* Configures the task group to drop all but the most
* recently performed {@linkcode TaskInstance }.
*
* @method keepLatest
* @memberof TaskGroupProperty
* @instance
*/
keepLatest(): this;
/**
* Sets the maximum number of task instances that are
* allowed to run in this task group at the same time.
* By default, with no task modifiers applied, this number
* is Infinity (there is no limit to the number of tasks
* that can run at the same time).
* {@linkcode TaskGroupProperty#restartable .restartable},
* {@linkcode TaskGroupProperty#enqueue .enqueue}, and
* {@linkcode TaskGroupProperty#drop .drop} set the
* default maxConcurrency to 1, but you can override this
* value to set the maximum number of concurrently running
* tasks to a number greater than 1.
*
* [See the AJAX Throttling example](/docs/examples/ajax-throttling)
*
* The example below uses a task group with `maxConcurrency(3)`
* to limit the number of concurrent AJAX requests (for anyone
* using tasks in this group) to 3.
*
* ```js
* ajax: taskGroup().maxConcurrency(3),
*
* doSomeAjax: task(function * (url) {
* return Ember.$.getJSON(url).promise();
* }).group('ajax'),
*
* doSomeAjax: task(function * (url) {
* return Ember.$.getJSON(url).promise();
* }).group('ajax'),
*
* elsewhere() {
* this.get('doSomeAjax').perform("http://www.example.com/json");
* },
* ```
*
* @method maxConcurrency
* @memberof TaskGroupProperty
* @param {Number} n The maximum number of concurrently running tasks
* @instance
*/
maxConcurrency(n: number): this;
}
export type TaskCancelation = Error & { name: 'TaskCancelation' };
export type TaskDefinition<T, Args extends any[]> =
| TaskFunction<T, Args>
| EncapsulatedTaskDescriptor<T, Args>;
export interface TaskModifier<T, Args extends any[]> {
(factory: AbstractTaskFactory<T, Args>, taskModifierOption: any): void;
}
interface AbstractTaskFactory<T, Args extends any[]> {
readonly name: string;
readonly taskDefinition: TaskDefinition<T, Args>;
getOptions(): Record<string, any>;
setDebug(isDebug: boolean): this;
setEvented(isEvented: boolean): this;
setGroup(groupName: string): this;
setMaxConcurrency(maxConcurrency: number): this;
setName(name: string): this;
setOnState(onStateCallback: OnStateCallback<T> | null): this;
setTaskDefinition(taskDefinition: TaskDefinition<T, Args>): this;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface TaskFactory<T, Args extends any[]>
extends AbstractTaskFactory<T, Args> {}
/**
* Registers a new modifier with the modifier registry
*/
export function registerModifier(
name: string,
definition: TaskModifier<any, any[]>
): void;
/**
* Returns a specified modifier, if it exists in the registry
*/
export function getModifier(
name: string
): TaskModifier<unknown, unknown[]> | null;
/**
* Returns whether a specified modifier exists in the registry
*/
export function hasModifier(name: string): boolean;
export interface YieldableState {
/**
* Return yielded TaskInstance. Useful for introspection on instance state.
* @method getTaskInstance
* @memberof YieldableState
*/
getTaskInstance(): TaskInstance<any>;
/**
* Cancel the yielded TaskInstance.
* @method cancel
* @memberof YieldableState
*/
cancel(): void;
/**
* Cause the TaskInstance to return from its yield with an optional value,
* and continue executing.
* @method next
* @param value
*/
next(value: any): void;
/**
* Short-circuit TaskInstance execution and have it return with an optional
* value.
* @param value
*/
return(value: any): void;
/**
* Raise a given error within the given task instance and halt execution
* @param error
*/
throw(error: any): void;
}
export abstract class Yieldable<T> implements PromiseLike<T> {
/**
* Defines what happens when the task encounters `yield myYieldable` and returns
* a disposer function that handles any cleanup.
*
* The state parameter is provided by the runtime, and provides operations for
* interacting with the yielding task instance and advancing, returning,
* throwing, or canceling its execution.
*
* @param {YieldableState} state
*/
abstract onYield(state: YieldableState): () => void;
then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null
): Promise<TResult1 | TResult2>;
catch<TResult = never>(
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null
): Promise<T | TResult>;
finally(onfinally?: (() => void) | null): Promise<T>;
}
type Evented =
| {
on(event: string, callback: (...args: any[]) => void): void;
off(event: string, callback: (...args: any[]) => void): void;
}
| {
one(event: string, callback: (...args: any[]) => void): void;
}
| {
addEventListener(event: string, callback: (...args: any[]) => void): void;
removeEventListener(
event: string,
callback: (...args: any[]) => void
): void;
};
type Resolved<T> = T extends PromiseLike<infer R> ? R : T;
type Settlement<T> =
| { state: 'fulfilled'; value: T }
| { state: 'rejected'; reason: any };
type Settled<T> = Settlement<Resolved<T>>;
// Decorator option types from ember-concurrency-decorators
// eslint-disable-next-line @typescript-eslint/ban-types
type OptionsFor<T extends object> = {
[K in OptionKeysFor<T>]?: OptionTypeFor<T, T[K]>;
};
// eslint-disable-next-line @typescript-eslint/ban-types
type OptionKeysFor<T extends object> = {
[K in keyof T]: OptionKeyFor<T, K, T[K]>;
}[keyof T];
type OptionKeyFor<T, K, F> = F extends (...args: any[]) => T ? K : never;
type OptionTypeFor<T, F> = F extends (...args: infer Args) => T
? Args[0] extends undefined
? true
: Args[0]
: never;
type TaskOptions = OptionsFor<TaskProperty<unknown, unknown[]>>;
type TaskGroupOptions = OptionsFor<TaskGroupProperty<unknown>>;
type AsyncArrowFunctionTaskOptions<
HostObject,
T,
Args extends any[]
> = TaskOptions & {
waitFor?: (
fn: AsyncArrowTaskFunction<HostObject, T, Args>
) => AsyncArrowTaskFunction<HostObject, T, Args>;
};
type MethodOrPropertyDecoratorWithParams<Params extends unknown[]> =
MethodDecorator &
PropertyDecorator &
((...params: Params) => MethodDecorator & PropertyDecorator);
/**
* A Task is a cancelable, restartable, asynchronous operation that
* is driven by a generator function. Tasks are automatically canceled
* when the object they live on is destroyed (e.g. a Component
* is unrendered).
*
* Turns the decorated generator function into a task.
*
* Optionally takes a hash of options that will be applied as modifiers to the
* task. For instance `maxConcurrency`, `on`, `group` or `keepLatest`.
*
* By default, tasks have no concurrency constraints
* (multiple instances of a task can be running at the same time)
* but much of a power of tasks lies in proper usage of Task Modifiers
* that you can apply to a task.
*
* You can also define an
* <a href="/docs/advanced/encapsulated-task">Encapsulated Task</a>
* by decorating an object that defines a `perform` generator
* method.
*
* ```js
* import Component from '@glimmer/component';
* import { task } from 'ember-concurrency';
*
* class MyComponent extends Component {
* @task
* *plainTask() {}
*
* @task({ maxConcurrency: 5, keepLatest: true, cancelOn: 'click' })
* *taskWithModifiers() {}
* }
* ```
*
* @function
* @param {object?} [options={}]
* @return {Task}
*/
export function task<T extends TaskOptions>(
baseOptions?: T
): MethodOrPropertyDecoratorWithParams<[T]>;
export function task<T>(
target: Object,
propertyKey: string,
descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T>;
export function task(target: Object, propertyKey: string): void;
/**
* A Task is a cancelable, restartable, asynchronous operation that
* is driven by a generator function. Tasks are automatically canceled
* when the object they live on is destroyed (e.g. a Component
* is unrendered).
*
* To define a task, use the `task(...)` function, and pass in
* a generator function, which will be invoked when the task
* is performed. The reason generator functions are used is
* that they (like the proposed ES7 async-await syntax) can
* be used to elegantly express asynchronous, cancelable
* operations.
*
* You can also define an
* <a href="/docs/advanced/encapsulated-task">Encapsulated Task</a>
* by passing in an object that defined a `perform` generator
* method.
*
* The following Component defines a task called `myTask` that,
* when performed, prints a message to the console, sleeps for 1 second,
* prints a final message to the console, and then completes.
*
* ```js
* import { task, timeout } from 'ember-concurrency';
* export default Component.extend({
* myTask: task(function * () {
* console.log("Pausing for a second...");
* yield timeout(1000);
* console.log("Done!");
* })
* });
* ```
*
* ```hbs
* <button {{action myTask.perform}}>Perform Task</button>
* ```
*
* By default, tasks have no concurrency constraints
* (multiple instances of a task can be running at the same time)
* but much of a power of tasks lies in proper usage of Task Modifiers
* that you can apply to a task.
*
* @param taskFn A generator function backing the task or an encapsulated task descriptor object with a `perform` generator method.
*/
export function task<T extends TaskFunction<any, any[]>>(
taskFn: T
): TaskProperty<TaskFunctionReturnType<T>, TaskFunctionArgs<T>>;
export function task<T extends EncapsulatedTaskDescriptor<any, any[]>>(
taskFn: T
): EncapsulatedTaskProperty<
EncapsulatedTaskDescriptorReturnType<T>,
EncapsulatedTaskDescriptorArgs<T>,
EncapsulatedTaskState<T>
>;
export function task<
HostObject,
T extends AsyncArrowTaskFunction<HostObject, any, any[]>
>(
hostObject: HostObject,
asyncArrowTaskFn: T
): TaskForAsyncTaskFunction<HostObject, T>;
export function task<
HostObject,
T extends AsyncArrowTaskFunction<HostObject, any, any[]>
>(asyncArrowTaskFn: T): TaskForAsyncTaskFunction<HostObject, T>;
export function task<
HostObject,
O extends AsyncArrowFunctionTaskOptions<HostObject, any, any[]>,
T extends AsyncArrowTaskFunction<HostObject, any, any[]>
>(
hostObject: HostObject,
baseOptions: O,
asyncArrowTaskFn: T
): TaskForAsyncTaskFunction<HostObject, T>;
export function task<
HostObject,
O extends AsyncArrowFunctionTaskOptions<HostObject, any, any[]>,
T extends AsyncArrowTaskFunction<HostObject, any, any[]>
>(baseOptions: O, asyncArrowTaskFn: T): TaskForAsyncTaskFunction<HostObject, T>;
export type AsyncTaskFunction<T, Args extends any[]> = (
...args: Args
) => Promise<T>;
/**
* Turns the decorated generator function into a task and applies the
* `drop` modifier.
*
* Optionally takes a hash of options that will be applied as modifiers to the
* task. For instance `maxConcurrency`, `on`, or `group`.
*
* You can also define an
* <a href="/docs/advanced/encapsulated-task">Encapsulated Task</a>
* by decorating an object that defines a `perform` generator
* method.
*
* ```js
* import Component from '@ember/component';
* import { task, dropTask } from 'ember-concurrency';
*
* class MyComponent extends Component {
* @task
* *plainTask() {}
*
* @dropTask({ cancelOn: 'click' })
* *myDropTask() {}
* }
* ```
*
* @function
* @param {object?} [options={}]
* @return {Task}
*/
export function dropTask<T extends TaskOptions>(
baseOptions?: T
): MethodOrPropertyDecoratorWithParams<[T]>;
export function dropTask<T>(
target: Object,
propertyKey: string,
descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T>;
export function dropTask(target: Object, propertyKey: string): void;
export function dropTask<
HostObject,
T extends AsyncArrowTaskFunction<HostObject, any, any[]>
>(asyncArrowTaskFn: T): TaskForAsyncTaskFunction<HostObject, T>;
export function dropTask<
HostObject,
O extends AsyncArrowFunctionTaskOptions<HostObject, any, any[]>,
T extends AsyncArrowTaskFunction<HostObject, any, any[]>
>(baseOptions: O, asyncArrowTaskFn: T): TaskForAsyncTaskFunction<HostObject, T>;
/**
* Turns the decorated generator function into a task and applies the
* `enqueue` modifier.