@cldmv/holdmytask 2.0.6 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,18 +16,18 @@ Use it with callbacks or promises, from ESM or CommonJS, with full TypeScript de
16
16
 
17
17
  ## ✨ What's New
18
18
 
19
- ### Latest: v2.0.6 (October 2026)
19
+ ### Latest: v2.1.0 (November 2026)
20
20
 
21
- - **Development dependencies only** — `eslint` 10.12.0, `globals` 17.13.0, `@cldmv/vitest-runner` 1.5.3 and `@types/node` 26.6.4, all lockfile-only moves. The published package and its supported Node.js range (`>=18.12`) are unchanged (#64, #65, #66).
22
- - **Test runner now declares Node.js 22.12 or newer** — `@cldmv/vitest-runner` 1.5.3 raises its minimum from 20.19 and brings `chalk` 6; the development toolchain already needed 22.12.
23
- - [View full v2.0.6 Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.0.6.md)
21
+ - **Built with tsup from `src/`, with `./main` deprecated** — the entries now live in `src/index.mjs` / `src/index.cjs` and tsup builds them into `dist/`; `dist/index.cjs` is a thin wrapper over the ESM bundle, not a second copy. The `holdmytask-dev` condition now sits on the package root for both `import` and `require()`, and the development-only `devcheck.mjs` is gone. `@cldmv/holdmytask/main` still works but emits a one-time `DeprecationWarning` (`CLDMV_HOLDMYTASK_MAIN`) and will be removed in the next major; import `@cldmv/holdmytask` instead (#81, #89).
22
+ - **Node.js `>=22.22.0` is now required** — up from `>=18.12`. The queue code itself is unchanged, but older Node.js versions are no longer built, tested or supported; stay on v2.0.6 if you can't upgrade.
23
+ - [View full v2.1.0 Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.1.0.md)
24
24
 
25
25
  ### Recent Releases
26
26
 
27
+ - **v2.0.6** (October 2026) — Development dependency updates only (`eslint`, `globals`, `@cldmv/vitest-runner`, `@types/node`); the published package is unchanged ([Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.0.6.md))
27
28
  - **v2.0.5** (October 2026) — Task-level `postDelay` / `startDelay` honored, failing callback tasks no longer crash the process, and header tooling on fix-headers 2.2.0 ([Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.0.5.md))
28
29
  - **v2.0.4** (October 2026) — Clearer `require()` error on Node.js without `require(esm)`; `brace-expansion` security patch in development tooling ([Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.0.4.md))
29
30
  - **v2.0.3** (October 2026) — Development toolchain moves to vitest 5; bundle-size and v4 workflow updates; verbatim Apache-2.0 license text ([Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.0.3.md))
30
- - **v2.0.2** (September 2026) — Development dependency update (`@humanfs/node`); no other changes ([Changelog](https://github.com/CLDMV/holdmytask/blob/master/docs/changelog/v2/v2.0.2.md))
31
31
 
32
32
  📚 **For complete version history and detailed release notes, see the [docs/changelog/](https://github.com/CLDMV/holdmytask/tree/master/docs/changelog/) folder.**
33
33
 
@@ -54,8 +54,8 @@ Use it with callbacks or promises, from ESM or CommonJS, with full TypeScript de
54
54
 
55
55
  ### Requirements
56
56
 
57
- - **Node.js v18.12.0 or higher** for ESM (`import`), as declared in the package's `engines` field
58
- - **CommonJS `require()`** needs Node.js `^20.19.0` or `>=22.12.0`. The CommonJS entry is a thin wrapper that loads the ESM build through Node's synchronous `require(esm)`. On older Node.js versions `require("@cldmv/holdmytask")` throws an `ERR_REQUIRE_ESM` error that names the supported versions; load the package with `import()` instead.
57
+ - **Node.js `>=22.22.0`**, as declared in the package's `engines` field
58
+ - **CommonJS `require()`** uses the same range. The CommonJS entry is a thin wrapper that loads the ESM build through Node's synchronous `require(esm)`. On older Node.js versions `require("@cldmv/holdmytask")` throws an `ERR_REQUIRE_ESM` error that names the supported versions; load the package with `import()` instead.
59
59
 
60
60
  ### Install
61
61
 
@@ -130,7 +130,7 @@ import HoldMyTask from "@cldmv/holdmytask";
130
130
  import * as HoldMyTaskLib from "@cldmv/holdmytask";
131
131
  // Uses optimized distribution files
132
132
 
133
- // CommonJS (Node.js ^20.19.0 or >=22.12.0)
133
+ // CommonJS (Node.js >=22.22.0)
134
134
  const HoldMyTask = require("@cldmv/holdmytask"); // the class itself
135
135
  const { HoldMyTask: Named } = require("@cldmv/holdmytask"); // or by name
136
136
  ```
@@ -161,17 +161,19 @@ The ESM entry also exports async factory helpers that resolve to a new instance:
161
161
  ### Development Source Access
162
162
 
163
163
  ```javascript
164
- import { HoldMyTask } from "@cldmv/holdmytask/main";
165
- // Resolves to dist files by default; resolves to src/ when Node.js runs with the holdmytask-dev condition
164
+ import { HoldMyTask } from "@cldmv/holdmytask";
165
+ // Resolves to the built dist/ files by default; resolves to src/ when Node.js runs with the holdmytask-dev condition
166
166
  ```
167
167
 
168
- To run against the unbuilt source (from a checkout of this repository), start Node.js with the `holdmytask-dev` export condition:
168
+ To run against the unbuilt source (from a checkout of this repository), start Node.js with the `holdmytask-dev` export condition. It applies to both `import` and `require()`:
169
169
 
170
170
  ```bash
171
171
  node --conditions=holdmytask-dev your-script.mjs
172
172
  ```
173
173
 
174
- **Note:** In a checkout of this repository, the root import runs a best-effort development environment check (`devcheck.mjs`) that exits with setup instructions when `src/` is present but the `holdmytask-dev` condition is not set. The check is skipped when the package is installed as a dependency and in CI.
174
+ ### Deprecated `@cldmv/holdmytask/main`
175
+
176
+ `@cldmv/holdmytask/main` still works, but it is deprecated and will be removed in the next major version. It is now an alias of the package root: it exports the same objects as `@cldmv/holdmytask` (its `HoldMyTask` is the same class) and emits a one-time `DeprecationWarning` with the code `CLDMV_HOLDMYTASK_MAIN`. Import `@cldmv/holdmytask` instead.
175
177
 
176
178
  ---
177
179
 
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  *
3
3
  * @Project: @cldmv/holdmytask
4
- * @Filename: /index.cjs
4
+ * @Filename: /src/index.cjs
5
5
  * @Date: 2025-11-08T14:04:10-08:00 (1762639450)
6
6
  * @Author: Nate Corcoran <CLDMV>
7
7
  * @Email: <Shinrai@users.noreply.github.com>
8
8
  * -----
9
9
  * @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
10
- * @Last modified time: 2026-10-02T12:20:28-07:00 (1790968828)
10
+ * @Last modified time: 2026-11-01T13:23:18-08:00 (1793568198)
11
11
  * -----
12
12
  * @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
13
13
  *
@@ -16,8 +16,14 @@
16
16
  /**
17
17
  * CommonJS entry point for holdmytask
18
18
  *
19
- * This file provides CommonJS (require) support for the holdmytask library.
20
- * It imports and re-exports the main HoldMyTask class from the ESM module.
19
+ * A thin, synchronous wrapper around the ESM entry: it loads ./index.mjs through Node's
20
+ * require(esm) and maps it to the historical CommonJS shape (the HoldMyTask class as
21
+ * module.exports, plus the class aliases as properties), instead of bundling a second
22
+ * copy of the library.
23
+ *
24
+ * It sits next to the ESM entry under the same name, so require("./index.mjs") resolves
25
+ * to src/index.mjs from source and to dist/index.mjs once built. tsup's onSuccess copies
26
+ * it verbatim into dist/ (tsup.config.mjs); it never passes through esbuild.
21
27
  *
22
28
  * @module holdmytask
23
29
  */
@@ -28,7 +34,7 @@
28
34
  // early with a message that says what to do instead.
29
35
  if (!process.features?.require_module) {
30
36
  const error = new Error(
31
- `@cldmv/holdmytask: require() needs Node.js ^20.19.0 or >=22.12.0 (this is ${process.version}). On older Node.js, load the package with import() instead.`
37
+ `@cldmv/holdmytask: require() needs Node.js >=22.22.0 (this is ${process.version}). On older Node.js, load the package with import() instead.`
32
38
  );
33
39
  error.code = "ERR_REQUIRE_ESM";
34
40
  throw error;
package/dist/index.mjs ADDED
@@ -0,0 +1,13 @@
1
+ var v=Object.defineProperty;var g=(m,e)=>v(m,"name",{value:e,configurable:!0});import{EventEmitter as w}from"events";var b=class{static{g(this,"MinHeap")}constructor(e){this.heap=[],this.compare=e}push(e){this.heap.push(e),this.bubbleUp(this.heap.length-1)}pop(){if(this.heap.length===0)return;let e=this.heap[0],t=this.heap.pop();return this.heap.length>0&&(this.heap[0]=t,this.sinkDown(0)),e}peek(){return this.heap[0]}size(){return this.heap.length}bubbleUp(e){for(;e>0;){let t=Math.floor((e-1)/2);if(this.compare(this.heap[e],this.heap[t])>=0)break;[this.heap[e],this.heap[t]]=[this.heap[t],this.heap[e]],e=t}}sinkDown(e){let t=this.heap.length;for(;;){let s=2*e+1,i=2*e+2,r=e;if(s<t&&this.compare(this.heap[s],this.heap[r])<0&&(r=s),i<t&&this.compare(this.heap[i],this.heap[r])<0&&(r=i),r===e)break;[this.heap[e],this.heap[r]]=[this.heap[r],this.heap[e]],e=r}}};var T=class m extends w{static{g(this,"HoldMyTask")}static _transformDelayProperties(e,t=null){if(!e||typeof e!="object")return e;let s={...e};return"start"in e&&!("startDelay"in e)&&(s.startDelay=e.start,t&&setImmediate(()=>t.emit("warning",{type:"deprecation",message:"Property 'start' is deprecated. Use 'startDelay' instead.",deprecated:"start",replacement:"startDelay"}))),delete s.start,"delay"in e&&!("postDelay"in e)&&(s.postDelay=e.delay,t&&setImmediate(()=>t.emit("warning",{type:"deprecation",message:"Property 'delay' is deprecated. Use 'postDelay' instead.",deprecated:"delay",replacement:"postDelay"}))),delete s.delay,s}_normalizeTaskDelayOptions(e){if(!("delay"in e)&&!("start"in e))return e;let t={...e},s=[{deprecated:"start",replacement:"startDelay"},{deprecated:"delay",replacement:"postDelay"}];for(let{deprecated:i,replacement:r}of s)i in e&&(r in e||(t[r]=e[i],this._warnTaskOptionDeprecated(i,r)),delete t[i]);return t}_warnTaskOptionDeprecated(e,t){this._warnedTaskOptions.has(e)||(this._warnedTaskOptions.add(e),setImmediate(()=>this.emit("warning",{type:"deprecation",message:`Task option '${e}' is deprecated. Use '${t}' instead.`,deprecated:e,replacement:t})))}constructor(e={}){if(super(),e.sync!==!1)this._initializeSync(e);else return this._initializeAsync(e)}_resolvePriorityKey(e,t){if(/^-?\d+$/.test(e))return Number(e);let s=parseInt(e),i=isNaN(s)?null:s,r=i===null?`Priority key '${e}' in '${t}' is not an integer and was ignored. Priority keys must be integers.`:`Priority key '${e}' in '${t}' is not an integer; it was applied to priority ${i}. Priority keys must be integers.`;return setImmediate(()=>this.emit("warning",{type:"invalid-priority",message:r,option:t,key:e,priority:i})),i}_initializeSync(e){this._syncMode=!0,this._initializeCommon(e)}async _initializeAsync(e){return this._syncMode=!1,new Promise(t=>{setImmediate(()=>{this._initializeCommon(e),t(this)})})}_initializeCommon(e){let t={...e};delete t.sync,delete t.async;let s={windowDuration:t.coalescingWindowDuration??200,maxDelay:t.coalescingMaxDelay??1e3,multipleCallbacks:t.coalescingMultipleCallbacks??!1,resolveAllPromises:t.coalescingResolveAllPromises??!0};[{old:"coalescingWindowDuration",new:"coalescing.defaults.windowDuration"},{old:"coalescingMaxDelay",new:"coalescing.defaults.maxDelay"},{old:"coalescingMultipleCallbacks",new:"coalescing.defaults.multipleCallbacks"},{old:"coalescingResolveAllPromises",new:"coalescing.defaults.resolveAllPromises"}].forEach(({old:d,new:l})=>{t[d]!==void 0&&setImmediate(()=>this.emit("warning",{type:"deprecation",message:`Option '${d}' is deprecated. Use '${l}' instead.`,deprecated:d,replacement:l}))});let r=t.coalescing||{},n=m._transformDelayProperties({...s,...r.defaults},this),a={};if(r.keys&&typeof r.keys=="object")for(let[d,l]of Object.entries(r.keys))l!=null&&(a[d]=m._transformDelayProperties(l,this));let o={};if(t.priorities&&typeof t.priorities=="object")for(let[d,l]of Object.entries(t.priorities)){if(l==null)continue;let c=this._resolvePriorityKey(d,"priorities");c!==null&&(o[c]=m._transformDelayProperties(l,this))}if(t.delays&&typeof t.delays=="object"){setImmediate(()=>this.emit("warning",{type:"deprecation",message:"Option 'delays' is deprecated. Use 'priorities' instead with { [priority]: { postDelay: value, startDelay: 0 } } format.",deprecated:"delays",replacement:"priorities"}));for(let[d,l]of Object.entries(t.delays)){if(l==null)continue;let c=this._resolvePriorityKey(d,"delays");c!==null&&(o[c]={postDelay:l,startDelay:0,...o[c]||{}})}}let p={...t};delete p.priorities,delete p.delays,delete p.coalescing;let h=p.maxQueue;h===-1&&(h=1/0),delete p.maxQueue,this.options={concurrency:1,tick:25,autoStart:!0,defaultPriority:0,maxQueue:h!==void 0?h:1/0,priorities:o,smartScheduling:!0,healingInterval:5e3,coalescing:{defaults:n,keys:a},coalescingWindowDuration:s.windowDuration,coalescingMaxDelay:s.maxDelay,coalescingMultipleCallbacks:s.multipleCallbacks,coalescingResolveAllPromises:s.resolveAllPromises,...p},this.pendingHeap=new b((d,l)=>d.readyAt-l.readyAt),this.readyHeap=new b((d,l)=>d.priority!==l.priority?l.priority-d.priority:d.readyAt!==l.readyAt?d.readyAt-l.readyAt:d.enqueueSeq-l.enqueueSeq),this.running=new Set,this.runningByPriority=new Map,this.tasks=new Map,this.nextId=1,this.enqueueSeq=1,this.isActive=!1,this.destroyed=!1,this.lastCompletedPriority=null,this.nextAvailableTime=0,this.schedulerTimeout=null,this.healingInterval=null,this.lastSchedulerRun=0,this.intervalId=null,this.coalescingGroups=new Map,this.coalescingRepresentatives=new Map,this.nextGroupId=1,this._warnedTaskOptions=new Set,this.options.autoStart&&this.resume()}static async _create(e={}){return new m({...e,sync:!1})}enqueue(e,t,s={}){if(this.destroyed){let u=new Error("Queue is destroyed");return setImmediate(()=>this.emit("error",{error:u,task:e,options:t})),Promise.reject(u)}if(this.tasks.size>=this.options.maxQueue){let u=new Error("Queue is full");return setImmediate(()=>this.emit("error",{error:u,task:e,options:t})),Promise.reject(u)}let i=null,r=s;typeof t=="function"?i=t:t&&typeof t=="object"&&(r={...t,...s}),r=this._normalizeTaskDelayOptions(r);let n=r.id?String(r.id):String(this.nextId++);if(r.id&&this.tasks.has(n)){let u=new Error(`Task with ID '${n}' already exists`);return setImmediate(()=>this.emit("error",{error:u,task:e,options:r})),Promise.reject(u)}let a=this.now();if(r.coalescingKey)return this._handleCoalescingTask(n,e,i,r,a);let o=r.priority??this.options.defaultPriority,h=this.getPriorityConfig(o,r).startDelay??0,d=r.timestamp??(h?a+h:a),l=null;r.expire!==void 0&&(r.expire===-1?l=null:r.expire>a?l=r.expire:l=a+r.expire);let c={id:n,task:e,callback:i,priority:o,readyAt:d,expireAt:l,enqueueSeq:this.enqueueSeq++,status:"pending",signal:r.signal,timeout:r.timeout,delay:r.postDelay,bypassDelay:r.bypassDelay||r.postDelay===-1,metadata:r.metadata};this.tasks.set(n,c),this.pendingHeap.push(c),r.signal?.aborted?this.cancel(n,"Task was aborted"):r.signal&&r.signal.addEventListener("abort",()=>{this.cancel(n,"Task was aborted")}),this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this._scheduleNextTick());let k=this.tasks,f={id:n,cancel:g(u=>this.cancel(n,u),"cancel"),status:g(()=>k.get(n)?.status??"canceled","status"),get startedAt(){return k.get(n)?.startedAt},get finishedAt(){return k.get(n)?.finishedAt},get result(){return k.get(n)?.result},get error(){return k.get(n)?.error},get metadata(){return k.get(n)?.metadata},get coalescingInfo(){return null}};if(!i){let u=new Promise((y,A)=>{c.resolve=y,c.reject=A});return c.promise=u,Object.defineProperty(u,"id",{value:n,enumerable:!0}),Object.defineProperty(u,"cancel",{value:g(y=>this.cancel(n,y),"value"),enumerable:!0}),Object.defineProperty(u,"status",{value:g(()=>{let y=this.tasks.get(n);return y?y.status:u._status??"canceled"},"value"),enumerable:!0}),Object.defineProperty(u,"startedAt",{get:g(()=>{let y=this.tasks.get(n);return y?y.startedAt:u._startedAt},"get"),enumerable:!0}),Object.defineProperty(u,"finishedAt",{get:g(()=>{let y=this.tasks.get(n);return y?y.finishedAt:u._finishedAt},"get"),enumerable:!0}),Object.defineProperty(u,"result",{get:g(()=>{let y=this.tasks.get(n);return y?y.result:u._result},"get"),enumerable:!0}),Object.defineProperty(u,"error",{get:g(()=>{let y=this.tasks.get(n);return y?y.error:u._error},"get"),enumerable:!0}),Object.defineProperty(u,"metadata",{get:g(()=>{let y=this.tasks.get(n);return y?y.metadata:void 0},"get"),enumerable:!0}),Object.defineProperty(u,"coalescingInfo",{get:g(()=>null,"get"),enumerable:!0}),u}return f}_handleCoalescingTask(e,t,s,i,r){let{coalescingKey:n}=i,a=this.getCoalescingConfig(n,i),o=i.priority??this.options.defaultPriority,p=this.getPriorityConfig(o,i),h=i.startDelay??a.startDelay??p.startDelay??0,d=i.timestamp??(h?r+h:r),l=r+a.windowDuration,c=r+a.maxDelay,k=i.postDelay??a.postDelay??p.postDelay,f={id:e,task:t,callback:s,priority:o,readyAt:d,status:"coalescing",signal:i.signal,timeout:i.timeout,delay:k,bypassDelay:i.bypassDelay||i.postDelay===-1,metadata:i.metadata,coalescingKey:n,enqueueSeq:this.enqueueSeq++};if(i.signal?.aborted){if(f.status="canceled",s)try{s(new Error("Task was aborted"),null)}catch(y){this.emit("error",{...f,error:y,callbackError:!0})}return this._createTaskHandle(f,s)}i.signal?.addEventListener("abort",()=>{this._cancelCoalescingTask(e,n,"Task was aborted")});let u=this._findCompatibleCoalescingGroup(n,r);return u?this._addToCoalescingGroup(u,f,l,c):this._createCoalescingGroup(n,f,l,c,a.multipleCallbacks,a.resolveAllPromises),this._createTaskHandle(f,s)}_findCompatibleCoalescingGroup(e,t){let s=this.coalescingGroups.get(e);if(!s)return null;for(let i of s)if(t<=i.windowEnd&&t<=i.mustRunBy)return i;return null}_createCoalescingGroup(e,t,s,i,r,n){let a=String(this.nextId++),o=String(this.nextGroupId++),p={id:a,task:this._createCoalescingRepresentativeTask(e,o),callback:null,priority:t.priority,readyAt:t.readyAt,expireAt:null,enqueueSeq:this.enqueueSeq++,status:"pending",signal:null,timeout:t.timeout,delay:t.delay||0,bypassDelay:t.bypassDelay||!1,metadata:{coalescingKey:e,groupId:o,representative:!0},isCoalescingRepresentative:!0},h={coalescingKey:e,groupId:o,tasks:new Map([[t.id,t]]),representativeId:a,windowEnd:s,mustRunBy:i,multipleCallbacks:r,resolveAllPromises:n,latestTask:t,originalTask:t.task};return this.coalescingGroups.has(e)||this.coalescingGroups.set(e,[]),this.coalescingGroups.get(e).push(h),this.coalescingRepresentatives.set(a,{coalescingKey:e,groupId:o}),this.tasks.set(a,p),this.pendingHeap.push(p),this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this._scheduleNextTick()),h}_addToCoalescingGroup(e,t,s,i){e.tasks.set(t.id,t),e.mustRunBy=Math.min(e.mustRunBy,i),e.latestTask=t,e.originalTask=t.task;let r=this.tasks.get(e.representativeId);r&&(r.readyAt=t.readyAt,r.priority=t.priority,r.timeout=t.timeout,r.delay=t.delay||r.delay,r.bypassDelay=t.bypassDelay||r.bypassDelay,this._rebuildHeaps(),this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this._scheduleNextTick()))}_createCoalescingRepresentativeTask(e,t){return async s=>{let r=this.coalescingGroups.get(e)?.find(n=>n.groupId===t);if(!r)throw new Error(`Coalescing group ${e}:${t} not found`);try{let n=await r.originalTask(s);return this._resolveCoalescingGroup(r,null,n),n}catch(n){throw this._resolveCoalescingGroup(r,n,null),n}finally{this._cleanupCoalescingGroup(e,t)}}}_resolveCoalescingGroup(e,t,s){if(e.multipleCallbacks){for(let i of e.tasks.values())if(i.status!=="canceled")if(i.status=t?"error":"completed",i.finishedAt=this.now(),t?i.error=t:i.result=s,i.callback)try{t?i.callback(t,null):i.callback(null,s)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.resolve&&(t?i.reject(t):i.resolve(s));for(let i of e.tasks.values())i.status==="canceled"&&i.reject&&i.reject(new Error("Task was canceled"))}else{for(let i of e.tasks.values())if(i.status!=="canceled")if(i===e.latestTask)if(i.status=t?"error":"completed",i.finishedAt=this.now(),t?i.error=t:i.result=s,i.callback)try{t?i.callback(t,null):i.callback(null,s)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.resolve&&(t?i.reject(t):i.resolve(s));else if(e.resolveAllPromises)if(i.status=t?"error":"coalesced",i.finishedAt=this.now(),t?i.error=t:i.result=s,i.callback)try{t?i.callback(t,null):i.callback(null,s)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.resolve&&(t?i.reject(t):i.resolve(s));else if(i.status="coalesced",i.finishedAt=this.now(),i.callback)try{i.callback(new Error("Task was coalesced with a newer task"),null)}catch(r){this.emit("error",{...i,error:r,callbackError:!0})}else i.reject&&i.reject(new Error("Task was coalesced with a newer task"));for(let i of e.tasks.values())i.status==="canceled"&&i.reject&&i.reject(new Error("Task was canceled"))}}_cancelCoalescingTask(e,t,s){let i=this.coalescingGroups.get(t)||[];for(let r of i){let n=r.tasks.get(e);if(n){if(n.status="canceled",n.finishedAt=this.now(),n.callback)try{n.callback(new Error(s),null)}catch(a){this.emit("error",{...n,error:a,callbackError:!0})}else n.reject&&n.reject(new Error(s));if(r.tasks.delete(e),r.tasks.size===0)this.tasks.get(r.representativeId)&&this.cancel(r.representativeId,"All coalesced tasks canceled"),this._cleanupCoalescingGroup(t,r.groupId);else{let a=Array.from(r.tasks.values());r.latestTask=a[a.length-1],r.originalTask=r.latestTask.task}return}}}_cleanupCoalescingGroup(e,t){let s=this.coalescingGroups.get(e);if(!s)return;let i=s.findIndex(r=>r.groupId===t);if(i>=0){let r=s[i];s.splice(i,1),this.coalescingRepresentatives.delete(r.representativeId),s.length===0&&this.coalescingGroups.delete(e)}}_rebuildHeaps(){let e=[...this.pendingHeap.heap];this.pendingHeap=new b((s,i)=>s.readyAt-i.readyAt);for(let s of e)this.pendingHeap.push(s);let t=[...this.readyHeap.heap];this.readyHeap=new b((s,i)=>s.priority!==i.priority?i.priority-s.priority:s.readyAt!==i.readyAt?s.readyAt-i.readyAt:s.enqueueSeq-i.enqueueSeq);for(let s of t)this.readyHeap.push(s)}_createTaskHandle(e,t){let s={id:e.id,cancel:g(i=>{e.coalescingKey?this._cancelCoalescingTask(e.id,e.coalescingKey,i||"Task canceled"):this.cancel(e.id,i||"Task canceled")},"cancel"),status:g(()=>e.status,"status"),get startedAt(){return e.startedAt},get finishedAt(){return e.finishedAt},get result(){return e.result},get error(){return e.error},get metadata(){if(e.coalescingKey){let i=this.findCoalescingGroupByTaskId(e.id);return i?i.task.metadata:e.metadata}return e.metadata},get coalescingInfo(){if(!e.coalescingKey)return null;let i=this.findCoalescingGroupByTaskId(e.id);return i?{coalescingKey:i.coalescingKey,groupId:i.groupId,representativeId:i.representativeId,taskCount:i.groupTasks.length,allTaskMetadata:i.groupTasks.map(r=>({id:r.id,metadata:r.metadata}))}:null}};if(!t){let i=new Promise((r,n)=>{e.resolve=r,e.reject=n});return e.promise=i,Object.defineProperty(i,"id",{value:e.id,enumerable:!0}),Object.defineProperty(i,"cancel",{value:s.cancel,enumerable:!0}),Object.defineProperty(i,"status",{value:s.status,enumerable:!0}),Object.defineProperty(i,"startedAt",{get:g(()=>i._startedAt!==void 0?i._startedAt:e.startedAt,"get"),enumerable:!0}),Object.defineProperty(i,"finishedAt",{get:g(()=>i._finishedAt!==void 0?i._finishedAt:e.finishedAt,"get"),enumerable:!0}),Object.defineProperty(i,"result",{get:g(()=>i._result!==void 0?i._result:e.result,"get"),enumerable:!0}),Object.defineProperty(i,"error",{get:g(()=>i._error!==void 0?i._error:e.error,"get"),enumerable:!0}),Object.defineProperty(i,"metadata",{get:g(()=>{if(e.coalescingKey){let r=this.findCoalescingGroupByTaskId(e.id);return r?r.task.metadata:e.metadata}return e.metadata},"get"),enumerable:!0}),Object.defineProperty(i,"coalescingInfo",{get:g(()=>{if(!e.coalescingKey)return null;let r=this.findCoalescingGroupByTaskId(e.id);return r?{coalescingKey:r.coalescingKey,groupId:r.groupId,representativeId:r.representativeId,taskCount:r.groupTasks.length,allTaskMetadata:r.groupTasks.map(n=>({id:n.id,metadata:n.metadata}))}:null},"get"),enumerable:!0}),i}return s}cancel(e,t){let s=this.tasks.get(e);return!s||s.status!=="pending"?!1:(s.status="canceled",s.finishedAt=this.now(),this.tasks.delete(e),this.emit("cancel",s,t),!s.callback&&s.reject&&s.reject(new Error(t||"Task canceled")),!0)}cancelTask(e,t){return this.cancel(e,t)}pause(){this.isActive=!1,this.options.smartScheduling?this.clearSchedulerTimers():this.clearTimers()}resume(){this.destroyed||(this.isActive=!0,this.options.smartScheduling?(this.startHealingInterval(),this.pendingHeap.size()>0||this.readyHeap.size()>0?this.runScheduler():this.scheduleSmartTimeout()):((this.pendingHeap.size()>0||this.readyHeap.size()>0)&&this.schedulerTick(),this._scheduleNextTick()))}clear(){let e=[];for(;this.pendingHeap.size()>0;){let t=this.pendingHeap.pop();t&&t.status==="pending"&&e.push(t)}for(let t of e)t.status="canceled",this.emit("cancel",t);for(let[t,s]of this.coalescingGroups)for(let i of s)for(let r of i.tasks.values())if(r.status="canceled",r.callback)try{r.callback(new Error("Queue cleared"),null)}catch(n){this.emit("error",{...r,error:n,callbackError:!0})}else r.reject&&r.reject(new Error("Queue cleared"));this.pendingHeap=new b((t,s)=>t.readyAt-s.readyAt),this.readyHeap=new b((t,s)=>t.priority!==s.priority?s.priority-t.priority:t.readyAt!==s.readyAt?t.readyAt-s.readyAt:t.enqueueSeq-s.enqueueSeq),this.tasks.clear(),this.coalescingGroups.clear(),this.coalescingRepresentatives.clear(),this.isActive&&this.options.smartScheduling&&this.scheduleSmartTimeout()}size(){return this.tasks.size}length(){return this.tasks.size}inflight(){return this.running.size}getCoalescingGroup(e,t=null){let s=this.coalescingGroups.get(e);if(!s||s.length===0)return null;if(t===null)return s.map(r=>({coalescingKey:r.coalescingKey,groupId:r.groupId,representativeId:r.representativeId,windowEnd:r.windowEnd,mustRunBy:r.mustRunBy,taskCount:r.tasks.size,tasks:Array.from(r.tasks.entries()).map(([n,a])=>({id:n,metadata:a.metadata,status:a.status,priority:a.priority,readyAt:a.readyAt,coalescingKey:a.coalescingKey}))}));let i=s.find(r=>r.groupId===t);return i?{coalescingKey:i.coalescingKey,groupId:i.groupId,representativeId:i.representativeId,windowEnd:i.windowEnd,mustRunBy:i.mustRunBy,taskCount:i.tasks.size,tasks:Array.from(i.tasks.entries()).map(([r,n])=>({id:r,metadata:n.metadata,status:n.status,priority:n.priority,readyAt:n.readyAt,coalescingKey:n.coalescingKey}))}:null}getCoalescingGroupMetadata(e,t=null){let s=this.coalescingGroups.get(e);if(!s||s.length===0)return[];let i=t?s.filter(n=>n.groupId===t):s,r=[];for(let n of i)for(let[a,o]of n.tasks)r.push({taskId:a,groupId:n.groupId,metadata:o.metadata});return r}getCoalescingGroupsSummary(){let e={};for(let[t,s]of this.coalescingGroups){let i=s.reduce((r,n)=>r+n.tasks.size,0);e[t]={groupCount:s.length,totalTasks:i}}return e}findCoalescingGroupByTaskId(e){for(let[t,s]of this.coalescingGroups)for(let i of s){let r=i.tasks.get(e);if(r)return{coalescingKey:t,groupId:i.groupId,representativeId:i.representativeId,windowEnd:i.windowEnd,mustRunBy:i.mustRunBy,task:{id:e,metadata:r.metadata,status:r.status,priority:r.priority,readyAt:r.readyAt},groupTasks:Array.from(i.tasks.entries()).map(([n,a])=>({id:n,metadata:a.metadata,status:a.status}))}}return null}destroy(){this.destroyed=!0,this.pause(),this.clear(),this.emit("drain")}now(){return this.options.now?.()??Date.now()}_scheduleNextTick(){if(!this.isActive||this.destroyed)return;this.clearTimers();let e=this.now(),t=1/0,s=this.pendingHeap.peek();if(s&&(t=s.readyAt),this.nextAvailableTime>e&&(t=Math.min(t,this.nextAvailableTime)),t===1/0&&this.readyHeap.size()>0&&(t=e),t<=e+this.options.tick)this.intervalId=setInterval(()=>this.schedulerTick(),this.options.tick);else{let i=Math.min(t-e,2147483647);this.timeoutId=setTimeout(()=>this.schedulerTick(),i)}}schedulerTick(){let e=this.now(),t=this.pendingHeap.peek();for(;t&&t.readyAt<=e;){let n=this.pendingHeap.pop();n&&n.status==="pending"&&(n.expireAt&&e>=n.expireAt?this._expireTask(n):(n.status="ready",this.readyHeap.push(n))),t=this.pendingHeap.peek()}let s=!1,i=this.now(),r=i<this.nextAvailableTime;for(;this.readyHeap.size()>0;){let n=this.readyHeap.peek();if(!n)break;if(n.expireAt&&i>=n.expireAt){this.readyHeap.pop(),this._expireTask(n);continue}let a=this._canStartTask(n),o=n.bypassDelay||!r;if(a&&o)this.readyHeap.pop(),this._startTask(n);else if(a){let h=this.readyHeap.heap.slice(),d=!1;for(let l=0;l<h.length;l++){let c=h[l];if(c.expireAt&&i>=c.expireAt){let k=h.filter(f=>f.id!==c.id);this.readyHeap.heap=[];for(let f of k)this.readyHeap.push(f);this._expireTask(c),h.splice(l,1),l--;continue}if(c.bypassDelay){d=!0;let k=h.filter(f=>f.id!==c.id);this.readyHeap.heap=[];for(let f of k)this.readyHeap.push(f);this._startTask(c);break}}if(!d){s=!0;break}}else{let h=this.readyHeap.heap.slice(),d=!1;for(let l=0;l<h.length;l++){let c=h[l];if(c.expireAt&&i>=c.expireAt){let u=h.filter(y=>y.id!==c.id);this.readyHeap.heap=[];for(let y of u)this.readyHeap.push(y);this._expireTask(c),h.splice(l,1),l--;continue}let k=this._canStartTask(c),f=c.bypassDelay||!r;if(k&&f){d=!0;let u=h.filter(y=>y.id!==c.id);this.readyHeap.heap=[];for(let y of u)this.readyHeap.push(y);this._startTask(c);break}}if(!d){s=!0;break}}}!this.options.smartScheduling&&(this.pendingHeap.size()>0||this.readyHeap.size()>0||s)&&this._scheduleNextTick()}_canStartTask(e){if(this.running.size>=this.options.concurrency)return!1;let t=this.options.priorities[e.priority];return!(t&&typeof t.concurrency=="number"&&(this.runningByPriority.get(e.priority)||0)>=t.concurrency)}_expireTask(e){if(e.status==="expired"||e.status==="canceled"||e.status==="completed")return;e.status="expired",this.tasks.delete(e.id),this.running.delete(e);let t=new Error(`Task expired after waiting ${this.now()-(e.readyAt||this.now())}ms in queue`);if(t.type="expire",t.taskId=e.id,e.callback){try{e.callback(t,null)}catch(s){this.emit("error",{error:s,task:e})}this._emitTaskError({error:t,task:e})}else e.reject&&e.reject(t)}_emitTaskError(e){this.listenerCount("error")>0&&this.emit("error",e)}async _startTask(e){if(e.status!=="ready")return;if(!e.callback&&e.signal?.aborted){e.reject(new Error("Task was aborted"));return}e.status="running",e.startedAt=this.now(),this.running.add(e);let t=this.runningByPriority.get(e.priority)||0;this.runningByPriority.set(e.priority,t+1),this.emit("start",e);let s=new AbortController,i;try{let r;e.timeout&&(r=new Promise((o,p)=>{i=setTimeout(()=>{s.abort(),p(new Error(`Task timed out after ${e.timeout}ms`))},e.timeout)}));let n=e.task(s.signal),a=e.timeout?await Promise.race([n,r]):await n;if(e.result=a,e.status="completed",e.finishedAt=this.now(),i&&clearTimeout(i),this.emit("success",e),e.promise&&(e.promise._result=e.result,e.promise._error=e.error,e.promise._startedAt=e.startedAt,e.promise._finishedAt=e.finishedAt,e.promise._status=e.status),e.callback)try{e.callback(null,a)}catch(o){this.emit("error",{...e,error:o,callbackError:!0})}else e.resolve&&e.resolve(a)}catch(r){if(e.error=r,e.status=r.message.includes("timed out")?"timeout":s.signal.aborted||r.name==="AbortError"?"canceled":"error",e.finishedAt=this.now(),e.callback&&this._emitTaskError(e),e.promise&&(e.promise._result=e.result,e.promise._error=e.error,e.promise._startedAt=e.startedAt,e.promise._finishedAt=e.finishedAt,e.promise._status=e.status),e.callback)try{let n=e.status==="timeout"?{type:"timeout",message:r.message}:s.signal.aborted||r.name==="AbortError"?{type:"canceled",message:"Task was aborted"}:{type:"error",error:r};e.callback(n,null)}catch(n){this.emit("error",{...e,error:n,callbackError:!0})}else e.reject&&e.reject(r)}finally{i&&clearTimeout(i),this.running.delete(e);let r=this.runningByPriority.get(e.priority)||0;r>0&&this.runningByPriority.set(e.priority,r-1),this.tasks.delete(e.id);let n=e.priority,a=e.delay,o=this.options.priorities[n]?.postDelay??0,p=a!==void 0?a:o;p>0?(this.lastCompletedPriority=n,this.nextAvailableTime=this.now()+p):(this.lastCompletedPriority=null,this.nextAvailableTime=0),setImmediate(()=>{this.running.size===0&&this.pendingHeap.size()===0&&this.readyHeap.size()===0?this.emit("drain"):this.isActive&&(this.options.smartScheduling?this.scheduleSmartTimeout():this.schedulerTick())})}}clearTimers(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=void 0),this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0)}scheduleSmartTimeout(){if(!this.isActive||this.destroyed)return;this.clearSchedulerTimers();let e=this.now(),t=1/0,s=!1;if(this.readyHeap.size()>0&&this.running.size<this.options.concurrency)if(!(e<this.nextAvailableTime))s=!0;else{let n=this.readyHeap.heap.slice();for(let a of n)if(a.bypassDelay&&(!a.expireAt||e<a.expireAt)){s=!0;break}s||(t=Math.min(t,this.nextAvailableTime))}let i=this.pendingHeap.peek();if(i&&(t=Math.min(t,i.readyAt)),s||t<=e+1){setImmediate(()=>this.runScheduler());return}if(t<1/0){let r=Math.min(t-e,2147483647);this.schedulerTimeout=setTimeout(()=>{this.runScheduler()},r)}}runScheduler(){!this.isActive||this.destroyed||(this.lastSchedulerRun=this.now(),this.schedulerTick(),this.scheduleSmartTimeout())}startHealingInterval(){this.healingInterval&&clearInterval(this.healingInterval),this.healingInterval=setInterval(()=>{if(!this.isActive||this.destroyed)return;let e=this.now(),t=this.pendingHeap.size()>0||this.readyHeap.size()>0,s=e-this.lastSchedulerRun;t&&s>this.options.healingInterval&&!this.schedulerTimeout&&(console.warn(`HoldMyTask: Healing scheduler - ${s}ms since last run`),this.runScheduler())},this.options.healingInterval)}clearSchedulerTimers(){this.schedulerTimeout&&(clearTimeout(this.schedulerTimeout),this.schedulerTimeout=null),this.healingInterval&&(clearInterval(this.healingInterval),this.healingInterval=null)}configureCoalescingKey(e,t){if(typeof e!="string"){let n=new Error("coalescingKey must be a string");setImmediate(()=>this.emit("error",{error:n,method:"configureCoalescingKey",coalescingKey:e,config:t}));return}if(typeof t!="object"||t===null){let n=new Error("config must be an object");setImmediate(()=>this.emit("error",{error:n,method:"configureCoalescingKey",coalescingKey:e,config:t}));return}let s=["windowDuration","maxDelay","delay","start","postDelay","startDelay","multipleCallbacks","resolveAllPromises"],i=Object.keys(t).filter(n=>!s.includes(n));if(i.length>0){let n=new Error(`Invalid config keys: ${i.join(", ")}. Valid keys: ${s.join(", ")}`);setImmediate(()=>this.emit("error",{error:n,method:"configureCoalescingKey",coalescingKey:e,config:t,invalidKeys:i}));return}let r=m._transformDelayProperties(t,this);this.options.coalescing.keys[e]={...this.options.coalescing.keys[e],...r}}getCoalescingConfig(e,t={}){let s=this.options.coalescing.keys&&this.options.coalescing.keys[e]||{},i=this.options.coalescing.defaults,r=this.getPriorityConfig(t.priority??this.options.defaultPriority),n=t.postDelay??t.delay??s.postDelay??r.postDelay??i.postDelay,a=t.startDelay??t.start??s.startDelay??r.startDelay??i.startDelay;return{windowDuration:t.coalescingWindowDuration??s.windowDuration??i.windowDuration,maxDelay:t.coalescingMaxDelay??s.maxDelay??i.maxDelay,postDelay:n,startDelay:a,delay:n,start:a,multipleCallbacks:t.coalescingMultipleCallbacks??s.multipleCallbacks??i.multipleCallbacks,resolveAllPromises:t.coalescingResolveAllPromises??s.resolveAllPromises??i.resolveAllPromises}}getCoalescingConfigurations(){let e={};for(let t of Object.keys(this.options.coalescing.keys))e[t]=this.getCoalescingConfig(t);return e}configurePriority(e,t){if(typeof e!="number"){let n=new Error("priority must be a number");setImmediate(()=>this.emit("error",{error:n,method:"configurePriority",priority:e,config:t}));return}if(typeof t!="object"||t===null){let n=new Error("config must be an object");setImmediate(()=>this.emit("error",{error:n,method:"configurePriority",priority:e,config:t}));return}let s=["delay","start","postDelay","startDelay"],i=Object.keys(t).filter(n=>!s.includes(n));if(i.length>0){let n=new Error(`Invalid config keys: ${i.join(", ")}. Valid keys: ${s.join(", ")}`);setImmediate(()=>this.emit("error",{error:n,method:"configurePriority",priority:e,config:t,invalidKeys:i}));return}let r=m._transformDelayProperties(t,this);this.options.priorities[e]={...this.options.priorities[e],...r}}getPriorityConfig(e,t={}){let s=this.options.priorities[e]||{},i=t.postDelay??t.delay??s.postDelay,r=t.startDelay??t.start??s.startDelay;return{postDelay:i,startDelay:r,delay:i,start:r}}getPriorityConfigurations(){let e={};for(let t of Object.keys(this.options.priorities))e[t]=this.getPriorityConfig(parseInt(t));return e}shutdown(){return this.destroy()}schedule(e,t,s={}){return this.enqueue(e,t,s)}add(e,t,s={}){return this.enqueue(e,t,s)}get(e){return this.tasks.get(String(e))||null}has(e){return this.tasks.has(String(e))}getTask(e){return this.get(e)}hasTask(e){return this.has(e)}inspect(){let e=this.now(),t=[...this.pendingHeap.heap].map(o=>({id:o.id,priority:o.priority,readyAt:o.readyAt,readyIn:o.readyAt-e,coalescingKey:o.coalescingKey,metadata:o.metadata,status:"pending"})),s=[...this.readyHeap.heap].map(o=>({id:o.id,priority:o.priority,coalescingKey:o.coalescingKey,metadata:o.metadata,status:"ready"})),i=Array.from(this.running).map(o=>({id:o.id,priority:o.priority,coalescingKey:o.coalescingKey,metadata:o.metadata,startedAt:o.startedAt,runningFor:e-o.startedAt,status:"running"})),r=this.inspectTimers(),n={isActive:this.isActive,isPaused:!this.isActive,smartScheduling:this.options.smartScheduling,concurrency:this.options.concurrency,currentConcurrency:this.running.size,tick:this.options.tick,nextActiveDelay:this.nextAvailableTime>e?this.nextAvailableTime-e:null,priorityConcurrency:{}};for(let[o,p]of this.runningByPriority.entries())if(p>0){let h=this.options.priorities[o];n.priorityConcurrency[o]={running:p,limit:h?.concurrency||this.options.concurrency,available:(h?.concurrency||this.options.concurrency)-p}}for(let[o,p]of Object.entries(this.options.priorities))p.concurrency&&!n.priorityConcurrency[o]&&(n.priorityConcurrency[o]={running:0,limit:p.concurrency,available:p.concurrency});let a={};for(let[o,p]of this.coalescingGroups.entries())a[o]={groupCount:p.size,totalTasks:Array.from(p.values()).reduce((h,d)=>h+d.tasks.size,0),groups:Array.from(p.entries()).map(([h,d])=>({groupId:h,taskCount:d.tasks.size,representativeId:d.representativeId,tasks:Array.from(d.tasks.entries()).map(([l,c])=>({id:c.id,metadata:c.metadata}))}))};return{timestamp:e,scheduler:n,timers:r,queues:{pending:{count:t.length,tasks:t},ready:{count:s.length,tasks:s},running:{count:i.length,tasks:i}},totals:{totalTasks:t.length+s.length+i.length,pendingTasks:t.length,readyTasks:s.length,runningTasks:i.length},coalescing:a,delays:{activeDelays:this.nextAvailableTime>e?1:0,delayDetails:this.nextAvailableTime>e?[{priority:this.lastCompletedPriority,expiresAt:this.nextAvailableTime,expiresIn:this.nextAvailableTime-e}]:[]}}}inspectTimers(){let e=this.now();return{schedulerInterval:{id:this.schedulerInterval,active:this.schedulerInterval!==null,type:"interval"},schedulerTimeout:{id:this.schedulerTimeout,active:this.schedulerTimeout!==null,type:"timeout"},nextScheduledRun:this.nextScheduledRun,nextRunIn:this.nextScheduledRun?this.nextScheduledRun-e:null,smartScheduling:this.options.smartScheduling,tickInterval:this.options.tick}}inspectTasks(){let e=this.now(),t={pending:[],ready:[],running:[],byPriority:{},byCoalescingKey:{},total:0};return[...this.pendingHeap.heap].forEach(s=>{let i={id:s.id,priority:s.priority,readyAt:s.readyAt,readyIn:s.readyAt-e,coalescingKey:s.coalescingKey,metadata:s.metadata};t.pending.push(i),t.total++,t.byPriority[s.priority]||(t.byPriority[s.priority]={pending:0,ready:0,running:0}),t.byPriority[s.priority].pending++,s.coalescingKey&&(t.byCoalescingKey[s.coalescingKey]||(t.byCoalescingKey[s.coalescingKey]={pending:0,ready:0,running:0}),t.byCoalescingKey[s.coalescingKey].pending++)}),[...this.readyHeap.heap].forEach(s=>{let i={id:s.id,priority:s.priority,coalescingKey:s.coalescingKey,metadata:s.metadata};t.ready.push(i),t.total++,t.byPriority[s.priority]||(t.byPriority[s.priority]={pending:0,ready:0,running:0}),t.byPriority[s.priority].ready++,s.coalescingKey&&(t.byCoalescingKey[s.coalescingKey]||(t.byCoalescingKey[s.coalescingKey]={pending:0,ready:0,running:0}),t.byCoalescingKey[s.coalescingKey].ready++)}),Array.from(this.running).forEach(s=>{let i={id:s.id,priority:s.priority,coalescingKey:s.coalescingKey,metadata:s.metadata,startedAt:s.startedAt,runningFor:e-s.startedAt};t.running.push(i),t.total++,t.byPriority[s.priority]||(t.byPriority[s.priority]={pending:0,ready:0,running:0}),t.byPriority[s.priority].running++,s.coalescingKey&&(t.byCoalescingKey[s.coalescingKey]||(t.byCoalescingKey[s.coalescingKey]={pending:0,ready:0,running:0}),t.byCoalescingKey[s.coalescingKey].running++)}),t}inspectScheduler(){let e=this.now(),t=1/0,s=null;if(this.pendingHeap.size()>0){let n=this.pendingHeap.peek();n&&n.readyAt<t&&(t=n.readyAt,s={id:n.id,priority:n.priority,readyAt:n.readyAt,source:"pending"})}if(this.readyHeap.size()>0){let n=this.readyHeap.peek();n&&(t=e,s={id:n.id,priority:n.priority,source:"ready"})}let i=null;this.nextAvailableTime>e&&(i={priority:this.lastCompletedPriority,expiresAt:this.nextAvailableTime});let r={};for(let[n,a]of this.runningByPriority.entries())if(a>0){let o=this.options.priorities[n];r[n]={running:a,limit:o?.concurrency||this.options.concurrency,available:(o?.concurrency||this.options.concurrency)-a}}for(let[n,a]of Object.entries(this.options.priorities))a.concurrency&&!r[n]&&(r[n]={running:0,limit:a.concurrency,available:a.concurrency});return{timestamp:e,isActive:this.isActive,smartScheduling:this.options.smartScheduling,concurrency:this.options.concurrency,currentConcurrency:this.running.size,availableSlots:this.options.concurrency-this.running.size,priorityConcurrency:r,timers:{schedulerInterval:this.schedulerInterval,schedulerTimeout:this.schedulerTimeout,nextScheduledRun:this.nextScheduledRun,nextRunIn:this.nextScheduledRun?this.nextScheduledRun-e:null},nextTask:s?{...s,readyIn:t-e,canRunNow:t<=e&&this.running.size<this.options.concurrency}:null,delays:{hasActiveDelays:this.nextAvailableTime>e,count:this.nextAvailableTime>e?1:0,nextExpiry:i?{...i,expiresIn:i.expiresAt-e}:null},queueCounts:{pending:this.pendingHeap.size(),ready:this.readyHeap.size(),running:this.running.size,total:this.pendingHeap.size()+this.readyHeap.size()+this.running.size}}}debugLog(e=!1){let t=this.inspect();console.log(`
2
+ === HoldMyTask Debug Information ===`),console.log(`Timestamp: ${new Date(t.timestamp).toISOString()}`),console.log(`Status: ${t.scheduler.isActive?"ACTIVE":"PAUSED"}`),console.log(`Smart Scheduling: ${t.scheduler.smartScheduling?"ON":"OFF"}`),console.log(`Concurrency: ${t.scheduler.currentConcurrency}/${t.scheduler.concurrency}`),console.log(`
3
+ --- Queue State ---`),console.log(`Total Tasks: ${t.totals.totalTasks}`),console.log(` Pending: ${t.totals.pendingTasks}`),console.log(` Ready: ${t.totals.readyTasks}`),console.log(` Running: ${t.totals.runningTasks}`),Object.keys(t.scheduler.priorityConcurrency).length>0&&(console.log(`
4
+ --- Priority Concurrency ---`),Object.entries(t.scheduler.priorityConcurrency).forEach(([s,i])=>{console.log(` Priority ${s}: ${i.running}/${i.limit} (${i.available} available)`)})),console.log(`
5
+ --- Timer State ---`),console.log(`Interval: ${t.timers.schedulerInterval.active?`Active (${t.timers.schedulerInterval.id})`:"None"}`),console.log(`Timeout: ${t.timers.schedulerTimeout.active?`Active (${t.timers.schedulerTimeout.id})`:"None"}`),t.timers.nextRunIn!==null&&console.log(`Next Run: ${t.timers.nextRunIn}ms`),t.delays.activeDelays>0&&(console.log(`
6
+ --- Active Delays ---`),t.delays.delayDetails.forEach(s=>{console.log(` Priority ${s.priority}: expires in ${s.expiresIn}ms`)})),Object.keys(t.coalescing).length>0&&(console.log(`
7
+ --- Coalescing Groups ---`),Object.entries(t.coalescing).forEach(([s,i])=>{console.log(` ${s}: ${i.groupCount} groups, ${i.totalTasks} tasks`)})),e&&(console.log(`
8
+ --- Detailed Task Information ---`),t.queues.pending.count>0&&(console.log(`
9
+ Pending Tasks:`),t.queues.pending.tasks.forEach(s=>{console.log(` ${s.id}: priority ${s.priority}, ready in ${s.readyIn}ms`)})),t.queues.ready.count>0&&(console.log(`
10
+ Ready Tasks:`),t.queues.ready.tasks.forEach(s=>{console.log(` ${s.id}: priority ${s.priority}`)})),t.queues.running.count>0&&(console.log(`
11
+ Running Tasks:`),t.queues.running.tasks.forEach(s=>{console.log(` ${s.id}: priority ${s.priority}, running for ${s.runningFor}ms`)}))),console.log(`=====================================
12
+ `)}};async function E(m={}){return new T(m)}g(E,"createHoldMyTask");async function j(m={}){return new T(m)}g(j,"createQueue");async function K(m={}){return new T(m)}g(K,"createTaskManager");async function z(m={}){return new T(m)}g(z,"createTaskProcessor");export{T as HoldMyTask,T as Queue,T as QueueManager,T as TaskManager,T as TaskProcessor,T as TaskQueue,E as createHoldMyTask,j as createQueue,K as createTaskManager,z as createTaskProcessor,T as default,T as queue};
13
+ //# sourceMappingURL=index.mjs.map
package/dist/main.mjs ADDED
@@ -0,0 +1,2 @@
1
+ export*from"./index.mjs";import{default as r}from"./index.mjs";var e='"@cldmv/holdmytask/main" is deprecated; import "@cldmv/holdmytask" instead.';typeof process<"u"&&typeof process.emitWarning=="function"?process.emitWarning(e,{type:"DeprecationWarning",code:"CLDMV_HOLDMYTASK_MAIN"}):console.warn(`DeprecationWarning: ${e}`);export{r as default};
2
+ //# sourceMappingURL=main.mjs.map
package/package.json CHANGED
@@ -1,34 +1,37 @@
1
1
  {
2
2
  "name": "@cldmv/holdmytask",
3
- "version": "2.0.6",
3
+ "version": "2.1.0",
4
4
  "description": "A tiny task queue that waits until your task is ready",
5
- "main": "./index.cjs",
6
- "module": "./index.mjs",
7
- "types": "./types/index.d.mts",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./types/src/index.d.mts",
8
8
  "exports": {
9
9
  ".": {
10
- "types": "./types/index.d.mts",
11
- "import": "./index.mjs",
12
- "require": "./index.cjs"
10
+ "holdmytask-dev": {
11
+ "types": "./types/src/index.d.mts",
12
+ "import": "./src/index.mjs",
13
+ "require": "./src/index.cjs"
14
+ },
15
+ "types": "./types/src/index.d.mts",
16
+ "import": "./dist/index.mjs",
17
+ "require": "./dist/index.cjs"
13
18
  },
14
19
  "./main": {
15
20
  "holdmytask-dev": {
16
- "types": "./types/src/hold-my-task.d.mts",
17
- "import": "./src/hold-my-task.mjs"
21
+ "types": "./types/src/index.d.mts",
22
+ "import": "./src/main.mjs"
18
23
  },
19
- "types": "./types/dist/hold-my-task.d.mts",
20
- "import": "./dist/hold-my-task.mjs"
24
+ "types": "./types/src/index.d.mts",
25
+ "import": "./dist/main.mjs"
21
26
  }
22
27
  },
23
28
  "engines": {
24
- "node": ">=18.12"
29
+ "node": ">=22.22.0"
25
30
  },
26
31
  "scripts": {
27
32
  "test": "node tests/run-vitest.mjs && npm run test:cjs",
28
- "test:cjs": "node --conditions=holdmytask-dev --test tests/cjs/entry.test.cjs",
33
+ "test:cjs": "npm run build && node --conditions=holdmytask-dev --test tests/cjs/entry.test.cjs",
29
34
  "test:watch": "vitest --config .configs/vitest.config.mjs",
30
- "test:run": "vitest run",
31
- "test:coverage": "vitest run --coverage",
32
35
  "test:types": "tsc --noEmit --project .configs/tsconfig.dts.jsonc",
33
36
  "coverage": "node tests/run-vitest.mjs --coverage-quiet && npm run test:cjs",
34
37
  "ci:coverage": "npm run coverage",
@@ -36,9 +39,10 @@
36
39
  "lint:fix": "eslint --config .configs/eslint.config.mjs . --fix",
37
40
  "format": "prettier --config .configs/.prettierrc --write .",
38
41
  "format:check": "prettier --config .configs/.prettierrc --check .",
39
- "build": "node build.mjs",
42
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsup",
40
43
  "build:types": "tsc --project .configs/tsconfig.dts.jsonc",
41
- "build:ci": "npm run build:types && npm run test:types && npm run build",
44
+ "build:ci": "npm run lint && npm run format:check && npm run build:types && npm run test:types && npm run build",
45
+ "prepack": "npm run build",
42
46
  "precommit": "npm run build:types && npm run test:types && npm run lint && npm run test",
43
47
  "fix:headers": "fix-headers --config .configs/fix-headers.json"
44
48
  },
@@ -81,24 +85,29 @@
81
85
  "url": "https://github.com/sponsors/shinrai"
82
86
  },
83
87
  "type": "module",
88
+ "overrides": {
89
+ "katex": ">=0.19.1 <1.0.0",
90
+ "minimatch": "^11.0.3"
91
+ },
84
92
  "devDependencies": {
85
- "@cldmv/configs": "^1.2.4",
86
- "@cldmv/fix-headers": "^2.2.0",
87
- "@cldmv/vitest-runner": "^1.2.0",
88
- "@eslint/css": "^2.0.0",
93
+ "@cldmv/configs": "^1.3.0",
94
+ "@cldmv/fix-headers": "^2.2.4",
95
+ "@cldmv/vitest-runner": "^1.5.6",
96
+ "@eslint/css": "^2.0.1",
89
97
  "@eslint/js": "^10.0.1",
90
- "@eslint/json": "^2.0.1",
98
+ "@eslint/json": "^2.1.1",
91
99
  "@eslint/markdown": "^8.0.3",
92
- "@html-eslint/eslint-plugin": "^0.66.1",
93
- "@html-eslint/parser": "^0.66.1",
94
- "@types/node": "^26.1.2",
95
- "@vitest/coverage-v8": "^5.0.3",
96
- "@vitest/ui": "^5.0.3",
97
- "eslint": "^10.8.0",
98
- "globals": "^17.9.0",
99
- "prettier": "^3.0.0",
100
- "typescript": "^7.0.2",
101
- "vitest": "^5.0.0"
100
+ "@html-eslint/eslint-plugin": "^0.67.0",
101
+ "@html-eslint/parser": "^0.67.0",
102
+ "@types/node": "^26.6.6",
103
+ "@vitest/coverage-v8": "^5.0.5",
104
+ "@vitest/ui": "^5.0.5",
105
+ "eslint": "^10.14.0",
106
+ "globals": "^17.14.0",
107
+ "prettier": "^3.9.10",
108
+ "tsup": "^9.0.0",
109
+ "typescript": "^6.0.3",
110
+ "vitest": "^5.0.5"
102
111
  },
103
112
  "repository": {
104
113
  "type": "git",
@@ -112,14 +121,14 @@
112
121
  "access": "public"
113
122
  },
114
123
  "files": [
115
- "index.mjs",
116
- "index.cjs",
124
+ "dist/",
125
+ "!dist/**/*.map",
126
+ "types/src/",
117
127
  "README.md",
118
- "LICENSE",
119
- "types/dist/",
120
- "types/index.d.mts",
121
- "types/index.d.mts.map",
122
- "dist/"
128
+ "LICENSE"
123
129
  ],
124
- "sideEffects": false
130
+ "sideEffects": [
131
+ "./src/main.mjs",
132
+ "./dist/main.mjs"
133
+ ]
125
134
  }