Repository navigation
Expand file tree
/
Copy pathclock.js
More file actions
3330 lines (2956 loc) · 119 KB
/
Copy pathclock.js
File metadata and controls
3330 lines (2956 loc) · 119 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
// clock.js is Biloba's page clock: fake timers for the page's own code, installed in a document only
// when a spec calls InstallClock. Biloba never runs it otherwise. engine/clock.js is a copy (`go
// generate ./engine`); edit this file, not that one.
//
// The timers themselves are @sinonjs/fake-timers, vendored unmodified at the bottom of this file:
//
// version: 15.4.0, src/fake-timers-src.js from the npm package
// tarball: https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-15.4.0.tgz
// integrity: sha512-DsG+8/LscQIQg68J6Ef3dv10u6nVyetYn923s3/sus5eaGfTo1of5WMZSLf0UJc9KDuKPilPH0UDJCjvNbDNCA==
// sha256 of src/fake-timers-src.js: c669ee91933b8e0e7d7fc41aa324aa9c0ec60058170c29788bd834f63b809b1e
//
// Its license, which applies to that section:
//
// Copyright (c) 2010-2014, Christian Johansen, christian@cjohansen.no. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions
// and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// What Biloba adds is the controller below, which plays the part Playwright's clock controller plays
// for its own copy: it decides when fake time moves. Installed time flows from the start time at the
// real rate (a driver on the real setTimeout advances the fake clock to match real elapsed time) until
// the spec pauses it; RunFor steps through due callbacks one task at a time so promise callbacks run in
// between, as they would between real tasks.
//
// The controller also smooths over the places sinon's semantics differ from a browser's, without
// touching sinon itself:
//
// - A callback that throws is reported with reportError, as the browser reports an uncaught error in a
// real timer, and the clock keeps going. sinon would rethrow it out of tick() and drop any later
// error from the same tick.
// - setInterval's delay is at least 1ms. sinon reschedules a 0ms interval at the same instant
// forever, where a browser clamps it.
// - performance.now() continues from the real value it had at install, rather than restarting at
// zero, so a document that read it before InstallClock does not see time run backwards. Only now()
// is replaced: sinon's "performance" fake swaps the whole object for one whose other methods do
// nothing. An animation frame's timestamp gets the same offset.
// - Date can be pinned (SetFixedTime) while timers keep running, which sinon has no notion of.
//
// Biloba's own code (biloba.js) never sees any of this: it captures the real requestAnimationFrame and
// friends when it installs, which is always before this file runs in a document.
//
// One clock per document. Go installs it in every document of the tab it can reach and re-registers a
// new-document script after each operation, carrying the clock's state so a document that loads later
// starts where the others are.
if (!window._bilobaInstallClock) {
window._bilobaInstallClock = (() => {
// Captured before sinon replaces them; the controller only ever uses these.
const real = {
setTimeout: window.setTimeout.bind(window),
clearTimeout: window.clearTimeout.bind(window),
now: performance.now.bind(performance),
dateNow: Date.now,
MessageChannel: window.MessageChannel,
reportError: window.reportError ? window.reportError.bind(window) : (e) => window.setTimeout(() => { throw e }),
}
const faked = ["setTimeout", "clearTimeout", "setInterval", "clearInterval", "Date", "requestAnimationFrame",
"cancelAnimationFrame", "requestIdleCallback", "cancelIdleCallback"]
// one real task: the page's microtasks run before it resolves, and a MessageChannel post is not
// subject to the 4ms clamp that nested setTimeouts get
const macrotask = () => new Promise(resolve => {
let channel = new real.MessageChannel()
channel.port1.onmessage = () => { channel.port1.close(); resolve() }
channel.port2.postMessage(null)
})
let fakeTimers = null
return (snapshot) => {
if (window._bilobaClock) return window._bilobaClock.state()
// A snapshot with a wall time is a clock that has been flowing since then: catch up.
let start = (snapshot.paused || snapshot.wall == null) ? snapshot.now : snapshot.now + (real.dateNow() - snapshot.wall)
fakeTimers = fakeTimers || loadFakeTimers()
let clock = fakeTimers.withGlobal(window).install({
now: Math.floor(start), toFake: faked, shouldClearNativeTimers: true, ignoreMissingTimers: true,
})
let perfBase = real.now()
let paused = !!snapshot.paused, fixed = snapshot.fixed == null ? null : snapshot.fixed
let generation = 0, driver = null, advancing = false, flowBase = clock.now, realBase = real.now()
// sinon's window functions call clock[name] on every call, so wrapping the clock's own wraps
// the page's. Keep sinon's own-property flag so uninstall restores the right thing.
let guard = (fn) => typeof fn !== "function" ? fn : function () {
try { return fn.apply(this, arguments) } catch (e) { real.reportError(e) }
}
let wrap = (name, make) => {
let original = clock[name]
let wrapped = make(original)
wrapped.hasOwnProperty = original.hasOwnProperty
clock[name] = wrapped
}
wrap("setTimeout", (o) => function (fn, delay, ...args) { let id = o(guard(fn), delay, ...args); nudge(); return id })
wrap("setInterval", (o) => function (fn, delay, ...args) { let id = o(guard(fn), Math.max(1, Number(delay) || 0), ...args); nudge(); return id })
wrap("requestAnimationFrame", (o) => function (fn) {
let id = o(typeof fn !== "function" ? fn : (t) => guard(fn)(perfBase + t)); nudge(); return id
})
if (clock.requestIdleCallback) wrap("requestIdleCallback", (o) => function (fn, options) { let id = o(guard(fn), options); nudge(); return id })
Object.defineProperty(performance, "now", { configurable: true, writable: true, value: function now() { return perfBase + clock.performance.now() } })
clock.Date.clock = { get now() { return fixed === null ? clock.now : fixed } }
let nextDue = (target) => {
let next = clock.timerHeap && clock.timerHeap.peek()
return next && next.callAt <= target ? next : null
}
// advance runs every timer and animation frame due up to target in order, one callback time
// per real task. A later clock operation (generation) takes over from it.
let advance = async (target, gen, deadline) => {
let fired = 0
advancing = true
try {
for (let next = nextDue(target); next; next = nextDue(target)) {
if (gen !== generation) return { fired }
if (deadline !== undefined && real.now() > deadline) return { fired, exceeded: true }
let at = next.callAt
clock.tick(Math.max(0, at - clock.now))
fired++
// a timer tick could not fire would otherwise be stepped to forever
if (clock.timerHeap.peek() === next && next.callAt === at) break
await macrotask()
}
if (gen === generation && target > clock.now) clock.tick(target - clock.now)
return { fired }
} finally {
advancing = false
}
}
// While time flows, a driver on the real setTimeout wakes for the next due callback, and at
// least once a frame, and brings fake time up to real elapsed time.
let flowNow = () => Math.floor(flowBase + (real.now() - realBase))
let schedule = () => {
real.clearTimeout(driver)
driver = null
if (paused) return
let next = clock.timerHeap && clock.timerHeap.peek()
let wait = next ? Math.min(16, Math.max(0, next.callAt - flowNow())) : 16
let gen = generation
driver = real.setTimeout(async () => {
if (gen !== generation) return
await advance(flowNow(), gen)
if (gen === generation) schedule()
}, wait)
}
let nudge = () => { if (!paused && !advancing) schedule() }
let takeOver = () => { generation++; real.clearTimeout(driver); driver = null }
let state = () => ({ now: clock.now, paused, fixed, wall: real.dateNow() })
let settle = () => {
if (!paused) { flowBase = clock.now; realBase = real.now(); schedule() }
return state()
}
window._bilobaClock = {
state,
pauseAt: (ms) => {
takeOver()
if (ms >= clock.now) clock.jump(ms - clock.now)
else clock.setSystemTime(ms)
paused = true
return state()
},
resume: () => { takeOver(); paused = false; return settle() },
runFor: async (ms, budget) => {
takeOver()
let gen = generation
let result = await advance(clock.now + ms, gen, real.now() + budget)
if (gen !== generation) return state()
return Object.assign(settle(), result)
},
fastForward: (ms) => { takeOver(); clock.jump(ms); return settle() },
setFixedTime: (ms) => { takeOver(); fixed = ms; return settle() },
setSystemTime: (ms) => { takeOver(); clock.setSystemTime(ms); fixed = null; return settle() },
uninstall: () => {
takeOver()
clock.uninstall()
delete performance.now
delete window._bilobaClock
return true
},
}
return settle()
}
// loadFakeTimers evaluates the vendored module in its own scope: it reads `require` for its one
// dependency (@sinonjs/commons, of which it uses only `global`) and writes `exports`. There is no
// `module` here, so it never reaches for Node's timers.
function loadFakeTimers() {
const exports = {}
const require = (name) => {
if (name === "@sinonjs/commons") return { global: globalThis }
throw new Error("clock.js: unexpected require(" + JSON.stringify(name) + ")")
}
;(function (exports, require) {
// ---- BEGIN @sinonjs/fake-timers 15.4.0 src/fake-timers-src.js (unmodified) ----
"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}
*/
/**
* @typedef {object} TemporalDuration
* @property {number} years - years component
* @property {number} months - months component
* @property {number} weeks - weeks component
* @property {number} days - days component
* @property {number} hours - hours component
* @property {number} minutes - minutes component
* @property {number} seconds - seconds component
* @property {number} milliseconds - milliseconds component
* @property {number} microseconds - microseconds component
* @property {number} nanoseconds - nanoseconds component
* @property {(options: {unit: string, relativeTo?: unknown}) => number} total - converts to a single unit
*/
/**
* @typedef {object} TemporalTimelike
* @property {number} epochMilliseconds - milliseconds since the Unix epoch (present on Temporal.Instant and Temporal.ZonedDateTime)
*/
/**
* @callback Tick
* @param {number|string|TemporalDuration} tickValue milliseconds, a string parseable by parseTime, or a Temporal.Duration
* @returns {number} will return the new `now` value
*/
/**
* @callback TickAsync
* @param {number|string|TemporalDuration} tickValue milliseconds, a string parseable by parseTime, or a Temporal.Duration
* @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|TemporalTimelike} [now] initial mocked time, as milliseconds since epoch, a Date, a Temporal.Instant, or a Temporal.ZonedDateTime
* @returns {void}
*/
/**
* @callback Jump
* @param {number|string|TemporalDuration} tickValue milliseconds, a human-readable value like "01:11:15", or a Temporal.Duration
* @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" | "Intl" | "Temporal"} 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,
* Temporal?: 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 {Record<string, any> & { now: () => number }} PerformanceLike
*/
/**
* @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 {any} [Temporal] - native `Temporal`
* @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 {PerformanceLike} [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|TemporalTimelike} [start] initial mocked time, as milliseconds since epoch, a Date, a Temporal.Instant, or a Temporal.ZonedDateTime
* @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
* @property {any} [Temporal] - fake Temporal object
*/
/* eslint-enable jsdoc/reject-any-type */
/**
* Configuration object for the `install` method.
* @typedef {object} Config
* @property {number|Date|TemporalTimelike} [now] initial mocked time, as milliseconds since epoch, a Date, a Temporal.Instant, or a Temporal.ZonedDateTime
* @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";
isPresent.Temporal =
_global.Temporal !== null &&
typeof _global.Temporal === "object" &&
typeof _global.Temporal.Now !== "undefined" &&
typeof _global.Temporal.Instant !== "undefined";
if (_global.clearTimeout) {
_global.clearTimeout(timeoutResult);
}
const NativeDate = _global.Date;
const NativeIntl = isPresent.Intl
? Object.defineProperties(
Object.create(null),
Object.getOwnPropertyDescriptors(_global.Intl),
)
: undefined;
const NativeTemporal = isPresent.Temporal ? _global.Temporal : 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|TemporalTimelike} epoch the system time
* @returns {number}
*/
function getEpoch(epoch) {
if (!epoch) {
return 0;
}
if (typeof epoch === "number") {
return epoch;
}
if (typeof (/** @type {Date} */ (epoch).getTime) === "function") {
return /** @type {Date} */ (epoch).getTime();
}
if (
typeof (
/** @type {TemporalTimelike} */ (epoch).epochMilliseconds
) === "number"
) {
// Temporal.Instant and Temporal.ZonedDateTime both have epochMilliseconds
return /** @type {TemporalTimelike} */ (epoch).epochMilliseconds;
}
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;
});