fake-timers.js 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.FakeTimers = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. "use strict";
  3. var every = require("./prototypes/array").every;
  4. function hasCallsLeft(callMap, spy) {
  5. if (callMap[spy.id] === undefined) {
  6. callMap[spy.id] = 0;
  7. }
  8. return callMap[spy.id] < spy.callCount;
  9. }
  10. function checkAdjacentCalls(callMap, spy, index, spies) {
  11. var calledBeforeNext = true;
  12. if (index !== spies.length - 1) {
  13. calledBeforeNext = spy.calledBefore(spies[index + 1]);
  14. }
  15. if (hasCallsLeft(callMap, spy) && calledBeforeNext) {
  16. callMap[spy.id] += 1;
  17. return true;
  18. }
  19. return false;
  20. }
  21. module.exports = function calledInOrder(spies) {
  22. var callMap = {};
  23. // eslint-disable-next-line no-underscore-dangle
  24. var _spies = arguments.length > 1 ? arguments : spies;
  25. return every(_spies, checkAdjacentCalls.bind(null, callMap));
  26. };
  27. },{"./prototypes/array":9}],2:[function(require,module,exports){
  28. "use strict";
  29. var functionName = require("./function-name");
  30. module.exports = function className(value) {
  31. return (
  32. (value.constructor && value.constructor.name) ||
  33. // The next branch is for IE11 support only:
  34. // Because the name property is not set on the prototype
  35. // of the Function object, we finally try to grab the
  36. // name from its definition. This will never be reached
  37. // in node, so we are not able to test this properly.
  38. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  39. (typeof value.constructor === "function" &&
  40. /* istanbul ignore next */
  41. functionName(value.constructor)) ||
  42. null
  43. );
  44. };
  45. },{"./function-name":5}],3:[function(require,module,exports){
  46. /* eslint-disable no-console */
  47. "use strict";
  48. // wrap returns a function that will invoke the supplied function and print a deprecation warning to the console each
  49. // time it is called.
  50. exports.wrap = function(func, msg) {
  51. var wrapped = function() {
  52. exports.printWarning(msg);
  53. return func.apply(this, arguments);
  54. };
  55. if (func.prototype) {
  56. wrapped.prototype = func.prototype;
  57. }
  58. return wrapped;
  59. };
  60. // defaultMsg returns a string which can be supplied to `wrap()` to notify the user that a particular part of the
  61. // sinon API has been deprecated.
  62. exports.defaultMsg = function(packageName, funcName) {
  63. return (
  64. packageName +
  65. "." +
  66. funcName +
  67. " is deprecated and will be removed from the public API in a future version of " +
  68. packageName +
  69. "."
  70. );
  71. };
  72. exports.printWarning = function(msg) {
  73. // Watch out for IE7 and below! :(
  74. /* istanbul ignore next */
  75. if (typeof console !== "undefined") {
  76. if (console.info) {
  77. console.info(msg);
  78. } else {
  79. console.log(msg);
  80. }
  81. }
  82. };
  83. },{}],4:[function(require,module,exports){
  84. "use strict";
  85. // This is an `every` implementation that works for all iterables
  86. module.exports = function every(obj, fn) {
  87. var pass = true;
  88. try {
  89. /* eslint-disable-next-line local-rules/no-prototype-methods */
  90. obj.forEach(function() {
  91. if (!fn.apply(this, arguments)) {
  92. // Throwing an error is the only way to break `forEach`
  93. throw new Error();
  94. }
  95. });
  96. } catch (e) {
  97. pass = false;
  98. }
  99. return pass;
  100. };
  101. },{}],5:[function(require,module,exports){
  102. "use strict";
  103. module.exports = function functionName(func) {
  104. if (!func) {
  105. return "";
  106. }
  107. return (
  108. func.displayName ||
  109. func.name ||
  110. // Use function decomposition as a last resort to get function
  111. // name. Does not rely on function decomposition to work - if it
  112. // doesn't debugging will be slightly less informative
  113. // (i.e. toString will say 'spy' rather than 'myFunc').
  114. (String(func).match(/function ([^\s(]+)/) || [])[1]
  115. );
  116. };
  117. },{}],6:[function(require,module,exports){
  118. "use strict";
  119. var globalObject;
  120. /* istanbul ignore else */
  121. if (typeof global !== "undefined") {
  122. // Node
  123. globalObject = global;
  124. } else if (typeof window !== "undefined") {
  125. // Browser
  126. globalObject = window;
  127. } else {
  128. // WebWorker
  129. globalObject = self;
  130. }
  131. module.exports = globalObject;
  132. },{}],7:[function(require,module,exports){
  133. "use strict";
  134. module.exports = {
  135. global: require("./global"),
  136. calledInOrder: require("./called-in-order"),
  137. className: require("./class-name"),
  138. deprecated: require("./deprecated"),
  139. every: require("./every"),
  140. functionName: require("./function-name"),
  141. orderByFirstCall: require("./order-by-first-call"),
  142. prototypes: require("./prototypes"),
  143. typeOf: require("./type-of"),
  144. valueToString: require("./value-to-string")
  145. };
  146. },{"./called-in-order":1,"./class-name":2,"./deprecated":3,"./every":4,"./function-name":5,"./global":6,"./order-by-first-call":8,"./prototypes":12,"./type-of":17,"./value-to-string":18}],8:[function(require,module,exports){
  147. "use strict";
  148. var sort = require("./prototypes/array").sort;
  149. var slice = require("./prototypes/array").slice;
  150. function comparator(a, b) {
  151. // uuid, won't ever be equal
  152. var aCall = a.getCall(0);
  153. var bCall = b.getCall(0);
  154. var aId = (aCall && aCall.callId) || -1;
  155. var bId = (bCall && bCall.callId) || -1;
  156. return aId < bId ? -1 : 1;
  157. }
  158. module.exports = function orderByFirstCall(spies) {
  159. return sort(slice(spies), comparator);
  160. };
  161. },{"./prototypes/array":9}],9:[function(require,module,exports){
  162. "use strict";
  163. var copyPrototype = require("./copy-prototype");
  164. module.exports = copyPrototype(Array.prototype);
  165. },{"./copy-prototype":10}],10:[function(require,module,exports){
  166. "use strict";
  167. var call = Function.call;
  168. module.exports = function copyPrototypeMethods(prototype) {
  169. /* eslint-disable local-rules/no-prototype-methods */
  170. return Object.getOwnPropertyNames(prototype).reduce(function(result, name) {
  171. // ignore size because it throws from Map
  172. if (
  173. name !== "size" &&
  174. name !== "caller" &&
  175. name !== "callee" &&
  176. name !== "arguments" &&
  177. typeof prototype[name] === "function"
  178. ) {
  179. result[name] = call.bind(prototype[name]);
  180. }
  181. return result;
  182. }, Object.create(null));
  183. };
  184. },{}],11:[function(require,module,exports){
  185. "use strict";
  186. var copyPrototype = require("./copy-prototype");
  187. module.exports = copyPrototype(Function.prototype);
  188. },{"./copy-prototype":10}],12:[function(require,module,exports){
  189. "use strict";
  190. module.exports = {
  191. array: require("./array"),
  192. function: require("./function"),
  193. map: require("./map"),
  194. object: require("./object"),
  195. set: require("./set"),
  196. string: require("./string")
  197. };
  198. },{"./array":9,"./function":11,"./map":13,"./object":14,"./set":15,"./string":16}],13:[function(require,module,exports){
  199. "use strict";
  200. var copyPrototype = require("./copy-prototype");
  201. module.exports = copyPrototype(Map.prototype);
  202. },{"./copy-prototype":10}],14:[function(require,module,exports){
  203. "use strict";
  204. var copyPrototype = require("./copy-prototype");
  205. module.exports = copyPrototype(Object.prototype);
  206. },{"./copy-prototype":10}],15:[function(require,module,exports){
  207. "use strict";
  208. var copyPrototype = require("./copy-prototype");
  209. module.exports = copyPrototype(Set.prototype);
  210. },{"./copy-prototype":10}],16:[function(require,module,exports){
  211. "use strict";
  212. var copyPrototype = require("./copy-prototype");
  213. module.exports = copyPrototype(String.prototype);
  214. },{"./copy-prototype":10}],17:[function(require,module,exports){
  215. "use strict";
  216. var type = require("type-detect");
  217. module.exports = function typeOf(value) {
  218. return type(value).toLowerCase();
  219. };
  220. },{"type-detect":19}],18:[function(require,module,exports){
  221. "use strict";
  222. function valueToString(value) {
  223. if (value && value.toString) {
  224. /* eslint-disable-next-line local-rules/no-prototype-methods */
  225. return value.toString();
  226. }
  227. return String(value);
  228. }
  229. module.exports = valueToString;
  230. },{}],19:[function(require,module,exports){
  231. (function (global, factory) {
  232. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  233. typeof define === 'function' && define.amd ? define(factory) :
  234. (global.typeDetect = factory());
  235. }(this, (function () { 'use strict';
  236. /* !
  237. * type-detect
  238. * Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
  239. * MIT Licensed
  240. */
  241. var promiseExists = typeof Promise === 'function';
  242. /* eslint-disable no-undef */
  243. var globalObject = typeof self === 'object' ? self : global; // eslint-disable-line id-blacklist
  244. var symbolExists = typeof Symbol !== 'undefined';
  245. var mapExists = typeof Map !== 'undefined';
  246. var setExists = typeof Set !== 'undefined';
  247. var weakMapExists = typeof WeakMap !== 'undefined';
  248. var weakSetExists = typeof WeakSet !== 'undefined';
  249. var dataViewExists = typeof DataView !== 'undefined';
  250. var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined';
  251. var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined';
  252. var setEntriesExists = setExists && typeof Set.prototype.entries === 'function';
  253. var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function';
  254. var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries());
  255. var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries());
  256. var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function';
  257. var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]());
  258. var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function';
  259. var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]());
  260. var toStringLeftSliceLength = 8;
  261. var toStringRightSliceLength = -1;
  262. /**
  263. * ### typeOf (obj)
  264. *
  265. * Uses `Object.prototype.toString` to determine the type of an object,
  266. * normalising behaviour across engine versions & well optimised.
  267. *
  268. * @param {Mixed} object
  269. * @return {String} object type
  270. * @api public
  271. */
  272. function typeDetect(obj) {
  273. /* ! Speed optimisation
  274. * Pre:
  275. * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled)
  276. * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled)
  277. * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled)
  278. * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled)
  279. * function x 2,556,769 ops/sec ±1.73% (77 runs sampled)
  280. * Post:
  281. * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled)
  282. * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled)
  283. * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled)
  284. * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled)
  285. * function x 31,296,870 ops/sec ±0.96% (83 runs sampled)
  286. */
  287. var typeofObj = typeof obj;
  288. if (typeofObj !== 'object') {
  289. return typeofObj;
  290. }
  291. /* ! Speed optimisation
  292. * Pre:
  293. * null x 28,645,765 ops/sec ±1.17% (82 runs sampled)
  294. * Post:
  295. * null x 36,428,962 ops/sec ±1.37% (84 runs sampled)
  296. */
  297. if (obj === null) {
  298. return 'null';
  299. }
  300. /* ! Spec Conformance
  301. * Test: `Object.prototype.toString.call(window)``
  302. * - Node === "[object global]"
  303. * - Chrome === "[object global]"
  304. * - Firefox === "[object Window]"
  305. * - PhantomJS === "[object Window]"
  306. * - Safari === "[object Window]"
  307. * - IE 11 === "[object Window]"
  308. * - IE Edge === "[object Window]"
  309. * Test: `Object.prototype.toString.call(this)``
  310. * - Chrome Worker === "[object global]"
  311. * - Firefox Worker === "[object DedicatedWorkerGlobalScope]"
  312. * - Safari Worker === "[object DedicatedWorkerGlobalScope]"
  313. * - IE 11 Worker === "[object WorkerGlobalScope]"
  314. * - IE Edge Worker === "[object WorkerGlobalScope]"
  315. */
  316. if (obj === globalObject) {
  317. return 'global';
  318. }
  319. /* ! Speed optimisation
  320. * Pre:
  321. * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled)
  322. * Post:
  323. * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled)
  324. */
  325. if (
  326. Array.isArray(obj) &&
  327. (symbolToStringTagExists === false || !(Symbol.toStringTag in obj))
  328. ) {
  329. return 'Array';
  330. }
  331. // Not caching existence of `window` and related properties due to potential
  332. // for `window` to be unset before tests in quasi-browser environments.
  333. if (typeof window === 'object' && window !== null) {
  334. /* ! Spec Conformance
  335. * (https://html.spec.whatwg.org/multipage/browsers.html#location)
  336. * WhatWG HTML$7.7.3 - The `Location` interface
  337. * Test: `Object.prototype.toString.call(window.location)``
  338. * - IE <=11 === "[object Object]"
  339. * - IE Edge <=13 === "[object Object]"
  340. */
  341. if (typeof window.location === 'object' && obj === window.location) {
  342. return 'Location';
  343. }
  344. /* ! Spec Conformance
  345. * (https://html.spec.whatwg.org/#document)
  346. * WhatWG HTML$3.1.1 - The `Document` object
  347. * Note: Most browsers currently adher to the W3C DOM Level 2 spec
  348. * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268)
  349. * which suggests that browsers should use HTMLTableCellElement for
  350. * both TD and TH elements. WhatWG separates these.
  351. * WhatWG HTML states:
  352. * > For historical reasons, Window objects must also have a
  353. * > writable, configurable, non-enumerable property named
  354. * > HTMLDocument whose value is the Document interface object.
  355. * Test: `Object.prototype.toString.call(document)``
  356. * - Chrome === "[object HTMLDocument]"
  357. * - Firefox === "[object HTMLDocument]"
  358. * - Safari === "[object HTMLDocument]"
  359. * - IE <=10 === "[object Document]"
  360. * - IE 11 === "[object HTMLDocument]"
  361. * - IE Edge <=13 === "[object HTMLDocument]"
  362. */
  363. if (typeof window.document === 'object' && obj === window.document) {
  364. return 'Document';
  365. }
  366. if (typeof window.navigator === 'object') {
  367. /* ! Spec Conformance
  368. * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray)
  369. * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray
  370. * Test: `Object.prototype.toString.call(navigator.mimeTypes)``
  371. * - IE <=10 === "[object MSMimeTypesCollection]"
  372. */
  373. if (typeof window.navigator.mimeTypes === 'object' &&
  374. obj === window.navigator.mimeTypes) {
  375. return 'MimeTypeArray';
  376. }
  377. /* ! Spec Conformance
  378. * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
  379. * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray
  380. * Test: `Object.prototype.toString.call(navigator.plugins)``
  381. * - IE <=10 === "[object MSPluginsCollection]"
  382. */
  383. if (typeof window.navigator.plugins === 'object' &&
  384. obj === window.navigator.plugins) {
  385. return 'PluginArray';
  386. }
  387. }
  388. if ((typeof window.HTMLElement === 'function' ||
  389. typeof window.HTMLElement === 'object') &&
  390. obj instanceof window.HTMLElement) {
  391. /* ! Spec Conformance
  392. * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
  393. * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement`
  394. * Test: `Object.prototype.toString.call(document.createElement('blockquote'))``
  395. * - IE <=10 === "[object HTMLBlockElement]"
  396. */
  397. if (obj.tagName === 'BLOCKQUOTE') {
  398. return 'HTMLQuoteElement';
  399. }
  400. /* ! Spec Conformance
  401. * (https://html.spec.whatwg.org/#htmltabledatacellelement)
  402. * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement`
  403. * Note: Most browsers currently adher to the W3C DOM Level 2 spec
  404. * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
  405. * which suggests that browsers should use HTMLTableCellElement for
  406. * both TD and TH elements. WhatWG separates these.
  407. * Test: Object.prototype.toString.call(document.createElement('td'))
  408. * - Chrome === "[object HTMLTableCellElement]"
  409. * - Firefox === "[object HTMLTableCellElement]"
  410. * - Safari === "[object HTMLTableCellElement]"
  411. */
  412. if (obj.tagName === 'TD') {
  413. return 'HTMLTableDataCellElement';
  414. }
  415. /* ! Spec Conformance
  416. * (https://html.spec.whatwg.org/#htmltableheadercellelement)
  417. * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement`
  418. * Note: Most browsers currently adher to the W3C DOM Level 2 spec
  419. * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
  420. * which suggests that browsers should use HTMLTableCellElement for
  421. * both TD and TH elements. WhatWG separates these.
  422. * Test: Object.prototype.toString.call(document.createElement('th'))
  423. * - Chrome === "[object HTMLTableCellElement]"
  424. * - Firefox === "[object HTMLTableCellElement]"
  425. * - Safari === "[object HTMLTableCellElement]"
  426. */
  427. if (obj.tagName === 'TH') {
  428. return 'HTMLTableHeaderCellElement';
  429. }
  430. }
  431. }
  432. /* ! Speed optimisation
  433. * Pre:
  434. * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled)
  435. * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled)
  436. * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled)
  437. * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled)
  438. * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled)
  439. * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled)
  440. * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled)
  441. * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled)
  442. * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled)
  443. * Post:
  444. * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled)
  445. * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled)
  446. * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled)
  447. * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled)
  448. * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled)
  449. * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled)
  450. * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled)
  451. * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled)
  452. * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled)
  453. */
  454. var stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]);
  455. if (typeof stringTag === 'string') {
  456. return stringTag;
  457. }
  458. var objPrototype = Object.getPrototypeOf(obj);
  459. /* ! Speed optimisation
  460. * Pre:
  461. * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled)
  462. * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled)
  463. * Post:
  464. * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled)
  465. * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled)
  466. */
  467. if (objPrototype === RegExp.prototype) {
  468. return 'RegExp';
  469. }
  470. /* ! Speed optimisation
  471. * Pre:
  472. * date x 2,130,074 ops/sec ±4.42% (68 runs sampled)
  473. * Post:
  474. * date x 3,953,779 ops/sec ±1.35% (77 runs sampled)
  475. */
  476. if (objPrototype === Date.prototype) {
  477. return 'Date';
  478. }
  479. /* ! Spec Conformance
  480. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag)
  481. * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise":
  482. * Test: `Object.prototype.toString.call(Promise.resolve())``
  483. * - Chrome <=47 === "[object Object]"
  484. * - Edge <=20 === "[object Object]"
  485. * - Firefox 29-Latest === "[object Promise]"
  486. * - Safari 7.1-Latest === "[object Promise]"
  487. */
  488. if (promiseExists && objPrototype === Promise.prototype) {
  489. return 'Promise';
  490. }
  491. /* ! Speed optimisation
  492. * Pre:
  493. * set x 2,222,186 ops/sec ±1.31% (82 runs sampled)
  494. * Post:
  495. * set x 4,545,879 ops/sec ±1.13% (83 runs sampled)
  496. */
  497. if (setExists && objPrototype === Set.prototype) {
  498. return 'Set';
  499. }
  500. /* ! Speed optimisation
  501. * Pre:
  502. * map x 2,396,842 ops/sec ±1.59% (81 runs sampled)
  503. * Post:
  504. * map x 4,183,945 ops/sec ±6.59% (82 runs sampled)
  505. */
  506. if (mapExists && objPrototype === Map.prototype) {
  507. return 'Map';
  508. }
  509. /* ! Speed optimisation
  510. * Pre:
  511. * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled)
  512. * Post:
  513. * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled)
  514. */
  515. if (weakSetExists && objPrototype === WeakSet.prototype) {
  516. return 'WeakSet';
  517. }
  518. /* ! Speed optimisation
  519. * Pre:
  520. * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled)
  521. * Post:
  522. * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled)
  523. */
  524. if (weakMapExists && objPrototype === WeakMap.prototype) {
  525. return 'WeakMap';
  526. }
  527. /* ! Spec Conformance
  528. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag)
  529. * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView":
  530. * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))``
  531. * - Edge <=13 === "[object Object]"
  532. */
  533. if (dataViewExists && objPrototype === DataView.prototype) {
  534. return 'DataView';
  535. }
  536. /* ! Spec Conformance
  537. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag)
  538. * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator":
  539. * Test: `Object.prototype.toString.call(new Map().entries())``
  540. * - Edge <=13 === "[object Object]"
  541. */
  542. if (mapExists && objPrototype === mapIteratorPrototype) {
  543. return 'Map Iterator';
  544. }
  545. /* ! Spec Conformance
  546. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag)
  547. * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator":
  548. * Test: `Object.prototype.toString.call(new Set().entries())``
  549. * - Edge <=13 === "[object Object]"
  550. */
  551. if (setExists && objPrototype === setIteratorPrototype) {
  552. return 'Set Iterator';
  553. }
  554. /* ! Spec Conformance
  555. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag)
  556. * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator":
  557. * Test: `Object.prototype.toString.call([][Symbol.iterator]())``
  558. * - Edge <=13 === "[object Object]"
  559. */
  560. if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) {
  561. return 'Array Iterator';
  562. }
  563. /* ! Spec Conformance
  564. * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag)
  565. * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator":
  566. * Test: `Object.prototype.toString.call(''[Symbol.iterator]())``
  567. * - Edge <=13 === "[object Object]"
  568. */
  569. if (stringIteratorExists && objPrototype === stringIteratorPrototype) {
  570. return 'String Iterator';
  571. }
  572. /* ! Speed optimisation
  573. * Pre:
  574. * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled)
  575. * Post:
  576. * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled)
  577. */
  578. if (objPrototype === null) {
  579. return 'Object';
  580. }
  581. return Object
  582. .prototype
  583. .toString
  584. .call(obj)
  585. .slice(toStringLeftSliceLength, toStringRightSliceLength);
  586. }
  587. return typeDetect;
  588. })));
  589. },{}],20:[function(require,module,exports){
  590. if (typeof Object.create === 'function') {
  591. // implementation from standard node.js 'util' module
  592. module.exports = function inherits(ctor, superCtor) {
  593. ctor.super_ = superCtor
  594. ctor.prototype = Object.create(superCtor.prototype, {
  595. constructor: {
  596. value: ctor,
  597. enumerable: false,
  598. writable: true,
  599. configurable: true
  600. }
  601. });
  602. };
  603. } else {
  604. // old school shim for old browsers
  605. module.exports = function inherits(ctor, superCtor) {
  606. ctor.super_ = superCtor
  607. var TempCtor = function () {}
  608. TempCtor.prototype = superCtor.prototype
  609. ctor.prototype = new TempCtor()
  610. ctor.prototype.constructor = ctor
  611. }
  612. }
  613. },{}],21:[function(require,module,exports){
  614. module.exports = function isBuffer(arg) {
  615. return arg && typeof arg === 'object'
  616. && typeof arg.copy === 'function'
  617. && typeof arg.fill === 'function'
  618. && typeof arg.readUInt8 === 'function';
  619. }
  620. },{}],22:[function(require,module,exports){
  621. // Copyright Joyent, Inc. and other Node contributors.
  622. //
  623. // Permission is hereby granted, free of charge, to any person obtaining a
  624. // copy of this software and associated documentation files (the
  625. // "Software"), to deal in the Software without restriction, including
  626. // without limitation the rights to use, copy, modify, merge, publish,
  627. // distribute, sublicense, and/or sell copies of the Software, and to permit
  628. // persons to whom the Software is furnished to do so, subject to the
  629. // following conditions:
  630. //
  631. // The above copyright notice and this permission notice shall be included
  632. // in all copies or substantial portions of the Software.
  633. //
  634. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  635. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  636. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  637. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  638. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  639. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  640. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  641. var formatRegExp = /%[sdj%]/g;
  642. exports.format = function(f) {
  643. if (!isString(f)) {
  644. var objects = [];
  645. for (var i = 0; i < arguments.length; i++) {
  646. objects.push(inspect(arguments[i]));
  647. }
  648. return objects.join(' ');
  649. }
  650. var i = 1;
  651. var args = arguments;
  652. var len = args.length;
  653. var str = String(f).replace(formatRegExp, function(x) {
  654. if (x === '%%') return '%';
  655. if (i >= len) return x;
  656. switch (x) {
  657. case '%s': return String(args[i++]);
  658. case '%d': return Number(args[i++]);
  659. case '%j':
  660. try {
  661. return JSON.stringify(args[i++]);
  662. } catch (_) {
  663. return '[Circular]';
  664. }
  665. default:
  666. return x;
  667. }
  668. });
  669. for (var x = args[i]; i < len; x = args[++i]) {
  670. if (isNull(x) || !isObject(x)) {
  671. str += ' ' + x;
  672. } else {
  673. str += ' ' + inspect(x);
  674. }
  675. }
  676. return str;
  677. };
  678. // Mark that a method should not be used.
  679. // Returns a modified function which warns once by default.
  680. // If --no-deprecation is set, then it is a no-op.
  681. exports.deprecate = function(fn, msg) {
  682. // Allow for deprecating things in the process of starting up.
  683. if (isUndefined(global.process)) {
  684. return function() {
  685. return exports.deprecate(fn, msg).apply(this, arguments);
  686. };
  687. }
  688. if (process.noDeprecation === true) {
  689. return fn;
  690. }
  691. var warned = false;
  692. function deprecated() {
  693. if (!warned) {
  694. if (process.throwDeprecation) {
  695. throw new Error(msg);
  696. } else if (process.traceDeprecation) {
  697. console.trace(msg);
  698. } else {
  699. console.error(msg);
  700. }
  701. warned = true;
  702. }
  703. return fn.apply(this, arguments);
  704. }
  705. return deprecated;
  706. };
  707. var debugs = {};
  708. var debugEnviron;
  709. exports.debuglog = function(set) {
  710. if (isUndefined(debugEnviron))
  711. debugEnviron = process.env.NODE_DEBUG || '';
  712. set = set.toUpperCase();
  713. if (!debugs[set]) {
  714. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  715. var pid = process.pid;
  716. debugs[set] = function() {
  717. var msg = exports.format.apply(exports, arguments);
  718. console.error('%s %d: %s', set, pid, msg);
  719. };
  720. } else {
  721. debugs[set] = function() {};
  722. }
  723. }
  724. return debugs[set];
  725. };
  726. /**
  727. * Echos the value of a value. Trys to print the value out
  728. * in the best way possible given the different types.
  729. *
  730. * @param {Object} obj The object to print out.
  731. * @param {Object} opts Optional options object that alters the output.
  732. */
  733. /* legacy: obj, showHidden, depth, colors*/
  734. function inspect(obj, opts) {
  735. // default options
  736. var ctx = {
  737. seen: [],
  738. stylize: stylizeNoColor
  739. };
  740. // legacy...
  741. if (arguments.length >= 3) ctx.depth = arguments[2];
  742. if (arguments.length >= 4) ctx.colors = arguments[3];
  743. if (isBoolean(opts)) {
  744. // legacy...
  745. ctx.showHidden = opts;
  746. } else if (opts) {
  747. // got an "options" object
  748. exports._extend(ctx, opts);
  749. }
  750. // set default options
  751. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  752. if (isUndefined(ctx.depth)) ctx.depth = 2;
  753. if (isUndefined(ctx.colors)) ctx.colors = false;
  754. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  755. if (ctx.colors) ctx.stylize = stylizeWithColor;
  756. return formatValue(ctx, obj, ctx.depth);
  757. }
  758. exports.inspect = inspect;
  759. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  760. inspect.colors = {
  761. 'bold' : [1, 22],
  762. 'italic' : [3, 23],
  763. 'underline' : [4, 24],
  764. 'inverse' : [7, 27],
  765. 'white' : [37, 39],
  766. 'grey' : [90, 39],
  767. 'black' : [30, 39],
  768. 'blue' : [34, 39],
  769. 'cyan' : [36, 39],
  770. 'green' : [32, 39],
  771. 'magenta' : [35, 39],
  772. 'red' : [31, 39],
  773. 'yellow' : [33, 39]
  774. };
  775. // Don't use 'blue' not visible on cmd.exe
  776. inspect.styles = {
  777. 'special': 'cyan',
  778. 'number': 'yellow',
  779. 'boolean': 'yellow',
  780. 'undefined': 'grey',
  781. 'null': 'bold',
  782. 'string': 'green',
  783. 'date': 'magenta',
  784. // "name": intentionally not styling
  785. 'regexp': 'red'
  786. };
  787. function stylizeWithColor(str, styleType) {
  788. var style = inspect.styles[styleType];
  789. if (style) {
  790. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  791. '\u001b[' + inspect.colors[style][1] + 'm';
  792. } else {
  793. return str;
  794. }
  795. }
  796. function stylizeNoColor(str, styleType) {
  797. return str;
  798. }
  799. function arrayToHash(array) {
  800. var hash = {};
  801. array.forEach(function(val, idx) {
  802. hash[val] = true;
  803. });
  804. return hash;
  805. }
  806. function formatValue(ctx, value, recurseTimes) {
  807. // Provide a hook for user-specified inspect functions.
  808. // Check that value is an object with an inspect function on it
  809. if (ctx.customInspect &&
  810. value &&
  811. isFunction(value.inspect) &&
  812. // Filter out the util module, it's inspect function is special
  813. value.inspect !== exports.inspect &&
  814. // Also filter out any prototype objects using the circular check.
  815. !(value.constructor && value.constructor.prototype === value)) {
  816. var ret = value.inspect(recurseTimes, ctx);
  817. if (!isString(ret)) {
  818. ret = formatValue(ctx, ret, recurseTimes);
  819. }
  820. return ret;
  821. }
  822. // Primitive types cannot have properties
  823. var primitive = formatPrimitive(ctx, value);
  824. if (primitive) {
  825. return primitive;
  826. }
  827. // Look up the keys of the object.
  828. var keys = Object.keys(value);
  829. var visibleKeys = arrayToHash(keys);
  830. if (ctx.showHidden) {
  831. keys = Object.getOwnPropertyNames(value);
  832. }
  833. // IE doesn't make error fields non-enumerable
  834. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  835. if (isError(value)
  836. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  837. return formatError(value);
  838. }
  839. // Some type of object without properties can be shortcutted.
  840. if (keys.length === 0) {
  841. if (isFunction(value)) {
  842. var name = value.name ? ': ' + value.name : '';
  843. return ctx.stylize('[Function' + name + ']', 'special');
  844. }
  845. if (isRegExp(value)) {
  846. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  847. }
  848. if (isDate(value)) {
  849. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  850. }
  851. if (isError(value)) {
  852. return formatError(value);
  853. }
  854. }
  855. var base = '', array = false, braces = ['{', '}'];
  856. // Make Array say that they are Array
  857. if (isArray(value)) {
  858. array = true;
  859. braces = ['[', ']'];
  860. }
  861. // Make functions say that they are functions
  862. if (isFunction(value)) {
  863. var n = value.name ? ': ' + value.name : '';
  864. base = ' [Function' + n + ']';
  865. }
  866. // Make RegExps say that they are RegExps
  867. if (isRegExp(value)) {
  868. base = ' ' + RegExp.prototype.toString.call(value);
  869. }
  870. // Make dates with properties first say the date
  871. if (isDate(value)) {
  872. base = ' ' + Date.prototype.toUTCString.call(value);
  873. }
  874. // Make error with message first say the error
  875. if (isError(value)) {
  876. base = ' ' + formatError(value);
  877. }
  878. if (keys.length === 0 && (!array || value.length == 0)) {
  879. return braces[0] + base + braces[1];
  880. }
  881. if (recurseTimes < 0) {
  882. if (isRegExp(value)) {
  883. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  884. } else {
  885. return ctx.stylize('[Object]', 'special');
  886. }
  887. }
  888. ctx.seen.push(value);
  889. var output;
  890. if (array) {
  891. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  892. } else {
  893. output = keys.map(function(key) {
  894. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  895. });
  896. }
  897. ctx.seen.pop();
  898. return reduceToSingleString(output, base, braces);
  899. }
  900. function formatPrimitive(ctx, value) {
  901. if (isUndefined(value))
  902. return ctx.stylize('undefined', 'undefined');
  903. if (isString(value)) {
  904. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  905. .replace(/'/g, "\\'")
  906. .replace(/\\"/g, '"') + '\'';
  907. return ctx.stylize(simple, 'string');
  908. }
  909. if (isNumber(value))
  910. return ctx.stylize('' + value, 'number');
  911. if (isBoolean(value))
  912. return ctx.stylize('' + value, 'boolean');
  913. // For some reason typeof null is "object", so special case here.
  914. if (isNull(value))
  915. return ctx.stylize('null', 'null');
  916. }
  917. function formatError(value) {
  918. return '[' + Error.prototype.toString.call(value) + ']';
  919. }
  920. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  921. var output = [];
  922. for (var i = 0, l = value.length; i < l; ++i) {
  923. if (hasOwnProperty(value, String(i))) {
  924. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  925. String(i), true));
  926. } else {
  927. output.push('');
  928. }
  929. }
  930. keys.forEach(function(key) {
  931. if (!key.match(/^\d+$/)) {
  932. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  933. key, true));
  934. }
  935. });
  936. return output;
  937. }
  938. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  939. var name, str, desc;
  940. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  941. if (desc.get) {
  942. if (desc.set) {
  943. str = ctx.stylize('[Getter/Setter]', 'special');
  944. } else {
  945. str = ctx.stylize('[Getter]', 'special');
  946. }
  947. } else {
  948. if (desc.set) {
  949. str = ctx.stylize('[Setter]', 'special');
  950. }
  951. }
  952. if (!hasOwnProperty(visibleKeys, key)) {
  953. name = '[' + key + ']';
  954. }
  955. if (!str) {
  956. if (ctx.seen.indexOf(desc.value) < 0) {
  957. if (isNull(recurseTimes)) {
  958. str = formatValue(ctx, desc.value, null);
  959. } else {
  960. str = formatValue(ctx, desc.value, recurseTimes - 1);
  961. }
  962. if (str.indexOf('\n') > -1) {
  963. if (array) {
  964. str = str.split('\n').map(function(line) {
  965. return ' ' + line;
  966. }).join('\n').substr(2);
  967. } else {
  968. str = '\n' + str.split('\n').map(function(line) {
  969. return ' ' + line;
  970. }).join('\n');
  971. }
  972. }
  973. } else {
  974. str = ctx.stylize('[Circular]', 'special');
  975. }
  976. }
  977. if (isUndefined(name)) {
  978. if (array && key.match(/^\d+$/)) {
  979. return str;
  980. }
  981. name = JSON.stringify('' + key);
  982. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  983. name = name.substr(1, name.length - 2);
  984. name = ctx.stylize(name, 'name');
  985. } else {
  986. name = name.replace(/'/g, "\\'")
  987. .replace(/\\"/g, '"')
  988. .replace(/(^"|"$)/g, "'");
  989. name = ctx.stylize(name, 'string');
  990. }
  991. }
  992. return name + ': ' + str;
  993. }
  994. function reduceToSingleString(output, base, braces) {
  995. var numLinesEst = 0;
  996. var length = output.reduce(function(prev, cur) {
  997. numLinesEst++;
  998. if (cur.indexOf('\n') >= 0) numLinesEst++;
  999. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  1000. }, 0);
  1001. if (length > 60) {
  1002. return braces[0] +
  1003. (base === '' ? '' : base + '\n ') +
  1004. ' ' +
  1005. output.join(',\n ') +
  1006. ' ' +
  1007. braces[1];
  1008. }
  1009. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  1010. }
  1011. // NOTE: These type checking functions intentionally don't use `instanceof`
  1012. // because it is fragile and can be easily faked with `Object.create()`.
  1013. function isArray(ar) {
  1014. return Array.isArray(ar);
  1015. }
  1016. exports.isArray = isArray;
  1017. function isBoolean(arg) {
  1018. return typeof arg === 'boolean';
  1019. }
  1020. exports.isBoolean = isBoolean;
  1021. function isNull(arg) {
  1022. return arg === null;
  1023. }
  1024. exports.isNull = isNull;
  1025. function isNullOrUndefined(arg) {
  1026. return arg == null;
  1027. }
  1028. exports.isNullOrUndefined = isNullOrUndefined;
  1029. function isNumber(arg) {
  1030. return typeof arg === 'number';
  1031. }
  1032. exports.isNumber = isNumber;
  1033. function isString(arg) {
  1034. return typeof arg === 'string';
  1035. }
  1036. exports.isString = isString;
  1037. function isSymbol(arg) {
  1038. return typeof arg === 'symbol';
  1039. }
  1040. exports.isSymbol = isSymbol;
  1041. function isUndefined(arg) {
  1042. return arg === void 0;
  1043. }
  1044. exports.isUndefined = isUndefined;
  1045. function isRegExp(re) {
  1046. return isObject(re) && objectToString(re) === '[object RegExp]';
  1047. }
  1048. exports.isRegExp = isRegExp;
  1049. function isObject(arg) {
  1050. return typeof arg === 'object' && arg !== null;
  1051. }
  1052. exports.isObject = isObject;
  1053. function isDate(d) {
  1054. return isObject(d) && objectToString(d) === '[object Date]';
  1055. }
  1056. exports.isDate = isDate;
  1057. function isError(e) {
  1058. return isObject(e) &&
  1059. (objectToString(e) === '[object Error]' || e instanceof Error);
  1060. }
  1061. exports.isError = isError;
  1062. function isFunction(arg) {
  1063. return typeof arg === 'function';
  1064. }
  1065. exports.isFunction = isFunction;
  1066. function isPrimitive(arg) {
  1067. return arg === null ||
  1068. typeof arg === 'boolean' ||
  1069. typeof arg === 'number' ||
  1070. typeof arg === 'string' ||
  1071. typeof arg === 'symbol' || // ES6 symbol
  1072. typeof arg === 'undefined';
  1073. }
  1074. exports.isPrimitive = isPrimitive;
  1075. exports.isBuffer = require('./support/isBuffer');
  1076. function objectToString(o) {
  1077. return Object.prototype.toString.call(o);
  1078. }
  1079. function pad(n) {
  1080. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  1081. }
  1082. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  1083. 'Oct', 'Nov', 'Dec'];
  1084. // 26 Feb 16:19:34
  1085. function timestamp() {
  1086. var d = new Date();
  1087. var time = [pad(d.getHours()),
  1088. pad(d.getMinutes()),
  1089. pad(d.getSeconds())].join(':');
  1090. return [d.getDate(), months[d.getMonth()], time].join(' ');
  1091. }
  1092. // log is just a thin wrapper to console.log that prepends a timestamp
  1093. exports.log = function() {
  1094. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  1095. };
  1096. /**
  1097. * Inherit the prototype methods from one constructor into another.
  1098. *
  1099. * The Function.prototype.inherits from lang.js rewritten as a standalone
  1100. * function (not on Function.prototype). NOTE: If this file is to be loaded
  1101. * during bootstrapping this function needs to be rewritten using some native
  1102. * functions as prototype setup using normal JavaScript does not work as
  1103. * expected during bootstrapping (see mirror.js in r114903).
  1104. *
  1105. * @param {function} ctor Constructor function which needs to inherit the
  1106. * prototype.
  1107. * @param {function} superCtor Constructor function to inherit prototype from.
  1108. */
  1109. exports.inherits = require('inherits');
  1110. exports._extend = function(origin, add) {
  1111. // Don't do anything if add isn't an object
  1112. if (!add || !isObject(add)) return origin;
  1113. var keys = Object.keys(add);
  1114. var i = keys.length;
  1115. while (i--) {
  1116. origin[keys[i]] = add[keys[i]];
  1117. }
  1118. return origin;
  1119. };
  1120. function hasOwnProperty(obj, prop) {
  1121. return Object.prototype.hasOwnProperty.call(obj, prop);
  1122. }
  1123. },{"./support/isBuffer":21,"inherits":20}],23:[function(require,module,exports){
  1124. "use strict";
  1125. var globalObject = require("@sinonjs/commons").global;
  1126. // eslint-disable-next-line complexity
  1127. function withGlobal(_global) {
  1128. var userAgent = _global.navigator && _global.navigator.userAgent;
  1129. var isRunningInIE = userAgent && userAgent.indexOf("MSIE ") > -1;
  1130. var maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint
  1131. var NOOP = function() {
  1132. return undefined;
  1133. };
  1134. var NOOP_ARRAY = function() {
  1135. return [];
  1136. };
  1137. var timeoutResult = _global.setTimeout(NOOP, 0);
  1138. var addTimerReturnsObject = typeof timeoutResult === "object";
  1139. var hrtimePresent =
  1140. _global.process && typeof _global.process.hrtime === "function";
  1141. var hrtimeBigintPresent =
  1142. hrtimePresent && typeof _global.process.hrtime.bigint === "function";
  1143. var nextTickPresent =
  1144. _global.process && typeof _global.process.nextTick === "function";
  1145. var utilPromisify = _global.process && require("util").promisify;
  1146. var performancePresent =
  1147. _global.performance && typeof _global.performance.now === "function";
  1148. var hasPerformancePrototype =
  1149. _global.Performance &&
  1150. (typeof _global.Performance).match(/^(function|object)$/);
  1151. var queueMicrotaskPresent = _global.hasOwnProperty("queueMicrotask");
  1152. var requestAnimationFramePresent =
  1153. _global.requestAnimationFrame &&
  1154. typeof _global.requestAnimationFrame === "function";
  1155. var cancelAnimationFramePresent =
  1156. _global.cancelAnimationFrame &&
  1157. typeof _global.cancelAnimationFrame === "function";
  1158. var requestIdleCallbackPresent =
  1159. _global.requestIdleCallback &&
  1160. typeof _global.requestIdleCallback === "function";
  1161. var cancelIdleCallbackPresent =
  1162. _global.cancelIdleCallback &&
  1163. typeof _global.cancelIdleCallback === "function";
  1164. var setImmediatePresent =
  1165. _global.setImmediate && typeof _global.setImmediate === "function";
  1166. // Make properties writable in IE, as per
  1167. // http://www.adequatelygood.com/Replacing-setTimeout-Globally.html
  1168. /* eslint-disable no-self-assign */
  1169. if (isRunningInIE) {
  1170. _global.setTimeout = _global.setTimeout;
  1171. _global.clearTimeout = _global.clearTimeout;
  1172. _global.setInterval = _global.setInterval;
  1173. _global.clearInterval = _global.clearInterval;
  1174. _global.Date = _global.Date;
  1175. }
  1176. // setImmediate is not a standard function
  1177. // avoid adding the prop to the window object if not present
  1178. if (setImmediatePresent) {
  1179. _global.setImmediate = _global.setImmediate;
  1180. _global.clearImmediate = _global.clearImmediate;
  1181. }
  1182. /* eslint-enable no-self-assign */
  1183. _global.clearTimeout(timeoutResult);
  1184. var NativeDate = _global.Date;
  1185. var uniqueTimerId = 1;
  1186. function isNumberFinite(num) {
  1187. if (Number.isFinite) {
  1188. return Number.isFinite(num);
  1189. }
  1190. if (typeof num !== "number") {
  1191. return false;
  1192. }
  1193. return isFinite(num);
  1194. }
  1195. /**
  1196. * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into
  1197. * number of milliseconds. This is used to support human-readable strings passed
  1198. * to clock.tick()
  1199. */
  1200. function parseTime(str) {
  1201. if (!str) {
  1202. return 0;
  1203. }
  1204. var strings = str.split(":");
  1205. var l = strings.length;
  1206. var i = l;
  1207. var ms = 0;
  1208. var parsed;
  1209. if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
  1210. throw new Error(
  1211. "tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits"
  1212. );
  1213. }
  1214. while (i--) {
  1215. parsed = parseInt(strings[i], 10);
  1216. if (parsed >= 60) {
  1217. throw new Error("Invalid time " + str);
  1218. }
  1219. ms += parsed * Math.pow(60, l - i - 1);
  1220. }
  1221. return ms * 1000;
  1222. }
  1223. /**
  1224. * Get the decimal part of the millisecond value as nanoseconds
  1225. *
  1226. * @param {Number} msFloat the number of milliseconds
  1227. * @returns {Number} an integer number of nanoseconds in the range [0,1e6)
  1228. *
  1229. * Example: nanoRemainer(123.456789) -> 456789
  1230. */
  1231. function nanoRemainder(msFloat) {
  1232. var modulo = 1e6;
  1233. var remainder = (msFloat * 1e6) % modulo;
  1234. var positiveRemainder = remainder < 0 ? remainder + modulo : remainder;
  1235. return Math.floor(positiveRemainder);
  1236. }
  1237. /**
  1238. * Used to grok the `now` parameter to createClock.
  1239. * @param epoch {Date|number} the system time
  1240. */
  1241. function getEpoch(epoch) {
  1242. if (!epoch) {
  1243. return 0;
  1244. }
  1245. if (typeof epoch.getTime === "function") {
  1246. return epoch.getTime();
  1247. }
  1248. if (typeof epoch === "number") {
  1249. return epoch;
  1250. }
  1251. throw new TypeError("now should be milliseconds since UNIX epoch");
  1252. }
  1253. function inRange(from, to, timer) {
  1254. return timer && timer.callAt >= from && timer.callAt <= to;
  1255. }
  1256. function mirrorDateProperties(target, source) {
  1257. var prop;
  1258. for (prop in source) {
  1259. if (source.hasOwnProperty(prop)) {
  1260. target[prop] = source[prop];
  1261. }
  1262. }
  1263. // set special now implementation
  1264. if (source.now) {
  1265. target.now = function now() {
  1266. return target.clock.now;
  1267. };
  1268. } else {
  1269. delete target.now;
  1270. }
  1271. // set special toSource implementation
  1272. if (source.toSource) {
  1273. target.toSource = function toSource() {
  1274. return source.toSource();
  1275. };
  1276. } else {
  1277. delete target.toSource;
  1278. }
  1279. // set special toString implementation
  1280. target.toString = function toString() {
  1281. return source.toString();
  1282. };
  1283. target.prototype = source.prototype;
  1284. target.parse = source.parse;
  1285. target.UTC = source.UTC;
  1286. target.prototype.toUTCString = source.prototype.toUTCString;
  1287. return target;
  1288. }
  1289. function createDate() {
  1290. function ClockDate(year, month, date, hour, minute, second, ms) {
  1291. // the Date constructor called as a function, ref Ecma-262 Edition 5.1, section 15.9.2.
  1292. // This remains so in the 10th edition of 2019 as well.
  1293. if (!(this instanceof ClockDate)) {
  1294. return new NativeDate(ClockDate.clock.now).toString();
  1295. }
  1296. // if Date is called as a constructor with 'new' keyword
  1297. // Defensive and verbose to avoid potential harm in passing
  1298. // explicit undefined when user does not pass argument
  1299. switch (arguments.length) {
  1300. case 0:
  1301. return new NativeDate(ClockDate.clock.now);
  1302. case 1:
  1303. return new NativeDate(year);
  1304. case 2:
  1305. return new NativeDate(year, month);
  1306. case 3:
  1307. return new NativeDate(year, month, date);
  1308. case 4:
  1309. return new NativeDate(year, month, date, hour);
  1310. case 5:
  1311. return new NativeDate(year, month, date, hour, minute);
  1312. case 6:
  1313. return new NativeDate(
  1314. year,
  1315. month,
  1316. date,
  1317. hour,
  1318. minute,
  1319. second
  1320. );
  1321. default:
  1322. return new NativeDate(
  1323. year,
  1324. month,
  1325. date,
  1326. hour,
  1327. minute,
  1328. second,
  1329. ms
  1330. );
  1331. }
  1332. }
  1333. return mirrorDateProperties(ClockDate, NativeDate);
  1334. }
  1335. function enqueueJob(clock, job) {
  1336. // enqueues a microtick-deferred task - ecma262/#sec-enqueuejob
  1337. if (!clock.jobs) {
  1338. clock.jobs = [];
  1339. }
  1340. clock.jobs.push(job);
  1341. }
  1342. function runJobs(clock) {
  1343. // runs all microtick-deferred tasks - ecma262/#sec-runjobs
  1344. if (!clock.jobs) {
  1345. return;
  1346. }
  1347. for (var i = 0; i < clock.jobs.length; i++) {
  1348. var job = clock.jobs[i];
  1349. job.func.apply(null, job.args);
  1350. if (clock.loopLimit && i > clock.loopLimit) {
  1351. throw new Error(
  1352. "Aborting after running " +
  1353. clock.loopLimit +
  1354. " timers, assuming an infinite loop!"
  1355. );
  1356. }
  1357. }
  1358. clock.jobs = [];
  1359. }
  1360. function addTimer(clock, timer) {
  1361. if (timer.func === undefined) {
  1362. throw new Error("Callback must be provided to timer calls");
  1363. }
  1364. timer.type = timer.immediate ? "Immediate" : "Timeout";
  1365. if (timer.hasOwnProperty("delay")) {
  1366. if (!isNumberFinite(timer.delay)) {
  1367. timer.delay = 0;
  1368. }
  1369. timer.delay = timer.delay > maxTimeout ? 1 : timer.delay;
  1370. timer.delay = Math.max(0, timer.delay);
  1371. }
  1372. if (timer.hasOwnProperty("interval")) {
  1373. timer.type = "Interval";
  1374. timer.interval = timer.interval > maxTimeout ? 1 : timer.interval;
  1375. }
  1376. if (timer.hasOwnProperty("animation")) {
  1377. timer.type = "AnimationFrame";
  1378. timer.animation = true;
  1379. }
  1380. if (!clock.timers) {
  1381. clock.timers = {};
  1382. }
  1383. timer.id = uniqueTimerId++;
  1384. timer.createdAt = clock.now;
  1385. timer.callAt =
  1386. clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0));
  1387. clock.timers[timer.id] = timer;
  1388. if (addTimerReturnsObject) {
  1389. var res = {
  1390. id: timer.id,
  1391. ref: function() {
  1392. return res;
  1393. },
  1394. unref: function() {
  1395. return res;
  1396. },
  1397. refresh: function() {
  1398. return res;
  1399. }
  1400. };
  1401. return res;
  1402. }
  1403. return timer.id;
  1404. }
  1405. /* eslint consistent-return: "off" */
  1406. function compareTimers(a, b) {
  1407. // Sort first by absolute timing
  1408. if (a.callAt < b.callAt) {
  1409. return -1;
  1410. }
  1411. if (a.callAt > b.callAt) {
  1412. return 1;
  1413. }
  1414. // Sort next by immediate, immediate timers take precedence
  1415. if (a.immediate && !b.immediate) {
  1416. return -1;
  1417. }
  1418. if (!a.immediate && b.immediate) {
  1419. return 1;
  1420. }
  1421. // Sort next by creation time, earlier-created timers take precedence
  1422. if (a.createdAt < b.createdAt) {
  1423. return -1;
  1424. }
  1425. if (a.createdAt > b.createdAt) {
  1426. return 1;
  1427. }
  1428. // Sort next by id, lower-id timers take precedence
  1429. if (a.id < b.id) {
  1430. return -1;
  1431. }
  1432. if (a.id > b.id) {
  1433. return 1;
  1434. }
  1435. // As timer ids are unique, no fallback `0` is necessary
  1436. }
  1437. function firstTimerInRange(clock, from, to) {
  1438. var timers = clock.timers;
  1439. var timer = null;
  1440. var id, isInRange;
  1441. for (id in timers) {
  1442. if (timers.hasOwnProperty(id)) {
  1443. isInRange = inRange(from, to, timers[id]);
  1444. if (
  1445. isInRange &&
  1446. (!timer || compareTimers(timer, timers[id]) === 1)
  1447. ) {
  1448. timer = timers[id];
  1449. }
  1450. }
  1451. }
  1452. return timer;
  1453. }
  1454. function firstTimer(clock) {
  1455. var timers = clock.timers;
  1456. var timer = null;
  1457. var id;
  1458. for (id in timers) {
  1459. if (timers.hasOwnProperty(id)) {
  1460. if (!timer || compareTimers(timer, timers[id]) === 1) {
  1461. timer = timers[id];
  1462. }
  1463. }
  1464. }
  1465. return timer;
  1466. }
  1467. function lastTimer(clock) {
  1468. var timers = clock.timers;
  1469. var timer = null;
  1470. var id;
  1471. for (id in timers) {
  1472. if (timers.hasOwnProperty(id)) {
  1473. if (!timer || compareTimers(timer, timers[id]) === -1) {
  1474. timer = timers[id];
  1475. }
  1476. }
  1477. }
  1478. return timer;
  1479. }
  1480. function callTimer(clock, timer) {
  1481. if (typeof timer.interval === "number") {
  1482. clock.timers[timer.id].callAt += timer.interval;
  1483. } else {
  1484. delete clock.timers[timer.id];
  1485. }
  1486. if (typeof timer.func === "function") {
  1487. timer.func.apply(null, timer.args);
  1488. } else {
  1489. /* eslint no-eval: "off" */
  1490. eval(timer.func);
  1491. }
  1492. }
  1493. function clearTimer(clock, timerId, ttype) {
  1494. if (!timerId) {
  1495. // null appears to be allowed in most browsers, and appears to be
  1496. // relied upon by some libraries, like Bootstrap carousel
  1497. return;
  1498. }
  1499. if (!clock.timers) {
  1500. clock.timers = {};
  1501. }
  1502. // in Node, timerId is an object with .ref()/.unref(), and
  1503. // its .id field is the actual timer id.
  1504. var id = typeof timerId === "object" ? timerId.id : timerId;
  1505. if (clock.timers.hasOwnProperty(id)) {
  1506. // check that the ID matches a timer of the correct type
  1507. var timer = clock.timers[id];
  1508. if (timer.type === ttype) {
  1509. delete clock.timers[id];
  1510. } else {
  1511. var clear =
  1512. ttype === "AnimationFrame"
  1513. ? "cancelAnimationFrame"
  1514. : "clear" + ttype;
  1515. var schedule =
  1516. timer.type === "AnimationFrame"
  1517. ? "requestAnimationFrame"
  1518. : "set" + timer.type;
  1519. throw new Error(
  1520. "Cannot clear timer: timer created with " +
  1521. schedule +
  1522. "() but cleared with " +
  1523. clear +
  1524. "()"
  1525. );
  1526. }
  1527. }
  1528. }
  1529. function uninstall(clock, target, config) {
  1530. var method, i, l;
  1531. var installedHrTime = "_hrtime";
  1532. var installedNextTick = "_nextTick";
  1533. for (i = 0, l = clock.methods.length; i < l; i++) {
  1534. method = clock.methods[i];
  1535. if (method === "hrtime" && target.process) {
  1536. target.process.hrtime = clock[installedHrTime];
  1537. } else if (method === "nextTick" && target.process) {
  1538. target.process.nextTick = clock[installedNextTick];
  1539. } else if (method === "performance") {
  1540. var originalPerfDescriptor = Object.getOwnPropertyDescriptor(
  1541. clock,
  1542. "_" + method
  1543. );
  1544. if (
  1545. originalPerfDescriptor &&
  1546. originalPerfDescriptor.get &&
  1547. !originalPerfDescriptor.set
  1548. ) {
  1549. Object.defineProperty(
  1550. target,
  1551. method,
  1552. originalPerfDescriptor
  1553. );
  1554. } else if (originalPerfDescriptor.configurable) {
  1555. target[method] = clock["_" + method];
  1556. }
  1557. } else {
  1558. if (target[method] && target[method].hadOwnProperty) {
  1559. target[method] = clock["_" + method];
  1560. if (
  1561. method === "clearInterval" &&
  1562. config.shouldAdvanceTime === true
  1563. ) {
  1564. target[method](clock.attachedInterval);
  1565. }
  1566. } else {
  1567. try {
  1568. delete target[method];
  1569. } catch (ignore) {
  1570. /* eslint no-empty: "off" */
  1571. }
  1572. }
  1573. }
  1574. }
  1575. // Prevent multiple executions which will completely remove these props
  1576. clock.methods = [];
  1577. // return pending timers, to enable checking what timers remained on uninstall
  1578. if (!clock.timers) {
  1579. return [];
  1580. }
  1581. return Object.keys(clock.timers).map(function mapper(key) {
  1582. return clock.timers[key];
  1583. });
  1584. }
  1585. function hijackMethod(target, method, clock) {
  1586. var prop;
  1587. clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(
  1588. target,
  1589. method
  1590. );
  1591. clock["_" + method] = target[method];
  1592. if (method === "Date") {
  1593. var date = mirrorDateProperties(clock[method], target[method]);
  1594. target[method] = date;
  1595. } else if (method === "performance") {
  1596. var originalPerfDescriptor = Object.getOwnPropertyDescriptor(
  1597. target,
  1598. method
  1599. );
  1600. // JSDOM has a read only performance field so we have to save/copy it differently
  1601. if (
  1602. originalPerfDescriptor &&
  1603. originalPerfDescriptor.get &&
  1604. !originalPerfDescriptor.set
  1605. ) {
  1606. Object.defineProperty(
  1607. clock,
  1608. "_" + method,
  1609. originalPerfDescriptor
  1610. );
  1611. var perfDescriptor = Object.getOwnPropertyDescriptor(
  1612. clock,
  1613. method
  1614. );
  1615. Object.defineProperty(target, method, perfDescriptor);
  1616. } else {
  1617. target[method] = clock[method];
  1618. }
  1619. } else {
  1620. target[method] = function() {
  1621. return clock[method].apply(clock, arguments);
  1622. };
  1623. for (prop in clock[method]) {
  1624. if (clock[method].hasOwnProperty(prop)) {
  1625. target[method][prop] = clock[method][prop];
  1626. }
  1627. }
  1628. }
  1629. target[method].clock = clock;
  1630. }
  1631. function doIntervalTick(clock, advanceTimeDelta) {
  1632. clock.tick(advanceTimeDelta);
  1633. }
  1634. var timers = {
  1635. setTimeout: _global.setTimeout,
  1636. clearTimeout: _global.clearTimeout,
  1637. setInterval: _global.setInterval,
  1638. clearInterval: _global.clearInterval,
  1639. Date: _global.Date
  1640. };
  1641. if (setImmediatePresent) {
  1642. timers.setImmediate = _global.setImmediate;
  1643. timers.clearImmediate = _global.clearImmediate;
  1644. }
  1645. if (hrtimePresent) {
  1646. timers.hrtime = _global.process.hrtime;
  1647. }
  1648. if (nextTickPresent) {
  1649. timers.nextTick = _global.process.nextTick;
  1650. }
  1651. if (performancePresent) {
  1652. timers.performance = _global.performance;
  1653. }
  1654. if (requestAnimationFramePresent) {
  1655. timers.requestAnimationFrame = _global.requestAnimationFrame;
  1656. }
  1657. if (queueMicrotaskPresent) {
  1658. timers.queueMicrotask = true;
  1659. }
  1660. if (cancelAnimationFramePresent) {
  1661. timers.cancelAnimationFrame = _global.cancelAnimationFrame;
  1662. }
  1663. if (requestIdleCallbackPresent) {
  1664. timers.requestIdleCallback = _global.requestIdleCallback;
  1665. }
  1666. if (cancelIdleCallbackPresent) {
  1667. timers.cancelIdleCallback = _global.cancelIdleCallback;
  1668. }
  1669. var keys =
  1670. Object.keys ||
  1671. function(obj) {
  1672. var ks = [];
  1673. var key;
  1674. for (key in obj) {
  1675. if (obj.hasOwnProperty(key)) {
  1676. ks.push(key);
  1677. }
  1678. }
  1679. return ks;
  1680. };
  1681. var originalSetTimeout = _global.setImmediate || _global.setTimeout;
  1682. /**
  1683. * @param start {Date|number} the system time - non-integer values are floored
  1684. * @param loopLimit {number} maximum number of timers that will be run when calling runAll()
  1685. */
  1686. function createClock(start, loopLimit) {
  1687. // eslint-disable-next-line no-param-reassign
  1688. start = Math.floor(getEpoch(start));
  1689. // eslint-disable-next-line no-param-reassign
  1690. loopLimit = loopLimit || 1000;
  1691. var nanos = 0;
  1692. var adjustedSystemTime = [0, 0]; // [millis, nanoremainder]
  1693. if (NativeDate === undefined) {
  1694. throw new Error(
  1695. "The global scope doesn't have a `Date` object" +
  1696. " (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)"
  1697. );
  1698. }
  1699. var clock = {
  1700. now: start,
  1701. timeouts: {},
  1702. Date: createDate(),
  1703. loopLimit: loopLimit
  1704. };
  1705. clock.Date.clock = clock;
  1706. function getTimeToNextFrame() {
  1707. return 16 - ((clock.now - start) % 16);
  1708. }
  1709. function hrtime(prev) {
  1710. var millisSinceStart = clock.now - adjustedSystemTime[0] - start;
  1711. var secsSinceStart = Math.floor(millisSinceStart / 1000);
  1712. var remainderInNanos =
  1713. (millisSinceStart - secsSinceStart * 1e3) * 1e6 +
  1714. nanos -
  1715. adjustedSystemTime[1];
  1716. if (Array.isArray(prev)) {
  1717. if (prev[1] > 1e9) {
  1718. throw new TypeError(
  1719. "Number of nanoseconds can't exceed a billion"
  1720. );
  1721. }
  1722. var oldSecs = prev[0];
  1723. var nanoDiff = remainderInNanos - prev[1];
  1724. var secDiff = secsSinceStart - oldSecs;
  1725. if (nanoDiff < 0) {
  1726. nanoDiff += 1e9;
  1727. secDiff -= 1;
  1728. }
  1729. return [secDiff, nanoDiff];
  1730. }
  1731. return [secsSinceStart, remainderInNanos];
  1732. }
  1733. if (hrtimeBigintPresent) {
  1734. hrtime.bigint = function() {
  1735. var parts = hrtime();
  1736. return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]); // eslint-disable-line
  1737. };
  1738. }
  1739. clock.requestIdleCallback = function requestIdleCallback(
  1740. func,
  1741. timeout
  1742. ) {
  1743. var timeToNextIdlePeriod = 0;
  1744. if (clock.countTimers() > 0) {
  1745. timeToNextIdlePeriod = 50; // const for now
  1746. }
  1747. var result = addTimer(clock, {
  1748. func: func,
  1749. args: Array.prototype.slice.call(arguments, 2),
  1750. delay:
  1751. typeof timeout === "undefined"
  1752. ? timeToNextIdlePeriod
  1753. : Math.min(timeout, timeToNextIdlePeriod)
  1754. });
  1755. return result.id || result;
  1756. };
  1757. clock.cancelIdleCallback = function cancelIdleCallback(timerId) {
  1758. return clearTimer(clock, timerId, "Timeout");
  1759. };
  1760. clock.setTimeout = function setTimeout(func, timeout) {
  1761. return addTimer(clock, {
  1762. func: func,
  1763. args: Array.prototype.slice.call(arguments, 2),
  1764. delay: timeout
  1765. });
  1766. };
  1767. if (typeof _global.Promise !== "undefined" && utilPromisify) {
  1768. clock.setTimeout[
  1769. utilPromisify.custom
  1770. ] = function promisifiedSetTimeout(timeout, arg) {
  1771. return new _global.Promise(function setTimeoutExecutor(
  1772. resolve
  1773. ) {
  1774. addTimer(clock, {
  1775. func: resolve,
  1776. args: [arg],
  1777. delay: timeout
  1778. });
  1779. });
  1780. };
  1781. }
  1782. clock.clearTimeout = function clearTimeout(timerId) {
  1783. return clearTimer(clock, timerId, "Timeout");
  1784. };
  1785. clock.nextTick = function nextTick(func) {
  1786. return enqueueJob(clock, {
  1787. func: func,
  1788. args: Array.prototype.slice.call(arguments, 1)
  1789. });
  1790. };
  1791. clock.queueMicrotask = function queueMicrotask(func) {
  1792. return clock.nextTick(func); // explicitly drop additional arguments
  1793. };
  1794. clock.setInterval = function setInterval(func, timeout) {
  1795. // eslint-disable-next-line no-param-reassign
  1796. timeout = parseInt(timeout, 10);
  1797. return addTimer(clock, {
  1798. func: func,
  1799. args: Array.prototype.slice.call(arguments, 2),
  1800. delay: timeout,
  1801. interval: timeout
  1802. });
  1803. };
  1804. clock.clearInterval = function clearInterval(timerId) {
  1805. return clearTimer(clock, timerId, "Interval");
  1806. };
  1807. if (setImmediatePresent) {
  1808. clock.setImmediate = function setImmediate(func) {
  1809. return addTimer(clock, {
  1810. func: func,
  1811. args: Array.prototype.slice.call(arguments, 1),
  1812. immediate: true
  1813. });
  1814. };
  1815. if (typeof _global.Promise !== "undefined" && utilPromisify) {
  1816. clock.setImmediate[
  1817. utilPromisify.custom
  1818. ] = function promisifiedSetImmediate(arg) {
  1819. return new _global.Promise(function setImmediateExecutor(
  1820. resolve
  1821. ) {
  1822. addTimer(clock, {
  1823. func: resolve,
  1824. args: [arg],
  1825. immediate: true
  1826. });
  1827. });
  1828. };
  1829. }
  1830. clock.clearImmediate = function clearImmediate(timerId) {
  1831. return clearTimer(clock, timerId, "Immediate");
  1832. };
  1833. }
  1834. clock.countTimers = function countTimers() {
  1835. return (
  1836. Object.keys(clock.timers || {}).length +
  1837. (clock.jobs || []).length
  1838. );
  1839. };
  1840. clock.requestAnimationFrame = function requestAnimationFrame(func) {
  1841. var result = addTimer(clock, {
  1842. func: func,
  1843. delay: getTimeToNextFrame(),
  1844. args: [clock.now + getTimeToNextFrame()],
  1845. animation: true
  1846. });
  1847. return result.id || result;
  1848. };
  1849. clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) {
  1850. return clearTimer(clock, timerId, "AnimationFrame");
  1851. };
  1852. clock.runMicrotasks = function runMicrotasks() {
  1853. runJobs(clock);
  1854. };
  1855. function doTick(tickValue, isAsync, resolve, reject) {
  1856. var msFloat =
  1857. typeof tickValue === "number"
  1858. ? tickValue
  1859. : parseTime(tickValue);
  1860. var ms = Math.floor(msFloat);
  1861. var remainder = nanoRemainder(msFloat);
  1862. var nanosTotal = nanos + remainder;
  1863. var tickTo = clock.now + ms;
  1864. if (msFloat < 0) {
  1865. throw new TypeError("Negative ticks are not supported");
  1866. }
  1867. // adjust for positive overflow
  1868. if (nanosTotal >= 1e6) {
  1869. tickTo += 1;
  1870. nanosTotal -= 1e6;
  1871. }
  1872. nanos = nanosTotal;
  1873. var tickFrom = clock.now;
  1874. var previous = clock.now;
  1875. var timer,
  1876. firstException,
  1877. oldNow,
  1878. nextPromiseTick,
  1879. compensationCheck,
  1880. postTimerCall;
  1881. clock.duringTick = true;
  1882. // perform microtasks
  1883. oldNow = clock.now;
  1884. runJobs(clock);
  1885. if (oldNow !== clock.now) {
  1886. // compensate for any setSystemTime() call during microtask callback
  1887. tickFrom += clock.now - oldNow;
  1888. tickTo += clock.now - oldNow;
  1889. }
  1890. function doTickInner() {
  1891. // perform each timer in the requested range
  1892. timer = firstTimerInRange(clock, tickFrom, tickTo);
  1893. // eslint-disable-next-line no-unmodified-loop-condition
  1894. while (timer && tickFrom <= tickTo) {
  1895. if (clock.timers[timer.id]) {
  1896. tickFrom = timer.callAt;
  1897. clock.now = timer.callAt;
  1898. oldNow = clock.now;
  1899. try {
  1900. runJobs(clock);
  1901. callTimer(clock, timer);
  1902. } catch (e) {
  1903. firstException = firstException || e;
  1904. }
  1905. if (isAsync) {
  1906. // finish up after native setImmediate callback to allow
  1907. // all native es6 promises to process their callbacks after
  1908. // each timer fires.
  1909. originalSetTimeout(nextPromiseTick);
  1910. return;
  1911. }
  1912. compensationCheck();
  1913. }
  1914. postTimerCall();
  1915. }
  1916. // perform process.nextTick()s again
  1917. oldNow = clock.now;
  1918. runJobs(clock);
  1919. if (oldNow !== clock.now) {
  1920. // compensate for any setSystemTime() call during process.nextTick() callback
  1921. tickFrom += clock.now - oldNow;
  1922. tickTo += clock.now - oldNow;
  1923. }
  1924. clock.duringTick = false;
  1925. // corner case: during runJobs new timers were scheduled which could be in the range [clock.now, tickTo]
  1926. timer = firstTimerInRange(clock, tickFrom, tickTo);
  1927. if (timer) {
  1928. try {
  1929. clock.tick(tickTo - clock.now); // do it all again - for the remainder of the requested range
  1930. } catch (e) {
  1931. firstException = firstException || e;
  1932. }
  1933. } else {
  1934. // no timers remaining in the requested range: move the clock all the way to the end
  1935. clock.now = tickTo;
  1936. // update nanos
  1937. nanos = nanosTotal;
  1938. }
  1939. if (firstException) {
  1940. throw firstException;
  1941. }
  1942. if (isAsync) {
  1943. resolve(clock.now);
  1944. } else {
  1945. return clock.now;
  1946. }
  1947. }
  1948. nextPromiseTick =
  1949. isAsync &&
  1950. function() {
  1951. try {
  1952. compensationCheck();
  1953. postTimerCall();
  1954. doTickInner();
  1955. } catch (e) {
  1956. reject(e);
  1957. }
  1958. };
  1959. compensationCheck = function() {
  1960. // compensate for any setSystemTime() call during timer callback
  1961. if (oldNow !== clock.now) {
  1962. tickFrom += clock.now - oldNow;
  1963. tickTo += clock.now - oldNow;
  1964. previous += clock.now - oldNow;
  1965. }
  1966. };
  1967. postTimerCall = function() {
  1968. timer = firstTimerInRange(clock, previous, tickTo);
  1969. previous = tickFrom;
  1970. };
  1971. return doTickInner();
  1972. }
  1973. /**
  1974. * @param {tickValue} {String|Number} number of milliseconds or a human-readable value like "01:11:15"
  1975. */
  1976. clock.tick = function tick(tickValue) {
  1977. return doTick(tickValue, false);
  1978. };
  1979. if (typeof _global.Promise !== "undefined") {
  1980. clock.tickAsync = function tickAsync(ms) {
  1981. return new _global.Promise(function(resolve, reject) {
  1982. originalSetTimeout(function() {
  1983. try {
  1984. doTick(ms, true, resolve, reject);
  1985. } catch (e) {
  1986. reject(e);
  1987. }
  1988. });
  1989. });
  1990. };
  1991. }
  1992. clock.next = function next() {
  1993. runJobs(clock);
  1994. var timer = firstTimer(clock);
  1995. if (!timer) {
  1996. return clock.now;
  1997. }
  1998. clock.duringTick = true;
  1999. try {
  2000. clock.now = timer.callAt;
  2001. callTimer(clock, timer);
  2002. runJobs(clock);
  2003. return clock.now;
  2004. } finally {
  2005. clock.duringTick = false;
  2006. }
  2007. };
  2008. if (typeof _global.Promise !== "undefined") {
  2009. clock.nextAsync = function nextAsync() {
  2010. return new _global.Promise(function(resolve, reject) {
  2011. originalSetTimeout(function() {
  2012. try {
  2013. var timer = firstTimer(clock);
  2014. if (!timer) {
  2015. resolve(clock.now);
  2016. return;
  2017. }
  2018. var err;
  2019. clock.duringTick = true;
  2020. clock.now = timer.callAt;
  2021. try {
  2022. callTimer(clock, timer);
  2023. } catch (e) {
  2024. err = e;
  2025. }
  2026. clock.duringTick = false;
  2027. originalSetTimeout(function() {
  2028. if (err) {
  2029. reject(err);
  2030. } else {
  2031. resolve(clock.now);
  2032. }
  2033. });
  2034. } catch (e) {
  2035. reject(e);
  2036. }
  2037. });
  2038. });
  2039. };
  2040. }
  2041. clock.runAll = function runAll() {
  2042. var numTimers, i;
  2043. runJobs(clock);
  2044. for (i = 0; i < clock.loopLimit; i++) {
  2045. if (!clock.timers) {
  2046. return clock.now;
  2047. }
  2048. numTimers = keys(clock.timers).length;
  2049. if (numTimers === 0) {
  2050. return clock.now;
  2051. }
  2052. clock.next();
  2053. }
  2054. throw new Error(
  2055. "Aborting after running " +
  2056. clock.loopLimit +
  2057. " timers, assuming an infinite loop!"
  2058. );
  2059. };
  2060. clock.runToFrame = function runToFrame() {
  2061. return clock.tick(getTimeToNextFrame());
  2062. };
  2063. if (typeof _global.Promise !== "undefined") {
  2064. clock.runAllAsync = function runAllAsync() {
  2065. return new _global.Promise(function(resolve, reject) {
  2066. var i = 0;
  2067. function doRun() {
  2068. originalSetTimeout(function() {
  2069. try {
  2070. var numTimers;
  2071. if (i < clock.loopLimit) {
  2072. if (!clock.timers) {
  2073. resolve(clock.now);
  2074. return;
  2075. }
  2076. numTimers = Object.keys(clock.timers)
  2077. .length;
  2078. if (numTimers === 0) {
  2079. resolve(clock.now);
  2080. return;
  2081. }
  2082. clock.next();
  2083. i++;
  2084. doRun();
  2085. return;
  2086. }
  2087. reject(
  2088. new Error(
  2089. "Aborting after running " +
  2090. clock.loopLimit +
  2091. " timers, assuming an infinite loop!"
  2092. )
  2093. );
  2094. } catch (e) {
  2095. reject(e);
  2096. }
  2097. });
  2098. }
  2099. doRun();
  2100. });
  2101. };
  2102. }
  2103. clock.runToLast = function runToLast() {
  2104. var timer = lastTimer(clock);
  2105. if (!timer) {
  2106. runJobs(clock);
  2107. return clock.now;
  2108. }
  2109. return clock.tick(timer.callAt - clock.now);
  2110. };
  2111. if (typeof _global.Promise !== "undefined") {
  2112. clock.runToLastAsync = function runToLastAsync() {
  2113. return new _global.Promise(function(resolve, reject) {
  2114. originalSetTimeout(function() {
  2115. try {
  2116. var timer = lastTimer(clock);
  2117. if (!timer) {
  2118. resolve(clock.now);
  2119. }
  2120. resolve(clock.tickAsync(timer.callAt));
  2121. } catch (e) {
  2122. reject(e);
  2123. }
  2124. });
  2125. });
  2126. };
  2127. }
  2128. clock.reset = function reset() {
  2129. nanos = 0;
  2130. clock.timers = {};
  2131. clock.jobs = [];
  2132. clock.now = start;
  2133. };
  2134. clock.setSystemTime = function setSystemTime(systemTime) {
  2135. // determine time difference
  2136. var newNow = getEpoch(systemTime);
  2137. var difference = newNow - clock.now;
  2138. var id, timer;
  2139. adjustedSystemTime[0] = adjustedSystemTime[0] + difference;
  2140. adjustedSystemTime[1] = adjustedSystemTime[1] + nanos;
  2141. // update 'system clock'
  2142. clock.now = newNow;
  2143. nanos = 0;
  2144. // update timers and intervals to keep them stable
  2145. for (id in clock.timers) {
  2146. if (clock.timers.hasOwnProperty(id)) {
  2147. timer = clock.timers[id];
  2148. timer.createdAt += difference;
  2149. timer.callAt += difference;
  2150. }
  2151. }
  2152. };
  2153. if (performancePresent) {
  2154. clock.performance = Object.create(null);
  2155. if (hasPerformancePrototype) {
  2156. var proto = _global.Performance.prototype;
  2157. Object.getOwnPropertyNames(proto).forEach(function(name) {
  2158. if (name.indexOf("getEntries") === 0) {
  2159. // match expected return type for getEntries functions
  2160. clock.performance[name] = NOOP_ARRAY;
  2161. } else {
  2162. clock.performance[name] = NOOP;
  2163. }
  2164. });
  2165. }
  2166. clock.performance.now = function FakeTimersNow() {
  2167. var hrt = hrtime();
  2168. var millis = hrt[0] * 1000 + hrt[1] / 1e6;
  2169. return millis;
  2170. };
  2171. }
  2172. if (hrtimePresent) {
  2173. clock.hrtime = hrtime;
  2174. }
  2175. return clock;
  2176. }
  2177. /**
  2178. * @param config {Object} optional config
  2179. * @param config.target {Object} the target to install timers in (default `window`)
  2180. * @param config.now {number|Date} a number (in milliseconds) or a Date object (default epoch)
  2181. * @param config.toFake {string[]} names of the methods that should be faked.
  2182. * @param config.loopLimit {number} the maximum number of timers that will be run when calling runAll()
  2183. * @param config.shouldAdvanceTime {Boolean} tells FakeTimers to increment mocked time automatically (default false)
  2184. * @param config.advanceTimeDelta {Number} increment mocked time every <<advanceTimeDelta>> ms (default: 20ms)
  2185. */
  2186. // eslint-disable-next-line complexity
  2187. function install(config) {
  2188. if (
  2189. arguments.length > 1 ||
  2190. config instanceof Date ||
  2191. Array.isArray(config) ||
  2192. typeof config === "number"
  2193. ) {
  2194. throw new TypeError(
  2195. "FakeTimers.install called with " +
  2196. String(config) +
  2197. " install requires an object parameter"
  2198. );
  2199. }
  2200. // eslint-disable-next-line no-param-reassign
  2201. config = typeof config !== "undefined" ? config : {};
  2202. config.shouldAdvanceTime = config.shouldAdvanceTime || false;
  2203. config.advanceTimeDelta = config.advanceTimeDelta || 20;
  2204. var i, l;
  2205. var target = config.target || _global;
  2206. var clock = createClock(config.now, config.loopLimit);
  2207. clock.uninstall = function() {
  2208. return uninstall(clock, target, config);
  2209. };
  2210. clock.methods = config.toFake || [];
  2211. if (clock.methods.length === 0) {
  2212. // do not fake nextTick by default - GitHub#126
  2213. clock.methods = keys(timers).filter(function(key) {
  2214. return key !== "nextTick" && key !== "queueMicrotask";
  2215. });
  2216. }
  2217. for (i = 0, l = clock.methods.length; i < l; i++) {
  2218. if (clock.methods[i] === "hrtime") {
  2219. if (
  2220. target.process &&
  2221. typeof target.process.hrtime === "function"
  2222. ) {
  2223. hijackMethod(target.process, clock.methods[i], clock);
  2224. }
  2225. } else if (clock.methods[i] === "nextTick") {
  2226. if (
  2227. target.process &&
  2228. typeof target.process.nextTick === "function"
  2229. ) {
  2230. hijackMethod(target.process, clock.methods[i], clock);
  2231. }
  2232. } else {
  2233. if (
  2234. clock.methods[i] === "setInterval" &&
  2235. config.shouldAdvanceTime === true
  2236. ) {
  2237. var intervalTick = doIntervalTick.bind(
  2238. null,
  2239. clock,
  2240. config.advanceTimeDelta
  2241. );
  2242. var intervalId = target[clock.methods[i]](
  2243. intervalTick,
  2244. config.advanceTimeDelta
  2245. );
  2246. clock.attachedInterval = intervalId;
  2247. }
  2248. hijackMethod(target, clock.methods[i], clock);
  2249. }
  2250. }
  2251. return clock;
  2252. }
  2253. return {
  2254. timers: timers,
  2255. createClock: createClock,
  2256. install: install,
  2257. withGlobal: withGlobal
  2258. };
  2259. }
  2260. var defaultImplementation = withGlobal(globalObject);
  2261. exports.timers = defaultImplementation.timers;
  2262. exports.createClock = defaultImplementation.createClock;
  2263. exports.install = defaultImplementation.install;
  2264. exports.withGlobal = withGlobal;
  2265. },{"@sinonjs/commons":7,"util":22}]},{},[23])(23)
  2266. });