@cldmv/holdmytask 1.2.0 → 1.3.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.
@@ -29,37 +29,289 @@ export class HoldMyTask extends EventEmitter {
29
29
  * @param {boolean} [options.autoStart=true] - Whether to automatically start the scheduler
30
30
  * @param {number} [options.defaultPriority=0] - Default priority for tasks (higher numbers = higher priority)
31
31
  * @param {number} [options.maxQueue=Infinity] - Maximum number of tasks that can be queued
32
- * @param {Object} [options.delays={}] - Map of priority levels to delay times in milliseconds between task completions
32
+ * @param {Object} [options.delays={}] - DEPRECATED: Use priorities[priority].delay instead. Legacy priority-to-delay mapping (auto-converted to priorities)
33
33
  * @param {boolean} [options.smartScheduling=true] - Use dynamic timeouts instead of constant polling for better performance
34
34
  * @param {number} [options.tick=25] - Polling interval in milliseconds when smartScheduling is disabled
35
35
  * @param {number} [options.healingInterval=5000] - Self-healing check interval in milliseconds (smart scheduling only)
36
+ * @param {Object} [options.priorities={}] - Priority-specific default configurations
37
+ * @param {Object} [options.coalescing] - Enhanced coalescing configuration (preferred over flat options)
38
+ * @param {Object} [options.coalescing.defaults] - Default coalescing settings for all keys
39
+ * @param {number} [options.coalescing.defaults.windowDuration=200] - Default window duration in milliseconds
40
+ * @param {number} [options.coalescing.defaults.maxDelay=1000] - Default maximum delay in milliseconds
41
+ * @param {number} [options.coalescing.defaults.postDelay] - Default post-completion delay in milliseconds
42
+ * @param {number} [options.coalescing.defaults.startDelay] - Default pre-execution delay in milliseconds
43
+ * @param {number} [options.coalescing.defaults.delay] - DEPRECATED: Use postDelay instead
44
+ * @param {number} [options.coalescing.defaults.start] - DEPRECATED: Use startDelay instead
45
+ * @param {boolean} [options.coalescing.defaults.resolveAllPromises=true] - Default promise resolution behavior
46
+ * @param {boolean} [options.coalescing.defaults.multipleCallbacks=false] - Default callback execution behavior
47
+ * @param {Object} [options.coalescing.keys] - Per-coalescingKey configuration overrides (windowDuration, maxDelay, postDelay, startDelay, etc.)
48
+ * @param {number} [options.coalescingWindowDuration=200] - DEPRECATED: Use coalescing.defaults.windowDuration instead
49
+ * @param {number} [options.coalescingMaxDelay=1000] - DEPRECATED: Use coalescing.defaults.maxDelay instead
50
+ * @param {boolean} [options.coalescingMultipleCallbacks=false] - DEPRECATED: Use coalescing.defaults.multipleCallbacks instead
51
+ * @param {boolean} [options.coalescingResolveAllPromises=true] - DEPRECATED: Use coalescing.defaults.resolveAllPromises instead
36
52
  * @example
53
+ * // Enhanced configuration with priority defaults and extended coalescing
37
54
  * const queue = new HoldMyTask({
38
55
  * concurrency: 2,
39
- * tick: 50,
40
- * defaultPriority: 1,
41
- * delays: { 0: 1000, 1: 500 }
56
+ * delays: { 0: 1000, 1: 500 },
57
+ * priorities: {
58
+ * 1: { postDelay: 100, startDelay: 0 }, // High priority: 100ms post-completion delay, immediate start
59
+ * 2: { postDelay: 200, startDelay: 50 }, // Medium priority: 200ms post-completion delay, 50ms pre-execution delay
60
+ * 3: { postDelay: 0, startDelay: 100 } // Low priority: no post-completion delay, 100ms pre-execution delay
61
+ * },
62
+ * coalescing: {
63
+ * defaults: {
64
+ * windowDuration: 200,
65
+ * maxDelay: 1000,
66
+ * postDelay: 50,
67
+ * startDelay: 25,
68
+ * resolveAllPromises: true
69
+ * },
70
+ * keys: {
71
+ * 'ui.update': { windowDuration: 100, maxDelay: 500, postDelay: 25, startDelay: 0 },
72
+ * 'api.batch': { windowDuration: 1000, maxDelay: 5000, postDelay: 100, startDelay: 200 },
73
+ * 'device.control': { windowDuration: 50, maxDelay: 200, delay: 10, start: 5 }
74
+ * }
75
+ * }
42
76
  * });
43
77
  *
44
78
  * @example
45
- * // Use traditional polling instead of smart scheduling
79
+ * // Backward compatible (deprecated but still supported)
46
80
  * const legacyQueue = new HoldMyTask({
47
- * smartScheduling: false,
48
- * tick: 50
81
+ * coalescingWindowDuration: 1500,
82
+ * coalescingMaxDelay: 3000,
83
+ * coalescingResolveAllPromises: true
49
84
  * });
50
85
  */
86
+
87
+ /**
88
+ * Transforms delay properties for backwards compatibility.
89
+ * Converts 'start' -> 'startDelay' and 'delay' -> 'postDelay' while preserving new names.
90
+ * @param {Object} config - Configuration object that may contain old or new property names
91
+ * @param {HoldMyTask} [instance] - Optional instance to emit deprecation warnings on
92
+ * @returns {Object} Transformed configuration with new property names
93
+ * @private
94
+ * @internal
95
+ */
96
+ static _transformDelayProperties(config, instance = null) {
97
+ if (!config || typeof config !== "object") {
98
+ return config;
99
+ }
100
+
101
+ const transformed = { ...config };
102
+
103
+ // Transform old names to new names (backwards compatibility)
104
+ // New names take precedence if both are provided
105
+ if ("start" in config && !("startDelay" in config)) {
106
+ transformed.startDelay = config.start;
107
+ if (instance) {
108
+ setImmediate(() =>
109
+ instance.emit("warning", {
110
+ type: "deprecation",
111
+ message: "Property 'start' is deprecated. Use 'startDelay' instead.",
112
+ deprecated: "start",
113
+ replacement: "startDelay"
114
+ })
115
+ );
116
+ }
117
+ }
118
+ delete transformed.start; // Always remove old property
119
+
120
+ if ("delay" in config && !("postDelay" in config)) {
121
+ transformed.postDelay = config.delay;
122
+ if (instance) {
123
+ setImmediate(() =>
124
+ instance.emit("warning", {
125
+ type: "deprecation",
126
+ message: "Property 'delay' is deprecated. Use 'postDelay' instead.",
127
+ deprecated: "delay",
128
+ replacement: "postDelay"
129
+ })
130
+ );
131
+ }
132
+ }
133
+ delete transformed.delay; // Always remove old property
134
+
135
+ return transformed;
136
+ }
137
+
51
138
  constructor(options = {}) {
52
139
  super();
140
+
141
+ // Sync mode is default for backwards compatibility
142
+ const syncMode = options.sync !== false;
143
+
144
+ if (syncMode) {
145
+ // Synchronous initialization - backwards compatible
146
+ this._initializeSync(options);
147
+ } else {
148
+ // Asynchronous initialization - modern usage
149
+ return this._initializeAsync(options);
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Synchronous initialization for backwards compatibility
155
+ * @private
156
+ * @param {Object} options - Configuration options
157
+ */
158
+ _initializeSync(options) {
159
+ this._syncMode = true;
160
+ this._initializeCommon(options);
161
+ }
162
+
163
+ /**
164
+ * Asynchronous initialization for modern usage
165
+ * @private
166
+ * @param {Object} options - Configuration options
167
+ * @returns {Promise<HoldMyTask>} Promise that resolves to this instance
168
+ */
169
+ async _initializeAsync(options) {
170
+ this._syncMode = false;
171
+
172
+ // Return promise for async initialization
173
+ return new Promise((resolve) => {
174
+ setImmediate(() => {
175
+ this._initializeCommon(options);
176
+ resolve(this);
177
+ });
178
+ });
179
+ }
180
+
181
+ /**
182
+ * Common initialization logic used by both sync and async modes
183
+ * @private
184
+ * @param {Object} options - Configuration options
185
+ */
186
+ _initializeCommon(options) {
187
+ // Remove internal options before processing
188
+ const cleanOptions = { ...options };
189
+ delete cleanOptions.sync;
190
+ delete cleanOptions.async;
191
+
192
+ // Backward compatibility: support old flat coalescing options
193
+ const legacyCoalescingDefaults = {
194
+ windowDuration: cleanOptions.coalescingWindowDuration ?? 200,
195
+ maxDelay: cleanOptions.coalescingMaxDelay ?? 1000,
196
+ multipleCallbacks: cleanOptions.coalescingMultipleCallbacks ?? false,
197
+ resolveAllPromises: cleanOptions.coalescingResolveAllPromises ?? true
198
+ };
199
+
200
+ // Emit deprecation warnings for legacy coalescing options
201
+ const deprecatedCoalescingOptions = [
202
+ { old: "coalescingWindowDuration", new: "coalescing.defaults.windowDuration" },
203
+ { old: "coalescingMaxDelay", new: "coalescing.defaults.maxDelay" },
204
+ { old: "coalescingMultipleCallbacks", new: "coalescing.defaults.multipleCallbacks" },
205
+ { old: "coalescingResolveAllPromises", new: "coalescing.defaults.resolveAllPromises" }
206
+ ];
207
+
208
+ deprecatedCoalescingOptions.forEach(({ old, new: replacement }) => {
209
+ if (cleanOptions[old] !== undefined) {
210
+ setImmediate(() =>
211
+ this.emit("warning", {
212
+ type: "deprecation",
213
+ message: `Option '${old}' is deprecated. Use '${replacement}' instead.`,
214
+ deprecated: old,
215
+ replacement: replacement
216
+ })
217
+ );
218
+ }
219
+ });
220
+
221
+ // Enhanced coalescing configuration
222
+ const coalescingConfig = cleanOptions.coalescing || {};
223
+ const coalescingDefaults = HoldMyTask._transformDelayProperties(
224
+ {
225
+ ...legacyCoalescingDefaults,
226
+ ...coalescingConfig.defaults
227
+ },
228
+ this
229
+ );
230
+
231
+ // Transform coalescing keys configurations
232
+ const transformedCoalescingKeys = {};
233
+ if (coalescingConfig.keys && typeof coalescingConfig.keys === "object") {
234
+ for (const [key, config] of Object.entries(coalescingConfig.keys)) {
235
+ if (config != null) {
236
+ transformedCoalescingKeys[key] = HoldMyTask._transformDelayProperties(config, this);
237
+ }
238
+ }
239
+ }
240
+
241
+ // Transform legacy delays to new priorities format for backward compatibility
242
+ const transformedPriorities = {};
243
+
244
+ // First, transform any existing priority configurations to use new property names
245
+ if (cleanOptions.priorities && typeof cleanOptions.priorities === "object") {
246
+ for (const [priority, config] of Object.entries(cleanOptions.priorities)) {
247
+ const priorityNum = parseInt(priority);
248
+ if (!isNaN(priorityNum) && config != null) {
249
+ transformedPriorities[priorityNum] = HoldMyTask._transformDelayProperties(config, this);
250
+ }
251
+ }
252
+ }
253
+
254
+ // Then, handle legacy delays option (very old backwards compatibility)
255
+ if (cleanOptions.delays && typeof cleanOptions.delays === "object") {
256
+ // Emit deprecation warning for legacy delays option
257
+ setImmediate(() =>
258
+ this.emit("warning", {
259
+ type: "deprecation",
260
+ message:
261
+ "Option 'delays' is deprecated. Use 'priorities' instead with { [priority]: { postDelay: value, startDelay: 0 } } format.",
262
+ deprecated: "delays",
263
+ replacement: "priorities"
264
+ })
265
+ );
266
+
267
+ for (const [priority, delay] of Object.entries(cleanOptions.delays)) {
268
+ const priorityNum = parseInt(priority);
269
+ if (!isNaN(priorityNum) && delay != null) {
270
+ transformedPriorities[priorityNum] = {
271
+ postDelay: delay, // Use new property name
272
+ startDelay: 0, // Use new property name
273
+ ...(transformedPriorities[priorityNum] || {}) // Don't override explicit priority config
274
+ };
275
+ }
276
+ }
277
+ }
278
+
279
+ // Extract properties that have been transformed or handled specially
280
+ const remainingOptions = { ...cleanOptions };
281
+ delete remainingOptions.priorities;
282
+ delete remainingOptions.delays;
283
+ delete remainingOptions.coalescing;
284
+
285
+ // Handle special maxQueue values (-1 means unlimited)
286
+ let maxQueue = remainingOptions.maxQueue;
287
+ if (maxQueue === -1) {
288
+ maxQueue = Infinity;
289
+ }
290
+ delete remainingOptions.maxQueue;
291
+
53
292
  this.options = {
54
293
  concurrency: 1,
55
294
  tick: 25,
56
295
  autoStart: true,
57
296
  defaultPriority: 0,
58
- maxQueue: Infinity,
59
- delays: {}, // priority -> delay in ms between tasks of that priority
297
+ maxQueue: maxQueue !== undefined ? maxQueue : Infinity,
298
+ priorities: transformedPriorities, // Unified priority configuration system
60
299
  smartScheduling: true, // Use smart timeouts instead of polling by default
61
300
  healingInterval: 5000, // Self-healing check interval (smart scheduling only)
62
- ...options
301
+
302
+ // Enhanced coalescing configuration
303
+ coalescing: {
304
+ defaults: coalescingDefaults,
305
+ keys: transformedCoalescingKeys
306
+ },
307
+
308
+ // Legacy coalescing options (kept for backward compatibility but deprecated)
309
+ coalescingWindowDuration: legacyCoalescingDefaults.windowDuration,
310
+ coalescingMaxDelay: legacyCoalescingDefaults.maxDelay,
311
+ coalescingMultipleCallbacks: legacyCoalescingDefaults.multipleCallbacks,
312
+ coalescingResolveAllPromises: legacyCoalescingDefaults.resolveAllPromises,
313
+
314
+ ...remainingOptions
63
315
  };
64
316
 
65
317
  // Initialize heaps
@@ -87,23 +339,50 @@ export class HoldMyTask extends EventEmitter {
87
339
  // Traditional polling state (used when smartScheduling is disabled)
88
340
  this.intervalId = null;
89
341
 
342
+ // Coalescing system - separate from main queue
343
+ this.coalescingGroups = new Map(); // coalescingKey -> Array<CoalescingGroup>
344
+ this.coalescingRepresentatives = new Map(); // representativeTaskId -> { coalescingKey, groupId }
345
+ this.nextGroupId = 1;
346
+
90
347
  if (this.options.autoStart) {
91
348
  this.resume();
92
349
  }
93
350
  }
94
351
 
352
+ /**
353
+ * Internal convenience method to create a new HoldMyTask instance with async initialization.
354
+ * This enables event listeners to be attached before validation errors can occur.
355
+ * @param {Object} [options={}] - Configuration options
356
+ * @returns {Promise<HoldMyTask>} Promise that resolves to the initialized instance
357
+ * @private
358
+ * @example
359
+ * // Internal usage - prefer new HoldMyTask({ sync: false }) for public API
360
+ * const queue = await HoldMyTask._create({ maxQueue: 100 });
361
+ */
362
+ static async _create(options = {}) {
363
+ // Create instance with async mode
364
+ return new HoldMyTask({ ...options, sync: false });
365
+ }
366
+
95
367
  /**
96
368
  * Adds a task to the queue for execution. Supports both callback and promise-based APIs.
97
369
  * @param {Function} task - The task function to execute. Can be sync or async.
98
370
  * @param {Function|Object} [optionsOrCallback] - Either a callback function or options object
99
371
  * @param {Object} [options={}] - Additional options (if callback was provided as second parameter)
372
+ * @param {string|number} [options.id] - Custom task ID for identification and later reference (must be unique)
100
373
  * @param {number} [options.priority] - Task priority (higher numbers run first)
101
374
  * @param {number} [options.timestamp] - When the task should be ready to run (milliseconds since epoch)
375
+ * @param {number} [options.start] - Milliseconds from now when the task should be ready to run (convenience for timestamp calculation)
102
376
  * @param {AbortSignal} [options.signal] - AbortSignal to cancel the task
103
377
  * @param {number} [options.timeout] - Task timeout in milliseconds (for execution time limit)
104
378
  * @param {number} [options.expire] - Task expiration timestamp or milliseconds from now (for queue waiting time limit)
105
- * @param {number} [options.delay] - Delay after task completion before next task of same priority
379
+ * @param {number} [options.delay] - DEPRECATED: Use postDelay instead. Delay after task completion before next task of same priority
106
380
  * @param {boolean} [options.bypassDelay] - If true, skip any active delay period and start immediately
381
+ * @param {string} [options.coalescingKey] - Key for task coalescing - tasks with same key will be coalesced within windows
382
+ * @param {number} [options.coalescingWindowDuration] - Override coalescing window duration (task-level override of key-level and defaults)
383
+ * @param {number} [options.coalescingMaxDelay] - Override coalescing max delay (task-level override of key-level and defaults)
384
+ * @param {boolean} [options.coalescingMultipleCallbacks] - Override callback behavior (task-level override of key-level and defaults)
385
+ * @param {boolean} [options.coalescingResolveAllPromises] - Override promise resolution behavior (task-level override of key-level and defaults)
107
386
  * @param {*} [options.metadata] - Arbitrary metadata to attach to the task
108
387
  * @returns {Promise|Object} Promise (if no callback) or task control object with id, cancel, status methods
109
388
  * @throws {Error} If queue is destroyed or full
@@ -125,14 +404,22 @@ export class HoldMyTask extends EventEmitter {
125
404
  *
126
405
  * // Alternative: use delay: -1 to bypass
127
406
  * const urgent2 = queue.enqueue(urgentTask, { priority: 10, delay: -1 });
407
+ *
408
+ * // Coalescing tasks - multiple device status checks become one
409
+ * queue.enqueue(checkDeviceStatus, callback1, { coalescingKey: "device-123", coalescingWindowDuration: 1000 });
410
+ * queue.enqueue(checkDeviceStatus, callback2, { coalescingKey: "device-123" }); // Gets coalesced with first
128
411
  */
129
412
  enqueue(task, optionsOrCallback, options = {}) {
130
413
  if (this.destroyed) {
131
- throw new Error("Queue is destroyed");
414
+ const error = new Error("Queue is destroyed");
415
+ setImmediate(() => this.emit("error", { error, task, options: optionsOrCallback }));
416
+ return Promise.reject(error);
132
417
  }
133
418
 
134
419
  if (this.tasks.size >= this.options.maxQueue) {
135
- throw new Error("Queue is full");
420
+ const error = new Error("Queue is full");
421
+ setImmediate(() => this.emit("error", { error, task, options: optionsOrCallback }));
422
+ return Promise.reject(error);
136
423
  }
137
424
 
138
425
  // Handle dual API: callback can be second or third parameter
@@ -145,16 +432,35 @@ export class HoldMyTask extends EventEmitter {
145
432
  finalOptions = { ...optionsOrCallback, ...options };
146
433
  }
147
434
 
148
- const id = String(this.nextId++);
435
+ // Generate ID - use custom ID if provided, otherwise auto-generate
436
+ const id = finalOptions.id ? String(finalOptions.id) : String(this.nextId++);
437
+
438
+ // Check if custom ID already exists
439
+ if (finalOptions.id && this.tasks.has(id)) {
440
+ const error = new Error(`Task with ID '${id}' already exists`);
441
+ setImmediate(() => this.emit("error", { error, task, options: finalOptions }));
442
+ return Promise.reject(error);
443
+ }
149
444
  const now = this.now();
150
- const readyAt = finalOptions.timestamp ?? now;
445
+
446
+ // Handle coalescing tasks separately
447
+ if (finalOptions.coalescingKey) {
448
+ return this._handleCoalescingTask(id, task, callback, finalOptions, now);
449
+ }
450
+
451
+ // Regular task handling - apply priority defaults for start delay
452
+ const priority = finalOptions.priority ?? this.options.defaultPriority;
453
+ const priorityConfig = this.getPriorityConfig(priority, finalOptions);
454
+ const effectiveStart = finalOptions.start ?? priorityConfig.startDelay ?? 0;
455
+ const readyAt = finalOptions.timestamp ?? (effectiveStart ? now + effectiveStart : now);
151
456
 
152
457
  // Calculate expiration timestamp
153
458
  let expireAt = null;
154
459
  if (finalOptions.expire !== undefined) {
155
- // If expire > current timestamp, treat as absolute timestamp
156
- // If expire <= current timestamp, treat as milliseconds from now
157
- if (finalOptions.expire > now) {
460
+ // If expire === -1, never expire (useful with coalescing)
461
+ if (finalOptions.expire === -1) {
462
+ expireAt = null;
463
+ } else if (finalOptions.expire > now) {
158
464
  expireAt = finalOptions.expire;
159
465
  } else {
160
466
  expireAt = now + finalOptions.expire;
@@ -165,7 +471,7 @@ export class HoldMyTask extends EventEmitter {
165
471
  id,
166
472
  task,
167
473
  callback,
168
- priority: finalOptions.priority ?? this.options.defaultPriority,
474
+ priority,
169
475
  readyAt,
170
476
  expireAt,
171
477
  enqueueSeq: this.enqueueSeq++,
@@ -182,11 +488,11 @@ export class HoldMyTask extends EventEmitter {
182
488
 
183
489
  // Check if signal is already aborted
184
490
  if (finalOptions.signal?.aborted) {
185
- this.cancelTask(id, "Task was aborted");
491
+ this.cancel(id, "Task was aborted");
186
492
  } else if (finalOptions.signal) {
187
493
  // For both callback and promise API, the queue handles signal abortion
188
494
  finalOptions.signal.addEventListener("abort", () => {
189
- this.cancelTask(id, "Task was aborted");
495
+ this.cancel(id, "Task was aborted");
190
496
  });
191
497
  }
192
498
 
@@ -194,14 +500,13 @@ export class HoldMyTask extends EventEmitter {
194
500
  if (this.options.smartScheduling) {
195
501
  this.scheduleSmartTimeout();
196
502
  } else {
197
- this.scheduleNextTick();
503
+ this._scheduleNextTick();
198
504
  }
199
505
  }
200
-
201
506
  const tasks = this.tasks; // Capture reference
202
507
  const taskHandle = {
203
508
  id,
204
- cancel: (reason) => this.cancelTask(id, reason),
509
+ cancel: (reason) => this.cancel(id, reason),
205
510
  status: () => tasks.get(id)?.status ?? "canceled",
206
511
  get startedAt() {
207
512
  return tasks.get(id)?.startedAt;
@@ -224,15 +529,620 @@ export class HoldMyTask extends EventEmitter {
224
529
  item.reject = reject;
225
530
  });
226
531
 
227
- // Attach task handle properties to the promise with live getters
228
- const tasksRef = this.tasks;
532
+ // Store promise reference on item so we can update properties when task completes
533
+ item.promise = promise;
534
+
535
+ // Attach task handle properties to the promise with cached fallback getters
229
536
  Object.defineProperty(promise, "id", { value: id, enumerable: true });
230
- Object.defineProperty(promise, "cancel", { value: (reason) => this.cancelTask(id, reason), enumerable: true });
231
- Object.defineProperty(promise, "status", { value: () => tasksRef.get(id)?.status ?? "canceled", enumerable: true });
232
- Object.defineProperty(promise, "startedAt", { get: () => tasksRef.get(id)?.startedAt, enumerable: true });
233
- Object.defineProperty(promise, "finishedAt", { get: () => tasksRef.get(id)?.finishedAt, enumerable: true });
234
- Object.defineProperty(promise, "result", { get: () => tasksRef.get(id)?.result, enumerable: true });
235
- Object.defineProperty(promise, "error", { get: () => tasksRef.get(id)?.error, enumerable: true });
537
+ Object.defineProperty(promise, "cancel", { value: (reason) => this.cancel(id, reason), enumerable: true });
538
+ Object.defineProperty(promise, "status", {
539
+ value: () => {
540
+ const currentItem = this.tasks.get(id);
541
+ return currentItem ? currentItem.status : (promise._status ?? "canceled");
542
+ },
543
+ enumerable: true
544
+ });
545
+ Object.defineProperty(promise, "startedAt", {
546
+ get: () => {
547
+ const currentItem = this.tasks.get(id);
548
+ return currentItem ? currentItem.startedAt : promise._startedAt;
549
+ },
550
+ enumerable: true
551
+ });
552
+ Object.defineProperty(promise, "finishedAt", {
553
+ get: () => {
554
+ const currentItem = this.tasks.get(id);
555
+ return currentItem ? currentItem.finishedAt : promise._finishedAt;
556
+ },
557
+ enumerable: true
558
+ });
559
+ Object.defineProperty(promise, "result", {
560
+ get: () => {
561
+ const currentItem = this.tasks.get(id);
562
+ return currentItem ? currentItem.result : promise._result;
563
+ },
564
+ enumerable: true
565
+ });
566
+ Object.defineProperty(promise, "error", {
567
+ get: () => {
568
+ const currentItem = this.tasks.get(id);
569
+ return currentItem ? currentItem.error : promise._error;
570
+ },
571
+ enumerable: true
572
+ });
573
+
574
+ return promise;
575
+ }
576
+
577
+ return taskHandle;
578
+ }
579
+
580
+ /**
581
+ * Handles tasks with coalescingKey through the coalescing system.
582
+ * @private
583
+ * @internal
584
+ * @param {string} id - Task ID
585
+ * @param {Function} task - Task function
586
+ * @param {Function|null} callback - Callback function (null for promise API)
587
+ * @param {Object} options - Task options
588
+ * @param {number} now - Current timestamp
589
+ * @returns {Promise|Object} Promise or task handle
590
+ */
591
+ _handleCoalescingTask(id, task, callback, options, now) {
592
+ const { coalescingKey } = options;
593
+
594
+ // Get effective coalescing configuration including new delay and start options
595
+ const coalescingConfig = this.getCoalescingConfig(coalescingKey, options);
596
+ const priority = options.priority ?? this.options.defaultPriority;
597
+ const priorityConfig = this.getPriorityConfig(priority, options);
598
+
599
+ // Apply configuration priority: task options > coalescing key config > priority defaults > coalescing defaults
600
+ const effectiveStart = options.start ?? coalescingConfig.startDelay ?? priorityConfig.startDelay ?? 0;
601
+
602
+ const readyAt = options.timestamp ?? (effectiveStart ? now + effectiveStart : now);
603
+ const windowEnd = now + coalescingConfig.windowDuration;
604
+ const mustRunBy = now + coalescingConfig.maxDelay;
605
+
606
+ // Apply effective delay configuration
607
+ const effectiveDelay = options.delay ?? coalescingConfig.postDelay ?? priorityConfig.postDelay;
608
+
609
+ // Create task item (not added to main queue directly)
610
+ const taskItem = {
611
+ id,
612
+ task,
613
+ callback,
614
+ priority,
615
+ readyAt,
616
+ status: "coalescing",
617
+ signal: options.signal,
618
+ timeout: options.timeout,
619
+ delay: effectiveDelay,
620
+ bypassDelay: options.bypassDelay || options.delay === -1,
621
+ metadata: options.metadata,
622
+ coalescingKey,
623
+ enqueueSeq: this.enqueueSeq++
624
+ };
625
+
626
+ // Handle signal abortion for coalescing tasks
627
+ if (options.signal?.aborted) {
628
+ taskItem.status = "canceled";
629
+ if (callback) {
630
+ try {
631
+ callback(new Error("Task was aborted"), null);
632
+ } catch (callbackError) {
633
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
634
+ }
635
+ }
636
+ return this._createTaskHandle(taskItem, callback);
637
+ }
638
+
639
+ // Add abort listener
640
+ options.signal?.addEventListener("abort", () => {
641
+ this._cancelCoalescingTask(id, coalescingKey, "Task was aborted");
642
+ });
643
+
644
+ // Find compatible coalescing group or create new one
645
+ const compatibleGroup = this._findCompatibleCoalescingGroup(coalescingKey, now);
646
+
647
+ if (compatibleGroup) {
648
+ // Add to existing group
649
+ this._addToCoalescingGroup(compatibleGroup, taskItem, windowEnd, mustRunBy);
650
+ } else {
651
+ // Create new coalescing group using coalescingConfig
652
+ this._createCoalescingGroup(
653
+ coalescingKey,
654
+ taskItem,
655
+ windowEnd,
656
+ mustRunBy,
657
+ coalescingConfig.multipleCallbacks,
658
+ coalescingConfig.resolveAllPromises
659
+ );
660
+ }
661
+
662
+ return this._createTaskHandle(taskItem, callback);
663
+ }
664
+
665
+ /**
666
+ * Finds a compatible coalescing group for a new task.
667
+ * @private
668
+ * @internal
669
+ * @param {string} coalescingKey - The coalescing key
670
+ * @param {number} now - Current timestamp
671
+ * @param {number} windowEnd - End of new task's coalescing window
672
+ * @param {number} mustRunBy - New task's mustRunBy deadline
673
+ * @returns {Object|null} Compatible coalescing group or null
674
+ */
675
+ _findCompatibleCoalescingGroup(coalescingKey, now) {
676
+ const groups = this.coalescingGroups.get(coalescingKey);
677
+ if (!groups) return null;
678
+
679
+ // Find a group that is within both coalescing window and mustRunBy deadline
680
+ for (const group of groups) {
681
+ if (now <= group.windowEnd && now <= group.mustRunBy) {
682
+ return group;
683
+ }
684
+ }
685
+
686
+ return null;
687
+ }
688
+
689
+ /**
690
+ * Creates a new coalescing group with a representative task in the main queue.
691
+ * @private
692
+ * @internal
693
+ * @param {string} coalescingKey - The coalescing key
694
+ * @param {Object} taskItem - The first task item for this group
695
+ * @param {number} windowEnd - End of coalescing window
696
+ * @param {number} mustRunBy - Latest execution deadline
697
+ * @param {boolean} multipleCallbacks - Whether to call multiple callbacks
698
+ * @param {boolean} resolveAllPromises - Whether to resolve all promises with same result
699
+ * @returns {Object} The created coalescing group
700
+ */
701
+ _createCoalescingGroup(coalescingKey, taskItem, windowEnd, mustRunBy, multipleCallbacks, resolveAllPromises) {
702
+ const representativeId = String(this.nextId++);
703
+ const groupId = String(this.nextGroupId++);
704
+
705
+ // Create representative task that will actually run
706
+ const representative = {
707
+ id: representativeId,
708
+ task: this._createCoalescingRepresentativeTask(coalescingKey, groupId),
709
+ callback: null, // Representative handles its own completion
710
+ priority: taskItem.priority,
711
+ readyAt: taskItem.readyAt,
712
+ expireAt: null, // Use mustRunBy logic instead
713
+ enqueueSeq: this.enqueueSeq++,
714
+ status: "pending",
715
+ signal: null, // Individual tasks handle their own signals
716
+ timeout: taskItem.timeout,
717
+ delay: taskItem.delay || 0,
718
+ bypassDelay: taskItem.bypassDelay || false,
719
+ metadata: { coalescingKey, groupId, representative: true },
720
+ isCoalescingRepresentative: true
721
+ };
722
+
723
+ // Create coalescing group
724
+ const group = {
725
+ coalescingKey,
726
+ groupId,
727
+ tasks: new Map([[taskItem.id, taskItem]]),
728
+ representativeId,
729
+ windowEnd,
730
+ mustRunBy,
731
+ multipleCallbacks,
732
+ resolveAllPromises,
733
+ latestTask: taskItem,
734
+ originalTask: taskItem.task // Store the actual task function
735
+ };
736
+
737
+ // Store group and representative mapping
738
+ if (!this.coalescingGroups.has(coalescingKey)) {
739
+ this.coalescingGroups.set(coalescingKey, []);
740
+ }
741
+ this.coalescingGroups.get(coalescingKey).push(group);
742
+ this.coalescingRepresentatives.set(representativeId, { coalescingKey, groupId });
743
+
744
+ // Add representative to main queue
745
+ this.tasks.set(representativeId, representative);
746
+ this.pendingHeap.push(representative);
747
+
748
+ if (this.isActive) {
749
+ if (this.options.smartScheduling) {
750
+ this.scheduleSmartTimeout();
751
+ } else {
752
+ this._scheduleNextTick();
753
+ }
754
+ }
755
+ return group;
756
+ }
757
+
758
+ /**
759
+ * Adds a task to an existing coalescing group, updating the representative if needed.
760
+ * @private
761
+ * @internal
762
+ * @param {Object} group - The existing coalescing group
763
+ * @param {Object} taskItem - The new task item to add
764
+ * @param {number} windowEnd - End of coalescing window
765
+ * @param {number} mustRunBy - Latest execution deadline
766
+ * @param {number} now - Current timestamp
767
+ * @returns {void}
768
+ */
769
+ _addToCoalescingGroup(group, taskItem, windowEnd, mustRunBy) {
770
+ // Add task to group
771
+ group.tasks.set(taskItem.id, taskItem);
772
+
773
+ // Update group timing - keep original window but preserve earliest mustRunBy
774
+ // NOTE: Don't extend windowEnd - coalescing window should be fixed from first task
775
+ group.mustRunBy = Math.min(group.mustRunBy, mustRunBy);
776
+
777
+ // Update latest task (this will be the task function that actually runs)
778
+ group.latestTask = taskItem;
779
+ group.originalTask = taskItem.task;
780
+
781
+ // Update representative task in queue if needed
782
+ const representative = this.tasks.get(group.representativeId);
783
+ if (representative) {
784
+ // Update timing - use latest task's timing
785
+ representative.readyAt = taskItem.readyAt;
786
+ representative.priority = taskItem.priority;
787
+ representative.timeout = taskItem.timeout;
788
+ representative.delay = taskItem.delay || representative.delay;
789
+ representative.bypassDelay = taskItem.bypassDelay || representative.bypassDelay;
790
+
791
+ // Rebuild heaps to reflect updated representative
792
+ this._rebuildHeaps();
793
+
794
+ if (this.isActive) {
795
+ if (this.options.smartScheduling) {
796
+ this.scheduleSmartTimeout();
797
+ } else {
798
+ this._scheduleNextTick();
799
+ }
800
+ }
801
+ }
802
+ }
803
+
804
+ /**
805
+ * Creates the representative task function that manages coalesced task execution.
806
+ * @private
807
+ * @internal
808
+ * @param {string} coalescingKey - The coalescing key
809
+ * @param {string} groupId - The group ID
810
+ * @returns {Function} The representative task function
811
+ */
812
+ _createCoalescingRepresentativeTask(coalescingKey, groupId) {
813
+ return async (signal) => {
814
+ const groups = this.coalescingGroups.get(coalescingKey);
815
+ const group = groups?.find((g) => g.groupId === groupId);
816
+
817
+ if (!group) {
818
+ throw new Error(`Coalescing group ${coalescingKey}:${groupId} not found`);
819
+ }
820
+
821
+ try {
822
+ // Execute the actual task (using latest task's function)
823
+ const result = await group.originalTask(signal);
824
+
825
+ // Handle callbacks/promises
826
+ this._resolveCoalescingGroup(group, null, result);
827
+
828
+ return result;
829
+ } catch (error) {
830
+ // Handle errors for all tasks in group
831
+ this._resolveCoalescingGroup(group, error, null);
832
+ throw error;
833
+ } finally {
834
+ // Clean up coalescing group
835
+ this._cleanupCoalescingGroup(coalescingKey, groupId);
836
+ }
837
+ };
838
+ }
839
+
840
+ /**
841
+ * Resolves all callbacks/promises in a coalescing group.
842
+ * @private
843
+ * @internal
844
+ * @param {Object} group - The coalescing group
845
+ * @param {Error|null} error - Error if task failed
846
+ * @param {*} result - Result if task succeeded
847
+ * @returns {void}
848
+ */
849
+ _resolveCoalescingGroup(group, error, result) {
850
+ if (group.multipleCallbacks) {
851
+ // Multiple callback mode - resolve all non-canceled tasks
852
+ for (const taskItem of group.tasks.values()) {
853
+ if (taskItem.status === "canceled") continue;
854
+
855
+ taskItem.status = error ? "error" : "completed";
856
+ taskItem.finishedAt = this.now();
857
+
858
+ if (error) {
859
+ taskItem.error = error;
860
+ } else {
861
+ taskItem.result = result;
862
+ }
863
+
864
+ if (taskItem.callback) {
865
+ try {
866
+ if (error) {
867
+ taskItem.callback(error, null);
868
+ } else {
869
+ taskItem.callback(null, result);
870
+ }
871
+ } catch (callbackError) {
872
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
873
+ }
874
+ } else if (taskItem.resolve) {
875
+ if (error) {
876
+ taskItem.reject(error);
877
+ } else {
878
+ taskItem.resolve(result);
879
+ }
880
+ }
881
+ }
882
+
883
+ // Clean up canceled tasks that didn't get resolved
884
+ for (const taskItem of group.tasks.values()) {
885
+ if (taskItem.status === "canceled" && taskItem.reject) {
886
+ taskItem.reject(new Error("Task was canceled"));
887
+ }
888
+ }
889
+ } else {
890
+ // Single callback mode - resolve latest only or all based on resolveAllPromises option
891
+ for (const taskItem of group.tasks.values()) {
892
+ if (taskItem.status === "canceled") continue;
893
+
894
+ if (taskItem === group.latestTask) {
895
+ // Always resolve the latest task
896
+ taskItem.status = error ? "error" : "completed";
897
+ taskItem.finishedAt = this.now();
898
+
899
+ if (error) {
900
+ taskItem.error = error;
901
+ } else {
902
+ taskItem.result = result;
903
+ }
904
+
905
+ if (taskItem.callback) {
906
+ try {
907
+ if (error) {
908
+ taskItem.callback(error, null);
909
+ } else {
910
+ taskItem.callback(null, result);
911
+ }
912
+ } catch (callbackError) {
913
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
914
+ }
915
+ } else if (taskItem.resolve) {
916
+ if (error) {
917
+ taskItem.reject(error);
918
+ } else {
919
+ taskItem.resolve(result);
920
+ }
921
+ }
922
+ } else {
923
+ // Handle other tasks based on resolveAllPromises setting
924
+ if (group.resolveAllPromises) {
925
+ // Resolve with same result as latest task
926
+ taskItem.status = error ? "error" : "coalesced";
927
+ taskItem.finishedAt = this.now();
928
+
929
+ if (error) {
930
+ taskItem.error = error;
931
+ } else {
932
+ taskItem.result = result;
933
+ }
934
+
935
+ if (taskItem.callback) {
936
+ try {
937
+ if (error) {
938
+ taskItem.callback(error, null);
939
+ } else {
940
+ taskItem.callback(null, result);
941
+ }
942
+ } catch (callbackError) {
943
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
944
+ }
945
+ } else if (taskItem.resolve) {
946
+ if (error) {
947
+ taskItem.reject(error);
948
+ } else {
949
+ taskItem.resolve(result);
950
+ }
951
+ }
952
+ } else {
953
+ // Reject other tasks (original behavior)
954
+ taskItem.status = "coalesced";
955
+ taskItem.finishedAt = this.now();
956
+
957
+ if (taskItem.callback) {
958
+ try {
959
+ taskItem.callback(new Error("Task was coalesced with a newer task"), null);
960
+ } catch (callbackError) {
961
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
962
+ }
963
+ } else if (taskItem.reject) {
964
+ taskItem.reject(new Error("Task was coalesced with a newer task"));
965
+ }
966
+ }
967
+ }
968
+ }
969
+
970
+ // Clean up canceled tasks
971
+ for (const taskItem of group.tasks.values()) {
972
+ if (taskItem.status === "canceled" && taskItem.reject) {
973
+ taskItem.reject(new Error("Task was canceled"));
974
+ }
975
+ }
976
+ }
977
+ }
978
+
979
+ /**
980
+ * Cancels a specific task within a coalescing group.
981
+ * @private
982
+ * @internal
983
+ * @param {string} taskId - ID of task to cancel
984
+ * @param {string} coalescingKey - The coalescing key
985
+ * @param {string} reason - Cancellation reason
986
+ * @returns {void}
987
+ */
988
+ _cancelCoalescingTask(taskId, coalescingKey, reason) {
989
+ const groups = this.coalescingGroups.get(coalescingKey) || [];
990
+
991
+ for (const group of groups) {
992
+ const taskItem = group.tasks.get(taskId);
993
+ if (!taskItem) continue;
994
+
995
+ taskItem.status = "canceled";
996
+ taskItem.finishedAt = this.now();
997
+
998
+ // Handle callback/promise
999
+ if (taskItem.callback) {
1000
+ try {
1001
+ taskItem.callback(new Error(reason), null);
1002
+ } catch (callbackError) {
1003
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
1004
+ }
1005
+ } else if (taskItem.reject) {
1006
+ taskItem.reject(new Error(reason));
1007
+ }
1008
+
1009
+ // Remove from group
1010
+ group.tasks.delete(taskId);
1011
+
1012
+ // If group is empty, clean up representative task
1013
+ if (group.tasks.size === 0) {
1014
+ const representative = this.tasks.get(group.representativeId);
1015
+ if (representative) {
1016
+ this.cancel(group.representativeId, "All coalesced tasks canceled");
1017
+ }
1018
+ this._cleanupCoalescingGroup(coalescingKey, group.groupId);
1019
+ } else {
1020
+ // Update latest task if needed
1021
+ const remainingTasks = Array.from(group.tasks.values());
1022
+ group.latestTask = remainingTasks[remainingTasks.length - 1];
1023
+ group.originalTask = group.latestTask.task;
1024
+ }
1025
+
1026
+ return; // Found and handled the task
1027
+ }
1028
+ }
1029
+
1030
+ /**
1031
+ * Cleans up a coalescing group after completion or cancellation.
1032
+ * @private
1033
+ * @internal
1034
+ * @param {string} coalescingKey - The coalescing key
1035
+ * @param {string} groupId - The group ID to clean up
1036
+ * @returns {void}
1037
+ */
1038
+ _cleanupCoalescingGroup(coalescingKey, groupId) {
1039
+ const groups = this.coalescingGroups.get(coalescingKey);
1040
+ if (!groups) return;
1041
+
1042
+ const groupIndex = groups.findIndex((g) => g.groupId === groupId);
1043
+ if (groupIndex >= 0) {
1044
+ const group = groups[groupIndex];
1045
+ groups.splice(groupIndex, 1);
1046
+
1047
+ // Remove representative mapping
1048
+ this.coalescingRepresentatives.delete(group.representativeId);
1049
+
1050
+ // If no more groups for this key, remove the key entirely
1051
+ if (groups.length === 0) {
1052
+ this.coalescingGroups.delete(coalescingKey);
1053
+ }
1054
+ }
1055
+ }
1056
+
1057
+ /**
1058
+ * Rebuilds the heap structures to reflect updated priorities/timing.
1059
+ * @private
1060
+ * @internal
1061
+ * @returns {void}
1062
+ */
1063
+ _rebuildHeaps() {
1064
+ // Rebuild pending heap
1065
+ const pendingTasks = [...this.pendingHeap.heap];
1066
+ this.pendingHeap = new MinHeap((a, b) => a.readyAt - b.readyAt);
1067
+ for (const task of pendingTasks) {
1068
+ this.pendingHeap.push(task);
1069
+ }
1070
+
1071
+ // Rebuild ready heap
1072
+ const readyTasks = [...this.readyHeap.heap];
1073
+ this.readyHeap = new MinHeap((a, b) => {
1074
+ if (a.priority !== b.priority) return b.priority - a.priority;
1075
+ if (a.readyAt !== b.readyAt) return a.readyAt - b.readyAt;
1076
+ return a.enqueueSeq - b.enqueueSeq;
1077
+ });
1078
+ for (const task of readyTasks) {
1079
+ this.readyHeap.push(task);
1080
+ }
1081
+ }
1082
+
1083
+ /**
1084
+ * Creates a task handle for both regular and coalescing tasks.
1085
+ * @private
1086
+ * @internal
1087
+ * @param {Object} item - The task item
1088
+ * @param {Function|null} callback - Callback function
1089
+ * @returns {Promise|Object} Promise or task control object
1090
+ */
1091
+ _createTaskHandle(item, callback) {
1092
+ const taskHandle = {
1093
+ id: item.id,
1094
+ cancel: (reason) => {
1095
+ if (item.coalescingKey) {
1096
+ this._cancelCoalescingTask(item.id, item.coalescingKey, reason || "Task canceled");
1097
+ } else {
1098
+ this.cancel(item.id, reason || "Task canceled");
1099
+ }
1100
+ },
1101
+ status: () => item.status,
1102
+ get startedAt() {
1103
+ return item.startedAt;
1104
+ },
1105
+ get finishedAt() {
1106
+ return item.finishedAt;
1107
+ },
1108
+ get result() {
1109
+ return item.result;
1110
+ },
1111
+ get error() {
1112
+ return item.error;
1113
+ }
1114
+ };
1115
+
1116
+ // Return Promise if no callback provided
1117
+ if (!callback) {
1118
+ const promise = new Promise((resolve, reject) => {
1119
+ item.resolve = resolve;
1120
+ item.reject = reject;
1121
+ });
1122
+
1123
+ // Store promise reference on item so we can update properties when task completes
1124
+ item.promise = promise;
1125
+
1126
+ // Attach task handle properties to the promise
1127
+ Object.defineProperty(promise, "id", { value: item.id, enumerable: true });
1128
+ Object.defineProperty(promise, "cancel", { value: taskHandle.cancel, enumerable: true });
1129
+ Object.defineProperty(promise, "status", { value: taskHandle.status, enumerable: true });
1130
+ Object.defineProperty(promise, "startedAt", {
1131
+ get: () => (promise._startedAt !== undefined ? promise._startedAt : item.startedAt),
1132
+ enumerable: true
1133
+ });
1134
+ Object.defineProperty(promise, "finishedAt", {
1135
+ get: () => (promise._finishedAt !== undefined ? promise._finishedAt : item.finishedAt),
1136
+ enumerable: true
1137
+ });
1138
+ Object.defineProperty(promise, "result", {
1139
+ get: () => (promise._result !== undefined ? promise._result : item.result),
1140
+ enumerable: true
1141
+ });
1142
+ Object.defineProperty(promise, "error", {
1143
+ get: () => (promise._error !== undefined ? promise._error : item.error),
1144
+ enumerable: true
1145
+ });
236
1146
 
237
1147
  return promise;
238
1148
  }
@@ -244,14 +1154,14 @@ export class HoldMyTask extends EventEmitter {
244
1154
  * Cancels a pending task by ID.
245
1155
  * @param {string} id - The task ID to cancel
246
1156
  * @param {string} [reason="Task canceled"] - Reason for cancellation
247
- * @returns {void}
1157
+ * @returns {boolean} True if task was found and cancelled, false otherwise
248
1158
  * @example
249
1159
  * const task = queue.enqueue(() => longRunningTask());
250
- * queue.cancelTask(task.id, "User requested cancellation");
1160
+ * const cancelled = queue.cancel(task.id, "User requested cancellation");
251
1161
  */
252
- cancelTask(id, reason) {
1162
+ cancel(id, reason) {
253
1163
  const item = this.tasks.get(id);
254
- if (!item || item.status !== "pending") return;
1164
+ if (!item || item.status !== "pending") return false;
255
1165
 
256
1166
  item.status = "canceled";
257
1167
  item.finishedAt = this.now();
@@ -262,6 +1172,18 @@ export class HoldMyTask extends EventEmitter {
262
1172
  if (!item.callback && item.reject) {
263
1173
  item.reject(new Error(reason || "Task canceled"));
264
1174
  }
1175
+
1176
+ return true;
1177
+ }
1178
+
1179
+ /**
1180
+ * Alias for cancel() method for backward compatibility.
1181
+ * @param {string|number} id - The task ID to cancel
1182
+ * @param {string} [reason="Task canceled"] - Reason for cancellation
1183
+ * @returns {boolean} True if task was found and cancelled, false otherwise
1184
+ */
1185
+ cancelTask(id, reason) {
1186
+ return this.cancel(id, reason);
265
1187
  }
266
1188
 
267
1189
  /**
@@ -308,7 +1230,7 @@ export class HoldMyTask extends EventEmitter {
308
1230
  if (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0) {
309
1231
  this.schedulerTick();
310
1232
  }
311
- this.scheduleNextTick();
1233
+ this._scheduleNextTick();
312
1234
  }
313
1235
  }
314
1236
 
@@ -334,6 +1256,24 @@ export class HoldMyTask extends EventEmitter {
334
1256
  this.emit("cancel", item);
335
1257
  }
336
1258
 
1259
+ // Clear coalescing groups
1260
+ for (const [_, groups] of this.coalescingGroups) {
1261
+ for (const group of groups) {
1262
+ for (const taskItem of group.tasks.values()) {
1263
+ taskItem.status = "canceled";
1264
+ if (taskItem.callback) {
1265
+ try {
1266
+ taskItem.callback(new Error("Queue cleared"), null);
1267
+ } catch (callbackError) {
1268
+ this.emit("error", { ...taskItem, error: callbackError, callbackError: true });
1269
+ }
1270
+ } else if (taskItem.reject) {
1271
+ taskItem.reject(new Error("Queue cleared"));
1272
+ }
1273
+ }
1274
+ }
1275
+ }
1276
+
337
1277
  this.pendingHeap = new MinHeap((a, b) => a.readyAt - b.readyAt);
338
1278
  this.readyHeap = new MinHeap((a, b) => {
339
1279
  if (a.priority !== b.priority) return b.priority - a.priority;
@@ -341,6 +1281,8 @@ export class HoldMyTask extends EventEmitter {
341
1281
  return a.enqueueSeq - b.enqueueSeq;
342
1282
  });
343
1283
  this.tasks.clear();
1284
+ this.coalescingGroups.clear();
1285
+ this.coalescingRepresentatives.clear();
344
1286
 
345
1287
  // Reschedule since we may have no work
346
1288
  if (this.isActive) {
@@ -411,8 +1353,9 @@ export class HoldMyTask extends EventEmitter {
411
1353
  * Schedules the next scheduler tick based on when tasks become ready.
412
1354
  * @returns {void}
413
1355
  * @private
1356
+ * @internal
414
1357
  */
415
- scheduleNextTick() {
1358
+ _scheduleNextTick() {
416
1359
  if (!this.isActive || this.destroyed) return;
417
1360
 
418
1361
  this.clearTimers();
@@ -456,7 +1399,7 @@ export class HoldMyTask extends EventEmitter {
456
1399
  if (task && task.status === "pending") {
457
1400
  // Check if task has expired before making it ready
458
1401
  if (task.expireAt && now >= task.expireAt) {
459
- this.expireTask(task);
1402
+ this._expireTask(task);
460
1403
  } else {
461
1404
  task.status = "ready";
462
1405
  this.readyHeap.push(task);
@@ -468,7 +1411,7 @@ export class HoldMyTask extends EventEmitter {
468
1411
  // Start tasks up to concurrency limit
469
1412
  let hasWaitingTasks = false;
470
1413
  const currentTime = this.now();
471
- const delay = this.lastCompletedPriority !== null ? this.options.delays[this.lastCompletedPriority] || 0 : 0;
1414
+ const delay = this.lastCompletedPriority !== null ? (this.options.priorities[this.lastCompletedPriority]?.postDelay ?? 0) : 0;
472
1415
  const delayActive = delay > 0 && currentTime < this.nextAvailableTime;
473
1416
 
474
1417
  while (this.running.size < this.options.concurrency && this.readyHeap.size() > 0) {
@@ -478,7 +1421,7 @@ export class HoldMyTask extends EventEmitter {
478
1421
  // Check if task has expired before starting it
479
1422
  if (task.expireAt && currentTime >= task.expireAt) {
480
1423
  this.readyHeap.pop(); // Remove expired task from heap
481
- this.expireTask(task);
1424
+ this._expireTask(task);
482
1425
  continue; // Check next task
483
1426
  }
484
1427
 
@@ -486,7 +1429,7 @@ export class HoldMyTask extends EventEmitter {
486
1429
 
487
1430
  if (canStart) {
488
1431
  this.readyHeap.pop(); // Remove it from heap
489
- this.startTask(task);
1432
+ this._startTask(task);
490
1433
  } else {
491
1434
  // Can't start due to delay - check if there are any bypass tasks in the heap
492
1435
  const heapArray = this.readyHeap.heap.slice(); // Copy heap array
@@ -503,7 +1446,7 @@ export class HoldMyTask extends EventEmitter {
503
1446
  for (const t of remainingTasks) {
504
1447
  this.readyHeap.push(t);
505
1448
  }
506
- this.expireTask(bypassTask);
1449
+ this._expireTask(bypassTask);
507
1450
  // Update heapArray for next iteration
508
1451
  heapArray.splice(i, 1);
509
1452
  i--; // Adjust index since we removed an item
@@ -519,7 +1462,7 @@ export class HoldMyTask extends EventEmitter {
519
1462
  for (const t of remainingTasks) {
520
1463
  this.readyHeap.push(t);
521
1464
  }
522
- this.startTask(bypassTask);
1465
+ this._startTask(bypassTask);
523
1466
  break;
524
1467
  }
525
1468
  }
@@ -535,7 +1478,7 @@ export class HoldMyTask extends EventEmitter {
535
1478
  // Schedule next tick if there are pending tasks or tasks that might become available
536
1479
  // Note: For smart scheduling, this is handled by runScheduler calling scheduleSmartTimeout
537
1480
  if (!this.options.smartScheduling && (this.pendingHeap.size() > 0 || this.readyHeap.size() > 0 || hasWaitingTasks)) {
538
- this.scheduleNextTick();
1481
+ this._scheduleNextTick();
539
1482
  }
540
1483
  }
541
1484
 
@@ -544,8 +1487,9 @@ export class HoldMyTask extends EventEmitter {
544
1487
  * @param {Object} item - The expired task item
545
1488
  * @returns {void}
546
1489
  * @private
1490
+ * @internal
547
1491
  */
548
- expireTask(item) {
1492
+ _expireTask(item) {
549
1493
  if (item.status === "expired" || item.status === "canceled" || item.status === "completed") {
550
1494
  return; // Already handled
551
1495
  }
@@ -578,8 +1522,9 @@ export class HoldMyTask extends EventEmitter {
578
1522
  * @param {Object} item - The task item to execute
579
1523
  * @returns {Promise<void>}
580
1524
  * @private
1525
+ * @internal
581
1526
  */
582
- async startTask(item) {
1527
+ async _startTask(item) {
583
1528
  if (item.status !== "ready") return;
584
1529
 
585
1530
  // For promise API, check if signal is already aborted
@@ -625,6 +1570,16 @@ export class HoldMyTask extends EventEmitter {
625
1570
 
626
1571
  this.emit("success", item);
627
1572
 
1573
+ // Store final values on promise handle before resolving (for promise API)
1574
+ if (item.promise) {
1575
+ // Store final values so getters can access them after task deletion
1576
+ item.promise._result = item.result;
1577
+ item.promise._error = item.error;
1578
+ item.promise._startedAt = item.startedAt;
1579
+ item.promise._finishedAt = item.finishedAt;
1580
+ item.promise._status = item.status;
1581
+ }
1582
+
628
1583
  // Call completion callback or resolve promise
629
1584
  if (item.callback) {
630
1585
  try {
@@ -650,6 +1605,16 @@ export class HoldMyTask extends EventEmitter {
650
1605
  this.emit("error", item);
651
1606
  }
652
1607
 
1608
+ // Store final values on promise handle before rejecting (for promise API)
1609
+ if (item.promise) {
1610
+ // Store final values so getters can access them after task deletion
1611
+ item.promise._result = item.result;
1612
+ item.promise._error = item.error;
1613
+ item.promise._startedAt = item.startedAt;
1614
+ item.promise._finishedAt = item.finishedAt;
1615
+ item.promise._status = item.status;
1616
+ }
1617
+
653
1618
  // Call completion callback or reject promise
654
1619
  if (item.callback) {
655
1620
  try {
@@ -674,15 +1639,15 @@ export class HoldMyTask extends EventEmitter {
674
1639
  }
675
1640
 
676
1641
  this.running.delete(item);
677
- if (item.status !== "completed") {
678
- this.tasks.delete(item.id); // Clean up failed/canceled tasks
679
- }
1642
+
1643
+ // Clean up all finished tasks (completed, failed, canceled)
1644
+ this.tasks.delete(item.id);
680
1645
 
681
1646
  // Update delay tracking after task completion
682
1647
  const completedPriority = item.priority;
683
1648
  const taskDelay = item.delay;
684
- const globalDelay = this.options.delays[completedPriority] || 0;
685
- const delay = taskDelay !== undefined ? taskDelay : globalDelay;
1649
+ const priorityDelay = this.options.priorities[completedPriority]?.postDelay ?? 0;
1650
+ const delay = taskDelay !== undefined ? taskDelay : priorityDelay;
686
1651
  if (delay > 0) {
687
1652
  this.lastCompletedPriority = completedPriority;
688
1653
  this.nextAvailableTime = this.now() + delay;
@@ -747,7 +1712,7 @@ export class HoldMyTask extends EventEmitter {
747
1712
 
748
1713
  // Check if we have ready tasks that can run immediately
749
1714
  if (this.readyHeap.size() > 0 && this.running.size < this.options.concurrency) {
750
- const delay = this.lastCompletedPriority !== null ? this.options.delays[this.lastCompletedPriority] || 0 : 0;
1715
+ const delay = this.lastCompletedPriority !== null ? (this.options.priorities[this.lastCompletedPriority]?.postDelay ?? 0) : 0;
751
1716
  const delayActive = delay > 0 && now < this.nextAvailableTime;
752
1717
 
753
1718
  if (!delayActive) {
@@ -857,4 +1822,304 @@ export class HoldMyTask extends EventEmitter {
857
1822
  this.healingInterval = null;
858
1823
  }
859
1824
  }
1825
+
1826
+ /**
1827
+ * Configure coalescing settings for specific keys dynamically.
1828
+ * @param {string} coalescingKey - The coalescing key to configure
1829
+ * @param {Object} config - Configuration for this key
1830
+ * @param {number} [config.windowDuration] - Window duration in milliseconds for this key
1831
+ * @param {number} [config.maxDelay] - Maximum delay in milliseconds for this key
1832
+ * @param {number} [config.postDelay] - Post-completion delay in milliseconds for this key
1833
+ * @param {number} [config.startDelay] - Pre-execution delay in milliseconds for this key
1834
+ * @param {number} [config.delay] - DEPRECATED: Use postDelay instead
1835
+ * @param {number} [config.start] - DEPRECATED: Use startDelay instead
1836
+ * @param {boolean} [config.multipleCallbacks] - Whether to call multiple callbacks for this key
1837
+ * @param {boolean} [config.resolveAllPromises] - Whether to resolve all promises for this key
1838
+ * @returns {void}
1839
+ *
1840
+ * @example
1841
+ * // Configure specific keys after queue creation
1842
+ * queue.configureCoalescingKey('ui.update', {
1843
+ * windowDuration: 100,
1844
+ * maxDelay: 500,
1845
+ * postDelay: 25,
1846
+ * startDelay: 0
1847
+ * });
1848
+ *
1849
+ * queue.configureCoalescingKey('api.batch', {
1850
+ * windowDuration: 1000,
1851
+ * maxDelay: 5000,
1852
+ * postDelay: 100,
1853
+ * startDelay: 200,
1854
+ * resolveAllPromises: false
1855
+ * });
1856
+ */
1857
+ configureCoalescingKey(coalescingKey, config) {
1858
+ if (typeof coalescingKey !== "string") {
1859
+ const error = new Error("coalescingKey must be a string");
1860
+ setImmediate(() => this.emit("error", { error, method: "configureCoalescingKey", coalescingKey, config }));
1861
+ return;
1862
+ }
1863
+ if (typeof config !== "object" || config === null) {
1864
+ const error = new Error("config must be an object");
1865
+ setImmediate(() => this.emit("error", { error, method: "configureCoalescingKey", coalescingKey, config }));
1866
+ return;
1867
+ }
1868
+
1869
+ // Validate configuration options (accept both old and new property names)
1870
+ const validKeys = [
1871
+ "windowDuration",
1872
+ "maxDelay",
1873
+ "delay",
1874
+ "start",
1875
+ "postDelay",
1876
+ "startDelay",
1877
+ "multipleCallbacks",
1878
+ "resolveAllPromises"
1879
+ ];
1880
+ const invalidKeys = Object.keys(config).filter((key) => !validKeys.includes(key));
1881
+ if (invalidKeys.length > 0) {
1882
+ const error = new Error(`Invalid config keys: ${invalidKeys.join(", ")}. Valid keys: ${validKeys.join(", ")}`);
1883
+ setImmediate(() => this.emit("error", { error, method: "configureCoalescingKey", coalescingKey, config, invalidKeys }));
1884
+ return;
1885
+ }
1886
+
1887
+ // Transform old property names to new ones for backwards compatibility
1888
+ const transformedConfig = HoldMyTask._transformDelayProperties(config, this);
1889
+
1890
+ // Merge with existing configuration for this key
1891
+ this.options.coalescing.keys[coalescingKey] = {
1892
+ ...this.options.coalescing.keys[coalescingKey],
1893
+ ...transformedConfig
1894
+ };
1895
+ }
1896
+
1897
+ /**
1898
+ * Get the effective coalescing configuration for a specific key.
1899
+ * @param {string} coalescingKey - The coalescing key to get configuration for
1900
+ * @param {Object} [taskOptions={}] - Task-level options that may override key configuration
1901
+ * @returns {Object} The effective configuration for this key
1902
+ *
1903
+ * @example
1904
+ * // Get effective configuration for a key
1905
+ * const config = queue.getCoalescingConfig('ui.update');
1906
+ * console.log(`UI updates coalesce within ${config.windowDuration}ms with ${config.postDelay}ms post-completion delay`);
1907
+ *
1908
+ * // Check with task-level overrides
1909
+ * const effectiveConfig = queue.getCoalescingConfig('ui.update', {
1910
+ * coalescingWindowDuration: 50,
1911
+ * delay: 30 // Still accepts old property names for backwards compatibility
1912
+ * });
1913
+ */
1914
+ getCoalescingConfig(coalescingKey, taskOptions = {}) {
1915
+ const keyConfig = (this.options.coalescing.keys && this.options.coalescing.keys[coalescingKey]) || {};
1916
+ const defaults = this.options.coalescing.defaults;
1917
+ const priorityConfig = this.getPriorityConfig(taskOptions.priority ?? this.options.defaultPriority);
1918
+
1919
+ const postDelay = taskOptions.delay ?? keyConfig.postDelay ?? priorityConfig.postDelay ?? defaults.postDelay;
1920
+ const startDelay = taskOptions.start ?? keyConfig.startDelay ?? priorityConfig.startDelay ?? defaults.startDelay;
1921
+
1922
+ return {
1923
+ windowDuration: taskOptions.coalescingWindowDuration ?? keyConfig.windowDuration ?? defaults.windowDuration,
1924
+ maxDelay: taskOptions.coalescingMaxDelay ?? keyConfig.maxDelay ?? defaults.maxDelay,
1925
+ // New clear property names
1926
+ postDelay,
1927
+ startDelay,
1928
+ // Old property names for backwards compatibility
1929
+ delay: postDelay,
1930
+ start: startDelay,
1931
+ multipleCallbacks: taskOptions.coalescingMultipleCallbacks ?? keyConfig.multipleCallbacks ?? defaults.multipleCallbacks,
1932
+ resolveAllPromises: taskOptions.coalescingResolveAllPromises ?? keyConfig.resolveAllPromises ?? defaults.resolveAllPromises
1933
+ };
1934
+ }
1935
+
1936
+ /**
1937
+ * Get all configured coalescing keys and their configurations.
1938
+ * @returns {Object} Map of coalescingKey to configuration
1939
+ *
1940
+ * @example
1941
+ * // See all configured coalescing keys
1942
+ * const allConfigs = queue.getCoalescingConfigurations();
1943
+ * Object.entries(allConfigs).forEach(([key, config]) => {
1944
+ * console.log(`${key}: ${config.windowDuration}ms window, ${config.maxDelay}ms max delay, ${config.postDelay}ms post-completion delay, ${config.startDelay}ms pre-execution delay`);
1945
+ * });
1946
+ */
1947
+ getCoalescingConfigurations() {
1948
+ const result = {};
1949
+ for (const key of Object.keys(this.options.coalescing.keys)) {
1950
+ result[key] = this.getCoalescingConfig(key);
1951
+ }
1952
+ return result;
1953
+ }
1954
+
1955
+ /**
1956
+ * Configure default settings for specific priorities dynamically.
1957
+ * @param {number} priority - The priority level to configure
1958
+ * @param {Object} config - Configuration for this priority
1959
+ * @param {number} [config.postDelay] - Default post-completion delay in milliseconds for this priority
1960
+ * @param {number} [config.startDelay] - Default pre-execution delay in milliseconds for this priority
1961
+ * @param {number} [config.delay] - DEPRECATED: Use postDelay instead
1962
+ * @param {number} [config.start] - DEPRECATED: Use startDelay instead
1963
+ * @returns {void}
1964
+ *
1965
+ * @example
1966
+ * // Configure priority defaults after queue creation
1967
+ * queue.configurePriority(1, {
1968
+ * postDelay: 100, // High priority tasks have 100ms delay after completion
1969
+ * startDelay: 0 // High priority tasks start immediately
1970
+ * });
1971
+ *
1972
+ * queue.configurePriority(3, {
1973
+ * postDelay: 0, // Low priority tasks have no delay after completion
1974
+ * startDelay: 200 // Low priority tasks wait 200ms before starting
1975
+ * });
1976
+ */
1977
+ configurePriority(priority, config) {
1978
+ if (typeof priority !== "number") {
1979
+ const error = new Error("priority must be a number");
1980
+ setImmediate(() => this.emit("error", { error, method: "configurePriority", priority, config }));
1981
+ return;
1982
+ }
1983
+ if (typeof config !== "object" || config === null) {
1984
+ const error = new Error("config must be an object");
1985
+ setImmediate(() => this.emit("error", { error, method: "configurePriority", priority, config }));
1986
+ return;
1987
+ }
1988
+
1989
+ // Validate configuration options (accept both old and new property names)
1990
+ const validKeys = ["delay", "start", "postDelay", "startDelay"];
1991
+ const invalidKeys = Object.keys(config).filter((key) => !validKeys.includes(key));
1992
+ if (invalidKeys.length > 0) {
1993
+ const error = new Error(`Invalid config keys: ${invalidKeys.join(", ")}. Valid keys: ${validKeys.join(", ")}`);
1994
+ setImmediate(() => this.emit("error", { error, method: "configurePriority", priority, config, invalidKeys }));
1995
+ return;
1996
+ }
1997
+
1998
+ // Transform old property names to new ones for backwards compatibility
1999
+ const transformedConfig = HoldMyTask._transformDelayProperties(config, this);
2000
+
2001
+ // Merge with existing configuration for this priority
2002
+ this.options.priorities[priority] = {
2003
+ ...this.options.priorities[priority],
2004
+ ...transformedConfig
2005
+ };
2006
+ }
2007
+
2008
+ /**
2009
+ * Get the effective configuration for a specific priority.
2010
+ * @param {number} priority - The priority level to get configuration for
2011
+ * @param {Object} [taskOptions={}] - Task-level options that may override priority configuration
2012
+ * @returns {Object} The effective configuration for this priority
2013
+ *
2014
+ * @example
2015
+ * // Get effective configuration for a priority
2016
+ * const config = queue.getPriorityConfig(1);
2017
+ * console.log(`Priority 1 tasks: ${config.delay}ms delay, ${config.start}ms start delay`);
2018
+ *
2019
+ * // Check with task-level overrides
2020
+ * const effectiveConfig = queue.getPriorityConfig(1, {
2021
+ * delay: 50,
2022
+ * start: 10
2023
+ * });
2024
+ */
2025
+ getPriorityConfig(priority, taskOptions = {}) {
2026
+ const priorityConfig = this.options.priorities[priority] || {};
2027
+
2028
+ const postDelay = taskOptions.delay ?? priorityConfig.postDelay;
2029
+ const startDelay = taskOptions.start ?? priorityConfig.startDelay;
2030
+
2031
+ return {
2032
+ // New clear property names
2033
+ postDelay,
2034
+ startDelay,
2035
+ // Old property names for backwards compatibility
2036
+ delay: postDelay,
2037
+ start: startDelay
2038
+ };
2039
+ }
2040
+
2041
+ /**
2042
+ * Get all configured priorities and their configurations.
2043
+ * @returns {Object} Map of priority to configuration
2044
+ *
2045
+ * @example
2046
+ * // See all configured priorities
2047
+ * const allConfigs = queue.getPriorityConfigurations();
2048
+ * Object.entries(allConfigs).forEach(([priority, config]) => {
2049
+ * console.log(`Priority ${priority}: ${config.delay}ms delay, ${config.start}ms start delay`);
2050
+ * });
2051
+ */
2052
+ getPriorityConfigurations() {
2053
+ const result = {};
2054
+ for (const priority of Object.keys(this.options.priorities)) {
2055
+ result[priority] = this.getPriorityConfig(parseInt(priority));
2056
+ }
2057
+ return result;
2058
+ }
2059
+
2060
+ /**
2061
+ * Alias for destroy() method for common queue system naming.
2062
+ * @returns {void}
2063
+ */
2064
+ shutdown() {
2065
+ return this.destroy();
2066
+ }
2067
+
2068
+ /**
2069
+ * Alias for enqueue() method for common queue system naming.
2070
+ * @param {Function} task - The task function to execute
2071
+ * @param {Function|Object} optionsOrCallback - Callback function or options object
2072
+ * @param {Object} options - Task options (if callback provided as second parameter)
2073
+ * @returns {Promise|TaskHandle} Promise if no callback provided, TaskHandle otherwise
2074
+ */
2075
+ schedule(task, optionsOrCallback, options = {}) {
2076
+ return this.enqueue(task, optionsOrCallback, options);
2077
+ }
2078
+
2079
+ /**
2080
+ * Alias for enqueue() method for common queue system naming.
2081
+ * @param {Function} task - The task function to execute
2082
+ * @param {Function|Object} optionsOrCallback - Callback function or options object
2083
+ * @param {Object} options - Task options (if callback provided as second parameter)
2084
+ * @returns {Promise|TaskHandle} Promise if no callback provided, TaskHandle otherwise
2085
+ */
2086
+ add(task, optionsOrCallback, options = {}) {
2087
+ return this.enqueue(task, optionsOrCallback, options);
2088
+ }
2089
+
2090
+ /**
2091
+ * Find a task by its ID.
2092
+ * @param {string|number} id - The task ID to find
2093
+ * @returns {Object|null} Task object if found, null otherwise
2094
+ */
2095
+ get(id) {
2096
+ return this.tasks.get(String(id)) || null;
2097
+ }
2098
+
2099
+ /**
2100
+ * Check if a task with the given ID exists.
2101
+ * @param {string|number} id - The task ID to check
2102
+ * @returns {boolean} True if task exists, false otherwise
2103
+ */
2104
+ has(id) {
2105
+ return this.tasks.has(String(id));
2106
+ }
2107
+
2108
+ /**
2109
+ * Alias for get() method for backward compatibility.
2110
+ * @param {string|number} id - The task ID to find
2111
+ * @returns {Object|null} Task object if found, null otherwise
2112
+ */
2113
+ getTask(id) {
2114
+ return this.get(id);
2115
+ }
2116
+
2117
+ /**
2118
+ * Alias for has() method for backward compatibility.
2119
+ * @param {string|number} id - The task ID to check
2120
+ * @returns {boolean} True if task exists, false otherwise
2121
+ */
2122
+ hasTask(id) {
2123
+ return this.has(id);
2124
+ }
860
2125
  }