{"version":3,"file":"timers.mjs","sources":["../../../lib/util/timers.js"],"sourcesContent":["'use strict'\n\n/**\n * This module offers an optimized timer implementation designed for scenarios\n * where high precision is not critical.\n *\n * The timer achieves faster performance by using a low-resolution approach,\n * with an accuracy target of within 500ms. This makes it particularly useful\n * for timers with delays of 1 second or more, where exact timing is less\n * crucial.\n *\n * It's important to note that Node.js timers are inherently imprecise, as\n * delays can occur due to the event loop being blocked by other operations.\n * Consequently, timers may trigger later than their scheduled time.\n */\n\n/**\n * The fastNow variable contains the internal fast timer clock value.\n *\n * @type {number}\n */\nlet fastNow = 0\n\n/**\n * RESOLUTION_MS represents the target resolution time in milliseconds.\n *\n * @type {number}\n * @default 1000\n */\nconst RESOLUTION_MS = 1e3\n\n/**\n * TICK_MS defines the desired interval in milliseconds between each tick.\n * The target value is set to half the resolution time, minus 1 ms, to account\n * for potential event loop overhead.\n *\n * @type {number}\n * @default 499\n */\nconst TICK_MS = (RESOLUTION_MS >> 1) - 1\n\n/**\n * fastNowTimeout is a Node.js timer used to manage and process\n * the FastTimers stored in the `fastTimers` array.\n *\n * @type {NodeJS.Timeout}\n */\nlet fastNowTimeout\n\n/**\n * The kFastTimer symbol is used to identify FastTimer instances.\n *\n * @type {Symbol}\n */\nconst kFastTimer = Symbol('kFastTimer')\n\n/**\n * The fastTimers array contains all active FastTimers.\n *\n * @type {FastTimer[]}\n */\nconst fastTimers = []\n\n/**\n * These constants represent the various states of a FastTimer.\n */\n\n/**\n * The `NOT_IN_LIST` constant indicates that the FastTimer is not included\n * in the `fastTimers` array. Timers with this status will not be processed\n * during the next tick by the `onTick` function.\n *\n * A FastTimer can be re-added to the `fastTimers` array by invoking the\n * `refresh` method on the FastTimer instance.\n *\n * @type {-2}\n */\nconst NOT_IN_LIST = -2\n\n/**\n * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled\n * for removal from the `fastTimers` array. A FastTimer in this state will\n * be removed in the next tick by the `onTick` function and will no longer\n * be processed.\n *\n * This status is also set when the `clear` method is called on the FastTimer instance.\n *\n * @type {-1}\n */\nconst TO_BE_CLEARED = -1\n\n/**\n * The `PENDING` constant signifies that the FastTimer is awaiting processing\n * in the next tick by the `onTick` function. Timers with this status will have\n * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick.\n *\n * @type {0}\n */\nconst PENDING = 0\n\n/**\n * The `ACTIVE` constant indicates that the FastTimer is active and waiting\n * for its timer to expire. During the next tick, the `onTick` function will\n * check if the timer has expired, and if so, it will execute the associated callback.\n *\n * @type {1}\n */\nconst ACTIVE = 1\n\n/**\n * The onTick function processes the fastTimers array.\n *\n * @returns {void}\n */\nfunction onTick () {\n  /**\n   * Increment the fastNow value by the TICK_MS value, despite the actual time\n   * that has passed since the last tick. This approach ensures independence\n   * from the system clock and delays caused by a blocked event loop.\n   *\n   * @type {number}\n   */\n  fastNow += TICK_MS\n\n  /**\n   * The `idx` variable is used to iterate over the `fastTimers` array.\n   * Expired timers are removed by replacing them with the last element in the array.\n   * Consequently, `idx` is only incremented when the current element is not removed.\n   *\n   * @type {number}\n   */\n  let idx = 0\n\n  /**\n   * The len variable will contain the length of the fastTimers array\n   * and will be decremented when a FastTimer should be removed from the\n   * fastTimers array.\n   *\n   * @type {number}\n   */\n  let len = fastTimers.length\n\n  while (idx < len) {\n    /**\n     * @type {FastTimer}\n     */\n    const timer = fastTimers[idx]\n\n    // If the timer is in the ACTIVE state and the timer has expired, it will\n    // be processed in the next tick.\n    if (timer._state === PENDING) {\n      // Set the _idleStart value to the fastNow value minus the TICK_MS value\n      // to account for the time the timer was in the PENDING state.\n      timer._idleStart = fastNow - TICK_MS\n      timer._state = ACTIVE\n    } else if (\n      timer._state === ACTIVE &&\n      fastNow >= timer._idleStart + timer._idleTimeout\n    ) {\n      timer._state = TO_BE_CLEARED\n      timer._idleStart = -1\n      timer._onTimeout(timer._timerArg)\n    }\n\n    if (timer._state === TO_BE_CLEARED) {\n      timer._state = NOT_IN_LIST\n\n      // Move the last element to the current index and decrement len if it is\n      // not the only element in the array.\n      if (--len !== 0) {\n        fastTimers[idx] = fastTimers[len]\n      }\n    } else {\n      ++idx\n    }\n  }\n\n  // Set the length of the fastTimers array to the new length and thus\n  // removing the excess FastTimers elements from the array.\n  fastTimers.length = len\n\n  // If there are still active FastTimers in the array, refresh the Timer.\n  // If there are no active FastTimers, the timer will be refreshed again\n  // when a new FastTimer is instantiated.\n  if (fastTimers.length !== 0) {\n    refreshTimeout()\n  }\n}\n\nfunction refreshTimeout () {\n  // If the fastNowTimeout is already set and the Timer has the refresh()-\n  // method available, call it to refresh the timer.\n  // Some timer objects returned by setTimeout may not have a .refresh()\n  // method (e.g. mocked timers in tests).\n  if (fastNowTimeout?.refresh) {\n    fastNowTimeout.refresh()\n    // fastNowTimeout is not instantiated yet or refresh is not availabe,\n    // create a new Timer.\n  } else {\n    clearTimeout(fastNowTimeout)\n    fastNowTimeout = setTimeout(onTick, TICK_MS)\n    // If the Timer has an unref method, call it to allow the process to exit,\n    // if there are no other active handles. When using fake timers or mocked\n    // environments (like Jest), .unref() may not be defined,\n    fastNowTimeout?.unref()\n  }\n}\n\n/**\n * The `FastTimer` class is a data structure designed to store and manage\n * timer information.\n */\nclass FastTimer {\n  [kFastTimer] = true\n\n  /**\n   * The state of the timer, which can be one of the following:\n   * - NOT_IN_LIST (-2)\n   * - TO_BE_CLEARED (-1)\n   * - PENDING (0)\n   * - ACTIVE (1)\n   *\n   * @type {-2|-1|0|1}\n   * @private\n   */\n  _state = NOT_IN_LIST\n\n  /**\n   * The number of milliseconds to wait before calling the callback.\n   *\n   * @type {number}\n   * @private\n   */\n  _idleTimeout = -1\n\n  /**\n   * The time in milliseconds when the timer was started. This value is used to\n   * calculate when the timer should expire.\n   *\n   * @type {number}\n   * @default -1\n   * @private\n   */\n  _idleStart = -1\n\n  /**\n   * The function to be executed when the timer expires.\n   * @type {Function}\n   * @private\n   */\n  _onTimeout\n\n  /**\n   * The argument to be passed to the callback when the timer expires.\n   *\n   * @type {*}\n   * @private\n   */\n  _timerArg\n\n  /**\n   * @constructor\n   * @param {Function} callback A function to be executed after the timer\n   * expires.\n   * @param {number} delay The time, in milliseconds that the timer should wait\n   * before the specified function or code is executed.\n   * @param {*} arg\n   */\n  constructor (callback, delay, arg) {\n    this._onTimeout = callback\n    this._idleTimeout = delay\n    this._timerArg = arg\n\n    this.refresh()\n  }\n\n  /**\n   * Sets the timer's start time to the current time, and reschedules the timer\n   * to call its callback at the previously specified duration adjusted to the\n   * current time.\n   * Using this on a timer that has already called its callback will reactivate\n   * the timer.\n   *\n   * @returns {void}\n   */\n  refresh () {\n    // In the special case that the timer is not in the list of active timers,\n    // add it back to the array to be processed in the next tick by the onTick\n    // function.\n    if (this._state === NOT_IN_LIST) {\n      fastTimers.push(this)\n    }\n\n    // If the timer is the only active timer, refresh the fastNowTimeout for\n    // better resolution.\n    if (!fastNowTimeout || fastTimers.length === 1) {\n      refreshTimeout()\n    }\n\n    // Setting the state to PENDING will cause the timer to be reset in the\n    // next tick by the onTick function.\n    this._state = PENDING\n  }\n\n  /**\n   * The `clear` method cancels the timer, preventing it from executing.\n   *\n   * @returns {void}\n   * @private\n   */\n  clear () {\n    // Set the state to TO_BE_CLEARED to mark the timer for removal in the next\n    // tick by the onTick function.\n    this._state = TO_BE_CLEARED\n\n    // Reset the _idleStart value to -1 to indicate that the timer is no longer\n    // active.\n    this._idleStart = -1\n  }\n}\n\n/**\n * This module exports a setTimeout and clearTimeout function that can be\n * used as a drop-in replacement for the native functions.\n */\nmodule.exports = {\n  /**\n   * The setTimeout() method sets a timer which executes a function once the\n   * timer expires.\n   * @param {Function} callback A function to be executed after the timer\n   * expires.\n   * @param {number} delay The time, in milliseconds that the timer should\n   * wait before the specified function or code is executed.\n   * @param {*} [arg] An optional argument to be passed to the callback function\n   * when the timer expires.\n   * @returns {NodeJS.Timeout|FastTimer}\n   */\n  setTimeout (callback, delay, arg) {\n    // If the delay is less than or equal to the RESOLUTION_MS value return a\n    // native Node.js Timer instance.\n    return delay <= RESOLUTION_MS\n      ? setTimeout(callback, delay, arg)\n      : new FastTimer(callback, delay, arg)\n  },\n  /**\n   * The clearTimeout method cancels an instantiated Timer previously created\n   * by calling setTimeout.\n   *\n   * @param {NodeJS.Timeout|FastTimer} timeout\n   */\n  clearTimeout (timeout) {\n    // If the timeout is a FastTimer, call its own clear method.\n    if (timeout[kFastTimer]) {\n      /**\n       * @type {FastTimer}\n       */\n      timeout.clear()\n      // Otherwise it is an instance of a native NodeJS.Timeout, so call the\n      // Node.js native clearTimeout function.\n    } else {\n      clearTimeout(timeout)\n    }\n  },\n  /**\n   * The setFastTimeout() method sets a fastTimer which executes a function once\n   * the timer expires.\n   * @param {Function} callback A function to be executed after the timer\n   * expires.\n   * @param {number} delay The time, in milliseconds that the timer should\n   * wait before the specified function or code is executed.\n   * @param {*} [arg] An optional argument to be passed to the callback function\n   * when the timer expires.\n   * @returns {FastTimer}\n   */\n  setFastTimeout (callback, delay, arg) {\n    return new FastTimer(callback, delay, arg)\n  },\n  /**\n   * The clearTimeout method cancels an instantiated FastTimer previously\n   * created by calling setFastTimeout.\n   *\n   * @param {FastTimer} timeout\n   */\n  clearFastTimeout (timeout) {\n    timeout.clear()\n  },\n  /**\n   * The now method returns the value of the internal fast timer clock.\n   *\n   * @returns {number}\n   */\n  now () {\n    return fastNow\n  },\n  /**\n   * Trigger the onTick function to process the fastTimers array.\n   * Exported for testing purposes only.\n   * Marking as deprecated to discourage any use outside of testing.\n   * @deprecated\n   * @param {number} [delay=0] The delay in milliseconds to add to the now value.\n   */\n  tick (delay = 0) {\n    fastNow += delay - RESOLUTION_MS + 1\n    onTick()\n    onTick()\n  },\n  /**\n   * Reset FastTimers.\n   * Exported for testing purposes only.\n   * Marking as deprecated to discourage any use outside of testing.\n   * @deprecated\n   */\n  reset () {\n    fastNow = 0\n    fastTimers.length = 0\n    clearTimeout(fastNowTimeout)\n    fastNowTimeout = null\n  },\n  /**\n   * Exporting for testing purposes only.\n   * Marking as deprecated to discourage any use outside of testing.\n   * @deprecated\n   */\n  kFastTimer\n}\n"],"names":["fastNowTimeout","fastNow","kFastTimer","Symbol","fastTimers","onTick","idx","len","length","timer","_state","_idleStart","_idleTimeout","_onTimeout","_timerArg","refreshTimeout","refresh","clearTimeout","setTimeout","unref","FastTimer","constructor","callback","delay","arg","this","push","clear","timers","timeout","setFastTimeout","clearFastTimeout","now","tick","reset"],"mappings":";;;;;;;;;;;;;;;;;;GAqBA,IA0BIA,eA1BAC,QAAU;;;;;;;;;;;;AAiCd,MAAMC,WAAaC,OAAO,cAOpBC,WAAa;;;;;;;;;;;AAqDnB,SAASC;;;;;;;;AAQPJ,SAnFc;;;;;;;;AA4Fd,IAAIK,IAAM,EASNC,IAAMH,WAAWI;;;;;;;KAErB,KAAOF,IAAMC,KAAK;;;;AAIhB,MAAME,MAAQL,WAAWE;;iCAhDb;IAoDRG,MAAMC;;;AAGRD,MAAME,WAAaV,QAlHT,IAmHVQ,MAAMC,OA/CG,OAiDTD,MAAMC,QACNT,SAAWQ,MAAME,WAAaF,MAAMG,eAEpCH,MAAMC,QAtEU,EAuEhBD,MAAME,YAAa,EACnBF,MAAMI,WAAWJ,MAAMK,aAxEP,IA2EdL,MAAMC,QACRD,MAAMC,QAxFQ;;;AA4FA,MAARH,MACJH,WAAWE,KAAOF,WAAWG,SAG7BD,GAER;;0DAIEF;WAAWI,OAASD;;;;AAKM,IAAtBH,WAAWI,QACbO,gBAEJ,CAEA,SAASA;;;;;AAKHf,gBAAgBgB,QAClBhB,eAAegB,WAIfC,aAAajB,gBACbA,eAAiBkB,WAAWb,OAjKhB;;;;AAqKZL,gBAAgBmB,QAEpB;;;;GAMA,MAAMC,UACJlB,CAACA,aAAc;;;;;;;;;;MAYfQ,QApJkB;;;;;;KA4JlBE,cAAe;;;;;;;;MAUfD,YAAa;;;;;MAObE;;;;;;KAQAC;;;;;;;;KAUA,WAAAO,CAAaC,SAAUC,MAAOC,KAC5BC,KAAKZ,WAAaS,SAClBG,KAAKb,aAAeW,MACpBE,KA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