@tanstack/pacer 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/cjs/async-debouncer.cjs +60 -44
  2. package/dist/cjs/async-debouncer.cjs.map +1 -1
  3. package/dist/cjs/async-debouncer.d.cts +37 -24
  4. package/dist/cjs/async-queuer.cjs +149 -125
  5. package/dist/cjs/async-queuer.cjs.map +1 -1
  6. package/dist/cjs/async-queuer.d.cts +65 -48
  7. package/dist/cjs/async-rate-limiter.cjs +63 -46
  8. package/dist/cjs/async-rate-limiter.cjs.map +1 -1
  9. package/dist/cjs/async-rate-limiter.d.cts +39 -27
  10. package/dist/cjs/async-throttler.cjs +70 -47
  11. package/dist/cjs/async-throttler.cjs.map +1 -1
  12. package/dist/cjs/async-throttler.d.cts +43 -25
  13. package/dist/cjs/debouncer.cjs +46 -22
  14. package/dist/cjs/debouncer.cjs.map +1 -1
  15. package/dist/cjs/debouncer.d.cts +25 -11
  16. package/dist/cjs/index.cjs +2 -0
  17. package/dist/cjs/index.cjs.map +1 -1
  18. package/dist/cjs/index.d.cts +2 -0
  19. package/dist/cjs/queuer.cjs +114 -104
  20. package/dist/cjs/queuer.cjs.map +1 -1
  21. package/dist/cjs/queuer.d.cts +53 -40
  22. package/dist/cjs/rate-limiter.cjs +54 -42
  23. package/dist/cjs/rate-limiter.cjs.map +1 -1
  24. package/dist/cjs/rate-limiter.d.cts +37 -45
  25. package/dist/cjs/throttler.cjs +61 -41
  26. package/dist/cjs/throttler.cjs.map +1 -1
  27. package/dist/cjs/throttler.d.cts +35 -22
  28. package/dist/cjs/types.d.cts +12 -0
  29. package/dist/cjs/utils.cjs +13 -0
  30. package/dist/cjs/utils.cjs.map +1 -0
  31. package/dist/cjs/utils.d.cts +1 -0
  32. package/dist/esm/async-debouncer.d.ts +37 -24
  33. package/dist/esm/async-debouncer.js +60 -44
  34. package/dist/esm/async-debouncer.js.map +1 -1
  35. package/dist/esm/async-queuer.d.ts +65 -48
  36. package/dist/esm/async-queuer.js +149 -125
  37. package/dist/esm/async-queuer.js.map +1 -1
  38. package/dist/esm/async-rate-limiter.d.ts +39 -27
  39. package/dist/esm/async-rate-limiter.js +63 -46
  40. package/dist/esm/async-rate-limiter.js.map +1 -1
  41. package/dist/esm/async-throttler.d.ts +43 -25
  42. package/dist/esm/async-throttler.js +70 -47
  43. package/dist/esm/async-throttler.js.map +1 -1
  44. package/dist/esm/debouncer.d.ts +25 -11
  45. package/dist/esm/debouncer.js +46 -22
  46. package/dist/esm/debouncer.js.map +1 -1
  47. package/dist/esm/index.d.ts +2 -0
  48. package/dist/esm/index.js +2 -0
  49. package/dist/esm/index.js.map +1 -1
  50. package/dist/esm/queuer.d.ts +53 -40
  51. package/dist/esm/queuer.js +114 -104
  52. package/dist/esm/queuer.js.map +1 -1
  53. package/dist/esm/rate-limiter.d.ts +37 -45
  54. package/dist/esm/rate-limiter.js +54 -42
  55. package/dist/esm/rate-limiter.js.map +1 -1
  56. package/dist/esm/throttler.d.ts +35 -22
  57. package/dist/esm/throttler.js +61 -41
  58. package/dist/esm/throttler.js.map +1 -1
  59. package/dist/esm/types.d.ts +12 -0
  60. package/dist/esm/utils.d.ts +1 -0
  61. package/dist/esm/utils.js +13 -0
  62. package/dist/esm/utils.js.map +1 -0
  63. package/package.json +8 -1
  64. package/src/async-debouncer.ts +90 -62
  65. package/src/async-queuer.ts +178 -145
  66. package/src/async-rate-limiter.ts +93 -67
  67. package/src/async-throttler.ts +98 -63
  68. package/src/debouncer.ts +71 -35
  69. package/src/index.ts +2 -0
  70. package/src/queuer.ts +135 -118
  71. package/src/rate-limiter.ts +79 -81
  72. package/src/throttler.ts +87 -61
  73. package/src/types.ts +17 -0
  74. package/src/utils.ts +13 -0
@@ -1 +1 @@
1
- {"version":3,"file":"queuer.js","sources":["../../src/queuer.ts"],"sourcesContent":["/**\n * Options for configuring a Queuer instance\n */\nexport interface QueuerOptions<TValue> {\n /**\n * Default position to add items to the queuer\n * @default 'back'\n */\n addItemsTo?: QueuePosition\n /**\n * Default position to get items from during processing\n * @default 'front'\n */\n getItemsFrom?: QueuePosition\n /**\n * Function to determine priority of items in the queuer\n * Higher priority items will be processed first\n */\n getPriority?: (item: TValue) => number\n /**\n * Initial items to populate the queuer with\n */\n initialItems?: Array<TValue>\n /**\n * Maximum number of items allowed in the queuer\n */\n maxSize?: number\n /**\n * Callback fired whenever an item is removed from the queuer\n */\n onGetNextItem?: (item: TValue, queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever an item is added or removed from the queuer\n */\n onUpdate?: (queuer: Queuer<TValue>) => void\n /**\n * Whether the queuer should start processing tasks immediately\n */\n started?: boolean\n /**\n * Time in milliseconds to wait between processing items\n */\n wait?: number\n}\n\nconst defaultOptions: Required<QueuerOptions<any>> = {\n addItemsTo: 'back',\n getItemsFrom: 'front',\n getPriority: () => 0,\n initialItems: [],\n maxSize: Infinity,\n onGetNextItem: () => {},\n onUpdate: () => {},\n started: false,\n wait: 0,\n}\n\n/**\n * Position type for addItem and getNextItem operations\n */\nexport type QueuePosition = 'front' | 'back'\n\n/**\n * A flexible queue data structure that defaults to FIFO (First In First Out) behavior\n * with optional position overrides for stack-like or double-ended operations.\n *\n * The queuer can automatically process items as they are added, with configurable\n * wait times between processing each item. Processing can be started/stopped\n * and the queuer will maintain its state.\n *\n * Supports priority-based ordering when a getPriority function is provided.\n * Items with higher priority values will be processed first.\n *\n * Default queue behavior:\n * - addItem(item): adds to back of queuer\n * - getNextItem(): removes and returns from front of queuer\n *\n * Stack (LIFO) behavior:\n * - addItem(item, 'back'): adds to back\n * - getNextItem('back'): removes and returns from back\n *\n * Double-ended queuer behavior:\n * - addItem(item, position): adds to specified position ('front' or 'back')\n * - getNextItem(position): removes and returns from specified position\n *\n * Processing behavior:\n * - start(): begins processing items in the queuer\n * - stop(): pauses processing\n * - wait: configurable delay between processing items\n * - onUpdate/onGetNextItem: callbacks for monitoring queuer state\n *\n * @example\n * ```ts\n * // FIFO queuer\n * const queuer = new Queuer<number>();\n * queuer.addItem(1); // [1]\n * queuer.addItem(2); // [1, 2]\n * queuer.getNextItem(); // returns 1, queuer is [2]\n *\n * // Priority queuer with processing\n * const priorityQueue = new Queuer<number>({\n * getPriority: (n) => n, // Higher numbers have priority\n * started: true, // Begin processing immediately\n * wait: 1000, // Wait 1s between items\n * onGetNextItem: (item) => console.log(item)\n * });\n * priorityQueue.addItem(1); // [1]\n * priorityQueue.addItem(3); // [3, 1] - 3 processed first\n * priorityQueue.addItem(2); // [3, 2, 1]\n * ```\n */\nexport class Queuer<TValue> {\n protected options: Required<QueuerOptions<TValue>>\n private items: Array<TValue> = []\n private executionCount = 0\n private onUpdates: Array<(item: TValue) => void> = []\n private running: boolean\n private pendingTick = false\n\n constructor(initialOptions: QueuerOptions<TValue> = defaultOptions) {\n this.options = { ...defaultOptions, ...initialOptions }\n this.running = this.options.started\n\n for (let i = 0; i < this.options.initialItems.length; i++) {\n const item = this.options.initialItems[i]!\n const isLast = i === this.options.initialItems.length - 1\n this.addItem(item, this.options.addItemsTo, isLast)\n }\n }\n\n /**\n * Processes items in the queuer\n */\n protected tick() {\n if (!this.running) {\n this.pendingTick = false\n return\n }\n while (!this.isEmpty()) {\n const nextItem = this.getNextItem(this.options.getItemsFrom)\n if (nextItem === undefined) {\n break\n }\n this.onUpdates.forEach((cb) => cb(nextItem))\n\n if (this.options.wait > 0) {\n // Use setTimeout to wait before processing next item\n setTimeout(() => this.tick(), this.options.wait)\n return\n }\n\n this.tick()\n }\n this.pendingTick = false\n }\n\n /**\n * Updates the queuer options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<QueuerOptions<TValue>>,\n ): QueuerOptions<TValue> {\n this.options = { ...this.options, ...newOptions }\n return this.options\n }\n\n /**\n * Adds an item to the queuer and starts processing if not already running\n * @returns true if item was added, false if queuer is full\n */\n addItem(\n item: TValue,\n position: QueuePosition = this.options.addItemsTo,\n runOnUpdate: boolean = true,\n ): boolean {\n if (this.isFull()) {\n return false\n }\n\n if (this.options.getPriority !== defaultOptions.getPriority) {\n // If custom priority function is provided, insert based on priority\n const priority = this.options.getPriority(item)\n const insertIndex = this.items.findIndex(\n (existing) => this.options.getPriority(existing) > priority,\n )\n\n if (insertIndex === -1) {\n this.items.push(item)\n } else {\n this.items.splice(insertIndex, 0, item)\n }\n } else {\n // Default FIFO/LIFO behavior\n if (position === 'front') {\n this.items.unshift(item)\n } else {\n this.items.push(item)\n }\n }\n\n if (this.running && !this.pendingTick) {\n this.pendingTick = true\n this.tick()\n }\n if (runOnUpdate) {\n this.options.onUpdate(this)\n }\n return true\n }\n\n /**\n * Removes and returns an item from the queuer using shift (default) or pop\n *\n * @example\n * ```ts\n * // Standard FIFO queuer\n * queuer.getNextItem()\n * // Stack-like behavior (LIFO)\n * queuer.getNextItem('back')\n * ```\n */\n getNextItem(\n position: QueuePosition = this.options.getItemsFrom,\n ): TValue | undefined {\n let item: TValue | undefined\n\n if (position === 'front') {\n item = this.items.shift()\n } else {\n item = this.items.pop()\n }\n\n if (item !== undefined) {\n this.executionCount++\n this.options.onUpdate(this)\n this.options.onGetNextItem(item, this)\n }\n return item\n }\n\n /**\n * Returns an item without removing it\n *\n * @example\n * ```ts\n * // Look at next item to getNextItem\n * queuer.peek()\n * // Look at last item (like stack top)\n * queuer.peek('back')\n * ```\n */\n peek(\n position: QueuePosition = this.options.getItemsFrom,\n ): TValue | undefined {\n if (position === 'front') {\n return this.items[0]\n }\n return this.items[this.items.length - 1]\n }\n\n /**\n * Returns true if the queuer is empty\n */\n isEmpty(): boolean {\n return this.items.length === 0\n }\n\n /**\n * Returns true if the queuer is full\n */\n isFull(): boolean {\n return this.items.length >= this.options.maxSize\n }\n\n /**\n * Returns the current size of the queuer\n */\n size(): number {\n return this.items.length\n }\n\n /**\n * Removes all items from the queuer\n */\n clear(): void {\n this.items = []\n this.options.onUpdate(this)\n }\n\n /**\n * Resets the queuer to its initial state\n */\n reset(withInitialItems?: boolean): void {\n this.clear()\n this.executionCount = 0\n if (withInitialItems) {\n this.items = [...this.options.initialItems]\n }\n this.running = this.options.started\n }\n\n /**\n * Returns a copy of all items in the queuer\n */\n getAllItems(): Array<TValue> {\n return [...this.items]\n }\n\n /**\n * Returns the number of items that have been removed from the queuer\n */\n getExecutionCount(): number {\n return this.executionCount\n }\n\n /**\n * Adds a callback to be called when an item is processed\n */\n onUpdate(cb: (item: TValue) => void) {\n this.onUpdates.push(cb)\n return () => {\n this.onUpdates = this.onUpdates.filter((d) => d !== cb)\n }\n }\n\n /**\n * Stops the queuer from processing items\n */\n stop() {\n this.running = false\n this.pendingTick = false\n this.options.onUpdate(this)\n }\n\n /**\n * Starts the queuer and processes items\n */\n start() {\n this.running = true\n if (!this.pendingTick && !this.isEmpty()) {\n this.pendingTick = true\n this.tick()\n }\n this.options.onUpdate(this)\n }\n\n /**\n * Returns true if the queuer is running\n */\n isRunning() {\n return this.running\n }\n\n /**\n * Returns true if the queuer is running but has no items to process\n */\n isIdle() {\n return this.running && this.isEmpty()\n }\n}\n\n/**\n * Creates a queue that processes items in a queuer immediately upon addition.\n * Items are processed sequentially in FIFO order by default.\n *\n * This is a simplified wrapper around the Queuer class that only exposes the\n * `addItem` method. This queue is always running and will process items as they are added.\n * For more control over queuer processing, use the Queuer class\n * directly which provides methods like `start`, `stop`, `reset`, and more.\n *\n * @example\n * ```ts\n * // Basic sequential processing\n * const processItems = queuer<number>({\n * wait: 1000,\n * onUpdate: (queuer) => console.log(queuer.getAllItems())\n * })\n * processItems(1) // Logs: 1\n * processItems(2) // Logs: 2 after 1 completes\n *\n * // Priority queuer\n * const processPriority = queuer<number>({\n * process: async (n) => console.log(n),\n * getPriority: n => n // Higher numbers processed first\n * })\n * processPriority(1)\n * processPriority(3) // Processed before 1\n * ```\n */\nexport function queue<TValue>(options: QueuerOptions<TValue> = {}) {\n const queuer = new Queuer<TValue>({ ...options, started: true })\n return queuer.addItem.bind(queuer)\n}\n"],"names":[],"mappings":"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AA,EAM5B,QAAQ;AACN,SAAK,UAAU;AACf,QAAI,CAAC,KAAK,eAAe,CAAC,KAAK,WAAW;AACxC,WAAK,cAAc;AACnB,WAAK,KAAK;AAAA,IAAA;AAEP,SAAA,QAAQ,SAAS,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM5B,YAAY;AACV,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,SAAS;AACA,WAAA,KAAK,WAAW,KAAK,QAAQ;AAAA,EAAA;AAExC;AA8BgB,SAAA,MAAc,UAAiC,IAAI;AAC3D,QAAA,SAAS,IAAI,OAAe,EAAE,GAAG,SAAS,SAAS,MAAM;AACxD,SAAA,OAAO,QAAQ,KAAK,MAAM;AACnC;"}
1
+ {"version":3,"file":"queuer.js","sources":["../../src/queuer.ts"],"sourcesContent":["/**\n * Options for configuring a Queuer instance\n */\nexport interface QueuerOptions<TValue> {\n /**\n * Default position to add items to the queuer\n * @default 'back'\n */\n addItemsTo?: QueuePosition\n /**\n * Default position to get items from during processing\n * @default 'front'\n */\n getItemsFrom?: QueuePosition\n /**\n * Function to determine priority of items in the queuer\n * Higher priority items will be processed first\n */\n getPriority?: (item: TValue) => number\n /**\n * Initial items to populate the queuer with\n */\n initialItems?: Array<TValue>\n /**\n * Maximum number of items allowed in the queuer\n */\n maxSize?: number\n /**\n * Callback fired whenever an item is removed from the queuer\n */\n onGetNextItem?: (item: TValue, queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever the queuer's running state changes\n */\n onIsRunningChange?: (queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever an item is added or removed from the queuer\n */\n onItemsChange?: (queuer: Queuer<TValue>) => void\n /**\n * Callback fired whenever an item is rejected from being added to the queuer\n */\n onReject?: (item: TValue, queuer: Queuer<TValue>) => void\n /**\n * Whether the queuer should start processing tasks immediately\n */\n started?: boolean\n /**\n * Time in milliseconds to wait between processing items\n */\n wait?: number\n}\n\nconst defaultOptions: Required<QueuerOptions<any>> = {\n addItemsTo: 'back',\n getItemsFrom: 'front',\n getPriority: (item) => item?.priority ?? 0,\n initialItems: [],\n maxSize: Infinity,\n onGetNextItem: () => {},\n onIsRunningChange: () => {},\n onItemsChange: () => {},\n onReject: () => {},\n started: false,\n wait: 0,\n}\n\n/**\n * Position type for addItem and getNextItem operations\n */\nexport type QueuePosition = 'front' | 'back'\n\n/**\n * A flexible queue data structure that defaults to FIFO (First In First Out) behavior\n * with optional position overrides for stack-like or double-ended operations.\n *\n * The queuer can automatically process items as they are added, with configurable\n * wait times between processing each item. Processing can be started/stopped\n * and the queuer will maintain its state.\n *\n * Supports priority-based ordering when a getPriority function is provided.\n * Items with higher priority values will be processed first.\n *\n * Default queue behavior:\n * - addItem(item): adds to back of queuer\n * - getNextItem(): removes and returns from front of queuer\n *\n * Stack (LIFO) behavior:\n * - addItem(item, 'back'): adds to back\n * - getNextItem('back'): removes and returns from back\n *\n * Double-ended queuer behavior:\n * - addItem(item, position): adds to specified position ('front' or 'back')\n * - getNextItem(position): removes and returns from specified position\n *\n * Processing behavior:\n * - start(): begins processing items in the queuer\n * - stop(): pauses processing\n * - wait: configurable delay between processing items\n * - onItemsChange/onGetNextItem: callbacks for monitoring queuer state\n *\n * @example\n * ```ts\n * // FIFO queuer\n * const queuer = new Queuer<number>();\n * queuer.addItem(1); // [1]\n * queuer.addItem(2); // [1, 2]\n * queuer.getNextItem(); // returns 1, queuer is [2]\n *\n * // Priority queuer with processing\n * const priorityQueue = new Queuer<number>({\n * getPriority: (n) => n, // Higher numbers have priority\n * started: true, // Begin processing immediately\n * wait: 1000, // Wait 1s between items\n * onGetNextItem: (item, queuer) => console.log(item)\n * });\n * priorityQueue.addItem(1); // [1]\n * priorityQueue.addItem(3); // [3, 1] - 3 processed first\n * priorityQueue.addItem(2); // [3, 2, 1]\n * ```\n */\nexport class Queuer<TValue> {\n private _options: Required<QueuerOptions<TValue>>\n private _items: Array<TValue> = []\n private _executionCount = 0\n private _rejectionCount = 0\n private _onItemsChanges: Array<(item: TValue) => void> = []\n private _running: boolean\n private _pendingTick = false\n\n constructor(initialOptions: QueuerOptions<TValue> = defaultOptions) {\n this._options = { ...defaultOptions, ...initialOptions }\n this._running = this._options.started\n\n for (let i = 0; i < this._options.initialItems.length; i++) {\n const item = this._options.initialItems[i]!\n const isLast = i === this._options.initialItems.length - 1\n this.addItem(item, this._options.addItemsTo, isLast)\n }\n }\n\n /**\n * Updates the queuer options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<QueuerOptions<TValue>>,\n ): QueuerOptions<TValue> {\n this._options = { ...this._options, ...newOptions }\n return this._options\n }\n\n /**\n * Returns the current queuer options\n */\n getOptions(): Required<QueuerOptions<TValue>> {\n return this._options\n }\n\n /**\n * Processes items in the queuer\n */\n private tick() {\n if (!this._running) {\n this._pendingTick = false\n return\n }\n while (!this.getIsEmpty()) {\n const nextItem = this.getNextItem(this._options.getItemsFrom)\n if (nextItem === undefined) {\n break\n }\n this._onItemsChanges.forEach((cb) => cb(nextItem))\n\n if (this._options.wait > 0) {\n // Use setTimeout to wait before processing next item\n setTimeout(() => this.tick(), this._options.wait)\n return\n }\n\n this.tick()\n }\n this._pendingTick = false\n }\n\n /**\n * Stops the queuer from processing items\n */\n stop() {\n this._running = false\n this._pendingTick = false\n this._options.onIsRunningChange(this)\n }\n\n /**\n * Starts the queuer and processes items\n */\n start() {\n this._running = true\n if (!this._pendingTick && !this.getIsEmpty()) {\n this._pendingTick = true\n this.tick()\n }\n this._options.onIsRunningChange(this)\n }\n\n /**\n * Removes all items from the queuer\n */\n clear(): void {\n this._items = []\n this._options.onItemsChange(this)\n }\n\n /**\n * Resets the queuer to its initial state\n */\n reset(withInitialItems?: boolean): void {\n this.clear()\n this._executionCount = 0\n if (withInitialItems) {\n this._items = [...this._options.initialItems]\n }\n this._running = this._options.started\n }\n\n /**\n * Adds an item to the queuer and starts processing if not already running\n * @returns true if item was added, false if queuer is full\n */\n addItem(\n item: TValue,\n position: QueuePosition = this._options.addItemsTo,\n runOnUpdate: boolean = true,\n ): boolean {\n if (this.getIsFull()) {\n this._rejectionCount++\n this._options.onReject(item, this)\n return false\n }\n\n if (this._options.getPriority !== defaultOptions.getPriority) {\n // If custom priority function is provided, insert based on priority\n const priority = this._options.getPriority(item)\n const insertIndex = this._items.findIndex(\n (existing) => this._options.getPriority(existing) > priority,\n )\n\n if (insertIndex === -1) {\n this._items.push(item)\n } else {\n this._items.splice(insertIndex, 0, item)\n }\n } else {\n // Default FIFO/LIFO behavior\n if (position === 'front') {\n this._items.unshift(item)\n } else {\n this._items.push(item)\n }\n }\n\n if (this._running && !this._pendingTick) {\n this._pendingTick = true\n this.tick()\n }\n if (runOnUpdate) {\n this._options.onItemsChange(this)\n }\n return true\n }\n\n /**\n * Removes and returns an item from the queuer using shift (default) or pop\n *\n * @example\n * ```ts\n * // Standard FIFO queuer\n * queuer.getNextItem()\n * // Stack-like behavior (LIFO)\n * queuer.getNextItem('back')\n * ```\n */\n getNextItem(\n position: QueuePosition = this._options.getItemsFrom,\n ): TValue | undefined {\n let item: TValue | undefined\n\n if (position === 'front') {\n item = this._items.shift()\n } else {\n item = this._items.pop()\n }\n\n if (item !== undefined) {\n this._executionCount++\n this._options.onItemsChange(this)\n this._options.onGetNextItem(item, this)\n }\n return item\n }\n\n /**\n * Returns an item without removing it\n *\n * @example\n * ```ts\n * // Look at next item to getNextItem\n * queuer.getPeek()\n * // Look at last item (like stack top)\n * queuer.getPeek('back')\n * ```\n */\n getPeek(\n position: QueuePosition = this._options.getItemsFrom,\n ): TValue | undefined {\n if (position === 'front') {\n return this._items[0]\n }\n return this._items[this._items.length - 1]\n }\n\n /**\n * Returns true if the queuer is empty\n */\n getIsEmpty(): boolean {\n return this._items.length === 0\n }\n\n /**\n * Returns true if the queuer is full\n */\n getIsFull(): boolean {\n return this._items.length >= this._options.maxSize\n }\n\n /**\n * Returns the current size of the queuer\n */\n getSize(): number {\n return this._items.length\n }\n\n /**\n * Returns a copy of all items in the queuer\n */\n getAllItems(): Array<TValue> {\n return [...this._items]\n }\n\n /**\n * Returns the number of items that have been removed from the queuer\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns the number of items that have been rejected from the queuer\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns true if the queuer is running\n */\n getIsRunning() {\n return this._running\n }\n\n /**\n * Returns true if the queuer is running but has no items to process\n */\n getIsIdle() {\n return this._running && this.getIsEmpty()\n }\n}\n\n/**\n * Creates a queue that processes items in a queuer immediately upon addition.\n * Items are processed sequentially in FIFO order by default.\n *\n * This is a simplified wrapper around the Queuer class that only exposes the\n * `addItem` method. This queue is always running and will process items as they are added.\n * For more control over queuer processing, use the Queuer class\n * directly which provides methods like `start`, `stop`, `reset`, and more.\n *\n * @example\n * ```ts\n * // Basic sequential processing\n * const processItems = queuer<number>({\n * wait: 1000,\n * onItemsChange: (queuer) => console.log(queuer.getAllItems())\n * })\n * processItems(1) // Logs: 1\n * processItems(2) // Logs: 2 after 1 completes\n *\n * // Priority queuer\n * const processPriority = queuer<number>({\n * process: async (n) => console.log(n),\n * getPriority: n => n // Higher numbers processed first\n * })\n * processPriority(1)\n * processPriority(3) // Processed before 1\n * ```\n */\nexport function queue<TValue>(options: QueuerOptions<TValue> = {}) {\n const queuer = new Queuer<TValue>({ ...options, started: true })\n return queuer.addItem.bind(queuer)\n}\n"],"names":[],"mappings":"AAqDA,MAAM,iBAA+C;AAAA,EACnD,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,aAAa,CAAC,UAAS,6BAAM,aAAY;AAAA,EACzC,cAAc,CAAC;AAAA,EACf,SAAS;AAAA,EACT,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,mBAAmB,MAAM;AAAA,EAAC;AAAA,EAC1B,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,SAAS;AAAA,EACT,MAAM;AACR;AAwDO,MAAM,OAAe;AAAA,EAS1B,YAA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A;AAAA;AAAA;AAAA,EAMd,YAAY;AACH,WAAA,KAAK,YAAY,KAAK,WAAW;AAAA,EAAA;AAE5C;AA8BgB,SAAA,MAAc,UAAiC,IAAI;AAC3D,QAAA,SAAS,IAAI,OAAe,EAAE,GAAG,SAAS,SAAS,MAAM;AACxD,SAAA,OAAO,QAAQ,KAAK,MAAM;AACnC;"}
@@ -1,28 +1,8 @@
1
- /**
2
- * Information about a rate limit rejection
3
- */
4
- export interface RateLimitRejectionInfo {
5
- /**
6
- * Number of milliseconds until the next execution will be possible
7
- */
8
- msUntilNextWindow: number;
9
- /**
10
- * Current number of executions in the window
11
- */
12
- currentExecutions: number;
13
- /**
14
- * Maximum allowed executions per window
15
- */
16
- limit: number;
17
- /**
18
- * Total number of rejections that have occurred
19
- */
20
- rejectionCount: number;
21
- }
1
+ import { AnyFunction } from './types.js';
22
2
  /**
23
3
  * Options for configuring a rate-limited function
24
4
  */
25
- export interface RateLimiterOptions {
5
+ export interface RateLimiterOptions<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
26
6
  /**
27
7
  * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.
28
8
  * Defaults to true.
@@ -33,13 +13,17 @@ export interface RateLimiterOptions {
33
13
  */
34
14
  limit: number;
35
15
  /**
36
- * Time window in milliseconds within which the limit applies
16
+ * Callback function that is called after the function is executed
37
17
  */
38
- window: number;
18
+ onExecute?: (rateLimiter: RateLimiter<TFn, TArgs>) => void;
39
19
  /**
40
20
  * Optional callback function that is called when an execution is rejected due to rate limiting
41
21
  */
42
- onReject?: (info: RateLimitRejectionInfo) => void;
22
+ onReject?: (rateLimiter: RateLimiter<TFn, TArgs>) => void;
23
+ /**
24
+ * Time window in milliseconds within which the limit applies
25
+ */
26
+ window: number;
43
27
  }
44
28
  /**
45
29
  * A class that creates a rate-limited function.
@@ -66,30 +50,22 @@ export interface RateLimiterOptions {
66
50
  * rateLimiter.maybeExecute('123');
67
51
  * ```
68
52
  */
69
- export declare class RateLimiter<TFn extends (...args: Array<any>) => any, TArgs extends Parameters<TFn>> {
53
+ export declare class RateLimiter<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
70
54
  private fn;
71
- private executionCount;
72
- private rejectionCount;
73
- private executionTimes;
74
- private options;
75
- constructor(fn: TFn, initialOptions: RateLimiterOptions);
55
+ private _executionCount;
56
+ private _rejectionCount;
57
+ private _executionTimes;
58
+ private _options;
59
+ constructor(fn: TFn, initialOptions: RateLimiterOptions<TFn, TArgs>);
76
60
  /**
77
61
  * Updates the rate limiter options
78
62
  * Returns the new options state
79
63
  */
80
- setOptions(newOptions: Partial<RateLimiterOptions>): RateLimiterOptions;
81
- /**
82
- * Returns the number of times the function has been executed
83
- */
84
- getExecutionCount(): number;
64
+ setOptions(newOptions: Partial<RateLimiterOptions<TFn, TArgs>>): RateLimiterOptions<TFn, TArgs>;
85
65
  /**
86
- * Returns the number of times the function has been rejected
66
+ * Returns the current rate limiter options
87
67
  */
88
- getRejectionCount(): number;
89
- /**
90
- * Returns the number of remaining executions allowed in the current window
91
- */
92
- getRemainingInWindow(): number;
68
+ getOptions(): Required<RateLimiterOptions<TFn, TArgs>>;
93
69
  /**
94
70
  * Attempts to execute the rate-limited function if within the configured limits.
95
71
  * Will reject execution if the number of calls in the current window exceeds the limit.
@@ -109,6 +85,22 @@ export declare class RateLimiter<TFn extends (...args: Array<any>) => any, TArgs
109
85
  private executeFunction;
110
86
  private rejectFunction;
111
87
  private cleanupOldExecutions;
88
+ /**
89
+ * Returns the number of times the function has been executed
90
+ */
91
+ getExecutionCount(): number;
92
+ /**
93
+ * Returns the number of times the function has been rejected
94
+ */
95
+ getRejectionCount(): number;
96
+ /**
97
+ * Returns the number of remaining executions allowed in the current window
98
+ */
99
+ getRemainingInWindow(): number;
100
+ /**
101
+ * Returns the number of milliseconds until the next execution will be possible
102
+ */
103
+ getMsUntilNextWindow(): number;
112
104
  /**
113
105
  * Resets the rate limiter state
114
106
  */
@@ -131,8 +123,8 @@ export declare class RateLimiter<TFn extends (...args: Array<any>) => any, TArgs
131
123
  * const rateLimited = rateLimit(makeApiCall, {
132
124
  * limit: 5,
133
125
  * window: 60000,
134
- * onReject: ({ msUntilNextWindow }) => {
135
- * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);
126
+ * onReject: (rateLimiter) => {
127
+ * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
136
128
  * }
137
129
  * });
138
130
  *
@@ -144,4 +136,4 @@ export declare class RateLimiter<TFn extends (...args: Array<any>) => any, TArgs
144
136
  * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds
145
137
  * ```
146
138
  */
147
- export declare function rateLimit<TFn extends (...args: Array<any>) => any>(fn: TFn, initialOptions: Omit<RateLimiterOptions, 'enabled'>): (...args: Parameters<TFn>) => boolean;
139
+ export declare function rateLimit<TFn extends AnyFunction>(fn: TFn, initialOptions: Omit<RateLimiterOptions<TFn, Parameters<TFn>>, 'enabled'>): (...args: Parameters<TFn>) => boolean;
@@ -1,15 +1,19 @@
1
1
  const defaultOptions = {
2
2
  enabled: true,
3
3
  limit: 1,
4
+ onExecute: () => {
5
+ },
6
+ onReject: () => {
7
+ },
4
8
  window: 0
5
9
  };
6
10
  class RateLimiter {
7
11
  constructor(fn, initialOptions) {
8
12
  this.fn = fn;
9
- this.executionCount = 0;
10
- this.rejectionCount = 0;
11
- this.executionTimes = [];
12
- this.options = {
13
+ this._executionCount = 0;
14
+ this._rejectionCount = 0;
15
+ this._executionTimes = [];
16
+ this._options = {
13
17
  ...defaultOptions,
14
18
  ...initialOptions
15
19
  };
@@ -19,30 +23,17 @@ class RateLimiter {
19
23
  * Returns the new options state
20
24
  */
21
25
  setOptions(newOptions) {
22
- this.options = {
23
- ...this.options,
26
+ this._options = {
27
+ ...this._options,
24
28
  ...newOptions
25
29
  };
26
- return this.options;
30
+ return this._options;
27
31
  }
28
32
  /**
29
- * Returns the number of times the function has been executed
30
- */
31
- getExecutionCount() {
32
- return this.executionCount;
33
- }
34
- /**
35
- * Returns the number of times the function has been rejected
36
- */
37
- getRejectionCount() {
38
- return this.rejectionCount;
39
- }
40
- /**
41
- * Returns the number of remaining executions allowed in the current window
33
+ * Returns the current rate limiter options
42
34
  */
43
- getRemainingInWindow() {
44
- this.cleanupOldExecutions();
45
- return Math.max(0, this.options.limit - this.executionTimes.length);
35
+ getOptions() {
36
+ return this._options;
46
37
  }
47
38
  /**
48
39
  * Attempts to execute the rate-limited function if within the configured limits.
@@ -61,7 +52,7 @@ class RateLimiter {
61
52
  */
62
53
  maybeExecute(...args) {
63
54
  this.cleanupOldExecutions();
64
- if (this.executionTimes.length < this.options.limit) {
55
+ if (this._executionTimes.length < this._options.limit) {
65
56
  this.executeFunction(...args);
66
57
  return true;
67
58
  }
@@ -69,39 +60,60 @@ class RateLimiter {
69
60
  return false;
70
61
  }
71
62
  executeFunction(...args) {
72
- if (!this.options.enabled) return;
63
+ var _a, _b;
64
+ if (!this._options.enabled) return;
73
65
  const now = Date.now();
74
- this.executionCount++;
75
- this.executionTimes.push(now);
66
+ this._executionCount++;
67
+ this._executionTimes.push(now);
76
68
  this.fn(...args);
69
+ (_b = (_a = this._options).onExecute) == null ? void 0 : _b.call(_a, this);
77
70
  }
78
71
  rejectFunction() {
79
- this.rejectionCount++;
80
- if (this.options.onReject) {
81
- const oldestExecution = Math.min(...this.executionTimes);
82
- const msUntilNextWindow = oldestExecution + this.options.window - Date.now();
83
- this.options.onReject({
84
- msUntilNextWindow,
85
- currentExecutions: this.executionTimes.length,
86
- limit: this.options.limit,
87
- rejectionCount: this.rejectionCount
88
- });
72
+ this._rejectionCount++;
73
+ if (this._options.onReject) {
74
+ this._options.onReject(this);
89
75
  }
90
76
  }
91
77
  cleanupOldExecutions() {
92
78
  const now = Date.now();
93
- const windowStart = now - this.options.window;
94
- this.executionTimes = this.executionTimes.filter(
79
+ const windowStart = now - this._options.window;
80
+ this._executionTimes = this._executionTimes.filter(
95
81
  (time) => time > windowStart
96
82
  );
97
83
  }
84
+ /**
85
+ * Returns the number of times the function has been executed
86
+ */
87
+ getExecutionCount() {
88
+ return this._executionCount;
89
+ }
90
+ /**
91
+ * Returns the number of times the function has been rejected
92
+ */
93
+ getRejectionCount() {
94
+ return this._rejectionCount;
95
+ }
96
+ /**
97
+ * Returns the number of remaining executions allowed in the current window
98
+ */
99
+ getRemainingInWindow() {
100
+ this.cleanupOldExecutions();
101
+ return Math.max(0, this._options.limit - this._executionTimes.length);
102
+ }
103
+ /**
104
+ * Returns the number of milliseconds until the next execution will be possible
105
+ */
106
+ getMsUntilNextWindow() {
107
+ const oldestExecution = Math.min(...this._executionTimes);
108
+ return oldestExecution + this._options.window - Date.now();
109
+ }
98
110
  /**
99
111
  * Resets the rate limiter state
100
112
  */
101
113
  reset() {
102
- this.executionTimes = [];
103
- this.executionCount = 0;
104
- this.rejectionCount = 0;
114
+ this._executionTimes = [];
115
+ this._executionCount = 0;
116
+ this._rejectionCount = 0;
105
117
  }
106
118
  }
107
119
  function rateLimit(fn, initialOptions) {
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limiter.js","sources":["../../src/rate-limiter.ts"],"sourcesContent":["/**\n * Information about a rate limit rejection\n */\nexport interface RateLimitRejectionInfo {\n /**\n * Number of milliseconds until the next execution will be possible\n */\n msUntilNextWindow: number\n /**\n * Current number of executions in the window\n */\n currentExecutions: number\n /**\n * Maximum allowed executions per window\n */\n limit: number\n /**\n * Total number of rejections that have occurred\n */\n rejectionCount: number\n}\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (info: RateLimitRejectionInfo) => void\n}\n\nconst defaultOptions: Required<Omit<RateLimiterOptions, 'onReject'>> = {\n enabled: true,\n limit: 1,\n window: 0,\n}\n\n/**\n * A class that creates a rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<\n TFn extends (...args: Array<any>) => any,\n TArgs extends Parameters<TFn>,\n> {\n private executionCount = 0\n private rejectionCount = 0\n private executionTimes: Array<number> = []\n private options: RateLimiterOptions\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions,\n ) {\n this.options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(newOptions: Partial<RateLimiterOptions>): RateLimiterOptions {\n this.options = {\n ...this.options,\n ...newOptions,\n }\n return this.options\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this.executionCount\n }\n\n /**\n * Returns the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this.rejectionCount\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this.options.limit - this.executionTimes.length)\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute(...args: TArgs): boolean {\n this.cleanupOldExecutions()\n\n if (this.executionTimes.length < this.options.limit) {\n this.executeFunction(...args)\n return true\n }\n\n this.rejectFunction()\n\n return false\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this.options.enabled) return\n const now = Date.now()\n this.executionCount++\n this.executionTimes.push(now)\n this.fn(...args)\n }\n\n private rejectFunction(): void {\n this.rejectionCount++\n if (this.options.onReject) {\n const oldestExecution = Math.min(...this.executionTimes)\n const msUntilNextWindow =\n oldestExecution + this.options.window - Date.now()\n\n this.options.onReject({\n msUntilNextWindow,\n currentExecutions: this.executionTimes.length,\n limit: this.options.limit,\n rejectionCount: this.rejectionCount,\n })\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this.options.window\n this.executionTimes = this.executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this.executionTimes = []\n this.executionCount = 0\n this.rejectionCount = 0\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * onReject: ({ msUntilNextWindow }) => {\n * console.log(`Rate limit exceeded. Try again in ${msUntilNextWindow}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function rateLimit<TFn extends (...args: Array<any>) => any>(\n fn: TFn,\n initialOptions: Omit<RateLimiterOptions, 'enabled'>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":"AA6CA,MAAM,iBAAiE;AAAA,EACrE,SAAS;AAAA,EACT,OAAO;AAAA,EACP,QAAQ;AACV;AA2BO,MAAM,YAGX;AAAA,EAMA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,iBAAiB;AACzB,SAAQ,iBAAiB;AACzB,SAAQ,iBAAgC,CAAC;AAOvC,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WAAW,YAA6D;AACtE,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,IACL;AACA,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,oBAA4B;AAC1B,WAAO,KAAK;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMd,uBAA+B;AAC7B,SAAK,qBAAqB;AACnB,WAAA,KAAK,IAAI,GAAG,KAAK,QAAQ,QAAQ,KAAK,eAAe,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBpE,gBAAgB,MAAsB;AACpC,SAAK,qBAAqB;AAE1B,QAAI,KAAK,eAAe,SAAS,KAAK,QAAQ,OAAO;AAC9C,WAAA,gBAAgB,GAAG,IAAI;AACrB,aAAA;AAAA,IAAA;AAGT,SAAK,eAAe;AAEb,WAAA;AAAA,EAAA;AAAA,EAGD,mBAAmB,MAAmB;AACxC,QAAA,CAAC,KAAK,QAAQ,QAAS;AACrB,UAAA,MAAM,KAAK,IAAI;AAChB,SAAA;AACA,SAAA,eAAe,KAAK,GAAG;AACvB,SAAA,GAAG,GAAG,IAAI;AAAA,EAAA;AAAA,EAGT,iBAAuB;AACxB,SAAA;AACD,QAAA,KAAK,QAAQ,UAAU;AACzB,YAAM,kBAAkB,KAAK,IAAI,GAAG,KAAK,cAAc;AACvD,YAAM,oBACJ,kBAAkB,KAAK,QAAQ,SAAS,KAAK,IAAI;AAEnD,WAAK,QAAQ,SAAS;AAAA,QACpB;AAAA,QACA,mBAAmB,KAAK,eAAe;AAAA,QACvC,OAAO,KAAK,QAAQ;AAAA,QACpB,gBAAgB,KAAK;AAAA,MAAA,CACtB;AAAA,IAAA;AAAA,EACH;AAAA,EAGM,uBAA6B;AAC7B,UAAA,MAAM,KAAK,IAAI;AACf,UAAA,cAAc,MAAM,KAAK,QAAQ;AAClC,SAAA,iBAAiB,KAAK,eAAe;AAAA,MACxC,CAAC,SAAS,OAAO;AAAA,IACnB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAMF,QAAc;AACZ,SAAK,iBAAiB,CAAC;AACvB,SAAK,iBAAiB;AACtB,SAAK,iBAAiB;AAAA,EAAA;AAE1B;AAgCgB,SAAA,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AAC/C,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;"}
1
+ {"version":3,"file":"rate-limiter.js","sources":["../../src/rate-limiter.ts"],"sourcesContent":["import type { AnyFunction } from './types'\n\n/**\n * Options for configuring a rate-limited function\n */\nexport interface RateLimiterOptions<\n TFn extends AnyFunction,\n TArgs extends Parameters<TFn>,\n> {\n /**\n * Whether the rate limiter is enabled. When disabled, maybeExecute will not trigger any executions.\n * Defaults to true.\n */\n enabled?: boolean\n /**\n * Maximum number of executions allowed within the time window\n */\n limit: number\n /**\n * Callback function that is called after the function is executed\n */\n onExecute?: (rateLimiter: RateLimiter<TFn, TArgs>) => void\n /**\n * Optional callback function that is called when an execution is rejected due to rate limiting\n */\n onReject?: (rateLimiter: RateLimiter<TFn, TArgs>) => void\n /**\n * Time window in milliseconds within which the limit applies\n */\n window: number\n}\n\nconst defaultOptions: Required<RateLimiterOptions<any, any>> = {\n enabled: true,\n limit: 1,\n onExecute: () => {},\n onReject: () => {},\n window: 0,\n}\n\n/**\n * A class that creates a rate-limited function.\n *\n * Rate limiting is a simple approach that allows a function to execute up to a limit within a time window,\n * then blocks all subsequent calls until the window passes. This can lead to \"bursty\" behavior where\n * all executions happen immediately, followed by a complete block.\n *\n * For smoother execution patterns, consider using:\n * - Throttling: Ensures consistent spacing between executions (e.g. max once per 200ms)\n * - Debouncing: Waits for a pause in calls before executing (e.g. after 500ms of no calls)\n *\n * Rate limiting is best used for hard API limits or resource constraints. For UI updates or\n * smoothing out frequent events, throttling or debouncing usually provide better user experience.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(\n * (id: string) => api.getData(id),\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Will execute immediately until limit reached, then block\n * rateLimiter.maybeExecute('123');\n * ```\n */\nexport class RateLimiter<\n TFn extends AnyFunction,\n TArgs extends Parameters<TFn>,\n> {\n private _executionCount = 0\n private _rejectionCount = 0\n private _executionTimes: Array<number> = []\n private _options: RateLimiterOptions<TFn, TArgs>\n\n constructor(\n private fn: TFn,\n initialOptions: RateLimiterOptions<TFn, TArgs>,\n ) {\n this._options = {\n ...defaultOptions,\n ...initialOptions,\n }\n }\n\n /**\n * Updates the rate limiter options\n * Returns the new options state\n */\n setOptions(\n newOptions: Partial<RateLimiterOptions<TFn, TArgs>>,\n ): RateLimiterOptions<TFn, TArgs> {\n this._options = {\n ...this._options,\n ...newOptions,\n }\n return this._options\n }\n\n /**\n * Returns the current rate limiter options\n */\n getOptions(): Required<RateLimiterOptions<TFn, TArgs>> {\n return this._options as Required<RateLimiterOptions<TFn, TArgs>>\n }\n\n /**\n * Attempts to execute the rate-limited function if within the configured limits.\n * Will reject execution if the number of calls in the current window exceeds the limit.\n *\n * @example\n * ```ts\n * const rateLimiter = new RateLimiter(fn, { limit: 5, window: 1000 });\n *\n * // First 5 calls will return true\n * rateLimiter.maybeExecute('arg1', 'arg2'); // true\n *\n * // Additional calls within the window will return false\n * rateLimiter.maybeExecute('arg1', 'arg2'); // false\n * ```\n */\n maybeExecute(...args: TArgs): boolean {\n this.cleanupOldExecutions()\n\n if (this._executionTimes.length < this._options.limit) {\n this.executeFunction(...args)\n return true\n }\n\n this.rejectFunction()\n\n return false\n }\n\n private executeFunction(...args: TArgs): void {\n if (!this._options.enabled) return\n const now = Date.now()\n this._executionCount++\n this._executionTimes.push(now)\n this.fn(...args) // execute the function\n this._options.onExecute?.(this)\n }\n\n private rejectFunction(): void {\n this._rejectionCount++\n if (this._options.onReject) {\n this._options.onReject(this)\n }\n }\n\n private cleanupOldExecutions(): void {\n const now = Date.now()\n const windowStart = now - this._options.window\n this._executionTimes = this._executionTimes.filter(\n (time) => time > windowStart,\n )\n }\n\n /**\n * Returns the number of times the function has been executed\n */\n getExecutionCount(): number {\n return this._executionCount\n }\n\n /**\n * Returns the number of times the function has been rejected\n */\n getRejectionCount(): number {\n return this._rejectionCount\n }\n\n /**\n * Returns the number of remaining executions allowed in the current window\n */\n getRemainingInWindow(): number {\n this.cleanupOldExecutions()\n return Math.max(0, this._options.limit - this._executionTimes.length)\n }\n\n /**\n * Returns the number of milliseconds until the next execution will be possible\n */\n getMsUntilNextWindow(): number {\n const oldestExecution = Math.min(...this._executionTimes)\n return oldestExecution + this._options.window - Date.now()\n }\n\n /**\n * Resets the rate limiter state\n */\n reset(): void {\n this._executionTimes = []\n this._executionCount = 0\n this._rejectionCount = 0\n }\n}\n\n/**\n * Creates a rate-limited function that will execute the provided function up to a maximum number of times within a time window.\n *\n * Note that rate limiting is a simpler form of execution control compared to throttling or debouncing:\n * - A rate limiter will allow all executions until the limit is reached, then block all subsequent calls until the window resets\n * - A throttler ensures even spacing between executions, which can be better for consistent performance\n * - A debouncer collapses multiple calls into one, which is better for handling bursts of events\n *\n * Consider using throttle() or debounce() if you need more intelligent execution control. Use rate limiting when you specifically\n * need to enforce a hard limit on the number of executions within a time period.\n *\n * @example\n * ```ts\n * // Rate limit to 5 calls per minute\n * const rateLimited = rateLimit(makeApiCall, {\n * limit: 5,\n * window: 60000,\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * }\n * });\n *\n * // First 5 calls will execute immediately\n * // Additional calls will be rejected until the minute window resets\n * rateLimited();\n *\n * // For more even execution, consider using throttle instead:\n * const throttled = throttle(makeApiCall, { wait: 12000 }); // One call every 12 seconds\n * ```\n */\nexport function rateLimit<TFn extends AnyFunction>(\n fn: TFn,\n initialOptions: Omit<RateLimiterOptions<TFn, Parameters<TFn>>, 'enabled'>,\n) {\n const rateLimiter = new RateLimiter(fn, initialOptions)\n return rateLimiter.maybeExecute.bind(rateLimiter)\n}\n"],"names":[],"mappings":"AAgCA,MAAM,iBAAyD;AAAA,EAC7D,SAAS;AAAA,EACT,OAAO;AAAA,EACP,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,UAAU,MAAM;AAAA,EAAC;AAAA,EACjB,QAAQ;AACV;AA2BO,MAAM,YAGX;AAAA,EAMA,YACU,IACR,gBACA;AAFQ,SAAA,KAAA;AANV,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAkB;AAC1B,SAAQ,kBAAiC,CAAC;AAOxC,SAAK,WAAW;AAAA,MACd,GAAG;AAAA,MACH,GAAG;AAAA,IACL;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOF,WACE,YACgC;AAChC,SAAK,WAAW;AAAA,MACd,GAAG,KAAK;AAA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EAMtE,uBAA+B;AAC7B,UAAM,kBAAkB,KAAK,IAAI,GAAG,KAAK,eAAe;AACxD,WAAO,kBAAkB,KAAK,SAAS,SAAS,KAAK,IAAI;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,EAM3D,QAAc;AACZ,SAAK,kBAAkB,CAAC;AACxB,SAAK,kBAAkB;AACvB,SAAK,kBAAkB;AAAA,EAAA;AAE3B;AAgCgB,SAAA,UACd,IACA,gBACA;AACA,QAAM,cAAc,IAAI,YAAY,IAAI,cAAc;AAC/C,SAAA,YAAY,aAAa,KAAK,WAAW;AAClD;"}
@@ -1,7 +1,8 @@
1
+ import { AnyFunction } from './types.js';
1
2
  /**
2
3
  * Options for configuring a throttled function
3
4
  */
4
- export interface ThrottlerOptions {
5
+ export interface ThrottlerOptions<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
5
6
  /**
6
7
  * Whether the throttler is enabled. When disabled, maybeExecute will not trigger any executions.
7
8
  * Defaults to true.
@@ -12,6 +13,10 @@ export interface ThrottlerOptions {
12
13
  * Defaults to true.
13
14
  */
14
15
  leading?: boolean;
16
+ /**
17
+ * Callback function that is called after the function is executed
18
+ */
19
+ onExecute?: (throttler: Throttler<TFn, TArgs>) => void;
15
20
  /**
16
21
  * Whether to execute on the trailing edge of the timeout.
17
22
  * Defaults to true.
@@ -33,8 +38,7 @@ export interface ThrottlerOptions {
33
38
  * - Leading: Execute immediately on first call (default: true)
34
39
  * - Trailing: Execute after wait period if called during throttle (default: true)
35
40
  *
36
- * For rate limiting or hard API limits, consider using RateLimiter instead.
37
- * For collapsing rapid-fire events, consider using Debouncer.
41
+ * For collapsing rapid-fire events where you only care about the last call, consider using Debouncer.
38
42
  *
39
43
  * @example
40
44
  * ```ts
@@ -50,31 +54,24 @@ export interface ThrottlerOptions {
50
54
  * throttler.maybeExecute('123'); // Throttled
51
55
  * ```
52
56
  */
53
- export declare class Throttler<TFn extends (...args: Array<any>) => any, TArgs extends Parameters<TFn>> {
57
+ export declare class Throttler<TFn extends AnyFunction, TArgs extends Parameters<TFn>> {
54
58
  private fn;
55
- private executionCount;
56
- private lastArgs;
57
- private lastExecutionTime;
58
- private options;
59
- private timeoutId;
60
- constructor(fn: TFn, initialOptions: ThrottlerOptions);
59
+ private _executionCount;
60
+ private _lastArgs;
61
+ private _lastExecutionTime;
62
+ private _options;
63
+ private _timeoutId;
64
+ private _isPending;
65
+ constructor(fn: TFn, initialOptions: ThrottlerOptions<TFn, TArgs>);
61
66
  /**
62
67
  * Updates the throttler options
63
68
  * Returns the new options state
64
69
  */
65
- setOptions(newOptions: Partial<ThrottlerOptions>): Required<ThrottlerOptions>;
70
+ setOptions(newOptions: Partial<ThrottlerOptions<TFn, TArgs>>): Required<ThrottlerOptions<TFn, TArgs>>;
66
71
  /**
67
- * Returns the number of times the function has been executed
72
+ * Returns the current throttler options
68
73
  */
69
- getExecutionCount(): number;
70
- /**
71
- * Returns the last execution time
72
- */
73
- getLastExecutionTime(): number;
74
- /**
75
- * Returns the next execution time
76
- */
77
- getNextExecutionTime(): number;
74
+ getOptions(): Required<ThrottlerOptions<TFn, TArgs>>;
78
75
  /**
79
76
  * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
80
77
  *
@@ -109,6 +106,22 @@ export declare class Throttler<TFn extends (...args: Array<any>) => any, TArgs e
109
106
  * Has no effect if there is no pending execution.
110
107
  */
111
108
  cancel(): void;
109
+ /**
110
+ * Returns the number of times the function has been executed
111
+ */
112
+ getExecutionCount(): number;
113
+ /**
114
+ * Returns `true` if there is a pending execution
115
+ */
116
+ getIsPending(): boolean;
117
+ /**
118
+ * Returns the last execution time
119
+ */
120
+ getLastExecutionTime(): number;
121
+ /**
122
+ * Returns the next execution time
123
+ */
124
+ getNextExecutionTime(): number;
112
125
  }
113
126
  /**
114
127
  * Creates a throttled function that limits how often the provided function can execute.
@@ -136,4 +149,4 @@ export declare class Throttler<TFn extends (...args: Array<any>) => any, TArgs e
136
149
  * });
137
150
  * ```
138
151
  */
139
- export declare function throttle<TFn extends (...args: Array<any>) => any>(fn: TFn, initialOptions: Omit<ThrottlerOptions, 'enabled'>): (...args: Parameters<TFn>) => void;
152
+ export declare function throttle<TFn extends AnyFunction, TArgs extends Parameters<TFn>>(fn: TFn, initialOptions: Omit<ThrottlerOptions<TFn, TArgs>, 'enabled'>): (...args: TArgs) => void;
@@ -2,14 +2,17 @@ const defaultOptions = {
2
2
  enabled: true,
3
3
  leading: true,
4
4
  trailing: true,
5
- wait: 0
5
+ wait: 0,
6
+ onExecute: () => {
7
+ }
6
8
  };
7
9
  class Throttler {
8
10
  constructor(fn, initialOptions) {
9
11
  this.fn = fn;
10
- this.executionCount = 0;
11
- this.lastExecutionTime = 0;
12
- this.options = {
12
+ this._executionCount = 0;
13
+ this._lastExecutionTime = 0;
14
+ this._isPending = false;
15
+ this._options = {
13
16
  ...defaultOptions,
14
17
  ...initialOptions
15
18
  };
@@ -19,29 +22,17 @@ class Throttler {
19
22
  * Returns the new options state
20
23
  */
21
24
  setOptions(newOptions) {
22
- this.options = {
23
- ...this.options,
25
+ this._options = {
26
+ ...this._options,
24
27
  ...newOptions
25
28
  };
26
- return this.options;
27
- }
28
- /**
29
- * Returns the number of times the function has been executed
30
- */
31
- getExecutionCount() {
32
- return this.executionCount;
33
- }
34
- /**
35
- * Returns the last execution time
36
- */
37
- getLastExecutionTime() {
38
- return this.lastExecutionTime;
29
+ return this._options;
39
30
  }
40
31
  /**
41
- * Returns the next execution time
32
+ * Returns the current throttler options
42
33
  */
43
- getNextExecutionTime() {
44
- return this.lastExecutionTime + this.options.wait;
34
+ getOptions() {
35
+ return this._options;
45
36
  }
46
37
  /**
47
38
  * Attempts to execute the throttled function. The execution behavior depends on the throttler options:
@@ -67,30 +58,34 @@ class Throttler {
67
58
  */
68
59
  maybeExecute(...args) {
69
60
  const now = Date.now();
70
- const timeSinceLastExecution = now - this.lastExecutionTime;
71
- if (timeSinceLastExecution >= this.options.wait) {
72
- if (this.options.leading) {
61
+ const timeSinceLastExecution = now - this._lastExecutionTime;
62
+ if (timeSinceLastExecution >= this._options.wait) {
63
+ if (this._options.leading) {
73
64
  this.executeFunction(...args);
74
65
  }
75
- this.lastExecutionTime = now;
66
+ this._lastExecutionTime = now;
67
+ this._isPending = false;
76
68
  } else {
77
- this.lastArgs = args;
78
- if (!this.timeoutId && this.options.trailing) {
79
- this.timeoutId = setTimeout(() => {
80
- if (this.lastArgs) {
81
- this.executeFunction(...this.lastArgs);
82
- this.lastArgs = void 0;
69
+ this._lastArgs = args;
70
+ if (!this._timeoutId && this._options.trailing) {
71
+ this._isPending = true;
72
+ this._timeoutId = setTimeout(() => {
73
+ if (this._lastArgs) {
74
+ this.executeFunction(...this._lastArgs);
75
+ this._lastArgs = void 0;
83
76
  }
84
- this.lastExecutionTime = Date.now();
85
- this.timeoutId = void 0;
86
- }, this.options.wait - timeSinceLastExecution);
77
+ this._lastExecutionTime = Date.now();
78
+ this._timeoutId = void 0;
79
+ this._isPending = false;
80
+ this._options.onExecute(this);
81
+ }, this._options.wait - timeSinceLastExecution);
87
82
  }
88
83
  }
89
84
  }
90
85
  executeFunction(...args) {
91
- if (!this.options.enabled) return;
92
- this.executionCount++;
86
+ if (!this._options.enabled) return;
93
87
  this.fn(...args);
88
+ this._executionCount++;
94
89
  }
95
90
  /**
96
91
  * Cancels any pending trailing execution and clears internal state.
@@ -102,12 +97,37 @@ class Throttler {
102
97
  * Has no effect if there is no pending execution.
103
98
  */
104
99
  cancel() {
105
- if (this.timeoutId) {
106
- clearTimeout(this.timeoutId);
107
- this.timeoutId = void 0;
108
- this.lastArgs = void 0;
100
+ if (this._timeoutId) {
101
+ clearTimeout(this._timeoutId);
102
+ this._timeoutId = void 0;
103
+ this._lastArgs = void 0;
104
+ this._isPending = false;
109
105
  }
110
106
  }
107
+ /**
108
+ * Returns the number of times the function has been executed
109
+ */
110
+ getExecutionCount() {
111
+ return this._executionCount;
112
+ }
113
+ /**
114
+ * Returns `true` if there is a pending execution
115
+ */
116
+ getIsPending() {
117
+ return this._options.enabled && this._isPending;
118
+ }
119
+ /**
120
+ * Returns the last execution time
121
+ */
122
+ getLastExecutionTime() {
123
+ return this._lastExecutionTime;
124
+ }
125
+ /**
126
+ * Returns the next execution time
127
+ */
128
+ getNextExecutionTime() {
129
+ return this._lastExecutionTime + this._options.wait;
130
+ }
111
131
  }
112
132
  function throttle(fn, initialOptions) {
113
133
  const throttler = new Throttler(fn, initialOptions);