chunk-runtime-hooks.e4219ed5.mjs 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832
  1. import { g as getCurrentSuite, w as withTimeout, a as getDefaultHookTimeout, s as suite, t as test, d as describe, i as it, b as bench, c as createExpect, e as globalExpect } from './chunk-runtime-chain.0ab05798.mjs';
  2. import { g as getWorkerState, R as RealDate, r as resetDate, m as mockDate, a as resetModules } from './chunk-mock-date.2917be60.mjs';
  3. import { p as parseStacktrace } from './chunk-utils-source-map.2be5aa48.mjs';
  4. import { c as commonjsGlobal } from './vendor-_commonjsHelpers.4da45ef5.mjs';
  5. import util from 'util';
  6. import { spyOn, fn, isMockFunction, spies } from './spy.mjs';
  7. import { s as safeSetTimeout } from './chunk-utils-timers.b48455ed.mjs';
  8. import * as chai from 'chai';
  9. import { assert, should } from 'chai';
  10. const beforeAll = (fn, timeout) => getCurrentSuite().on("beforeAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true));
  11. const afterAll = (fn, timeout) => getCurrentSuite().on("afterAll", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true));
  12. const beforeEach = (fn, timeout) => getCurrentSuite().on("beforeEach", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true));
  13. const afterEach = (fn, timeout) => getCurrentSuite().on("afterEach", withTimeout(fn, timeout ?? getDefaultHookTimeout(), true));
  14. function withCallback(fn) {
  15. return new Promise(
  16. (resolve, reject) => fn((err) => {
  17. if (err)
  18. reject(err);
  19. else
  20. resolve();
  21. })
  22. );
  23. }
  24. const filesCount = /* @__PURE__ */ new Map();
  25. const cache = /* @__PURE__ */ new Map();
  26. function runOnce(fn, key) {
  27. const filepath = getWorkerState().filepath || "__unknown_files__";
  28. if (!key) {
  29. filesCount.set(filepath, (filesCount.get(filepath) || 0) + 1);
  30. key = String(filesCount.get(filepath));
  31. }
  32. const id = `${filepath}:${key}`;
  33. if (!cache.has(id))
  34. cache.set(id, fn());
  35. return cache.get(id);
  36. }
  37. function isFirstRun() {
  38. let firstRun = false;
  39. runOnce(() => {
  40. firstRun = true;
  41. }, "__vitest_first_run__");
  42. return firstRun;
  43. }
  44. function resetRunOnceCounter() {
  45. filesCount.clear();
  46. }
  47. /**
  48. * A reference to the global object
  49. *
  50. * @type {object} globalObject
  51. */
  52. var globalObject$1;
  53. /* istanbul ignore else */
  54. if (typeof commonjsGlobal !== "undefined") {
  55. // Node
  56. globalObject$1 = commonjsGlobal;
  57. } else if (typeof window !== "undefined") {
  58. // Browser
  59. globalObject$1 = window;
  60. } else {
  61. // WebWorker
  62. globalObject$1 = self;
  63. }
  64. var global = globalObject$1;
  65. var call = Function.call;
  66. var copyPrototype$6 = function copyPrototypeMethods(prototype) {
  67. // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
  68. return Object.getOwnPropertyNames(prototype).reduce(function(result, name) {
  69. // ignore size because it throws from Map
  70. if (
  71. name !== "size" &&
  72. name !== "caller" &&
  73. name !== "callee" &&
  74. name !== "arguments" &&
  75. typeof prototype[name] === "function"
  76. ) {
  77. result[name] = call.bind(prototype[name]);
  78. }
  79. return result;
  80. }, Object.create(null));
  81. };
  82. var copyPrototype$5 = copyPrototype$6;
  83. var array = copyPrototype$5(Array.prototype);
  84. var every$1 = array.every;
  85. /**
  86. * @private
  87. */
  88. function hasCallsLeft(callMap, spy) {
  89. if (callMap[spy.id] === undefined) {
  90. callMap[spy.id] = 0;
  91. }
  92. return callMap[spy.id] < spy.callCount;
  93. }
  94. /**
  95. * @private
  96. */
  97. function checkAdjacentCalls(callMap, spy, index, spies) {
  98. var calledBeforeNext = true;
  99. if (index !== spies.length - 1) {
  100. calledBeforeNext = spy.calledBefore(spies[index + 1]);
  101. }
  102. if (hasCallsLeft(callMap, spy) && calledBeforeNext) {
  103. callMap[spy.id] += 1;
  104. return true;
  105. }
  106. return false;
  107. }
  108. /**
  109. * A Sinon proxy object (fake, spy, stub)
  110. *
  111. * @typedef {object} SinonProxy
  112. * @property {Function} calledBefore - A method that determines if this proxy was called before another one
  113. * @property {string} id - Some id
  114. * @property {number} callCount - Number of times this proxy has been called
  115. */
  116. /**
  117. * Returns true when the spies have been called in the order they were supplied in
  118. *
  119. * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments
  120. * @returns {boolean} true when spies are called in order, false otherwise
  121. */
  122. function calledInOrder(spies) {
  123. var callMap = {};
  124. // eslint-disable-next-line no-underscore-dangle
  125. var _spies = arguments.length > 1 ? arguments : spies;
  126. return every$1(_spies, checkAdjacentCalls.bind(null, callMap));
  127. }
  128. var calledInOrder_1 = calledInOrder;
  129. /**
  130. * Returns a display name for a function
  131. *
  132. * @param {Function} func
  133. * @returns {string}
  134. */
  135. var functionName$1 = function functionName(func) {
  136. if (!func) {
  137. return "";
  138. }
  139. try {
  140. return (
  141. func.displayName ||
  142. func.name ||
  143. // Use function decomposition as a last resort to get function
  144. // name. Does not rely on function decomposition to work - if it
  145. // doesn't debugging will be slightly less informative
  146. // (i.e. toString will say 'spy' rather than 'myFunc').
  147. (String(func).match(/function ([^\s(]+)/) || [])[1]
  148. );
  149. } catch (e) {
  150. // Stringify may fail and we might get an exception, as a last-last
  151. // resort fall back to empty string.
  152. return "";
  153. }
  154. };
  155. var functionName = functionName$1;
  156. /**
  157. * Returns a display name for a value from a constructor
  158. *
  159. * @param {object} value A value to examine
  160. * @returns {(string|null)} A string or null
  161. */
  162. function className(value) {
  163. return (
  164. (value.constructor && value.constructor.name) ||
  165. // The next branch is for IE11 support only:
  166. // Because the name property is not set on the prototype
  167. // of the Function object, we finally try to grab the
  168. // name from its definition. This will never be reached
  169. // in node, so we are not able to test this properly.
  170. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  171. (typeof value.constructor === "function" &&
  172. /* istanbul ignore next */
  173. functionName(value.constructor)) ||
  174. null
  175. );
  176. }
  177. var className_1 = className;
  178. var deprecated = {};
  179. /* eslint-disable no-console */
  180. (function (exports) {
  181. /**
  182. * Returns a function that will invoke the supplied function and print a
  183. * deprecation warning to the console each time it is called.
  184. *
  185. * @param {Function} func
  186. * @param {string} msg
  187. * @returns {Function}
  188. */
  189. exports.wrap = function(func, msg) {
  190. var wrapped = function() {
  191. exports.printWarning(msg);
  192. return func.apply(this, arguments);
  193. };
  194. if (func.prototype) {
  195. wrapped.prototype = func.prototype;
  196. }
  197. return wrapped;
  198. };
  199. /**
  200. * Returns a string which can be supplied to `wrap()` to notify the user that a
  201. * particular part of the sinon API has been deprecated.
  202. *
  203. * @param {string} packageName
  204. * @param {string} funcName
  205. * @returns {string}
  206. */
  207. exports.defaultMsg = function(packageName, funcName) {
  208. return (
  209. packageName +
  210. "." +
  211. funcName +
  212. " is deprecated and will be removed from the public API in a future version of " +
  213. packageName +
  214. "."
  215. );
  216. };
  217. /**
  218. * Prints a warning on the console, when it exists
  219. *
  220. * @param {string} msg
  221. * @returns {undefined}
  222. */
  223. exports.printWarning = function(msg) {
  224. /* istanbul ignore next */
  225. if (typeof process === "object" && process.emitWarning) {
  226. // Emit Warnings in Node
  227. process.emitWarning(msg);
  228. } else if (console.info) {
  229. console.info(msg);
  230. } else {
  231. console.log(msg);
  232. }
  233. };
  234. } (deprecated));
  235. /**
  236. * Returns true when fn returns true for all members of obj.
  237. * This is an every implementation that works for all iterables
  238. *
  239. * @param {object} obj
  240. * @param {Function} fn
  241. * @returns {boolean}
  242. */
  243. var every = function every(obj, fn) {
  244. var pass = true;
  245. try {
  246. // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
  247. obj.forEach(function() {
  248. if (!fn.apply(this, arguments)) {
  249. // Throwing an error is the only way to break `forEach`
  250. throw new Error();
  251. }
  252. });
  253. } catch (e) {
  254. pass = false;
  255. }
  256. return pass;
  257. };
  258. var sort = array.sort;
  259. var slice = array.slice;
  260. /**
  261. * @private
  262. */
  263. function comparator(a, b) {
  264. // uuid, won't ever be equal
  265. var aCall = a.getCall(0);
  266. var bCall = b.getCall(0);
  267. var aId = (aCall && aCall.callId) || -1;
  268. var bId = (bCall && bCall.callId) || -1;
  269. return aId < bId ? -1 : 1;
  270. }
  271. /**
  272. * A Sinon proxy object (fake, spy, stub)
  273. *
  274. * @typedef {object} SinonProxy
  275. * @property {Function} getCall - A method that can return the first call
  276. */
  277. /**
  278. * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call
  279. *
  280. * @param {SinonProxy[] | SinonProxy} spies
  281. * @returns {SinonProxy[]}
  282. */
  283. function orderByFirstCall(spies) {
  284. return sort(slice(spies), comparator);
  285. }
  286. var orderByFirstCall_1 = orderByFirstCall;
  287. var copyPrototype$4 = copyPrototype$6;
  288. var _function = copyPrototype$4(Function.prototype);
  289. var copyPrototype$3 = copyPrototype$6;
  290. var map = copyPrototype$3(Map.prototype);
  291. var copyPrototype$2 = copyPrototype$6;
  292. var object = copyPrototype$2(Object.prototype);
  293. var copyPrototype$1 = copyPrototype$6;
  294. var set = copyPrototype$1(Set.prototype);
  295. var copyPrototype = copyPrototype$6;
  296. var string = copyPrototype(String.prototype);
  297. var prototypes = {
  298. array: array,
  299. function: _function,
  300. map: map,
  301. object: object,
  302. set: set,
  303. string: string
  304. };
  305. var typeDetect = {exports: {}};
  306. (function (module, exports) {
  307. (function (global, factory) {
  308. module.exports = factory() ;
  309. }(commonjsGlobal, (function () {
  310. /* !
  311. * type-detect
  312. * Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
  313. * MIT Licensed
  314. */
  315. var promiseExists = typeof Promise === 'function';
  316. /* eslint-disable no-undef */
  317. var globalObject = typeof self === 'object' ? self : commonjsGlobal; // eslint-disable-line id-blacklist
  318. var symbolExists = typeof Symbol !== 'undefined';
  319. var mapExists = typeof Map !== 'undefined';
  320. var setExists = typeof Set !== 'undefined';
  321. var weakMapExists = typeof WeakMap !== 'undefined';
  322. var weakSetExists = typeof WeakSet !== 'undefined';
  323. var dataViewExists = typeof DataView !== 'undefined';
  324. var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined';
  325. var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined';
  326. var setEntriesExists = setExists && typeof Set.prototype.entries === 'function';
  327. var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function';
  328. var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries());
  329. var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries());
  330. var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function';
  331. var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]());
  332. var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function';
  333. var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]());
  334. var toStringLeftSliceLength = 8;
  335. var toStringRightSliceLength = -1;
  336. /**
  337. * ### typeOf (obj)
  338. *
  339. * Uses `Object.prototype.toString` to determine the type of an object,
  340. * normalising behaviour across engine versions & well optimised.
  341. *
  342. * @param {Mixed} object
  343. * @return {String} object type
  344. * @api public
  345. */
  346. function typeDetect(obj) {
  347. /* ! Speed optimisation
  348. * Pre:
  349. * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled)
  350. * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled)
  351. * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled)
  352. * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled)
  353. * function x 2,556,769 ops/sec ±1.73% (77 runs sampled)
  354. * Post:
  355. * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled)
  356. * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled)
  357. * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled)
  358. * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled)
  359. * function x 31,296,870 ops/sec ±0.96% (83 runs sampled)
  360. */
  361. var typeofObj = typeof obj;
  362. if (typeofObj !== 'object') {
  363. return typeofObj;
  364. }
  365. /* ! Speed optimisation
  366. * Pre:
  367. * null x 28,645,765 ops/sec ±1.17% (82 runs sampled)
  368. * Post:
  369. * null x 36,428,962 ops/sec ±1.37% (84 runs sampled)
  370. */
  371. if (obj === null) {
  372. return 'null';
  373. }
  374. /* ! Spec Conformance
  375. * Test: `Object.prototype.toString.call(window)``
  376. * - Node === "[object global]"
  377. * - Chrome === "[object global]"
  378. * - Firefox === "[object Window]"
  379. * - PhantomJS === "[object Window]"
  380. * - Safari === "[object Window]"
  381. * - IE 11 === "[object Window]"
  382. * - IE Edge === "[object Window]"
  383. * Test: `Object.prototype.toString.call(this)``
  384. * - Chrome Worker === "[object global]"
  385. * - Firefox Worker === "[object DedicatedWorkerGlobalScope]"
  386. * - Safari Worker === "[object DedicatedWorkerGlobalScope]"
  387. * - IE 11 Worker === "[object WorkerGlobalScope]"
  388. * - IE Edge Worker === "[object WorkerGlobalScope]"
  389. */
  390. if (obj === globalObject) {
  391. return 'global';
  392. }
  393. /* ! Speed optimisation
  394. * Pre:
  395. * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled)
  396. * Post:
  397. * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled)
  398. */
  399. if (
  400. Array.isArray(obj) &&
  401. (symbolToStringTagExists === false || !(Symbol.toStringTag in obj))
  402. ) {
  403. return 'Array';
  404. }
  405. // Not caching existence of `window` and related properties due to potential
  406. // for `window` to be unset before tests in quasi-browser environments.
  407. if (typeof window === 'object' && window !== null) {
  408. /* ! Spec Conformance
  409. * (https://html.spec.whatwg.org/multipage/browsers.html#location)
  410. * WhatWG HTML$7.7.3 - The `Location` interface
  411. * Test: `Object.prototype.toString.call(window.location)``
  412. * - IE <=11 === "[object Object]"
  413. * - IE Edge <=13 === "[object Object]"
  414. */
  415. if (typeof window.location === 'object' && obj === window.location) {
  416. return 'Location';
  417. }
  418. /* ! Spec Conformance
  419. * (https://html.spec.whatwg.org/#document)
  420. * WhatWG HTML$3.1.1 - The `Document` object
  421. * Note: Most browsers currently adher to the W3C DOM Level 2 spec
  422. * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268)
  423. * which suggests that browsers should use HTMLTableCellElement for
  424. * both TD and TH elements. WhatWG separates these.
  425. * WhatWG HTML states:
  426. * > For historical reasons, Window objects must also have a
  427. * > writable, configurable, non-enumerable property named
  428. * > HTMLDocument whose value is the Document interface object.
  429. * Test: `Object.prototype.toString.call(document)``
  430. * - Chrome === "[object HTMLDocument]"
  431. * - Firefox === "[object HTMLDocument]"
  432. * - Safari === "[object HTMLDocument]"
  433. * - IE <=10 === "[object Document]"
  434. * - IE 11 === "[object HTMLDocument]"
  435. * - IE Edge <=13 === "[object HTMLDocument]"
  436. */
  437. if (typeof window.document === 'object' && obj === window.document) {
  438. return 'Document';
  439. }
  440. if (typeof window.navigator === 'object') {
  441. /* ! Spec Conformance
  442. * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray)
  443. * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray
  444. * Test: `Object.prototype.toString.call(navigator.mimeTypes)``
  445. * - IE <=10 === "[object MSMimeTypesCollection]"
  446. */
  447. if (typeof window.navigator.mimeTypes === 'object' &&
  448. obj === window.navigator.mimeTypes) {
  449. return 'MimeTypeArray';
  450. }
  451. /* ! Spec Conformance
  452. * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
  453. * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray
  454. * Test: `Object.prototype.toString.call(navigator.plugins)``
  455. * - IE <=10 === "[object MSPluginsCollection]"
  456. */
  457. if (typeof window.navigator.plugins === 'object' &&
  458. obj === window.navigator.plugins) {
  459. return 'PluginArray';
  460. }
  461. }
  462. if ((typeof window.HTMLElement === 'function' ||
  463. typeof window.HTMLElement === 'object') &&
  464. obj instanceof window.HTMLElement) {
  465. /* ! Spec Conformance
  466. * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
  467. * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement`
  468. * Test: `Object.prototype.toString.call(document.createElement('blockquote'))``
  469. * - IE <=10 === "[object HTMLBlockElement]"
  470. */
  471. if (obj.tagName === 'BLOCKQUOTE') {
  472. return 'HTMLQuoteElement';
  473. }
  474. /* ! Spec Conformance
  475. * (https://html.spec.whatwg.org/#htmltabledatacellelement)
  476. * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement`
  477. * Note: Most browsers currently adher to the W3C DOM Level 2 spec
  478. * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
  479. * which suggests that browsers should use HTMLTableCellElement for
  480. * both TD and TH elements. WhatWG separates these.
  481. * Test: Object.prototype.toString.call(document.createElement('td'))
  482. * - Chrome === "[object HTMLTableCellElement]"
  483. * - Firefox === "[object HTMLTableCellElement]"
  484. * - Safari === "[object HTMLTableCellElement]"
  485. */
  486. if (obj.tagName === 'TD') {
  487. return 'HTMLTableDataCellElement';
  488. }
  489. /* ! Spec Conformance
  490. * (https://html.spec.whatwg.org/#htmltableheadercellelement)
  491. * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement`
  492. * Note: Most browsers currently adher to the W3C DOM Level 2 spec
  493. * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
  494. * which suggests that browsers should use HTMLTableCellElement for
  495. * both TD and TH elements. WhatWG separates these.
  496. * Test: Object.prototype.toString.call(document.createElement('th'))
  497. * - Chrome === "[object HTMLTableCellElement]"
  498. * - Firefox === "[object HTMLTableCellElement]"
  499. * - Safari === "[object HTMLTableCellElement]"
  500. */
  501. if (obj.tagName === 'TH') {
  502. return 'HTMLTableHeaderCellElement';
  503. }
  504. }
  505. }
  506. /* ! Speed optimisation
  507. * Pre:
  508. * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled)
  509. * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled)
  510. * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled)
  511. * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled)
  512. * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled)
  513. * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled)
  514. * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled)
  515. * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled)
  516. * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled)
  517. * Post:
  518. * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled)
  519. * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled)
  520. * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled)
  521. * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled)
  522. * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled)
  523. * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled)
  524. * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled)
  525. * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled)
  526. * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled)
  527. */
  528. var stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]);
  529. if (typeof stringTag === 'string') {
  530. return stringTag;
  531. }
  532. var objPrototype = Object.getPrototypeOf(obj);
  533. /* ! Speed optimisation
  534. * Pre:
  535. * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled)
  536. * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled)
  537. * Post:
  538. * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled)
  539. * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled)
  540. */
  541. if (objPrototype === RegExp.prototype) {
  542. return 'RegExp';
  543. }
  544. /* ! Speed optimisation
  545. * Pre:
  546. * date x 2,130,074 ops/sec ±4.42% (68 runs sampled)
  547. * Post:
  548. * date x 3,953,779 ops/sec ±1.35% (77 runs sampled)
  549. */
  550. if (objPrototype === Date.prototype) {
  551. return 'Date';
  552. }
  553. /* ! Spec Conformance
  554. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag)
  555. * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise":
  556. * Test: `Object.prototype.toString.call(Promise.resolve())``
  557. * - Chrome <=47 === "[object Object]"
  558. * - Edge <=20 === "[object Object]"
  559. * - Firefox 29-Latest === "[object Promise]"
  560. * - Safari 7.1-Latest === "[object Promise]"
  561. */
  562. if (promiseExists && objPrototype === Promise.prototype) {
  563. return 'Promise';
  564. }
  565. /* ! Speed optimisation
  566. * Pre:
  567. * set x 2,222,186 ops/sec ±1.31% (82 runs sampled)
  568. * Post:
  569. * set x 4,545,879 ops/sec ±1.13% (83 runs sampled)
  570. */
  571. if (setExists && objPrototype === Set.prototype) {
  572. return 'Set';
  573. }
  574. /* ! Speed optimisation
  575. * Pre:
  576. * map x 2,396,842 ops/sec ±1.59% (81 runs sampled)
  577. * Post:
  578. * map x 4,183,945 ops/sec ±6.59% (82 runs sampled)
  579. */
  580. if (mapExists && objPrototype === Map.prototype) {
  581. return 'Map';
  582. }
  583. /* ! Speed optimisation
  584. * Pre:
  585. * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled)
  586. * Post:
  587. * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled)
  588. */
  589. if (weakSetExists && objPrototype === WeakSet.prototype) {
  590. return 'WeakSet';
  591. }
  592. /* ! Speed optimisation
  593. * Pre:
  594. * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled)
  595. * Post:
  596. * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled)
  597. */
  598. if (weakMapExists && objPrototype === WeakMap.prototype) {
  599. return 'WeakMap';
  600. }
  601. /* ! Spec Conformance
  602. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag)
  603. * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView":
  604. * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))``
  605. * - Edge <=13 === "[object Object]"
  606. */
  607. if (dataViewExists && objPrototype === DataView.prototype) {
  608. return 'DataView';
  609. }
  610. /* ! Spec Conformance
  611. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag)
  612. * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator":
  613. * Test: `Object.prototype.toString.call(new Map().entries())``
  614. * - Edge <=13 === "[object Object]"
  615. */
  616. if (mapExists && objPrototype === mapIteratorPrototype) {
  617. return 'Map Iterator';
  618. }
  619. /* ! Spec Conformance
  620. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag)
  621. * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator":
  622. * Test: `Object.prototype.toString.call(new Set().entries())``
  623. * - Edge <=13 === "[object Object]"
  624. */
  625. if (setExists && objPrototype === setIteratorPrototype) {
  626. return 'Set Iterator';
  627. }
  628. /* ! Spec Conformance
  629. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag)
  630. * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator":
  631. * Test: `Object.prototype.toString.call([][Symbol.iterator]())``
  632. * - Edge <=13 === "[object Object]"
  633. */
  634. if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) {
  635. return 'Array Iterator';
  636. }
  637. /* ! Spec Conformance
  638. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag)
  639. * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator":
  640. * Test: `Object.prototype.toString.call(''[Symbol.iterator]())``
  641. * - Edge <=13 === "[object Object]"
  642. */
  643. if (stringIteratorExists && objPrototype === stringIteratorPrototype) {
  644. return 'String Iterator';
  645. }
  646. /* ! Speed optimisation
  647. * Pre:
  648. * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled)
  649. * Post:
  650. * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled)
  651. */
  652. if (objPrototype === null) {
  653. return 'Object';
  654. }
  655. return Object
  656. .prototype
  657. .toString
  658. .call(obj)
  659. .slice(toStringLeftSliceLength, toStringRightSliceLength);
  660. }
  661. return typeDetect;
  662. })));
  663. } (typeDetect));
  664. var type = typeDetect.exports;
  665. /**
  666. * Returns the lower-case result of running type from type-detect on the value
  667. *
  668. * @param {*} value
  669. * @returns {string}
  670. */
  671. var typeOf = function typeOf(value) {
  672. return type(value).toLowerCase();
  673. };
  674. /**
  675. * Returns a string representation of the value
  676. *
  677. * @param {*} value
  678. * @returns {string}
  679. */
  680. function valueToString(value) {
  681. if (value && value.toString) {
  682. // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods
  683. return value.toString();
  684. }
  685. return String(value);
  686. }
  687. var valueToString_1 = valueToString;
  688. var lib = {
  689. global: global,
  690. calledInOrder: calledInOrder_1,
  691. className: className_1,
  692. deprecated: deprecated,
  693. every: every,
  694. functionName: functionName$1,
  695. orderByFirstCall: orderByFirstCall_1,
  696. prototypes: prototypes,
  697. typeOf: typeOf,
  698. valueToString: valueToString_1
  699. };
  700. const globalObject = lib.global;
  701. /**
  702. * @typedef {object} IdleDeadline
  703. * @property {boolean} didTimeout - whether or not the callback was called before reaching the optional timeout
  704. * @property {function():number} timeRemaining - a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period
  705. */
  706. /**
  707. * Queues a function to be called during a browser's idle periods
  708. *
  709. * @callback RequestIdleCallback
  710. * @param {function(IdleDeadline)} callback
  711. * @param {{timeout: number}} options - an options object
  712. * @returns {number} the id
  713. */
  714. /**
  715. * @callback NextTick
  716. * @param {VoidVarArgsFunc} callback - the callback to run
  717. * @param {...*} arguments - optional arguments to call the callback with
  718. * @returns {void}
  719. */
  720. /**
  721. * @callback SetImmediate
  722. * @param {VoidVarArgsFunc} callback - the callback to run
  723. * @param {...*} arguments - optional arguments to call the callback with
  724. * @returns {NodeImmediate}
  725. */
  726. /**
  727. * @callback VoidVarArgsFunc
  728. * @param {...*} callback - the callback to run
  729. * @returns {void}
  730. */
  731. /**
  732. * @typedef RequestAnimationFrame
  733. * @property {function(number):void} requestAnimationFrame
  734. * @returns {number} - the id
  735. */
  736. /**
  737. * @typedef Performance
  738. * @property {function(): number} now
  739. */
  740. /* eslint-disable jsdoc/require-property-description */
  741. /**
  742. * @typedef {object} Clock
  743. * @property {number} now - the current time
  744. * @property {Date} Date - the Date constructor
  745. * @property {number} loopLimit - the maximum number of timers before assuming an infinite loop
  746. * @property {RequestIdleCallback} requestIdleCallback
  747. * @property {function(number):void} cancelIdleCallback
  748. * @property {setTimeout} setTimeout
  749. * @property {clearTimeout} clearTimeout
  750. * @property {NextTick} nextTick
  751. * @property {queueMicrotask} queueMicrotask
  752. * @property {setInterval} setInterval
  753. * @property {clearInterval} clearInterval
  754. * @property {SetImmediate} setImmediate
  755. * @property {function(NodeImmediate):void} clearImmediate
  756. * @property {function():number} countTimers
  757. * @property {RequestAnimationFrame} requestAnimationFrame
  758. * @property {function(number):void} cancelAnimationFrame
  759. * @property {function():void} runMicrotasks
  760. * @property {function(string | number): number} tick
  761. * @property {function(string | number): Promise<number>} tickAsync
  762. * @property {function(): number} next
  763. * @property {function(): Promise<number>} nextAsync
  764. * @property {function(): number} runAll
  765. * @property {function(): number} runToFrame
  766. * @property {function(): Promise<number>} runAllAsync
  767. * @property {function(): number} runToLast
  768. * @property {function(): Promise<number>} runToLastAsync
  769. * @property {function(): void} reset
  770. * @property {function(number | Date): void} setSystemTime
  771. * @property {Performance} performance
  772. * @property {function(number[]): number[]} hrtime - process.hrtime (legacy)
  773. * @property {function(): void} uninstall Uninstall the clock.
  774. * @property {Function[]} methods - the methods that are faked
  775. * @property {boolean} [shouldClearNativeTimers] inherited from config
  776. */
  777. /* eslint-enable jsdoc/require-property-description */
  778. /**
  779. * Configuration object for the `install` method.
  780. *
  781. * @typedef {object} Config
  782. * @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch)
  783. * @property {string[]} [toFake] names of the methods that should be faked.
  784. * @property {number} [loopLimit] the maximum number of timers that will be run when calling runAll()
  785. * @property {boolean} [shouldAdvanceTime] tells FakeTimers to increment mocked time automatically (default false)
  786. * @property {number} [advanceTimeDelta] increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
  787. * @property {boolean} [shouldClearNativeTimers] forwards clear timer calls to native functions if they are not fakes (default: false)
  788. */
  789. /* eslint-disable jsdoc/require-property-description */
  790. /**
  791. * The internal structure to describe a scheduled fake timer
  792. *
  793. * @typedef {object} Timer
  794. * @property {Function} func
  795. * @property {*[]} args
  796. * @property {number} delay
  797. * @property {number} callAt
  798. * @property {number} createdAt
  799. * @property {boolean} immediate
  800. * @property {number} id
  801. * @property {Error} [error]
  802. */
  803. /**
  804. * A Node timer
  805. *
  806. * @typedef {object} NodeImmediate
  807. * @property {function(): boolean} hasRef
  808. * @property {function(): NodeImmediate} ref
  809. * @property {function(): NodeImmediate} unref
  810. */
  811. /* eslint-enable jsdoc/require-property-description */
  812. /* eslint-disable complexity */
  813. /**
  814. * Mocks available features in the specified global namespace.
  815. *
  816. * @param {*} _global Namespace to mock (e.g. `window`)
  817. * @returns {FakeTimers}
  818. */
  819. function withGlobal(_global) {
  820. const userAgent = _global.navigator && _global.navigator.userAgent;
  821. const isRunningInIE = userAgent && userAgent.indexOf("MSIE ") > -1;
  822. const maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint
  823. const idCounterStart = 1e12; // arbitrarily large number to avoid collisions with native timer IDs
  824. const NOOP = function () {
  825. return undefined;
  826. };
  827. const NOOP_ARRAY = function () {
  828. return [];
  829. };
  830. const timeoutResult = _global.setTimeout(NOOP, 0);
  831. const addTimerReturnsObject = typeof timeoutResult === "object";
  832. const hrtimePresent =
  833. _global.process && typeof _global.process.hrtime === "function";
  834. const hrtimeBigintPresent =
  835. hrtimePresent && typeof _global.process.hrtime.bigint === "function";
  836. const nextTickPresent =
  837. _global.process && typeof _global.process.nextTick === "function";
  838. const utilPromisify = _global.process && util.promisify;
  839. const performancePresent =
  840. _global.performance && typeof _global.performance.now === "function";
  841. const hasPerformancePrototype =
  842. _global.Performance &&
  843. (typeof _global.Performance).match(/^(function|object)$/);
  844. const hasPerformanceConstructorPrototype =
  845. _global.performance &&
  846. _global.performance.constructor &&
  847. _global.performance.constructor.prototype;
  848. const queueMicrotaskPresent = _global.hasOwnProperty("queueMicrotask");
  849. const requestAnimationFramePresent =
  850. _global.requestAnimationFrame &&
  851. typeof _global.requestAnimationFrame === "function";
  852. const cancelAnimationFramePresent =
  853. _global.cancelAnimationFrame &&
  854. typeof _global.cancelAnimationFrame === "function";
  855. const requestIdleCallbackPresent =
  856. _global.requestIdleCallback &&
  857. typeof _global.requestIdleCallback === "function";
  858. const cancelIdleCallbackPresent =
  859. _global.cancelIdleCallback &&
  860. typeof _global.cancelIdleCallback === "function";
  861. const setImmediatePresent =
  862. _global.setImmediate && typeof _global.setImmediate === "function";
  863. // Make properties writable in IE, as per
  864. // https://www.adequatelygood.com/Replacing-setTimeout-Globally.html
  865. /* eslint-disable no-self-assign */
  866. if (isRunningInIE) {
  867. _global.setTimeout = _global.setTimeout;
  868. _global.clearTimeout = _global.clearTimeout;
  869. _global.setInterval = _global.setInterval;
  870. _global.clearInterval = _global.clearInterval;
  871. _global.Date = _global.Date;
  872. }
  873. // setImmediate is not a standard function
  874. // avoid adding the prop to the window object if not present
  875. if (setImmediatePresent) {
  876. _global.setImmediate = _global.setImmediate;
  877. _global.clearImmediate = _global.clearImmediate;
  878. }
  879. /* eslint-enable no-self-assign */
  880. _global.clearTimeout(timeoutResult);
  881. const NativeDate = _global.Date;
  882. let uniqueTimerId = idCounterStart;
  883. /**
  884. * @param {number} num
  885. * @returns {boolean}
  886. */
  887. function isNumberFinite(num) {
  888. if (Number.isFinite) {
  889. return Number.isFinite(num);
  890. }
  891. return isFinite(num);
  892. }
  893. let isNearInfiniteLimit = false;
  894. /**
  895. * @param {Clock} clock
  896. * @param {number} i
  897. */
  898. function checkIsNearInfiniteLimit(clock, i) {
  899. if (clock.loopLimit && i === clock.loopLimit - 1) {
  900. isNearInfiniteLimit = true;
  901. }
  902. }
  903. /**
  904. *
  905. */
  906. function resetIsNearInfiniteLimit() {
  907. isNearInfiniteLimit = false;
  908. }
  909. /**
  910. * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
  911. * number of milliseconds. This is used to support human-readable strings passed
  912. * to clock.tick()
  913. *
  914. * @param {string} str
  915. * @returns {number}
  916. */
  917. function parseTime(str) {
  918. if (!str) {
  919. return 0;
  920. }
  921. const strings = str.split(":");
  922. const l = strings.length;
  923. let i = l;
  924. let ms = 0;
  925. let parsed;
  926. if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
  927. throw new Error(
  928. "tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits"
  929. );
  930. }
  931. while (i--) {
  932. parsed = parseInt(strings[i], 10);
  933. if (parsed >= 60) {
  934. throw new Error(`Invalid time ${str}`);
  935. }
  936. ms += parsed * Math.pow(60, l - i - 1);
  937. }
  938. return ms * 1000;
  939. }
  940. /**
  941. * Get the decimal part of the millisecond value as nanoseconds
  942. *
  943. * @param {number} msFloat the number of milliseconds
  944. * @returns {number} an integer number of nanoseconds in the range [0,1e6)
  945. *
  946. * Example: nanoRemainer(123.456789) -> 456789
  947. */
  948. function nanoRemainder(msFloat) {
  949. const modulo = 1e6;
  950. const remainder = (msFloat * 1e6) % modulo;
  951. const positiveRemainder =
  952. remainder < 0 ? remainder + modulo : remainder;
  953. return Math.floor(positiveRemainder);
  954. }
  955. /**
  956. * Used to grok the `now` parameter to createClock.
  957. *
  958. * @param {Date|number} epoch the system time
  959. * @returns {number}
  960. */
  961. function getEpoch(epoch) {
  962. if (!epoch) {
  963. return 0;
  964. }
  965. if (typeof epoch.getTime === "function") {
  966. return epoch.getTime();
  967. }
  968. if (typeof epoch === "number") {
  969. return epoch;
  970. }
  971. throw new TypeError("now should be milliseconds since UNIX epoch");
  972. }
  973. /**
  974. * @param {number} from
  975. * @param {number} to
  976. * @param {Timer} timer
  977. * @returns {boolean}
  978. */
  979. function inRange(from, to, timer) {
  980. return timer && timer.callAt >= from && timer.callAt <= to;
  981. }
  982. /**
  983. * @param {Clock} clock
  984. * @param {Timer} job
  985. */
  986. function getInfiniteLoopError(clock, job) {
  987. const infiniteLoopError = new Error(
  988. `Aborting after running ${clock.loopLimit} timers, assuming an infinite loop!`
  989. );
  990. if (!job.error) {
  991. return infiniteLoopError;
  992. }
  993. // pattern never matched in Node
  994. const computedTargetPattern = /target\.*[<|(|[].*?[>|\]|)]\s*/;
  995. let clockMethodPattern = new RegExp(
  996. String(Object.keys(clock).join("|"))
  997. );
  998. if (addTimerReturnsObject) {
  999. // node.js environment
  1000. clockMethodPattern = new RegExp(
  1001. `\\s+at (Object\\.)?(?:${Object.keys(clock).join("|")})\\s+`
  1002. );
  1003. }
  1004. let matchedLineIndex = -1;
  1005. job.error.stack.split("\n").some(function (line, i) {
  1006. // If we've matched a computed target line (e.g. setTimeout) then we
  1007. // don't need to look any further. Return true to stop iterating.
  1008. const matchedComputedTarget = line.match(computedTargetPattern);
  1009. /* istanbul ignore if */
  1010. if (matchedComputedTarget) {
  1011. matchedLineIndex = i;
  1012. return true;
  1013. }
  1014. // If we've matched a clock method line, then there may still be
  1015. // others further down the trace. Return false to keep iterating.
  1016. const matchedClockMethod = line.match(clockMethodPattern);
  1017. if (matchedClockMethod) {
  1018. matchedLineIndex = i;
  1019. return false;
  1020. }
  1021. // If we haven't matched anything on this line, but we matched
  1022. // previously and set the matched line index, then we can stop.
  1023. // If we haven't matched previously, then we should keep iterating.
  1024. return matchedLineIndex >= 0;
  1025. });
  1026. const stack = `${infiniteLoopError}\n${job.type || "Microtask"} - ${
  1027. job.func.name || "anonymous"
  1028. }\n${job.error.stack
  1029. .split("\n")
  1030. .slice(matchedLineIndex + 1)
  1031. .join("\n")}`;
  1032. try {
  1033. Object.defineProperty(infiniteLoopError, "stack", {
  1034. value: stack,
  1035. });
  1036. } catch (e) {
  1037. // noop
  1038. }
  1039. return infiniteLoopError;
  1040. }
  1041. /**
  1042. * @param {Date} target
  1043. * @param {Date} source
  1044. * @returns {Date} the target after modifications
  1045. */
  1046. function mirrorDateProperties(target, source) {
  1047. let prop;
  1048. for (prop in source) {
  1049. if (source.hasOwnProperty(prop)) {
  1050. target[prop] = source[prop];
  1051. }
  1052. }
  1053. // set special now implementation
  1054. if (source.now) {
  1055. target.now = function now() {
  1056. return target.clock.now;
  1057. };
  1058. } else {
  1059. delete target.now;
  1060. }
  1061. // set special toSource implementation
  1062. if (source.toSource) {
  1063. target.toSource = function toSource() {
  1064. return source.toSource();
  1065. };
  1066. } else {
  1067. delete target.toSource;
  1068. }
  1069. // set special toString implementation
  1070. target.toString = function toString() {
  1071. return source.toString();
  1072. };
  1073. target.prototype = source.prototype;
  1074. target.parse = source.parse;
  1075. target.UTC = source.UTC;
  1076. target.prototype.toUTCString = source.prototype.toUTCString;
  1077. target.isFake = true;
  1078. return target;
  1079. }
  1080. //eslint-disable-next-line jsdoc/require-jsdoc
  1081. function createDate() {
  1082. /**
  1083. * @param {number} year
  1084. * @param {number} month
  1085. * @param {number} date
  1086. * @param {number} hour
  1087. * @param {number} minute
  1088. * @param {number} second
  1089. * @param {number} ms
  1090. *
  1091. * @returns {Date}
  1092. */
  1093. function ClockDate(year, month, date, hour, minute, second, ms) {
  1094. // the Date constructor called as a function, ref Ecma-262 Edition 5.1, section 15.9.2.
  1095. // This remains so in the 10th edition of 2019 as well.
  1096. if (!(this instanceof ClockDate)) {
  1097. return new NativeDate(ClockDate.clock.now).toString();
  1098. }
  1099. // if Date is called as a constructor with 'new' keyword
  1100. // Defensive and verbose to avoid potential harm in passing
  1101. // explicit undefined when user does not pass argument
  1102. switch (arguments.length) {
  1103. case 0:
  1104. return new NativeDate(ClockDate.clock.now);
  1105. case 1:
  1106. return new NativeDate(year);
  1107. case 2:
  1108. return new NativeDate(year, month);
  1109. case 3:
  1110. return new NativeDate(year, month, date);
  1111. case 4:
  1112. return new NativeDate(year, month, date, hour);
  1113. case 5:
  1114. return new NativeDate(year, month, date, hour, minute);
  1115. case 6:
  1116. return new NativeDate(
  1117. year,
  1118. month,
  1119. date,
  1120. hour,
  1121. minute,
  1122. second
  1123. );
  1124. default:
  1125. return new NativeDate(
  1126. year,
  1127. month,
  1128. date,
  1129. hour,
  1130. minute,
  1131. second,
  1132. ms
  1133. );
  1134. }
  1135. }
  1136. return mirrorDateProperties(ClockDate, NativeDate);
  1137. }
  1138. //eslint-disable-next-line jsdoc/require-jsdoc
  1139. function enqueueJob(clock, job) {
  1140. // enqueues a microtick-deferred task - ecma262/#sec-enqueuejob
  1141. if (!clock.jobs) {
  1142. clock.jobs = [];
  1143. }
  1144. clock.jobs.push(job);
  1145. }
  1146. //eslint-disable-next-line jsdoc/require-jsdoc
  1147. function runJobs(clock) {
  1148. // runs all microtick-deferred tasks - ecma262/#sec-runjobs
  1149. if (!clock.jobs) {
  1150. return;
  1151. }
  1152. for (let i = 0; i < clock.jobs.length; i++) {
  1153. const job = clock.jobs[i];
  1154. job.func.apply(null, job.args);
  1155. checkIsNearInfiniteLimit(clock, i);
  1156. if (clock.loopLimit && i > clock.loopLimit) {
  1157. throw getInfiniteLoopError(clock, job);
  1158. }
  1159. }
  1160. resetIsNearInfiniteLimit();
  1161. clock.jobs = [];
  1162. }
  1163. /**
  1164. * @param {Clock} clock
  1165. * @param {Timer} timer
  1166. * @returns {number} id of the created timer
  1167. */
  1168. function addTimer(clock, timer) {
  1169. if (timer.func === undefined) {
  1170. throw new Error("Callback must be provided to timer calls");
  1171. }
  1172. if (addTimerReturnsObject) {
  1173. // Node.js environment
  1174. if (typeof timer.func !== "function") {
  1175. throw new TypeError(
  1176. `[ERR_INVALID_CALLBACK]: Callback must be a function. Received ${
  1177. timer.func
  1178. } of type ${typeof timer.func}`
  1179. );
  1180. }
  1181. }
  1182. if (isNearInfiniteLimit) {
  1183. timer.error = new Error();
  1184. }
  1185. timer.type = timer.immediate ? "Immediate" : "Timeout";
  1186. if (timer.hasOwnProperty("delay")) {
  1187. if (typeof timer.delay !== "number") {
  1188. timer.delay = parseInt(timer.delay, 10);
  1189. }
  1190. if (!isNumberFinite(timer.delay)) {
  1191. timer.delay = 0;
  1192. }
  1193. timer.delay = timer.delay > maxTimeout ? 1 : timer.delay;
  1194. timer.delay = Math.max(0, timer.delay);
  1195. }
  1196. if (timer.hasOwnProperty("interval")) {
  1197. timer.type = "Interval";
  1198. timer.interval = timer.interval > maxTimeout ? 1 : timer.interval;
  1199. }
  1200. if (timer.hasOwnProperty("animation")) {
  1201. timer.type = "AnimationFrame";
  1202. timer.animation = true;
  1203. }
  1204. if (timer.hasOwnProperty("idleCallback")) {
  1205. timer.type = "IdleCallback";
  1206. timer.idleCallback = true;
  1207. }
  1208. if (!clock.timers) {
  1209. clock.timers = {};
  1210. }
  1211. timer.id = uniqueTimerId++;
  1212. timer.createdAt = clock.now;
  1213. timer.callAt =
  1214. clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
  1215. clock.timers[timer.id] = timer;
  1216. if (addTimerReturnsObject) {
  1217. const res = {
  1218. refed: true,
  1219. ref: function () {
  1220. this.refed = true;
  1221. return res;
  1222. },
  1223. unref: function () {
  1224. this.refed = false;
  1225. return res;
  1226. },
  1227. hasRef: function () {
  1228. return this.refed;
  1229. },
  1230. refresh: function () {
  1231. timer.callAt =
  1232. clock.now +
  1233. (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
  1234. // it _might_ have been removed, but if not the assignment is perfectly fine
  1235. clock.timers[timer.id] = timer;
  1236. return res;
  1237. },
  1238. [Symbol.toPrimitive]: function () {
  1239. return timer.id;
  1240. },
  1241. };
  1242. return res;
  1243. }
  1244. return timer.id;
  1245. }
  1246. /* eslint consistent-return: "off" */
  1247. /**
  1248. * Timer comparitor
  1249. *
  1250. * @param {Timer} a
  1251. * @param {Timer} b
  1252. * @returns {number}
  1253. */
  1254. function compareTimers(a, b) {
  1255. // Sort first by absolute timing
  1256. if (a.callAt < b.callAt) {
  1257. return -1;
  1258. }
  1259. if (a.callAt > b.callAt) {
  1260. return 1;
  1261. }
  1262. // Sort next by immediate, immediate timers take precedence
  1263. if (a.immediate && !b.immediate) {
  1264. return -1;
  1265. }
  1266. if (!a.immediate && b.immediate) {
  1267. return 1;
  1268. }
  1269. // Sort next by creation time, earlier-created timers take precedence
  1270. if (a.createdAt < b.createdAt) {
  1271. return -1;
  1272. }
  1273. if (a.createdAt > b.createdAt) {
  1274. return 1;
  1275. }
  1276. // Sort next by id, lower-id timers take precedence
  1277. if (a.id < b.id) {
  1278. return -1;
  1279. }
  1280. if (a.id > b.id) {
  1281. return 1;
  1282. }
  1283. // As timer ids are unique, no fallback `0` is necessary
  1284. }
  1285. /**
  1286. * @param {Clock} clock
  1287. * @param {number} from
  1288. * @param {number} to
  1289. *
  1290. * @returns {Timer}
  1291. */
  1292. function firstTimerInRange(clock, from, to) {
  1293. const timers = clock.timers;
  1294. let timer = null;
  1295. let id, isInRange;
  1296. for (id in timers) {
  1297. if (timers.hasOwnProperty(id)) {
  1298. isInRange = inRange(from, to, timers[id]);
  1299. if (
  1300. isInRange &&
  1301. (!timer || compareTimers(timer, timers[id]) === 1)
  1302. ) {
  1303. timer = timers[id];
  1304. }
  1305. }
  1306. }
  1307. return timer;
  1308. }
  1309. /**
  1310. * @param {Clock} clock
  1311. * @returns {Timer}
  1312. */
  1313. function firstTimer(clock) {
  1314. const timers = clock.timers;
  1315. let timer = null;
  1316. let id;
  1317. for (id in timers) {
  1318. if (timers.hasOwnProperty(id)) {
  1319. if (!timer || compareTimers(timer, timers[id]) === 1) {
  1320. timer = timers[id];
  1321. }
  1322. }
  1323. }
  1324. return timer;
  1325. }
  1326. /**
  1327. * @param {Clock} clock
  1328. * @returns {Timer}
  1329. */
  1330. function lastTimer(clock) {
  1331. const timers = clock.timers;
  1332. let timer = null;
  1333. let id;
  1334. for (id in timers) {
  1335. if (timers.hasOwnProperty(id)) {
  1336. if (!timer || compareTimers(timer, timers[id]) === -1) {
  1337. timer = timers[id];
  1338. }
  1339. }
  1340. }
  1341. return timer;
  1342. }
  1343. /**
  1344. * @param {Clock} clock
  1345. * @param {Timer} timer
  1346. */
  1347. function callTimer(clock, timer) {
  1348. if (typeof timer.interval === "number") {
  1349. clock.timers[timer.id].callAt += timer.interval;
  1350. } else {
  1351. delete clock.timers[timer.id];
  1352. }
  1353. if (typeof timer.func === "function") {
  1354. timer.func.apply(null, timer.args);
  1355. } else {
  1356. /* eslint no-eval: "off" */
  1357. const eval2 = eval;
  1358. (function () {
  1359. eval2(timer.func);
  1360. })();
  1361. }
  1362. }
  1363. /**
  1364. * Gets clear handler name for a given timer type
  1365. *
  1366. * @param {string} ttype
  1367. */
  1368. function getClearHandler(ttype) {
  1369. if (ttype === "IdleCallback" || ttype === "AnimationFrame") {
  1370. return `cancel${ttype}`;
  1371. }
  1372. return `clear${ttype}`;
  1373. }
  1374. /**
  1375. * Gets schedule handler name for a given timer type
  1376. *
  1377. * @param {string} ttype
  1378. */
  1379. function getScheduleHandler(ttype) {
  1380. if (ttype === "IdleCallback" || ttype === "AnimationFrame") {
  1381. return `request${ttype}`;
  1382. }
  1383. return `set${ttype}`;
  1384. }
  1385. /**
  1386. * Creates an anonymous function to warn only once
  1387. */
  1388. function createWarnOnce() {
  1389. let calls = 0;
  1390. return function (msg) {
  1391. // eslint-disable-next-line
  1392. !calls++ && console.warn(msg);
  1393. };
  1394. }
  1395. const warnOnce = createWarnOnce();
  1396. /**
  1397. * @param {Clock} clock
  1398. * @param {number} timerId
  1399. * @param {string} ttype
  1400. */
  1401. function clearTimer(clock, timerId, ttype) {
  1402. if (!timerId) {
  1403. // null appears to be allowed in most browsers, and appears to be
  1404. // relied upon by some libraries, like Bootstrap carousel
  1405. return;
  1406. }
  1407. if (!clock.timers) {
  1408. clock.timers = {};
  1409. }
  1410. // in Node, the ID is stored as the primitive value for `Timeout` objects
  1411. // for `Immediate` objects, no ID exists, so it gets coerced to NaN
  1412. const id = Number(timerId);
  1413. if (Number.isNaN(id) || id < idCounterStart) {
  1414. const handlerName = getClearHandler(ttype);
  1415. if (clock.shouldClearNativeTimers === true) {
  1416. const nativeHandler = clock[`_${handlerName}`];
  1417. return typeof nativeHandler === "function"
  1418. ? nativeHandler(timerId)
  1419. : undefined;
  1420. }
  1421. warnOnce(
  1422. `FakeTimers: ${handlerName} was invoked to clear a native timer instead of one created by this library.` +
  1423. "\nTo automatically clean-up native timers, use `shouldClearNativeTimers`."
  1424. );
  1425. }
  1426. if (clock.timers.hasOwnProperty(id)) {
  1427. // check that the ID matches a timer of the correct type
  1428. const timer = clock.timers[id];
  1429. if (
  1430. timer.type === ttype ||
  1431. (timer.type === "Timeout" && ttype === "Interval") ||
  1432. (timer.type === "Interval" && ttype === "Timeout")
  1433. ) {
  1434. delete clock.timers[id];
  1435. } else {
  1436. const clear = getClearHandler(ttype);
  1437. const schedule = getScheduleHandler(timer.type);
  1438. throw new Error(
  1439. `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`
  1440. );
  1441. }
  1442. }
  1443. }
  1444. /**
  1445. * @param {Clock} clock
  1446. * @param {Config} config
  1447. * @returns {Timer[]}
  1448. */
  1449. function uninstall(clock, config) {
  1450. let method, i, l;
  1451. const installedHrTime = "_hrtime";
  1452. const installedNextTick = "_nextTick";
  1453. for (i = 0, l = clock.methods.length; i < l; i++) {
  1454. method = clock.methods[i];
  1455. if (method === "hrtime" && _global.process) {
  1456. _global.process.hrtime = clock[installedHrTime];
  1457. } else if (method === "nextTick" && _global.process) {
  1458. _global.process.nextTick = clock[installedNextTick];
  1459. } else if (method === "performance") {
  1460. const originalPerfDescriptor = Object.getOwnPropertyDescriptor(
  1461. clock,
  1462. `_${method}`
  1463. );
  1464. if (
  1465. originalPerfDescriptor &&
  1466. originalPerfDescriptor.get &&
  1467. !originalPerfDescriptor.set
  1468. ) {
  1469. Object.defineProperty(
  1470. _global,
  1471. method,
  1472. originalPerfDescriptor
  1473. );
  1474. } else if (originalPerfDescriptor.configurable) {
  1475. _global[method] = clock[`_${method}`];
  1476. }
  1477. } else {
  1478. if (_global[method] && _global[method].hadOwnProperty) {
  1479. _global[method] = clock[`_${method}`];
  1480. } else {
  1481. try {
  1482. delete _global[method];
  1483. } catch (ignore) {
  1484. /* eslint no-empty: "off" */
  1485. }
  1486. }
  1487. }
  1488. }
  1489. if (config.shouldAdvanceTime === true) {
  1490. _global.clearInterval(clock.attachedInterval);
  1491. }
  1492. // Prevent multiple executions which will completely remove these props
  1493. clock.methods = [];
  1494. // return pending timers, to enable checking what timers remained on uninstall
  1495. if (!clock.timers) {
  1496. return [];
  1497. }
  1498. return Object.keys(clock.timers).map(function mapper(key) {
  1499. return clock.timers[key];
  1500. });
  1501. }
  1502. /**
  1503. * @param {object} target the target containing the method to replace
  1504. * @param {string} method the keyname of the method on the target
  1505. * @param {Clock} clock
  1506. */
  1507. function hijackMethod(target, method, clock) {
  1508. clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(
  1509. target,
  1510. method
  1511. );
  1512. clock[`_${method}`] = target[method];
  1513. if (method === "Date") {
  1514. const date = mirrorDateProperties(clock[method], target[method]);
  1515. target[method] = date;
  1516. } else if (method === "performance") {
  1517. const originalPerfDescriptor = Object.getOwnPropertyDescriptor(
  1518. target,
  1519. method
  1520. );
  1521. // JSDOM has a read only performance field so we have to save/copy it differently
  1522. if (
  1523. originalPerfDescriptor &&
  1524. originalPerfDescriptor.get &&
  1525. !originalPerfDescriptor.set
  1526. ) {
  1527. Object.defineProperty(
  1528. clock,
  1529. `_${method}`,
  1530. originalPerfDescriptor
  1531. );
  1532. const perfDescriptor = Object.getOwnPropertyDescriptor(
  1533. clock,
  1534. method
  1535. );
  1536. Object.defineProperty(target, method, perfDescriptor);
  1537. } else {
  1538. target[method] = clock[method];
  1539. }
  1540. } else {
  1541. target[method] = function () {
  1542. return clock[method].apply(clock, arguments);
  1543. };
  1544. Object.defineProperties(
  1545. target[method],
  1546. Object.getOwnPropertyDescriptors(clock[method])
  1547. );
  1548. }
  1549. target[method].clock = clock;
  1550. }
  1551. /**
  1552. * @param {Clock} clock
  1553. * @param {number} advanceTimeDelta
  1554. */
  1555. function doIntervalTick(clock, advanceTimeDelta) {
  1556. clock.tick(advanceTimeDelta);
  1557. }
  1558. /**
  1559. * @typedef {object} Timers
  1560. * @property {setTimeout} setTimeout
  1561. * @property {clearTimeout} clearTimeout
  1562. * @property {setInterval} setInterval
  1563. * @property {clearInterval} clearInterval
  1564. * @property {Date} Date
  1565. * @property {SetImmediate=} setImmediate
  1566. * @property {function(NodeImmediate): void=} clearImmediate
  1567. * @property {function(number[]):number[]=} hrtime
  1568. * @property {NextTick=} nextTick
  1569. * @property {Performance=} performance
  1570. * @property {RequestAnimationFrame=} requestAnimationFrame
  1571. * @property {boolean=} queueMicrotask
  1572. * @property {function(number): void=} cancelAnimationFrame
  1573. * @property {RequestIdleCallback=} requestIdleCallback
  1574. * @property {function(number): void=} cancelIdleCallback
  1575. */
  1576. /** @type {Timers} */
  1577. const timers = {
  1578. setTimeout: _global.setTimeout,
  1579. clearTimeout: _global.clearTimeout,
  1580. setInterval: _global.setInterval,
  1581. clearInterval: _global.clearInterval,
  1582. Date: _global.Date,
  1583. };
  1584. if (setImmediatePresent) {
  1585. timers.setImmediate = _global.setImmediate;
  1586. timers.clearImmediate = _global.clearImmediate;
  1587. }
  1588. if (hrtimePresent) {
  1589. timers.hrtime = _global.process.hrtime;
  1590. }
  1591. if (nextTickPresent) {
  1592. timers.nextTick = _global.process.nextTick;
  1593. }
  1594. if (performancePresent) {
  1595. timers.performance = _global.performance;
  1596. }
  1597. if (requestAnimationFramePresent) {
  1598. timers.requestAnimationFrame = _global.requestAnimationFrame;
  1599. }
  1600. if (queueMicrotaskPresent) {
  1601. timers.queueMicrotask = true;
  1602. }
  1603. if (cancelAnimationFramePresent) {
  1604. timers.cancelAnimationFrame = _global.cancelAnimationFrame;
  1605. }
  1606. if (requestIdleCallbackPresent) {
  1607. timers.requestIdleCallback = _global.requestIdleCallback;
  1608. }
  1609. if (cancelIdleCallbackPresent) {
  1610. timers.cancelIdleCallback = _global.cancelIdleCallback;
  1611. }
  1612. const originalSetTimeout = _global.setImmediate || _global.setTimeout;
  1613. /**
  1614. * @param {Date|number} [start] the system time - non-integer values are floored
  1615. * @param {number} [loopLimit] maximum number of timers that will be run when calling runAll()
  1616. * @returns {Clock}
  1617. */
  1618. function createClock(start, loopLimit) {
  1619. // eslint-disable-next-line no-param-reassign
  1620. start = Math.floor(getEpoch(start));
  1621. // eslint-disable-next-line no-param-reassign
  1622. loopLimit = loopLimit || 1000;
  1623. let nanos = 0;
  1624. const adjustedSystemTime = [0, 0]; // [millis, nanoremainder]
  1625. if (NativeDate === undefined) {
  1626. throw new Error(
  1627. "The global scope doesn't have a `Date` object" +
  1628. " (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)"
  1629. );
  1630. }
  1631. const clock = {
  1632. now: start,
  1633. Date: createDate(),
  1634. loopLimit: loopLimit,
  1635. };
  1636. clock.Date.clock = clock;
  1637. //eslint-disable-next-line jsdoc/require-jsdoc
  1638. function getTimeToNextFrame() {
  1639. return 16 - ((clock.now - start) % 16);
  1640. }
  1641. //eslint-disable-next-line jsdoc/require-jsdoc
  1642. function hrtime(prev) {
  1643. const millisSinceStart = clock.now - adjustedSystemTime[0] - start;
  1644. const secsSinceStart = Math.floor(millisSinceStart / 1000);
  1645. const remainderInNanos =
  1646. (millisSinceStart - secsSinceStart * 1e3) * 1e6 +
  1647. nanos -
  1648. adjustedSystemTime[1];
  1649. if (Array.isArray(prev)) {
  1650. if (prev[1] > 1e9) {
  1651. throw new TypeError(
  1652. "Number of nanoseconds can't exceed a billion"
  1653. );
  1654. }
  1655. const oldSecs = prev[0];
  1656. let nanoDiff = remainderInNanos - prev[1];
  1657. let secDiff = secsSinceStart - oldSecs;
  1658. if (nanoDiff < 0) {
  1659. nanoDiff += 1e9;
  1660. secDiff -= 1;
  1661. }
  1662. return [secDiff, nanoDiff];
  1663. }
  1664. return [secsSinceStart, remainderInNanos];
  1665. }
  1666. if (hrtimeBigintPresent) {
  1667. hrtime.bigint = function () {
  1668. const parts = hrtime();
  1669. return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]); // eslint-disable-line
  1670. };
  1671. }
  1672. clock.requestIdleCallback = function requestIdleCallback(
  1673. func,
  1674. timeout
  1675. ) {
  1676. let timeToNextIdlePeriod = 0;
  1677. if (clock.countTimers() > 0) {
  1678. timeToNextIdlePeriod = 50; // const for now
  1679. }
  1680. const result = addTimer(clock, {
  1681. func: func,
  1682. args: Array.prototype.slice.call(arguments, 2),
  1683. delay:
  1684. typeof timeout === "undefined"
  1685. ? timeToNextIdlePeriod
  1686. : Math.min(timeout, timeToNextIdlePeriod),
  1687. idleCallback: true,
  1688. });
  1689. return Number(result);
  1690. };
  1691. clock.cancelIdleCallback = function cancelIdleCallback(timerId) {
  1692. return clearTimer(clock, timerId, "IdleCallback");
  1693. };
  1694. clock.setTimeout = function setTimeout(func, timeout) {
  1695. return addTimer(clock, {
  1696. func: func,
  1697. args: Array.prototype.slice.call(arguments, 2),
  1698. delay: timeout,
  1699. });
  1700. };
  1701. if (typeof _global.Promise !== "undefined" && utilPromisify) {
  1702. clock.setTimeout[
  1703. utilPromisify.custom
  1704. ] = function promisifiedSetTimeout(timeout, arg) {
  1705. return new _global.Promise(function setTimeoutExecutor(
  1706. resolve
  1707. ) {
  1708. addTimer(clock, {
  1709. func: resolve,
  1710. args: [arg],
  1711. delay: timeout,
  1712. });
  1713. });
  1714. };
  1715. }
  1716. clock.clearTimeout = function clearTimeout(timerId) {
  1717. return clearTimer(clock, timerId, "Timeout");
  1718. };
  1719. clock.nextTick = function nextTick(func) {
  1720. return enqueueJob(clock, {
  1721. func: func,
  1722. args: Array.prototype.slice.call(arguments, 1),
  1723. error: isNearInfiniteLimit ? new Error() : null,
  1724. });
  1725. };
  1726. clock.queueMicrotask = function queueMicrotask(func) {
  1727. return clock.nextTick(func); // explicitly drop additional arguments
  1728. };
  1729. clock.setInterval = function setInterval(func, timeout) {
  1730. // eslint-disable-next-line no-param-reassign
  1731. timeout = parseInt(timeout, 10);
  1732. return addTimer(clock, {
  1733. func: func,
  1734. args: Array.prototype.slice.call(arguments, 2),
  1735. delay: timeout,
  1736. interval: timeout,
  1737. });
  1738. };
  1739. clock.clearInterval = function clearInterval(timerId) {
  1740. return clearTimer(clock, timerId, "Interval");
  1741. };
  1742. if (setImmediatePresent) {
  1743. clock.setImmediate = function setImmediate(func) {
  1744. return addTimer(clock, {
  1745. func: func,
  1746. args: Array.prototype.slice.call(arguments, 1),
  1747. immediate: true,
  1748. });
  1749. };
  1750. if (typeof _global.Promise !== "undefined" && utilPromisify) {
  1751. clock.setImmediate[
  1752. utilPromisify.custom
  1753. ] = function promisifiedSetImmediate(arg) {
  1754. return new _global.Promise(function setImmediateExecutor(
  1755. resolve
  1756. ) {
  1757. addTimer(clock, {
  1758. func: resolve,
  1759. args: [arg],
  1760. immediate: true,
  1761. });
  1762. });
  1763. };
  1764. }
  1765. clock.clearImmediate = function clearImmediate(timerId) {
  1766. return clearTimer(clock, timerId, "Immediate");
  1767. };
  1768. }
  1769. clock.countTimers = function countTimers() {
  1770. return (
  1771. Object.keys(clock.timers || {}).length +
  1772. (clock.jobs || []).length
  1773. );
  1774. };
  1775. clock.requestAnimationFrame = function requestAnimationFrame(func) {
  1776. const result = addTimer(clock, {
  1777. func: func,
  1778. delay: getTimeToNextFrame(),
  1779. args: [clock.now + getTimeToNextFrame()],
  1780. animation: true,
  1781. });
  1782. return Number(result);
  1783. };
  1784. clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) {
  1785. return clearTimer(clock, timerId, "AnimationFrame");
  1786. };
  1787. clock.runMicrotasks = function runMicrotasks() {
  1788. runJobs(clock);
  1789. };
  1790. /**
  1791. * @param {number|string} tickValue milliseconds or a string parseable by parseTime
  1792. * @param {boolean} isAsync
  1793. * @param {Function} resolve
  1794. * @param {Function} reject
  1795. * @returns {number|undefined} will return the new `now` value or nothing for async
  1796. */
  1797. function doTick(tickValue, isAsync, resolve, reject) {
  1798. const msFloat =
  1799. typeof tickValue === "number"
  1800. ? tickValue
  1801. : parseTime(tickValue);
  1802. const ms = Math.floor(msFloat);
  1803. const remainder = nanoRemainder(msFloat);
  1804. let nanosTotal = nanos + remainder;
  1805. let tickTo = clock.now + ms;
  1806. if (msFloat < 0) {
  1807. throw new TypeError("Negative ticks are not supported");
  1808. }
  1809. // adjust for positive overflow
  1810. if (nanosTotal >= 1e6) {
  1811. tickTo += 1;
  1812. nanosTotal -= 1e6;
  1813. }
  1814. nanos = nanosTotal;
  1815. let tickFrom = clock.now;
  1816. let previous = clock.now;
  1817. // ESLint fails to detect this correctly
  1818. /* eslint-disable prefer-const */
  1819. let timer,
  1820. firstException,
  1821. oldNow,
  1822. nextPromiseTick,
  1823. compensationCheck,
  1824. postTimerCall;
  1825. /* eslint-enable prefer-const */
  1826. clock.duringTick = true;
  1827. // perform microtasks
  1828. oldNow = clock.now;
  1829. runJobs(clock);
  1830. if (oldNow !== clock.now) {
  1831. // compensate for any setSystemTime() call during microtask callback
  1832. tickFrom += clock.now - oldNow;
  1833. tickTo += clock.now - oldNow;
  1834. }
  1835. //eslint-disable-next-line jsdoc/require-jsdoc
  1836. function doTickInner() {
  1837. // perform each timer in the requested range
  1838. timer = firstTimerInRange(clock, tickFrom, tickTo);
  1839. // eslint-disable-next-line no-unmodified-loop-condition
  1840. while (timer && tickFrom <= tickTo) {
  1841. if (clock.timers[timer.id]) {
  1842. tickFrom = timer.callAt;
  1843. clock.now = timer.callAt;
  1844. oldNow = clock.now;
  1845. try {
  1846. runJobs(clock);
  1847. callTimer(clock, timer);
  1848. } catch (e) {
  1849. firstException = firstException || e;
  1850. }
  1851. if (isAsync) {
  1852. // finish up after native setImmediate callback to allow
  1853. // all native es6 promises to process their callbacks after
  1854. // each timer fires.
  1855. originalSetTimeout(nextPromiseTick);
  1856. return;
  1857. }
  1858. compensationCheck();
  1859. }
  1860. postTimerCall();
  1861. }
  1862. // perform process.nextTick()s again
  1863. oldNow = clock.now;
  1864. runJobs(clock);
  1865. if (oldNow !== clock.now) {
  1866. // compensate for any setSystemTime() call during process.nextTick() callback
  1867. tickFrom += clock.now - oldNow;
  1868. tickTo += clock.now - oldNow;
  1869. }
  1870. clock.duringTick = false;
  1871. // corner case: during runJobs new timers were scheduled which could be in the range [clock.now, tickTo]
  1872. timer = firstTimerInRange(clock, tickFrom, tickTo);
  1873. if (timer) {
  1874. try {
  1875. clock.tick(tickTo - clock.now); // do it all again - for the remainder of the requested range
  1876. } catch (e) {
  1877. firstException = firstException || e;
  1878. }
  1879. } else {
  1880. // no timers remaining in the requested range: move the clock all the way to the end
  1881. clock.now = tickTo;
  1882. // update nanos
  1883. nanos = nanosTotal;
  1884. }
  1885. if (firstException) {
  1886. throw firstException;
  1887. }
  1888. if (isAsync) {
  1889. resolve(clock.now);
  1890. } else {
  1891. return clock.now;
  1892. }
  1893. }
  1894. nextPromiseTick =
  1895. isAsync &&
  1896. function () {
  1897. try {
  1898. compensationCheck();
  1899. postTimerCall();
  1900. doTickInner();
  1901. } catch (e) {
  1902. reject(e);
  1903. }
  1904. };
  1905. compensationCheck = function () {
  1906. // compensate for any setSystemTime() call during timer callback
  1907. if (oldNow !== clock.now) {
  1908. tickFrom += clock.now - oldNow;
  1909. tickTo += clock.now - oldNow;
  1910. previous += clock.now - oldNow;
  1911. }
  1912. };
  1913. postTimerCall = function () {
  1914. timer = firstTimerInRange(clock, previous, tickTo);
  1915. previous = tickFrom;
  1916. };
  1917. return doTickInner();
  1918. }
  1919. /**
  1920. * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
  1921. * @returns {number} will return the new `now` value
  1922. */
  1923. clock.tick = function tick(tickValue) {
  1924. return doTick(tickValue, false);
  1925. };
  1926. if (typeof _global.Promise !== "undefined") {
  1927. /**
  1928. * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15"
  1929. * @returns {Promise}
  1930. */
  1931. clock.tickAsync = function tickAsync(tickValue) {
  1932. return new _global.Promise(function (resolve, reject) {
  1933. originalSetTimeout(function () {
  1934. try {
  1935. doTick(tickValue, true, resolve, reject);
  1936. } catch (e) {
  1937. reject(e);
  1938. }
  1939. });
  1940. });
  1941. };
  1942. }
  1943. clock.next = function next() {
  1944. runJobs(clock);
  1945. const timer = firstTimer(clock);
  1946. if (!timer) {
  1947. return clock.now;
  1948. }
  1949. clock.duringTick = true;
  1950. try {
  1951. clock.now = timer.callAt;
  1952. callTimer(clock, timer);
  1953. runJobs(clock);
  1954. return clock.now;
  1955. } finally {
  1956. clock.duringTick = false;
  1957. }
  1958. };
  1959. if (typeof _global.Promise !== "undefined") {
  1960. clock.nextAsync = function nextAsync() {
  1961. return new _global.Promise(function (resolve, reject) {
  1962. originalSetTimeout(function () {
  1963. try {
  1964. const timer = firstTimer(clock);
  1965. if (!timer) {
  1966. resolve(clock.now);
  1967. return;
  1968. }
  1969. let err;
  1970. clock.duringTick = true;
  1971. clock.now = timer.callAt;
  1972. try {
  1973. callTimer(clock, timer);
  1974. } catch (e) {
  1975. err = e;
  1976. }
  1977. clock.duringTick = false;
  1978. originalSetTimeout(function () {
  1979. if (err) {
  1980. reject(err);
  1981. } else {
  1982. resolve(clock.now);
  1983. }
  1984. });
  1985. } catch (e) {
  1986. reject(e);
  1987. }
  1988. });
  1989. });
  1990. };
  1991. }
  1992. clock.runAll = function runAll() {
  1993. let numTimers, i;
  1994. runJobs(clock);
  1995. for (i = 0; i < clock.loopLimit; i++) {
  1996. if (!clock.timers) {
  1997. resetIsNearInfiniteLimit();
  1998. return clock.now;
  1999. }
  2000. numTimers = Object.keys(clock.timers).length;
  2001. if (numTimers === 0) {
  2002. resetIsNearInfiniteLimit();
  2003. return clock.now;
  2004. }
  2005. clock.next();
  2006. checkIsNearInfiniteLimit(clock, i);
  2007. }
  2008. const excessJob = firstTimer(clock);
  2009. throw getInfiniteLoopError(clock, excessJob);
  2010. };
  2011. clock.runToFrame = function runToFrame() {
  2012. return clock.tick(getTimeToNextFrame());
  2013. };
  2014. if (typeof _global.Promise !== "undefined") {
  2015. clock.runAllAsync = function runAllAsync() {
  2016. return new _global.Promise(function (resolve, reject) {
  2017. let i = 0;
  2018. /**
  2019. *
  2020. */
  2021. function doRun() {
  2022. originalSetTimeout(function () {
  2023. try {
  2024. let numTimers;
  2025. if (i < clock.loopLimit) {
  2026. if (!clock.timers) {
  2027. resetIsNearInfiniteLimit();
  2028. resolve(clock.now);
  2029. return;
  2030. }
  2031. numTimers = Object.keys(clock.timers)
  2032. .length;
  2033. if (numTimers === 0) {
  2034. resetIsNearInfiniteLimit();
  2035. resolve(clock.now);
  2036. return;
  2037. }
  2038. clock.next();
  2039. i++;
  2040. doRun();
  2041. checkIsNearInfiniteLimit(clock, i);
  2042. return;
  2043. }
  2044. const excessJob = firstTimer(clock);
  2045. reject(getInfiniteLoopError(clock, excessJob));
  2046. } catch (e) {
  2047. reject(e);
  2048. }
  2049. });
  2050. }
  2051. doRun();
  2052. });
  2053. };
  2054. }
  2055. clock.runToLast = function runToLast() {
  2056. const timer = lastTimer(clock);
  2057. if (!timer) {
  2058. runJobs(clock);
  2059. return clock.now;
  2060. }
  2061. return clock.tick(timer.callAt - clock.now);
  2062. };
  2063. if (typeof _global.Promise !== "undefined") {
  2064. clock.runToLastAsync = function runToLastAsync() {
  2065. return new _global.Promise(function (resolve, reject) {
  2066. originalSetTimeout(function () {
  2067. try {
  2068. const timer = lastTimer(clock);
  2069. if (!timer) {
  2070. resolve(clock.now);
  2071. }
  2072. resolve(clock.tickAsync(timer.callAt));
  2073. } catch (e) {
  2074. reject(e);
  2075. }
  2076. });
  2077. });
  2078. };
  2079. }
  2080. clock.reset = function reset() {
  2081. nanos = 0;
  2082. clock.timers = {};
  2083. clock.jobs = [];
  2084. clock.now = start;
  2085. };
  2086. clock.setSystemTime = function setSystemTime(systemTime) {
  2087. // determine time difference
  2088. const newNow = getEpoch(systemTime);
  2089. const difference = newNow - clock.now;
  2090. let id, timer;
  2091. adjustedSystemTime[0] = adjustedSystemTime[0] + difference;
  2092. adjustedSystemTime[1] = adjustedSystemTime[1] + nanos;
  2093. // update 'system clock'
  2094. clock.now = newNow;
  2095. nanos = 0;
  2096. // update timers and intervals to keep them stable
  2097. for (id in clock.timers) {
  2098. if (clock.timers.hasOwnProperty(id)) {
  2099. timer = clock.timers[id];
  2100. timer.createdAt += difference;
  2101. timer.callAt += difference;
  2102. }
  2103. }
  2104. };
  2105. if (performancePresent) {
  2106. clock.performance = Object.create(null);
  2107. clock.performance.now = function FakeTimersNow() {
  2108. const hrt = hrtime();
  2109. const millis = hrt[0] * 1000 + hrt[1] / 1e6;
  2110. return millis;
  2111. };
  2112. }
  2113. if (hrtimePresent) {
  2114. clock.hrtime = hrtime;
  2115. }
  2116. return clock;
  2117. }
  2118. /* eslint-disable complexity */
  2119. /**
  2120. * @param {Config=} [config] Optional config
  2121. * @returns {Clock}
  2122. */
  2123. function install(config) {
  2124. if (
  2125. arguments.length > 1 ||
  2126. config instanceof Date ||
  2127. Array.isArray(config) ||
  2128. typeof config === "number"
  2129. ) {
  2130. throw new TypeError(
  2131. `FakeTimers.install called with ${String(
  2132. config
  2133. )} install requires an object parameter`
  2134. );
  2135. }
  2136. if (_global.Date.isFake === true) {
  2137. // Timers are already faked; this is a problem.
  2138. // Make the user reset timers before continuing.
  2139. throw new TypeError(
  2140. "Can't install fake timers twice on the same global object."
  2141. );
  2142. }
  2143. // eslint-disable-next-line no-param-reassign
  2144. config = typeof config !== "undefined" ? config : {};
  2145. config.shouldAdvanceTime = config.shouldAdvanceTime || false;
  2146. config.advanceTimeDelta = config.advanceTimeDelta || 20;
  2147. config.shouldClearNativeTimers =
  2148. config.shouldClearNativeTimers || false;
  2149. if (config.target) {
  2150. throw new TypeError(
  2151. "config.target is no longer supported. Use `withGlobal(target)` instead."
  2152. );
  2153. }
  2154. let i, l;
  2155. const clock = createClock(config.now, config.loopLimit);
  2156. clock.shouldClearNativeTimers = config.shouldClearNativeTimers;
  2157. clock.uninstall = function () {
  2158. return uninstall(clock, config);
  2159. };
  2160. clock.methods = config.toFake || [];
  2161. if (clock.methods.length === 0) {
  2162. // do not fake nextTick by default - GitHub#126
  2163. clock.methods = Object.keys(timers).filter(function (key) {
  2164. return key !== "nextTick" && key !== "queueMicrotask";
  2165. });
  2166. }
  2167. if (config.shouldAdvanceTime === true) {
  2168. const intervalTick = doIntervalTick.bind(
  2169. null,
  2170. clock,
  2171. config.advanceTimeDelta
  2172. );
  2173. const intervalId = _global.setInterval(
  2174. intervalTick,
  2175. config.advanceTimeDelta
  2176. );
  2177. clock.attachedInterval = intervalId;
  2178. }
  2179. if (clock.methods.includes("performance")) {
  2180. const proto = (() => {
  2181. if (hasPerformancePrototype) {
  2182. return _global.Performance.prototype;
  2183. }
  2184. if (hasPerformanceConstructorPrototype) {
  2185. return _global.performance.constructor.prototype;
  2186. }
  2187. })();
  2188. if (proto) {
  2189. Object.getOwnPropertyNames(proto).forEach(function (name) {
  2190. if (name !== "now") {
  2191. clock.performance[name] =
  2192. name.indexOf("getEntries") === 0
  2193. ? NOOP_ARRAY
  2194. : NOOP;
  2195. }
  2196. });
  2197. } else if ((config.toFake || []).includes("performance")) {
  2198. // user explicitly tried to fake performance when not present
  2199. throw new ReferenceError(
  2200. "non-existent performance object cannot be faked"
  2201. );
  2202. }
  2203. }
  2204. for (i = 0, l = clock.methods.length; i < l; i++) {
  2205. const nameOfMethodToReplace = clock.methods[i];
  2206. if (nameOfMethodToReplace === "hrtime") {
  2207. if (
  2208. _global.process &&
  2209. typeof _global.process.hrtime === "function"
  2210. ) {
  2211. hijackMethod(_global.process, nameOfMethodToReplace, clock);
  2212. }
  2213. } else if (nameOfMethodToReplace === "nextTick") {
  2214. if (
  2215. _global.process &&
  2216. typeof _global.process.nextTick === "function"
  2217. ) {
  2218. hijackMethod(_global.process, nameOfMethodToReplace, clock);
  2219. }
  2220. } else {
  2221. hijackMethod(_global, nameOfMethodToReplace, clock);
  2222. }
  2223. }
  2224. return clock;
  2225. }
  2226. /* eslint-enable complexity */
  2227. return {
  2228. timers: timers,
  2229. createClock: createClock,
  2230. install: install,
  2231. withGlobal: withGlobal,
  2232. };
  2233. }
  2234. /**
  2235. * @typedef {object} FakeTimers
  2236. * @property {Timers} timers
  2237. * @property {createClock} createClock
  2238. * @property {Function} install
  2239. * @property {withGlobal} withGlobal
  2240. */
  2241. /* eslint-enable complexity */
  2242. /** @type {FakeTimers} */
  2243. const defaultImplementation = withGlobal(globalObject);
  2244. defaultImplementation.timers;
  2245. defaultImplementation.createClock;
  2246. defaultImplementation.install;
  2247. var withGlobal_1 = withGlobal;
  2248. class FakeTimers {
  2249. constructor({
  2250. global,
  2251. config
  2252. }) {
  2253. this._now = RealDate.now;
  2254. this._userConfig = config;
  2255. this._fakingDate = false;
  2256. this._fakingTime = false;
  2257. this._fakeTimers = withGlobal_1(global);
  2258. }
  2259. clearAllTimers() {
  2260. if (this._fakingTime)
  2261. this._clock.reset();
  2262. }
  2263. dispose() {
  2264. this.useRealTimers();
  2265. }
  2266. runAllTimers() {
  2267. if (this._checkFakeTimers())
  2268. this._clock.runAll();
  2269. }
  2270. runOnlyPendingTimers() {
  2271. if (this._checkFakeTimers())
  2272. this._clock.runToLast();
  2273. }
  2274. advanceTimersToNextTimer(steps = 1) {
  2275. if (this._checkFakeTimers()) {
  2276. for (let i = steps; i > 0; i--) {
  2277. this._clock.next();
  2278. this._clock.tick(0);
  2279. if (this._clock.countTimers() === 0)
  2280. break;
  2281. }
  2282. }
  2283. }
  2284. advanceTimersByTime(msToRun) {
  2285. if (this._checkFakeTimers())
  2286. this._clock.tick(msToRun);
  2287. }
  2288. runAllTicks() {
  2289. if (this._checkFakeTimers()) {
  2290. this._clock.runMicrotasks();
  2291. }
  2292. }
  2293. useRealTimers() {
  2294. if (this._fakingDate) {
  2295. resetDate();
  2296. this._fakingDate = false;
  2297. }
  2298. if (this._fakingTime) {
  2299. this._clock.uninstall();
  2300. this._fakingTime = false;
  2301. }
  2302. }
  2303. useFakeTimers() {
  2304. if (this._fakingDate) {
  2305. throw new Error(
  2306. '"setSystemTime" was called already and date was mocked. Reset timers using `vi.useRealTimers()` if you want to use fake timers again.'
  2307. );
  2308. }
  2309. if (!this._fakingTime) {
  2310. const toFake = Object.keys(this._fakeTimers.timers);
  2311. this._clock = this._fakeTimers.install({
  2312. now: Date.now(),
  2313. toFake,
  2314. ...this._userConfig
  2315. });
  2316. this._fakingTime = true;
  2317. }
  2318. }
  2319. reset() {
  2320. if (this._checkFakeTimers()) {
  2321. const { now } = this._clock;
  2322. this._clock.reset();
  2323. this._clock.setSystemTime(now);
  2324. }
  2325. }
  2326. setSystemTime(now) {
  2327. if (this._fakingTime) {
  2328. this._clock.setSystemTime(now);
  2329. } else {
  2330. mockDate(now ?? this.getRealSystemTime());
  2331. this._fakingDate = true;
  2332. }
  2333. }
  2334. getRealSystemTime() {
  2335. return this._now();
  2336. }
  2337. getTimerCount() {
  2338. if (this._checkFakeTimers())
  2339. return this._clock.countTimers();
  2340. return 0;
  2341. }
  2342. configure(config) {
  2343. this._userConfig = config;
  2344. }
  2345. _checkFakeTimers() {
  2346. if (!this._fakingTime) {
  2347. throw new Error(
  2348. 'Timers are not mocked. Try calling "vi.useFakeTimers()" first.'
  2349. );
  2350. }
  2351. return this._fakingTime;
  2352. }
  2353. }
  2354. class VitestUtils {
  2355. constructor() {
  2356. this.spyOn = spyOn;
  2357. this.fn = fn;
  2358. this._mocker = typeof __vitest_mocker__ !== "undefined" ? __vitest_mocker__ : null;
  2359. this._mockedDate = null;
  2360. if (!this._mocker) {
  2361. const errorMsg = 'Vitest was initialized with native Node instead of Vite Node.\n\nOne of the following is possible:\n- "vitest" is imported outside of your tests (in that case, use "vitest/node" or import.meta.vitest)\n- "vitest" is imported inside "globalSetup" (use "setupFiles", because "globalSetup" runs in a different context)\n- Your dependency inside "node_modules" imports "vitest" directly (in that case, inline that dependency, using "deps.inline" config)\n- Otherwise, it might be a Vitest bug. Please report it to https://github.com/vitest-dev/vitest/issues\n';
  2362. throw new Error(errorMsg);
  2363. }
  2364. const workerState = getWorkerState();
  2365. this._timers = new FakeTimers({
  2366. global: globalThis,
  2367. config: workerState.config.fakeTimers
  2368. });
  2369. }
  2370. useFakeTimers(config) {
  2371. if (config) {
  2372. this._timers.configure(config);
  2373. } else {
  2374. const workerState = getWorkerState();
  2375. this._timers.configure(workerState.config.fakeTimers);
  2376. }
  2377. this._timers.useFakeTimers();
  2378. return this;
  2379. }
  2380. useRealTimers() {
  2381. this._timers.useRealTimers();
  2382. this._mockedDate = null;
  2383. return this;
  2384. }
  2385. runOnlyPendingTimers() {
  2386. this._timers.runOnlyPendingTimers();
  2387. return this;
  2388. }
  2389. runAllTimers() {
  2390. this._timers.runAllTimers();
  2391. return this;
  2392. }
  2393. runAllTicks() {
  2394. this._timers.runAllTicks();
  2395. return this;
  2396. }
  2397. advanceTimersByTime(ms) {
  2398. this._timers.advanceTimersByTime(ms);
  2399. return this;
  2400. }
  2401. advanceTimersToNextTimer() {
  2402. this._timers.advanceTimersToNextTimer();
  2403. return this;
  2404. }
  2405. getTimerCount() {
  2406. return this._timers.getTimerCount();
  2407. }
  2408. setSystemTime(time) {
  2409. const date = time instanceof Date ? time : new Date(time);
  2410. this._mockedDate = date;
  2411. this._timers.setSystemTime(date);
  2412. return this;
  2413. }
  2414. getMockedSystemTime() {
  2415. return this._mockedDate;
  2416. }
  2417. getRealSystemTime() {
  2418. return this._timers.getRealSystemTime();
  2419. }
  2420. clearAllTimers() {
  2421. this._timers.clearAllTimers();
  2422. return this;
  2423. }
  2424. getImporter() {
  2425. const err = new Error("mock");
  2426. const [, , importer] = parseStacktrace(err, true);
  2427. return importer.file;
  2428. }
  2429. mock(path, factory) {
  2430. this._mocker.queueMock(path, this.getImporter(), factory);
  2431. }
  2432. unmock(path) {
  2433. this._mocker.queueUnmock(path, this.getImporter());
  2434. }
  2435. doMock(path, factory) {
  2436. this._mocker.queueMock(path, this.getImporter(), factory);
  2437. }
  2438. doUnmock(path) {
  2439. this._mocker.queueUnmock(path, this.getImporter());
  2440. }
  2441. async importActual(path) {
  2442. return this._mocker.importActual(path, this.getImporter());
  2443. }
  2444. async importMock(path) {
  2445. return this._mocker.importMock(path, this.getImporter());
  2446. }
  2447. mocked(item, _options = {}) {
  2448. return item;
  2449. }
  2450. isMockFunction(fn2) {
  2451. return isMockFunction(fn2);
  2452. }
  2453. clearAllMocks() {
  2454. spies.forEach((spy) => spy.mockClear());
  2455. return this;
  2456. }
  2457. resetAllMocks() {
  2458. spies.forEach((spy) => spy.mockReset());
  2459. return this;
  2460. }
  2461. restoreAllMocks() {
  2462. spies.forEach((spy) => spy.mockRestore());
  2463. return this;
  2464. }
  2465. stubGlobal(name, value) {
  2466. if (globalThis.window) {
  2467. globalThis.window[name] = value;
  2468. } else {
  2469. globalThis[name] = value;
  2470. }
  2471. return this;
  2472. }
  2473. resetModules() {
  2474. const state = getWorkerState();
  2475. resetModules(state.moduleCache);
  2476. return this;
  2477. }
  2478. async dynamicImportSettled() {
  2479. const state = getWorkerState();
  2480. const promises = [];
  2481. for (const mod of state.moduleCache.values()) {
  2482. if (mod.promise)
  2483. promises.push(mod.promise);
  2484. }
  2485. await Promise.allSettled(promises);
  2486. await new Promise((resolve) => safeSetTimeout(resolve, 1)).then(() => Promise.resolve());
  2487. }
  2488. }
  2489. const vitest = new VitestUtils();
  2490. const vi = vitest;
  2491. function getRunningMode() {
  2492. return process.env.VITEST_MODE === "WATCH" ? "watch" : "run";
  2493. }
  2494. function isWatchMode() {
  2495. return getRunningMode() === "watch";
  2496. }
  2497. var index = /*#__PURE__*/Object.freeze({
  2498. __proto__: null,
  2499. suite: suite,
  2500. test: test,
  2501. describe: describe,
  2502. it: it,
  2503. bench: bench,
  2504. runOnce: runOnce,
  2505. isFirstRun: isFirstRun,
  2506. beforeAll: beforeAll,
  2507. afterAll: afterAll,
  2508. beforeEach: beforeEach,
  2509. afterEach: afterEach,
  2510. withCallback: withCallback,
  2511. assert: assert,
  2512. should: should,
  2513. createExpect: createExpect,
  2514. chai: chai,
  2515. expect: globalExpect,
  2516. vitest: vitest,
  2517. vi: vi,
  2518. getRunningMode: getRunningMode,
  2519. isWatchMode: isWatchMode
  2520. });
  2521. export { afterAll as a, beforeAll as b, beforeEach as c, afterEach as d, runOnce as e, isFirstRun as f, vitest as g, getRunningMode as h, index as i, isWatchMode as j, resetRunOnceCounter as r, vi as v, withCallback as w };