-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathfake-timers-src.js
More file actions
2976 lines (2615 loc) · 100 KB
/
fake-timers-src.js
File metadata and controls
2976 lines (2615 loc) · 100 KB
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
"use strict";
const globalObject = require("@sinonjs/commons").global;
let timersModule, timersPromisesModule;
if (typeof require === "function" && typeof module === "object") {
try {
timersModule = require("timers");
} catch {
// ignored
}
try {
timersPromisesModule = require("timers/promises");
} catch {
// ignored
}
}
/**
* @typedef {"nextAsync" | "manual" | "interval"} TickMode
*/
/**
* @typedef {object} NextAsyncTickMode
* @property {"nextAsync"} mode - runs timers one macrotask at a time
*/
/**
* @typedef {object} ManualTickMode
* @property {"manual"} mode - advances only when the caller explicitly ticks
*/
/**
* @typedef {object} IntervalTickMode
* @property {"interval"} mode - advances automatically on a native interval
* @property {number} [delta] - interval duration in milliseconds
*/
/**
* @typedef {IntervalTickMode | NextAsyncTickMode | ManualTickMode} TimerTickMode
*/
/**
* @callback FakeTimersFunction
* @param {...unknown[]} args
* @returns {unknown}
*/
/**
* @callback VoidVarArgsFunc
* @param {...unknown[]} args - optional arguments to call the callback with
* @returns {void}
*/
/**
* @callback NextTick
* @param {VoidVarArgsFunc} callback - the callback to run
* @param {...unknown[]} args - optional arguments to call the callback with
* @returns {void}
*/
/**
* @callback SetImmediate
* @param {VoidVarArgsFunc} callback - the callback to run
* @param {...unknown[]} args - optional arguments to call the callback with
* @returns {NodeImmediate}
*/
/**
* @callback SetTimeout
* @param {VoidVarArgsFunc} callback - the callback to run
* @param {number} [delay] - optional delay in milliseconds
* @param {...unknown[]} args - optional arguments to call the callback with
* @returns {TimerId} - the timeout identifier
*/
/**
* @callback ClearTimeout
* @param {TimerId} [id] - the timeout identifier to clear
* @returns {void}
*/
/**
* @callback SetInterval
* @param {VoidVarArgsFunc} callback - the callback to run
* @param {number} [delay] - optional delay in milliseconds
* @param {...unknown[]} args - optional arguments to call the callback with
* @returns {TimerId} - the interval identifier
*/
/**
* @callback ClearInterval
* @param {TimerId} [id] - the interval identifier to clear
* @returns {void}
*/
/**
* @callback QueueMicrotask
* @param {VoidVarArgsFunc} callback - the callback to run
* @returns {void}
*/
/**
* @callback TimeRemaining
* @returns {number}
*/
/**
* @typedef {object} IdleDeadline
* @property {boolean} didTimeout - whether or not the callback was called before reaching the optional timeout
* @property {TimeRemaining} timeRemaining - a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period
*/
/**
* @callback RequestIdleCallbackCallback
* @param {IdleDeadline} deadline
*/
/**
* Queues a function to be called during a browser's idle periods
* @callback RequestIdleCallback
* @param {RequestIdleCallbackCallback} callback
* @param {{timeout?: number}} [options] - an options object
* @returns {number} the id
*/
/**
* @callback AnimationFrameCallback
* @param {number} timestamp
*/
/**
* @callback RequestAnimationFrame
* @param {AnimationFrameCallback} callback
* @returns {TimerId} - the request id
*/
/**
* @callback CancelAnimationFrame
* @param {TimerId} id - cancels a frame callback
* @returns {void}
*/
/**
* @callback CancelIdleCallback
* @param {TimerId} id - cancels a scheduled idle callback
* @returns {void}
*/
/**
* @callback ClearImmediate
* @param {NodeImmediate} id - faked `clearImmediate`
* @returns {void}
*/
/**
* @callback CountTimers
* @returns {number}
*/
/**
* @callback RunMicrotasks
* @returns {void}
*/
/**
* @callback Tick
* @param {number|string} tickValue milliseconds or a string parseable by parseTime
* @returns {number} will return the new `now` value
*/
/**
* @callback TickAsync
* @param {number|string} tickValue milliseconds or a string parseable by parseTime
* @returns {Promise<number>}
*/
/**
* @callback Next
* @returns {number}
*/
/**
* @callback NextAsync
* @returns {Promise<number>}
*/
/**
* @callback RunAll
* @returns {number}
*/
/**
* @callback RunToFrame
* @returns {number}
*/
/**
* @callback RunAllAsync
* @returns {Promise<number>}
*/
/**
* @callback RunToLast
* @returns {number}
*/
/**
* @callback RunToLastAsync
* @returns {Promise<number>}
*/
/**
* @callback Reset
* @returns {void}
*/
/**
* @callback SetSystemTime
* @param {number|Date} [now] initial mocked time, as milliseconds since epoch or a Date
* @returns {void}
*/
/**
* @callback Jump
* @param {number|string} tickValue milliseconds or a human-readable value like "01:11:15"
* @returns {number}
*/
/**
* @callback Uninstall
* @returns {void}
*/
/**
* @callback SetTickMode
* @param {SetTickModeConfig} tickModeConfig - The new configuration for how the clock should tick.
* @returns {void}
*/
/**
* @callback Hrtime
* @param {Array<number>} [prev]
* @returns {Array<number>}
*/
/**
* @callback WithGlobal
* @param {object} _global Namespace to mock (e.g. `window`)
* @returns {FakeTimers}
*/
/**
* @typedef {"setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime" | "requestAnimationFrame" | "cancelAnimationFrame" | "requestIdleCallback" | "cancelIdleCallback" | "performance" | "queueMicrotask"} FakeMethod
*/
/**
* @typedef {number | NodeImmediate | Timer} TimerId
*/
/* eslint-disable jsdoc/reject-any-type */
/**
* @typedef {Record<string, any> & {
* setTimeout?: SetTimeout,
* clearTimeout?: ClearTimeout,
* setInterval?: SetInterval,
* clearInterval?: ClearInterval,
* setImmediate?: SetImmediate,
* clearImmediate?: ClearImmediate,
* queueMicrotask?: QueueMicrotask,
* requestAnimationFrame?: RequestAnimationFrame,
* cancelAnimationFrame?: CancelAnimationFrame,
* requestIdleCallback?: RequestIdleCallback,
* cancelIdleCallback?: CancelIdleCallback,
* process?: any,
* performance?: any,
* Performance?: any,
* Intl?: any,
* Promise?: typeof Promise,
* Date: typeof Date & { isFake?: boolean, toSource?: () => string, clock?: any }
* }} GlobalObject
*/
/**
* @typedef {object} TimerHeap
* @property {Timer[]} timers - the heap-ordered timers
* @property {() => Timer | undefined} peek - returns the next timer without removing it
* @property {(timer: Timer) => void} push - adds a timer to the heap
* @property {() => Timer | undefined} pop - removes and returns the next timer
* @property {(timer: Timer) => void} remove - removes a specific timer
*/
/**
* @typedef {object} ClockTickMode
* @property {TickMode} mode - active tick mode
* @property {number} counter - increments whenever the mode changes
* @property {number} [delta] - interval length in milliseconds
*/
/**
* @typedef {object} SetTickModeConfig
* @property {TickMode} mode - desired tick mode
* @property {number} [delta] - interval length in milliseconds
*/
/**
* @typedef {Record<string, any> & { clock: Clock }} IntlWithClock
*/
/**
* @typedef {object} Timers
* @property {SetTimeout} setTimeout - native `setTimeout`
* @property {ClearTimeout} clearTimeout - native `clearTimeout`
* @property {SetInterval} setInterval - native `setInterval`
* @property {ClearInterval} clearInterval - native `clearInterval`
* @property {typeof Date} Date - native `Date`
* @property {typeof Intl} [Intl] - native `Intl`
* @property {SetImmediate} [setImmediate] - native `setImmediate`, if available
* @property {ClearImmediate} [clearImmediate] - native `clearImmediate`, if available
* @property {Hrtime} [hrtime] - native `process.hrtime`, if available
* @property {NextTick} [nextTick] - native `process.nextTick`, if available
* @property {Performance} [performance] - native `performance`, if available
* @property {RequestAnimationFrame} [requestAnimationFrame] - native `requestAnimationFrame`, if available
* @property {QueueMicrotask} [queueMicrotask] - whether `queueMicrotask` exists
* @property {CancelAnimationFrame} [cancelAnimationFrame] - native `cancelAnimationFrame`, if available
* @property {RequestIdleCallback} [requestIdleCallback] - native `requestIdleCallback`, if available
* @property {CancelIdleCallback} [cancelIdleCallback] - native `cancelIdleCallback`, if available
*/
/**
* @typedef {object} ClockState
* @property {number} tickFrom - lower bound of the current tick range
* @property {number} tickTo - upper bound of the current tick range
* @property {number} [previous] - previous timer time used during ticking
* @property {number | null} [oldNow] - previous value of `now`
* @property {Timer} [timer] - timer currently being processed
* @property {unknown} [firstException] - first exception raised while processing timers
* @property {number} [nanosTotal] - accumulated nanoseconds from fractional ticks
* @property {number} [msFloat] - accumulated fractional milliseconds
* @property {number} [ms] - accumulated whole milliseconds
*/
/**
* @typedef {object} TimerInitialProps
* @property {VoidVarArgsFunc} func - callback or string to execute
* @property {unknown[]} [args] - arguments passed to the callback
* @property {'Timeout' | 'Interval' | 'Immediate' | 'AnimationFrame' | 'IdleCallback'} [type] - timer kind
* @property {number} [delay] - requested delay in milliseconds
* @property {number} [callAt] - scheduled execution time
* @property {number} [createdAt] - time at which the timer was created
* @property {boolean} [immediate] - whether this timer should run before non-immediate timers at the same time
* @property {number} [id] - unique timer identifier
* @property {Error} [error] - captured stack for loop diagnostics
* @property {number} [interval] - interval for repeated timers
* @property {boolean} [animation] - whether this is an animation frame timer
* @property {boolean} [requestIdleCallback] - whether this is an idle callback timer
* @property {number} [order] - execution order for timers at the same time
* @property {number} [heapIndex] - index in the timer heap
*/
/**
* @callback CreateClockCallback
* @param {number|Date} [start] initial mocked time, as milliseconds since epoch or a Date
* @param {number} [loopLimit] maximum number of timers run before aborting with an infinite-loop error
* @returns {Clock}
*/
/**
* @callback InstallCallback
* @param {Config} [config] Optional config
* @returns {Clock}
*/
/**
* @typedef {object} FakeTimers
* @property {Timers} timers - the native timer APIs saved for later restoration
* @property {CreateClockCallback} createClock - creates a new fake clock
* @property {InstallCallback} install - installs the fake timers onto the default global object
* @property {WithGlobal} withGlobal - creates a fake-timers instance for a provided global object
*/
/**
* @typedef {object} Clock
* @property {number} now - current mocked time in milliseconds
* @property {typeof Date & {clock?: Clock, isFake?: boolean, toSource?: () => string}} Date - fake Date constructor bound to this clock
* @property {number} loopLimit - maximum number of timers before assuming an infinite loop
* @property {RequestIdleCallback} requestIdleCallback - schedules an idle callback
* @property {CancelIdleCallback} cancelIdleCallback - cancels a scheduled idle callback
* @property {SetTimeout} setTimeout - faked `setTimeout`
* @property {ClearTimeout} clearTimeout - faked `clearTimeout`
* @property {NextTick} nextTick - faked `process.nextTick`
* @property {QueueMicrotask} queueMicrotask - faked `queueMicrotask`
* @property {SetInterval} setInterval - faked `setInterval`
* @property {ClearInterval} clearInterval - faked `clearInterval`
* @property {SetImmediate} setImmediate - faked `setImmediate`
* @property {ClearImmediate} clearImmediate - faked `clearImmediate`
* @property {CountTimers} countTimers - counts scheduled timers
* @property {RequestAnimationFrame} requestAnimationFrame - schedules a frame callback
* @property {CancelAnimationFrame} cancelAnimationFrame - cancels a frame callback
* @property {RunMicrotasks} runMicrotasks - drains microtasks
* @property {Tick} tick - advances fake time synchronously
* @property {TickAsync} tickAsync - advances fake time asynchronously
* @property {Next} next - runs the next scheduled timer
* @property {NextAsync} nextAsync - runs the next scheduled timer asynchronously
* @property {RunAll} runAll - runs all scheduled timers
* @property {RunToFrame} runToFrame - runs timers up to the next animation frame
* @property {RunAllAsync} runAllAsync - runs all scheduled timers asynchronously
* @property {RunToLast} runToLast - runs timers up to the last scheduled timer
* @property {RunToLastAsync} runToLastAsync - runs timers up to the last scheduled timer asynchronously
* @property {Reset} reset - clears all timers and resets the clock
* @property {SetSystemTime} setSystemTime - sets the clock to a specific wall-clock time
* @property {Jump} jump - advances time and returns the new `now`
* @property {any} performance - fake performance object
* @property {Hrtime} hrtime - faked `process.hrtime`
* @property {Uninstall} uninstall - restores native timers
* @property {string[]} methods - names of faked methods
* @property {boolean} [shouldClearNativeTimers] - inherited from config
* @property {{methodName:string, original:unknown}[] | undefined} timersModuleMethods - saved Node timers module methods
* @property {{methodName:string, original:unknown}[] | undefined} timersPromisesModuleMethods - saved Node timers/promises methods
* @property {Map<VoidVarArgsFunc, AbortSignal>} abortListenerMap - active abort listeners
* @property {SetTickMode} setTickMode - switches the auto-tick mode
* @property {Map<number, Timer>} [timers] - internal timer storage
* @property {TimerHeap} [timerHeap] - internal timer heap
* @property {boolean} [duringTick] - internal flag
* @property {boolean} isNearInfiniteLimit - internal flag indicating the loop limit is nearly reached
* @property {TimerId} [attachedInterval] - internal flag
* @property {ClockTickMode} [tickMode] - internal flag
* @property {Timer[]} [jobs] - internal flag
* @property {IntlWithClock} [Intl] - fake Intl object
*/
/* eslint-enable jsdoc/reject-any-type */
/**
* Configuration object for the `install` method.
* @typedef {object} Config
* @property {number|Date} [now] initial mocked time, as milliseconds since epoch or a Date
* @property {FakeMethod[]} [toFake] method names that should be faked
* @property {FakeMethod[]} [toNotFake] method names that should remain native
* @property {number} [loopLimit] maximum number of timers run before aborting with an infinite-loop error
* @property {boolean} [shouldAdvanceTime] automatically increments mocked time while the clock is installed
* @property {number} [advanceTimeDelta] interval in milliseconds used when `shouldAdvanceTime` is enabled
* @property {boolean} [shouldClearNativeTimers] forwards clear calls to native methods when the timer is not fake
* @property {boolean} [ignoreMissingTimers] suppresses errors when a requested timer is missing from the global object
* @property {GlobalObject} [target] global object to install onto
*/
/**
* The internal structure to describe a scheduled fake timer
* @typedef {TimerInitialProps} Timer
* @property {unknown[]} args - arguments passed to the callback
* @property {number} callAt - scheduled execution time
* @property {number} createdAt - time at which the timer was created
* @property {number} id - unique timer identifier
* @property {'Timeout' | 'Interval' | 'Immediate' | 'AnimationFrame' | 'IdleCallback'} type - timer kind
*/
/**
* @callback NodeImmediateHasRef
* @returns {boolean}
*/
/**
* @callback NodeImmediateRef
* @returns {NodeImmediate}
*/
/**
* @callback NodeImmediateUnref
* @returns {NodeImmediate}
*/
/**
* A Node timer
* @typedef {object} NodeImmediate
* @property {NodeImmediateHasRef} hasRef - reports whether the timer keeps the event loop alive
* @property {NodeImmediateRef} ref - marks the timer as referenced
* @property {NodeImmediateUnref} unref - marks the timer as unreferenced
*/
/* eslint-disable complexity */
/**
* Mocks available features in the specified global namespace.
* @param {GlobalObject} _global Namespace to mock (e.g. `window`)
* @returns {FakeTimers}
*/
function withGlobal(_global) {
const maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint
const idCounterStart = 1e12; // arbitrarily large number to avoid collisions with native timer IDs
const NOOP = function () {
return undefined;
};
const NOOP_ARRAY = function () {
return [];
};
const isPresent = {};
let timeoutResult,
addTimerReturnsObject = false;
if (_global.setTimeout) {
isPresent.setTimeout = true;
timeoutResult = _global.setTimeout(NOOP, 0);
addTimerReturnsObject = typeof timeoutResult === "object";
}
isPresent.clearTimeout = Boolean(_global.clearTimeout);
isPresent.setInterval = Boolean(_global.setInterval);
isPresent.clearInterval = Boolean(_global.clearInterval);
isPresent.hrtime =
_global.process && typeof _global.process.hrtime === "function";
isPresent.hrtimeBigint =
isPresent.hrtime && typeof _global.process.hrtime.bigint === "function";
isPresent.nextTick =
_global.process && typeof _global.process.nextTick === "function";
const utilPromisify = _global.process && require("util").promisify;
isPresent.performance =
_global.performance && typeof _global.performance.now === "function";
const hasPerformancePrototype =
_global.Performance &&
(typeof _global.Performance).match(/^(function|object)$/);
const hasPerformanceConstructorPrototype =
_global.performance &&
_global.performance.constructor &&
_global.performance.constructor.prototype;
isPresent.queueMicrotask = Object.prototype.hasOwnProperty.call(
_global,
"queueMicrotask",
);
isPresent.requestAnimationFrame =
_global.requestAnimationFrame &&
typeof _global.requestAnimationFrame === "function";
isPresent.cancelAnimationFrame =
_global.cancelAnimationFrame &&
typeof _global.cancelAnimationFrame === "function";
isPresent.requestIdleCallback =
_global.requestIdleCallback &&
typeof _global.requestIdleCallback === "function";
isPresent.cancelIdleCallback =
_global.cancelIdleCallback &&
typeof _global.cancelIdleCallback === "function";
isPresent.setImmediate =
_global.setImmediate && typeof _global.setImmediate === "function";
isPresent.clearImmediate =
_global.clearImmediate && typeof _global.clearImmediate === "function";
isPresent.Intl = _global.Intl && typeof _global.Intl === "object";
if (_global.clearTimeout) {
_global.clearTimeout(timeoutResult);
}
const NativeDate = _global.Date;
const NativeIntl = isPresent.Intl
? Object.defineProperties(
Object.create(null),
Object.getOwnPropertyDescriptors(_global.Intl),
)
: undefined;
let uniqueTimerId = idCounterStart;
/** @type {number} */
let uniqueTimerOrder = 0;
if (NativeDate === undefined) {
throw new Error(
"The global scope doesn't have a `Date` object" +
" (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)",
);
}
isPresent.Date = true;
/**
* The PerformanceEntry object encapsulates a single performance metric
* that is part of the browser's performance timeline.
*
* This is an object returned by the `mark` and `measure` methods on the Performance prototype
*/
class FakePerformanceEntry {
constructor(name, entryType, startTime, duration) {
this.name = name;
this.entryType = entryType;
this.startTime = startTime;
this.duration = duration;
}
toJSON() {
return JSON.stringify({ ...this });
}
}
/**
* @param {number} num
* @returns {boolean}
*/
function isNumberFinite(num) {
if (Number.isFinite) {
return Number.isFinite(num);
}
return isFinite(num);
}
/**
* @param {Clock} clock
* @param {number} i
*/
function checkIsNearInfiniteLimit(clock, i) {
if (clock.loopLimit && i === clock.loopLimit - 1) {
clock.isNearInfiniteLimit = true;
}
}
/**
* @param {Clock} clock
*/
function resetIsNearInfiniteLimit(clock) {
if (clock) {
clock.isNearInfiniteLimit = false;
}
}
/**
* Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
* number of milliseconds. This is used to support human-readable strings passed
* to clock.tick()
* @param {string} str
* @returns {number}
*/
function parseTime(str) {
if (!str) {
return 0;
}
const strings = str.split(":");
const l = strings.length;
let i = l;
let ms = 0;
let parsed;
if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
throw new Error(
"tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits",
);
}
while (i--) {
parsed = parseInt(strings[i], 10);
if (parsed >= 60) {
throw new Error(`Invalid time ${str}`);
}
ms += parsed * Math.pow(60, l - i - 1);
}
return ms * 1000;
}
/**
* Get the decimal part of the millisecond value as nanoseconds
* @param {number} msFloat the number of milliseconds
* @returns {number} an integer number of nanoseconds in the range [0,1e6)
*
* Example: nanoRemainer(123.456789) -> 456789
*/
function nanoRemainder(msFloat) {
const modulo = 1e6;
const remainder = (msFloat * 1e6) % modulo;
const positiveRemainder =
remainder < 0 ? remainder + modulo : remainder;
return Math.floor(positiveRemainder);
}
/**
* Used to grok the `now` parameter to createClock.
* @param {Date|number} epoch the system time
* @returns {number}
*/
function getEpoch(epoch) {
if (!epoch) {
return 0;
}
if (typeof epoch === "number") {
return epoch;
}
if (typeof epoch.getTime === "function") {
return epoch.getTime();
}
throw new TypeError("now should be milliseconds since UNIX epoch");
}
/**
* @param {number} from
* @param {number} to
* @param {Timer} timer
* @returns {boolean}
*/
function inRange(from, to, timer) {
return timer && timer.callAt >= from && timer.callAt <= to;
}
/**
* @param {Clock} clock
* @param {Timer} job
* @returns {Error}
*/
function getInfiniteLoopError(clock, job) {
const infiniteLoopError = new Error(
`Aborting after running ${clock.loopLimit} timers, assuming an infinite loop!`,
);
if (!job.error) {
return infiniteLoopError;
}
// pattern never matched in Node
const computedTargetPattern = /target\.*[<|(|[].*?[>|\]|)]\s*/;
let clockMethodPattern = new RegExp(
String(Object.keys(clock).join("|")),
);
if (addTimerReturnsObject) {
// node.js environment
clockMethodPattern = new RegExp(
`\\s+at (Object\\.)?(?:${Object.keys(clock).join("|")})\\s+`,
);
}
let matchedLineIndex = -1;
job.error.stack.split("\n").some(function (line, i) {
// If we've matched a computed target line (e.g. setTimeout) then we
// don't need to look any further. Return true to stop iterating.
const matchedComputedTarget = line.match(computedTargetPattern);
/* istanbul ignore if */
if (matchedComputedTarget) {
matchedLineIndex = i;
return true;
}
// If we've matched a clock method line, then there may still be
// others further down the trace. Return false to keep iterating.
const matchedClockMethod = line.match(clockMethodPattern);
if (matchedClockMethod) {
matchedLineIndex = i;
return false;
}
// If we haven't matched anything on this line, but we matched
// previously and set the matched line index, then we can stop.
// If we haven't matched previously, then we should keep iterating.
return matchedLineIndex >= 0;
});
const stack = `${infiniteLoopError}\n${job.type || "Microtask"} - ${
job.func.name || "anonymous"
}\n${job.error.stack
.split("\n")
.slice(matchedLineIndex + 1)
.join("\n")}`;
try {
Object.defineProperty(infiniteLoopError, "stack", {
value: stack,
});
} catch {
// noop
}
return infiniteLoopError;
}
/**
* @returns {typeof Date & { clock: Clock }}
*/
function createDate() {
class ClockDate extends NativeDate {
/** @type {Clock} */
static clock;
constructor(...args) {
// Preserve fake time when Date is called without arguments.
if (args.length === 0) {
super(ClockDate.clock.now);
} else {
// The subclass is intentionally thin for explicit args.
// @ts-expect-error Date constructor overloads are intentionally dynamic.
super(...args);
}
// ensures identity checks using the constructor prop still works
// this should have no other functional effect
Object.defineProperty(this, "constructor", {
value: NativeDate,
enumerable: false,
});
}
static [Symbol.hasInstance](instance) {
return instance instanceof NativeDate;
}
}
ClockDate.isFake = true;
if (NativeDate.now) {
ClockDate.now = function now() {
return ClockDate.clock.now;
};
}
const NativeDateWithToSource =
/** @type {typeof Date & { toSource?: () => string }} */ (
NativeDate
);
if (NativeDateWithToSource.toSource) {
ClockDate.toSource = function toSource() {
return NativeDateWithToSource.toSource();
};
}
ClockDate.toString = function toString() {
return NativeDateWithToSource.toString();
};
// noinspection UnnecessaryLocalVariableJS
/**
* A normal Class constructor cannot be called without `new`, but Date can, so we need
* to wrap it in a Proxy in order to ensure this functionality of Date is kept intact
* @type {typeof ClockDate}
*/
const ClockDateProxy = new Proxy(ClockDate, {
// handler for [[Call]] invocations (i.e. not using `new`)
apply() {
// the Date constructor called as a function, ref Ecma-262 Edition 5.1, section 15.9.2.
// This remains so in the 10th edition of 2019 as well.
if (this instanceof ClockDate) {
throw new TypeError(
"A Proxy should only capture `new` calls with the `construct` handler. This is not supposed to be possible, so check the logic.",
);
}
return new NativeDate(ClockDate.clock.now).toString();
},
});
return /** @type {typeof Date & { clock: Clock }} */ (
/** @type {unknown} */ (ClockDateProxy)
);
}
/**
* Mirror Intl by default on our fake implementation
*
* Most of the properties are the original native ones,
* but we need to take control of those that have a
* dependency on the current clock.
* @param {Clock} clock
* @returns {IntlWithClock} the partly fake Intl implementation
*/
function createIntl(clock) {
/** @type {IntlWithClock} */
const IntlWithClock = { clock: clock };
/*
* All properties of Intl are non-enumerable, so we need
* to do a bit of work to get them out.
*/
Object.getOwnPropertyNames(NativeIntl).forEach(
(property) => (IntlWithClock[property] = NativeIntl[property]),
);
IntlWithClock.DateTimeFormat = function (...args) {
const realFormatter = new NativeIntl.DateTimeFormat(...args);
const formatter = {};
["formatRange", "formatRangeToParts", "resolvedOptions"].forEach(
(method) => {
formatter[method] =
realFormatter[method].bind(realFormatter);
},
);
["format", "formatToParts"].forEach((method) => {
formatter[method] = function (date) {
return realFormatter[method](
date || IntlWithClock.clock.now,
);
};
});
return formatter;
};
IntlWithClock.DateTimeFormat.prototype = Object.create(
NativeIntl.DateTimeFormat.prototype,
);
IntlWithClock.DateTimeFormat.supportedLocalesOf =
NativeIntl.DateTimeFormat.supportedLocalesOf;
return IntlWithClock;
}
//eslint-disable-next-line jsdoc/require-jsdoc
function enqueueJob(clock, job) {
// enqueues a microtick-deferred task - ecma262/#sec-enqueuejob
if (!clock.jobs) {
clock.jobs = [];
}
clock.jobs.push(job);
}
//eslint-disable-next-line jsdoc/require-jsdoc
function runJobs(clock) {
// runs all microtick-deferred tasks - ecma262/#sec-runjobs
if (!clock.jobs) {
return;
}
const wasNearLimit = clock.isNearInfiniteLimit;
for (let i = 0; i < clock.jobs.length; i++) {
const job = clock.jobs[i];
job.func.apply(null, job.args);
checkIsNearInfiniteLimit(clock, i);
if (clock.loopLimit && i > clock.loopLimit) {
throw getInfiniteLoopError(clock, job);
}
}
if (!wasNearLimit) {
resetIsNearInfiniteLimit(clock);
}
clock.jobs = [];
}
/**
* A compact "soonest timer first" container.
*
* Think of this as a waiting room for scheduled callbacks where the next
* callback to run is always kept at the front of the list. The internal
* array is arranged so we can find, add, remove, and reorder timers
* efficiently without sorting the whole list every time something changes.
*
* The important idea is not the data structure name, but the behavior:
* the timer that should run next stays near the front, and when one timer
* moves, the rest are shifted just enough to keep that promise true.
*/
class TimerHeap {
constructor() {
this.timers = [];
}
/**
* Look at the next timer without removing it.
* This is the timer the clock would run first if time advanced now.
* @returns {Timer}
*/
peek() {
return this.timers[0];
}
/**
* Add a timer to the waiting room, then move it upward until it is in
* the right place relative to the timers it should run before and after.
* @param {Timer} timer
*/
push(timer) {
this.timers.push(timer);
this.bubbleUp(this.timers.length - 1);
}
/**
* Remove and return the next timer to run.
*
* We pull the front timer out, move the last timer into the empty spot,
* and then shift that replacement down until the ordering is correct
* again. That avoids rebuilding the whole list from scratch.
* @returns {Timer|undefined}
*/
pop() {
if (this.timers.length === 0) {
return undefined;
}
const first = this.timers[0];
const last = this.timers.pop();
if (this.timers.length > 0) {
this.timers[0] = last;
last.heapIndex = 0;
this.bubbleDown(0);
}
delete first.heapIndex;
return first;
}
/**
* Remove a specific timer from the waiting room.
*
* The heap stores timers in a shape that lets us jump directly to the
* timer's current position, replace it with the last timer, and then
* move that replacement up or down until the ordering is correct again.
* @param {Timer} timer
* @returns {boolean}
*/
remove(timer) {