@cldmv/holdmytask 2.0.6 → 2.1.1

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.
@@ -0,0 +1,802 @@
1
+ /**
2
+ * A sophisticated task queue that manages task execution with priorities, delays, and concurrency control.
3
+ * Tasks can be scheduled with timestamps, priorities, and completion delays between tasks of the same priority.
4
+ * Supports both callback and promise-based APIs with comprehensive lifecycle management.
5
+ * @extends EventEmitter
6
+ */
7
+ export class HoldMyTask {
8
+ /**
9
+ * Creates a new HoldMyTask queue instance.
10
+ * @param {Object} [options={}] - Configuration options for the task queue
11
+ * @param {number} [options.concurrency=1] - Maximum number of tasks to run concurrently
12
+ * @param {number} [options.tick=25] - Scheduler tick interval in milliseconds
13
+ * @param {boolean} [options.autoStart=true] - Whether to automatically start the scheduler
14
+ * @param {number} [options.defaultPriority=0] - Default priority for tasks (higher numbers = higher priority)
15
+ * @param {number} [options.maxQueue=Infinity] - Maximum number of tasks that can be queued
16
+ * @param {Object} [options.delays={}] - DEPRECATED: Use priorities[priority].delay instead. Legacy priority-to-delay mapping (auto-converted to priorities)
17
+ * @param {boolean} [options.smartScheduling=true] - Use dynamic timeouts instead of constant polling for better performance
18
+ * @param {number} [options.tick=25] - Polling interval in milliseconds when smartScheduling is disabled
19
+ * @param {number} [options.healingInterval=5000] - Self-healing check interval in milliseconds (smart scheduling only)
20
+ * @param {Object} [options.priorities={}] - Priority-specific default configurations, keyed by integer priority. A non-integer key emits an "invalid-priority" warning event
21
+ * @param {number} [options.priorities[priority].concurrency] - Maximum concurrent tasks for this priority (defaults to global concurrency limit)
22
+ * @param {number} [options.priorities[priority].postDelay] - Delay after task completion before next task of same priority
23
+ * @param {number} [options.priorities[priority].startDelay] - Delay before task execution (pre-execution delay)
24
+ * @param {Object} [options.coalescing] - Enhanced coalescing configuration (preferred over flat options)
25
+ * @param {Object} [options.coalescing.defaults] - Default coalescing settings for all keys
26
+ * @param {number} [options.coalescing.defaults.windowDuration=200] - Default window duration in milliseconds
27
+ * @param {number} [options.coalescing.defaults.maxDelay=1000] - Default maximum delay in milliseconds
28
+ * @param {number} [options.coalescing.defaults.postDelay] - Default post-completion delay in milliseconds
29
+ * @param {number} [options.coalescing.defaults.startDelay] - Default pre-execution delay in milliseconds
30
+ * @param {number} [options.coalescing.defaults.delay] - DEPRECATED: Use postDelay instead
31
+ * @param {number} [options.coalescing.defaults.start] - DEPRECATED: Use startDelay instead
32
+ * @param {boolean} [options.coalescing.defaults.resolveAllPromises=true] - Default promise resolution behavior
33
+ * @param {boolean} [options.coalescing.defaults.multipleCallbacks=false] - Default callback execution behavior
34
+ * @param {Object} [options.coalescing.keys] - Per-coalescingKey configuration overrides (windowDuration, maxDelay, postDelay, startDelay, etc.)
35
+ * @param {number} [options.coalescingWindowDuration=200] - DEPRECATED: Use coalescing.defaults.windowDuration instead
36
+ * @param {number} [options.coalescingMaxDelay=1000] - DEPRECATED: Use coalescing.defaults.maxDelay instead
37
+ * @param {boolean} [options.coalescingMultipleCallbacks=false] - DEPRECATED: Use coalescing.defaults.multipleCallbacks instead
38
+ * @param {boolean} [options.coalescingResolveAllPromises=true] - DEPRECATED: Use coalescing.defaults.resolveAllPromises instead
39
+ * @example
40
+ * // Enhanced configuration with priority defaults and extended coalescing
41
+ * const queue = new HoldMyTask({
42
+ * concurrency: 8, // Global maximum: 8 total tasks across all priorities
43
+ * delays: { 0: 1000, 1: 500 },
44
+ * priorities: {
45
+ * 1: { concurrency: 1, postDelay: 100, startDelay: 0 }, // Critical: Only 1 at a time, 100ms post-delay
46
+ * 2: { concurrency: 3, postDelay: 200, startDelay: 50 }, // Important: Up to 3 at a time, 200ms post-delay
47
+ * 3: { concurrency: 5, postDelay: 0, startDelay: 100 } // Background: Up to 5 at a time, 100ms pre-delay
48
+ * },
49
+ * coalescing: {
50
+ * defaults: {
51
+ * windowDuration: 200,
52
+ * maxDelay: 1000,
53
+ * postDelay: 50,
54
+ * startDelay: 25,
55
+ * resolveAllPromises: true
56
+ * },
57
+ * keys: {
58
+ * 'ui.update': { windowDuration: 100, maxDelay: 500, postDelay: 25, startDelay: 0 },
59
+ * 'api.batch': { windowDuration: 1000, maxDelay: 5000, postDelay: 100, startDelay: 200 },
60
+ * 'device.control': { windowDuration: 50, maxDelay: 200, delay: 10, start: 5 }
61
+ * }
62
+ * }
63
+ * });
64
+ *
65
+ * @example
66
+ * // Backward compatible (deprecated but still supported)
67
+ * const legacyQueue = new HoldMyTask({
68
+ * coalescingWindowDuration: 1500,
69
+ * coalescingMaxDelay: 3000,
70
+ * coalescingResolveAllPromises: true
71
+ * });
72
+ */
73
+ /**
74
+ * Transforms delay properties for backwards compatibility.
75
+ * Converts 'start' -> 'startDelay' and 'delay' -> 'postDelay' while preserving new names.
76
+ * @param {Object} config - Configuration object that may contain old or new property names
77
+ * @param {HoldMyTask} [instance] - Optional instance to emit deprecation warnings on
78
+ * @returns {Object} Transformed configuration with new property names
79
+ * @private
80
+ * @internal
81
+ */
82
+ private static _transformDelayProperties;
83
+ /**
84
+ * Internal convenience method to create a new HoldMyTask instance with async initialization.
85
+ * This enables event listeners to be attached before validation errors can occur.
86
+ * @param {Object} [options={}] - Configuration options
87
+ * @returns {Promise<HoldMyTask>} Promise that resolves to the initialized instance
88
+ * @private
89
+ * @example
90
+ * // Internal usage - prefer new HoldMyTask({ sync: false }) for public API
91
+ * const queue = await HoldMyTask._create({ maxQueue: 100 });
92
+ */
93
+ private static _create;
94
+ constructor(options?: {});
95
+ /**
96
+ * Normalizes task-level delay option names passed to enqueue().
97
+ * `postDelay` / `startDelay` are the current names; `delay` / `start` are deprecated aliases.
98
+ * When both forms are given, the current name wins. Each deprecated alias emits one
99
+ * deprecation `warning` event per queue instance (not one per task), so a hot enqueue
100
+ * path doesn't flood listeners.
101
+ * @param {Object} options - Task options (never mutated)
102
+ * @returns {Object} A copy of the options using the current names
103
+ * @private
104
+ * @internal
105
+ */
106
+ private _normalizeTaskDelayOptions;
107
+ /**
108
+ * Emits a deprecation warning for a task-level option, once per option name per instance.
109
+ * @param {string} deprecated - Deprecated option name
110
+ * @param {string} replacement - Current option name
111
+ * @returns {void}
112
+ * @private
113
+ * @internal
114
+ */
115
+ private _warnTaskOptionDeprecated;
116
+ /**
117
+ * Resolves a `priorities` / `delays` object key to a numeric priority.
118
+ * Integer keys ("0", "10", "-1") resolve silently. Any other key emits a `warning` event of
119
+ * type "invalid-priority" so a typo can't silently disable a priority config: a key
120
+ * parseInt can't read (e.g. "high") is ignored, and a key it truncates (e.g. "2.5") keeps
121
+ * its historical meaning - the truncated priority - but is reported.
122
+ * @param {string} key - The object key as written in the config
123
+ * @param {string} option - The option the key came from ("priorities" or "delays")
124
+ * @returns {number|null} The numeric priority, or null when the key is ignored
125
+ * @private
126
+ * @internal
127
+ */
128
+ private _resolvePriorityKey;
129
+ /**
130
+ * Synchronous initialization for backwards compatibility
131
+ * @private
132
+ * @param {Object} options - Configuration options
133
+ */
134
+ private _initializeSync;
135
+ _syncMode: boolean | undefined;
136
+ /**
137
+ * Asynchronous initialization for modern usage
138
+ * @private
139
+ * @param {Object} options - Configuration options
140
+ * @returns {Promise<HoldMyTask>} Promise that resolves to this instance
141
+ */
142
+ private _initializeAsync;
143
+ /**
144
+ * Common initialization logic used by both sync and async modes
145
+ * @private
146
+ * @param {Object} options - Configuration options
147
+ */
148
+ private _initializeCommon;
149
+ options: {
150
+ constructor: Function;
151
+ toString(): string;
152
+ toLocaleString(): string;
153
+ valueOf(): Object;
154
+ hasOwnProperty(v: PropertyKey): boolean;
155
+ isPrototypeOf(v: Object): boolean;
156
+ propertyIsEnumerable(v: PropertyKey): boolean;
157
+ concurrency: number;
158
+ tick: number;
159
+ autoStart: boolean;
160
+ defaultPriority: number;
161
+ maxQueue: any;
162
+ priorities: {};
163
+ smartScheduling: boolean;
164
+ healingInterval: number;
165
+ coalescing: {
166
+ defaults: Object;
167
+ keys: {};
168
+ };
169
+ coalescingWindowDuration: any;
170
+ coalescingMaxDelay: any;
171
+ coalescingMultipleCallbacks: any;
172
+ coalescingResolveAllPromises: any;
173
+ } | undefined;
174
+ pendingHeap: MinHeap | undefined;
175
+ readyHeap: MinHeap | undefined;
176
+ running: Set<any> | undefined;
177
+ runningByPriority: Map<any, any> | undefined;
178
+ tasks: Map<any, any> | undefined;
179
+ nextId: number | undefined;
180
+ enqueueSeq: number | undefined;
181
+ isActive: boolean | undefined;
182
+ destroyed: boolean | undefined;
183
+ lastCompletedPriority: any;
184
+ nextAvailableTime: any;
185
+ schedulerTimeout: number | null | undefined;
186
+ healingInterval: number | null | undefined;
187
+ lastSchedulerRun: number | undefined;
188
+ intervalId: number | null | undefined;
189
+ coalescingGroups: Map<any, any> | undefined;
190
+ coalescingRepresentatives: Map<any, any> | undefined;
191
+ nextGroupId: number | undefined;
192
+ _warnedTaskOptions: Set<any> | undefined;
193
+ /**
194
+ * Adds a task to the queue for execution. Supports both callback and promise-based APIs.
195
+ * @param {Function} task - The task function to execute. Can be sync or async.
196
+ * @param {Function|Object} [optionsOrCallback] - Either a callback function or options object
197
+ * @param {Object} [options={}] - Additional options (if callback was provided as second parameter)
198
+ * @param {string|number} [options.id] - Custom task ID for identification and later reference (must be unique)
199
+ * @param {number} [options.priority] - Task priority (higher numbers run first)
200
+ * @param {number} [options.timestamp] - When the task should be ready to run (milliseconds since epoch)
201
+ * @param {number} [options.startDelay] - Milliseconds from now when the task should be ready to run (convenience for timestamp calculation). Overrides the priority's startDelay
202
+ * @param {number} [options.start] - DEPRECATED: Use startDelay instead
203
+ * @param {AbortSignal} [options.signal] - AbortSignal to cancel the task
204
+ * @param {number} [options.timeout] - Task timeout in milliseconds (for execution time limit)
205
+ * @param {number} [options.expire] - Task expiration timestamp or milliseconds from now (for queue waiting time limit)
206
+ * @param {number} [options.postDelay] - Delay after this task completes before the next task can start. Overrides the priority's postDelay; use -1 to bypass the current delay period
207
+ * @param {number} [options.delay] - DEPRECATED: Use postDelay instead
208
+ * @param {boolean} [options.bypassDelay] - If true, skip any active delay period and start immediately
209
+ * @param {string} [options.coalescingKey] - Key for task coalescing - tasks with same key will be coalesced within windows
210
+ * @param {number} [options.coalescingWindowDuration] - Override coalescing window duration (task-level override of key-level and defaults)
211
+ * @param {number} [options.coalescingMaxDelay] - Override coalescing max delay (task-level override of key-level and defaults)
212
+ * @param {boolean} [options.coalescingMultipleCallbacks] - Override callback behavior (task-level override of key-level and defaults)
213
+ * @param {boolean} [options.coalescingResolveAllPromises] - Override promise resolution behavior (task-level override of key-level and defaults)
214
+ * @param {*} [options.metadata] - Arbitrary metadata to attach to the task
215
+ * @returns {Promise|Object} Promise (if no callback) or task control object with id, cancel, status methods
216
+ * @throws {Error} If queue is destroyed or full
217
+ * @example
218
+ * // Promise API
219
+ * const result = await queue.enqueue(async () => fetchData());
220
+ *
221
+ * // Callback API
222
+ * queue.enqueue(() => processData(), (err, result) => {
223
+ * if (err) console.error(err);
224
+ * else console.log(result);
225
+ * });
226
+ *
227
+ * // With options
228
+ * const task = queue.enqueue(myTask, { priority: 5, timeout: 30000, expire: 10000 });
229
+ *
230
+ * // Bypass current delay for urgent task
231
+ * const urgent = queue.enqueue(urgentTask, { priority: 10, bypassDelay: true });
232
+ *
233
+ * // Alternative: use postDelay: -1 to bypass
234
+ * const urgent2 = queue.enqueue(urgentTask, { priority: 10, postDelay: -1 });
235
+ *
236
+ * // Coalescing tasks - multiple device status checks become one
237
+ * queue.enqueue(checkDeviceStatus, callback1, { coalescingKey: "device-123", coalescingWindowDuration: 1000 });
238
+ * queue.enqueue(checkDeviceStatus, callback2, { coalescingKey: "device-123" }); // Gets coalesced with first
239
+ */
240
+ enqueue(task: Function, optionsOrCallback?: Function | Object, options?: {
241
+ id?: string | number | undefined;
242
+ priority?: number | undefined;
243
+ timestamp?: number | undefined;
244
+ startDelay?: number | undefined;
245
+ start?: number | undefined;
246
+ signal?: AbortSignal | undefined;
247
+ timeout?: number | undefined;
248
+ expire?: number | undefined;
249
+ postDelay?: number | undefined;
250
+ delay?: number | undefined;
251
+ bypassDelay?: boolean | undefined;
252
+ coalescingKey?: string | undefined;
253
+ coalescingWindowDuration?: number | undefined;
254
+ coalescingMaxDelay?: number | undefined;
255
+ coalescingMultipleCallbacks?: boolean | undefined;
256
+ coalescingResolveAllPromises?: boolean | undefined;
257
+ metadata?: any;
258
+ }): Promise<any> | Object;
259
+ /**
260
+ * Handles tasks with coalescingKey through the coalescing system.
261
+ * @private
262
+ * @internal
263
+ * @param {string} id - Task ID
264
+ * @param {Function} task - Task function
265
+ * @param {Function|null} callback - Callback function (null for promise API)
266
+ * @param {Object} options - Task options
267
+ * @param {number} now - Current timestamp
268
+ * @returns {Promise|Object} Promise or task handle
269
+ */
270
+ private _handleCoalescingTask;
271
+ /**
272
+ * Finds a compatible coalescing group for a new task.
273
+ * @private
274
+ * @internal
275
+ * @param {string} coalescingKey - The coalescing key
276
+ * @param {number} now - Current timestamp
277
+ * @param {number} windowEnd - End of new task's coalescing window
278
+ * @param {number} mustRunBy - New task's mustRunBy deadline
279
+ * @returns {Object|null} Compatible coalescing group or null
280
+ */
281
+ private _findCompatibleCoalescingGroup;
282
+ /**
283
+ * Creates a new coalescing group with a representative task in the main queue.
284
+ * @private
285
+ * @internal
286
+ * @param {string} coalescingKey - The coalescing key
287
+ * @param {Object} taskItem - The first task item for this group
288
+ * @param {number} windowEnd - End of coalescing window
289
+ * @param {number} mustRunBy - Latest execution deadline
290
+ * @param {boolean} multipleCallbacks - Whether to call multiple callbacks
291
+ * @param {boolean} resolveAllPromises - Whether to resolve all promises with same result
292
+ * @returns {Object} The created coalescing group
293
+ */
294
+ private _createCoalescingGroup;
295
+ /**
296
+ * Adds a task to an existing coalescing group, updating the representative if needed.
297
+ * @private
298
+ * @internal
299
+ * @param {Object} group - The existing coalescing group
300
+ * @param {Object} taskItem - The new task item to add
301
+ * @param {number} windowEnd - End of coalescing window
302
+ * @param {number} mustRunBy - Latest execution deadline
303
+ * @param {number} now - Current timestamp
304
+ * @returns {void}
305
+ */
306
+ private _addToCoalescingGroup;
307
+ /**
308
+ * Creates the representative task function that manages coalesced task execution.
309
+ * @private
310
+ * @internal
311
+ * @param {string} coalescingKey - The coalescing key
312
+ * @param {string} groupId - The group ID
313
+ * @returns {Function} The representative task function
314
+ */
315
+ private _createCoalescingRepresentativeTask;
316
+ /**
317
+ * Resolves all callbacks/promises in a coalescing group.
318
+ * @private
319
+ * @internal
320
+ * @param {Object} group - The coalescing group
321
+ * @param {Error|null} error - Error if task failed
322
+ * @param {*} result - Result if task succeeded
323
+ * @returns {void}
324
+ */
325
+ private _resolveCoalescingGroup;
326
+ /**
327
+ * Cancels a specific task within a coalescing group.
328
+ * @private
329
+ * @internal
330
+ * @param {string} taskId - ID of task to cancel
331
+ * @param {string} coalescingKey - The coalescing key
332
+ * @param {string} reason - Cancellation reason
333
+ * @returns {void}
334
+ */
335
+ private _cancelCoalescingTask;
336
+ /**
337
+ * Cleans up a coalescing group after completion or cancellation.
338
+ * @private
339
+ * @internal
340
+ * @param {string} coalescingKey - The coalescing key
341
+ * @param {string} groupId - The group ID to clean up
342
+ * @returns {void}
343
+ */
344
+ private _cleanupCoalescingGroup;
345
+ /**
346
+ * Rebuilds the heap structures to reflect updated priorities/timing.
347
+ * @private
348
+ * @internal
349
+ * @returns {void}
350
+ */
351
+ private _rebuildHeaps;
352
+ /**
353
+ * Creates a task handle for both regular and coalescing tasks.
354
+ * @private
355
+ * @internal
356
+ * @param {Object} item - The task item
357
+ * @param {Function|null} callback - Callback function
358
+ * @returns {Promise|Object} Promise or task control object
359
+ */
360
+ private _createTaskHandle;
361
+ /**
362
+ * Cancels a pending task by ID.
363
+ * @param {string} id - The task ID to cancel
364
+ * @param {string} [reason="Task canceled"] - Reason for cancellation
365
+ * @returns {boolean} True if task was found and cancelled, false otherwise
366
+ * @example
367
+ * const task = queue.enqueue(() => longRunningTask());
368
+ * const cancelled = queue.cancel(task.id, "User requested cancellation");
369
+ */
370
+ cancel(id: string, reason?: string): boolean;
371
+ /**
372
+ * Alias for cancel() method for backward compatibility.
373
+ * @param {string|number} id - The task ID to cancel
374
+ * @param {string} [reason="Task canceled"] - Reason for cancellation
375
+ * @returns {boolean} True if task was found and cancelled, false otherwise
376
+ */
377
+ cancelTask(id: string | number, reason?: string): boolean;
378
+ /**
379
+ * Pauses the task queue, stopping execution of new tasks.
380
+ * Currently running tasks will continue to completion.
381
+ * @returns {void}
382
+ * @example
383
+ * queue.pause();
384
+ * // Queue stops processing new tasks
385
+ */
386
+ pause(): void;
387
+ /**
388
+ * Resumes the task queue after being paused.
389
+ * @returns {void}
390
+ * @example
391
+ * queue.resume();
392
+ * // Queue resumes processing tasks
393
+ */
394
+ resume(): void;
395
+ /**
396
+ * Clears all pending and ready tasks from the queue.
397
+ * Currently running tasks will continue to completion.
398
+ * @returns {void}
399
+ * @example
400
+ * queue.clear();
401
+ * // All queued tasks are removed
402
+ */
403
+ clear(): void;
404
+ /**
405
+ * Returns the number of tasks in the queue.
406
+ * @returns {number} Number of tasks in the queue
407
+ * @example
408
+ * const totalTasks = queue.size(); // 5
409
+ */
410
+ size(): number;
411
+ /**
412
+ * Returns the number of tasks in the queue (alias for size()).
413
+ * @returns {number} Number of tasks in the queue
414
+ * @example
415
+ * const totalTasks = queue.length(); // 5
416
+ */
417
+ length(): number;
418
+ /**
419
+ * Returns the number of currently running tasks.
420
+ * @returns {number} Number of running tasks
421
+ * @example
422
+ * const runningTasks = queue.inflight(); // 2
423
+ */
424
+ inflight(): number;
425
+ /**
426
+ * Gets information about a coalescing group by key and group ID.
427
+ * @param {string} coalescingKey - The coalescing key
428
+ * @param {string} [groupId] - Optional group ID. If omitted, returns all groups for the key
429
+ * @returns {Object|Array|null} Group info object, array of groups, or null if not found
430
+ * @example
431
+ * // Get all groups for a coalescing key
432
+ * const groups = queue.getCoalescingGroup('ui.update');
433
+ *
434
+ * // Get specific group by ID
435
+ * const group = queue.getCoalescingGroup('ui.update', '1');
436
+ * console.log(group.tasks.size); // Number of tasks in group
437
+ *
438
+ * // Access individual task metadata
439
+ * for (const [taskId, task] of group.tasks) {
440
+ * console.log(`Task ${taskId}:`, task.metadata);
441
+ * }
442
+ */
443
+ getCoalescingGroup(coalescingKey: string, groupId?: string): Object | any[] | null;
444
+ /**
445
+ * Gets metadata for all tasks in a coalescing group.
446
+ * @param {string} coalescingKey - The coalescing key
447
+ * @param {string} [groupId] - Optional group ID. If omitted, returns metadata from all groups for the key
448
+ * @returns {Array} Array of metadata objects with task IDs
449
+ * @example
450
+ * // Get metadata from all groups for a key
451
+ * const allMetadata = queue.getCoalescingGroupMetadata('ui.update');
452
+ *
453
+ * // Get metadata from specific group
454
+ * const groupMetadata = queue.getCoalescingGroupMetadata('ui.update', '1');
455
+ *
456
+ * // Example output:
457
+ * // [
458
+ * // { taskId: '123', metadata: { userId: 100, action: 'save' } },
459
+ * // { taskId: '124', metadata: { userId: 200, action: 'delete' } }
460
+ * // ]
461
+ */
462
+ getCoalescingGroupMetadata(coalescingKey: string, groupId?: string): any[];
463
+ /**
464
+ * Gets a summary of all active coalescing groups.
465
+ * @returns {Object} Summary object with coalescing key stats
466
+ * @example
467
+ * const summary = queue.getCoalescingGroupsSummary();
468
+ * console.log(summary);
469
+ * // {
470
+ * // 'ui.update': { groupCount: 2, totalTasks: 5 },
471
+ * // 'api.batch': { groupCount: 1, totalTasks: 3 }
472
+ * // }
473
+ */
474
+ getCoalescingGroupsSummary(): Object;
475
+ /**
476
+ * Finds the coalescing group that contains a specific task ID.
477
+ * @param {string|number} taskId - The task ID to search for
478
+ * @returns {Object|null} Group information including the task's metadata, or null if not found
479
+ * @example
480
+ * const groupInfo = queue.findCoalescingGroupByTaskId('123');
481
+ * if (groupInfo) {
482
+ * console.log('Task is in group:', groupInfo.groupId);
483
+ * console.log('Task metadata:', groupInfo.task.metadata);
484
+ * console.log('Other tasks in group:', groupInfo.groupTasks.length);
485
+ * }
486
+ */
487
+ findCoalescingGroupByTaskId(taskId: string | number): Object | null;
488
+ /**
489
+ * Destroys the queue, canceling all tasks and stopping the scheduler.
490
+ * Once destroyed, the queue cannot be reused.
491
+ * @returns {void}
492
+ * @example
493
+ * queue.destroy();
494
+ * // Queue is permanently shut down
495
+ */
496
+ destroy(): void;
497
+ /**
498
+ * Returns the current timestamp in milliseconds.
499
+ * @returns {number} Current timestamp
500
+ * @example
501
+ * const timestamp = queue.now(); // 1699564800000
502
+ */
503
+ now(): number;
504
+ /**
505
+ * Schedules the next scheduler tick based on when tasks become ready.
506
+ * @returns {void}
507
+ * @private
508
+ * @internal
509
+ */
510
+ private _scheduleNextTick;
511
+ timeoutId: number | undefined;
512
+ /**
513
+ * Main scheduler tick that moves ready tasks and starts execution.
514
+ * @returns {void}
515
+ * @private
516
+ */
517
+ private schedulerTick;
518
+ /**
519
+ * Checks if a task can start based on both global and per-priority concurrency limits.
520
+ * @param {Object} task - The task to check
521
+ * @returns {boolean} True if the task can start, false if concurrency limits prevent it
522
+ * @private
523
+ */
524
+ private _canStartTask;
525
+ /**
526
+ * Handles an expired task by removing it and calling appropriate error handling.
527
+ * @param {Object} item - The expired task item
528
+ * @returns {void}
529
+ * @private
530
+ * @internal
531
+ */
532
+ private _expireTask;
533
+ /**
534
+ * Emits a task failure as an `error` event when, and only when, a listener is attached.
535
+ * Used for callback-API task failures, which are always delivered to the task's callback
536
+ * as well; with no listener, EventEmitter would otherwise throw the event and crash the
537
+ * process before (or after) the callback could handle it.
538
+ * @param {Object} payload - Event payload
539
+ * @returns {void}
540
+ * @private
541
+ * @internal
542
+ */
543
+ private _emitTaskError;
544
+ /**
545
+ * Starts execution of a ready task.
546
+ * @param {Object} item - The task item to execute
547
+ * @returns {Promise<void>}
548
+ * @private
549
+ * @internal
550
+ */
551
+ private _startTask;
552
+ /**
553
+ * Clears all active timers (intervals and timeouts).
554
+ * @returns {void}
555
+ * @private
556
+ */
557
+ private clearTimers;
558
+ /**
559
+ * Calculates when the next scheduler run should happen and sets appropriate timeout.
560
+ * @private
561
+ * @returns {void}
562
+ *
563
+ * @description
564
+ * Smart scheduling that calculates the optimal time for the next scheduler run based on:
565
+ * - When the next pending task becomes ready
566
+ * - When delay periods end
567
+ * - Whether there are tasks that can run immediately
568
+ *
569
+ * Uses setTimeout for precise timing instead of constant polling intervals.
570
+ */
571
+ private scheduleSmartTimeout;
572
+ /**
573
+ * Runs the main scheduler logic and reschedules if needed.
574
+ * @private
575
+ * @returns {void}
576
+ *
577
+ * @description
578
+ * Executes the scheduler tick logic and then determines if more scheduling is needed.
579
+ * Tracks when scheduler last ran for healing mechanism.
580
+ */
581
+ private runScheduler;
582
+ /**
583
+ * Starts the self-healing interval that ensures scheduler continues working.
584
+ * @private
585
+ * @returns {void}
586
+ *
587
+ * @description
588
+ * Healing mechanism that periodically checks if the scheduler should be running
589
+ * but isn't due to timeout failures or other issues. Runs every healingInterval milliseconds.
590
+ */
591
+ private startHealingInterval;
592
+ /**
593
+ * Clears all scheduler-related timers.
594
+ * @private
595
+ * @returns {void}
596
+ *
597
+ * @description
598
+ * Cleans up both the main scheduler timeout and the healing interval timer.
599
+ */
600
+ private clearSchedulerTimers;
601
+ /**
602
+ * Configure coalescing settings for specific keys dynamically.
603
+ * @param {string} coalescingKey - The coalescing key to configure
604
+ * @param {Object} config - Configuration for this key
605
+ * @param {number} [config.windowDuration] - Window duration in milliseconds for this key
606
+ * @param {number} [config.maxDelay] - Maximum delay in milliseconds for this key
607
+ * @param {number} [config.postDelay] - Post-completion delay in milliseconds for this key
608
+ * @param {number} [config.startDelay] - Pre-execution delay in milliseconds for this key
609
+ * @param {number} [config.delay] - DEPRECATED: Use postDelay instead
610
+ * @param {number} [config.start] - DEPRECATED: Use startDelay instead
611
+ * @param {boolean} [config.multipleCallbacks] - Whether to call multiple callbacks for this key
612
+ * @param {boolean} [config.resolveAllPromises] - Whether to resolve all promises for this key
613
+ * @returns {void}
614
+ *
615
+ * @example
616
+ * // Configure specific keys after queue creation
617
+ * queue.configureCoalescingKey('ui.update', {
618
+ * windowDuration: 100,
619
+ * maxDelay: 500,
620
+ * postDelay: 25,
621
+ * startDelay: 0
622
+ * });
623
+ *
624
+ * queue.configureCoalescingKey('api.batch', {
625
+ * windowDuration: 1000,
626
+ * maxDelay: 5000,
627
+ * postDelay: 100,
628
+ * startDelay: 200,
629
+ * resolveAllPromises: false
630
+ * });
631
+ */
632
+ configureCoalescingKey(coalescingKey: string, config: {
633
+ windowDuration?: number | undefined;
634
+ maxDelay?: number | undefined;
635
+ postDelay?: number | undefined;
636
+ startDelay?: number | undefined;
637
+ delay?: number | undefined;
638
+ start?: number | undefined;
639
+ multipleCallbacks?: boolean | undefined;
640
+ resolveAllPromises?: boolean | undefined;
641
+ }): void;
642
+ /**
643
+ * Get the effective coalescing configuration for a specific key.
644
+ * @param {string} coalescingKey - The coalescing key to get configuration for
645
+ * @param {Object} [taskOptions={}] - Task-level options that may override key configuration
646
+ * @returns {Object} The effective configuration for this key
647
+ *
648
+ * @example
649
+ * // Get effective configuration for a key
650
+ * const config = queue.getCoalescingConfig('ui.update');
651
+ * console.log(`UI updates coalesce within ${config.windowDuration}ms with ${config.postDelay}ms post-completion delay`);
652
+ *
653
+ * // Check with task-level overrides
654
+ * const effectiveConfig = queue.getCoalescingConfig('ui.update', {
655
+ * coalescingWindowDuration: 50,
656
+ * postDelay: 30 // Deprecated task-level name delay is still accepted
657
+ * });
658
+ */
659
+ getCoalescingConfig(coalescingKey: string, taskOptions?: Object): Object;
660
+ /**
661
+ * Get all configured coalescing keys and their configurations.
662
+ * @returns {Object} Map of coalescingKey to configuration
663
+ *
664
+ * @example
665
+ * // See all configured coalescing keys
666
+ * const allConfigs = queue.getCoalescingConfigurations();
667
+ * Object.entries(allConfigs).forEach(([key, config]) => {
668
+ * console.log(`${key}: ${config.windowDuration}ms window, ${config.maxDelay}ms max delay, ${config.postDelay}ms post-completion delay, ${config.startDelay}ms pre-execution delay`);
669
+ * });
670
+ */
671
+ getCoalescingConfigurations(): Object;
672
+ /**
673
+ * Configure default settings for specific priorities dynamically.
674
+ * @param {number} priority - The priority level to configure
675
+ * @param {Object} config - Configuration for this priority
676
+ * @param {number} [config.postDelay] - Default post-completion delay in milliseconds for this priority
677
+ * @param {number} [config.startDelay] - Default pre-execution delay in milliseconds for this priority
678
+ * @param {number} [config.delay] - DEPRECATED: Use postDelay instead
679
+ * @param {number} [config.start] - DEPRECATED: Use startDelay instead
680
+ * @returns {void}
681
+ *
682
+ * @example
683
+ * // Configure priority defaults after queue creation
684
+ * queue.configurePriority(1, {
685
+ * postDelay: 100, // High priority tasks have 100ms delay after completion
686
+ * startDelay: 0 // High priority tasks start immediately
687
+ * });
688
+ *
689
+ * queue.configurePriority(3, {
690
+ * postDelay: 0, // Low priority tasks have no delay after completion
691
+ * startDelay: 200 // Low priority tasks wait 200ms before starting
692
+ * });
693
+ */
694
+ configurePriority(priority: number, config: {
695
+ postDelay?: number | undefined;
696
+ startDelay?: number | undefined;
697
+ delay?: number | undefined;
698
+ start?: number | undefined;
699
+ }): void;
700
+ /**
701
+ * Get the effective configuration for a specific priority.
702
+ * @param {number} priority - The priority level to get configuration for
703
+ * @param {Object} [taskOptions={}] - Task-level options that may override priority configuration
704
+ * @returns {Object} The effective configuration for this priority
705
+ *
706
+ * @example
707
+ * // Get effective configuration for a priority
708
+ * const config = queue.getPriorityConfig(1);
709
+ * console.log(`Priority 1 tasks: ${config.delay}ms delay, ${config.start}ms start delay`);
710
+ *
711
+ * // Check with task-level overrides
712
+ * const effectiveConfig = queue.getPriorityConfig(1, {
713
+ * postDelay: 50,
714
+ * startDelay: 10 // Deprecated task-level names delay/start are still accepted
715
+ * });
716
+ */
717
+ getPriorityConfig(priority: number, taskOptions?: Object): Object;
718
+ /**
719
+ * Get all configured priorities and their configurations.
720
+ * @returns {Object} Map of priority to configuration
721
+ *
722
+ * @example
723
+ * // See all configured priorities
724
+ * const allConfigs = queue.getPriorityConfigurations();
725
+ * Object.entries(allConfigs).forEach(([priority, config]) => {
726
+ * console.log(`Priority ${priority}: ${config.delay}ms delay, ${config.start}ms start delay`);
727
+ * });
728
+ */
729
+ getPriorityConfigurations(): Object;
730
+ /**
731
+ * Alias for destroy() method for common queue system naming.
732
+ * @returns {void}
733
+ */
734
+ shutdown(): void;
735
+ /**
736
+ * Alias for enqueue() method for common queue system naming.
737
+ * @param {Function} task - The task function to execute
738
+ * @param {Function|Object} optionsOrCallback - Callback function or options object
739
+ * @param {Object} options - Task options (if callback provided as second parameter)
740
+ * @returns {Promise|TaskHandle} Promise if no callback provided, TaskHandle otherwise
741
+ */
742
+ schedule(task: Function, optionsOrCallback: Function | Object, options?: Object): Promise<any> | TaskHandle;
743
+ /**
744
+ * Alias for enqueue() method for common queue system naming.
745
+ * @param {Function} task - The task function to execute
746
+ * @param {Function|Object} optionsOrCallback - Callback function or options object
747
+ * @param {Object} options - Task options (if callback provided as second parameter)
748
+ * @returns {Promise|TaskHandle} Promise if no callback provided, TaskHandle otherwise
749
+ */
750
+ add(task: Function, optionsOrCallback: Function | Object, options?: Object): Promise<any> | TaskHandle;
751
+ /**
752
+ * Find a task by its ID.
753
+ * @param {string|number} id - The task ID to find
754
+ * @returns {Object|null} Task object if found, null otherwise
755
+ */
756
+ get(id: string | number): Object | null;
757
+ /**
758
+ * Check if a task with the given ID exists.
759
+ * @param {string|number} id - The task ID to check
760
+ * @returns {boolean} True if task exists, false otherwise
761
+ */
762
+ has(id: string | number): boolean;
763
+ /**
764
+ * Alias for get() method for backward compatibility.
765
+ * @param {string|number} id - The task ID to find
766
+ * @returns {Object|null} Task object if found, null otherwise
767
+ */
768
+ getTask(id: string | number): Object | null;
769
+ /**
770
+ * Alias for has() method for backward compatibility.
771
+ * @param {string|number} id - The task ID to check
772
+ * @returns {boolean} True if task exists, false otherwise
773
+ */
774
+ hasTask(id: string | number): boolean;
775
+ /**
776
+ * Get detailed information about the current queue state for debugging.
777
+ * @returns {Object} Comprehensive queue state information
778
+ */
779
+ inspect(): Object;
780
+ /**
781
+ * Get information about active timers and scheduler state.
782
+ * @returns {Object} Timer and scheduler information
783
+ */
784
+ inspectTimers(): Object;
785
+ /**
786
+ * Get a summary of all queued tasks by status.
787
+ * @returns {Object} Task summary by status
788
+ */
789
+ inspectTasks(): Object;
790
+ /**
791
+ * Get detailed information about the scheduler state and timing.
792
+ * @returns {Object} Scheduler state information
793
+ */
794
+ inspectScheduler(): Object;
795
+ /**
796
+ * Log comprehensive queue state to console for debugging.
797
+ * @param {boolean} [detailed=false] - Whether to include detailed task information
798
+ */
799
+ debugLog(detailed?: boolean): void;
800
+ }
801
+ import { MinHeap } from "./utils.mjs";
802
+ //# sourceMappingURL=hold-my-task.d.mts.map