@mrjacket/ahko 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.2.0] - 2026-09-22 — Idle Scheduling
9
+
10
+ ### Added
11
+ - Platform-agnostic `IdleScheduler` supporting browser `requestIdleCallback`, Node.js `setImmediate`, and universal fallback `setTimeout(..., 0)`.
12
+ - Support for `idle` strategy (`EScheduleStrategy.IDLE`).
13
+ - Optional `idleTimeout` parameter in `IScheduleOptions` forwarding to `requestIdleCallback({ timeout })`.
14
+ - Convenience method `ahko.idle(task, options)`.
15
+ - Immediate resource cleanup and handle cancellation when idle tasks are cancelled prior to callback execution.
16
+ - Comprehensive unit test suite covering cross-runtime execution, fallback paths, cancellation, and concurrency.
17
+
18
+ ---
19
+
8
20
  ## [0.1.0] - 2026-09-22 — Core Scheduler
9
21
 
10
22
  ### Added
package/README.md CHANGED
@@ -1,21 +1,41 @@
1
- <h1><img src=".github/images/ahko.png" width="80" height="80"> ahko</h1>
2
-
3
- [![npm version](https://img.shields.io/npm/v/@mrjacket/ahko.svg?color=success)](https://www.npmjs.com/package/@mrjacket/ahko)
4
- [![npm downloads](https://img.shields.io/npm/dm/@mrjacket/ahko.svg)](https://www.npmjs.com/package/@mrjacket/ahko)
5
- [![node](https://img.shields.io/node/v/@mrjacket/ahko.svg)](https://www.npmjs.com/package/@mrjacket/ahko)
6
- [![ci](https://github.com/x-name15/ahko/actions/workflows/ci.yml/badge.svg)](https://github.com/x-name15/ahko/actions/workflows/ci.yml)
7
- [![types](https://img.shields.io/npm/types/@mrjacket/ahko.svg)](https://www.npmjs.com/package/@mrjacket/ahko)
8
- [![license](https://img.shields.io/npm/l/@mrjacket/ahko.svg)](https://github.com/x-name15/ahko/blob/main/LICENSE)
9
-
10
- > Let your code chill.
11
-
12
- `@mrjacket/ahko` is a low-energy, production-grade task scheduler for JavaScript and TypeScript.
13
-
14
- Inspired by Aashii Kedarui / Ahko from *"The 100 Girlfriends Who Really, Really, Really, Really, Really Love You"*, AHKO brings calm, controlled execution to asynchronous workflows without rush, bursts, or unnecessary complexity.
1
+ <p align="center">
2
+ <img src=".github/images/ahko.png" width="120" height="120" alt="ahko">
3
+ </p>
4
+
5
+ <h1 align="center">ahko</h1>
6
+
7
+ <p align="center">
8
+ <strong>Let your code chill.</strong>
9
+ </p>
10
+
11
+ <p align="center">
12
+ <a href="https://www.npmjs.com/package/@mrjacket/ahko">
13
+ <img src="https://img.shields.io/npm/v/@mrjacket/ahko.svg?color=success" alt="npm version">
14
+ </a>
15
+ <a href="https://www.npmjs.com/package/@mrjacket/ahko">
16
+ <img src="https://img.shields.io/npm/dm/@mrjacket/ahko.svg" alt="npm downloads">
17
+ </a>
18
+ <a href="https://www.npmjs.com/package/@mrjacket/ahko">
19
+ <img src="https://img.shields.io/node/v/@mrjacket/ahko.svg" alt="node">
20
+ </a>
21
+ <a href="https://github.com/x-name15/ahko/actions/workflows/ci.yml">
22
+ <img src="https://github.com/x-name15/ahko/actions/workflows/ci.yml/badge.svg" alt="ci">
23
+ </a>
24
+ <a href="https://www.npmjs.com/package/@mrjacket/ahko">
25
+ <img src="https://img.shields.io/npm/types/@mrjacket/ahko.svg" alt="types">
26
+ </a>
27
+ <a href="https://github.com/x-name15/ahko/blob/main/LICENSE">
28
+ <img src="https://img.shields.io/npm/l/@mrjacket/ahko.svg" alt="license">
29
+ </a>
30
+ </p>
31
+
32
+ `ahko` is a low-energy task scheduler for JavaScript and TypeScript.
33
+
34
+ Inspired by Aashii Kedarui / Ahko from *"The 100 Girlfriends Who Really, Really, Really, Really, Really Love You"*, @mrjacket/ahko brings calm, controlled execution to asynchronous workflows without rush, bursts, or unnecessary complexity.
15
35
 
16
36
  ---
17
37
 
18
- ## 📦 Installation
38
+ ## Installation
19
39
 
20
40
  ```bash
21
41
  npm install @mrjacket/ahko
@@ -25,7 +45,7 @@ Requires **Node.js >= 22.12.0** or a modern browser environment. Zero external d
25
45
 
26
46
  ---
27
47
 
28
- ## ⚡ Quick Start
48
+ ## Quick Start
29
49
 
30
50
  ```typescript
31
51
  import { Ahko } from "@mrjacket/ahko";
@@ -41,7 +61,7 @@ const data = await ahko.schedule(async ({ signal, taskId }) => {
41
61
 
42
62
  ---
43
63
 
44
- ## 🧘 Core Capabilities
64
+ ## Core Capabilities
45
65
 
46
66
  ### 1. Concurrency Control
47
67
 
@@ -117,7 +137,7 @@ console.log(stats);
117
137
 
118
138
  ---
119
139
 
120
- ## 📖 API Reference
140
+ ## API Reference
121
141
 
122
142
  ### `new Ahko(options?: IAhkoOptions)`
123
143
 
@@ -142,7 +162,7 @@ Returns a snapshot of current task counters and capacity.
142
162
 
143
163
  ---
144
164
 
145
- ## 🛡️ Errors
165
+ ## Errors
146
166
 
147
167
  - `AhkoError`: Base class for all scheduler errors.
148
168
  - `AhkoCancellationError`: Thrown when a task is aborted.
@@ -152,6 +172,8 @@ Returns a snapshot of current task counters and capacity.
152
172
 
153
173
  ---
154
174
 
155
- ## 📜 License
175
+ ## License
176
+ [GNU General Public License v3.0 (GPL-3.0-only)](LICENSE)
156
177
 
157
- [GNU General Public License v3.0 (GPL-3.0-only)](LICENSE) © [x-name15](https://github.com/x-name15)
178
+ ### Credits
179
+ **Author:** Mr Jacket / Felix Manrique / x-name15 (we are all the same person)
package/dist/ahko.d.ts CHANGED
@@ -2,7 +2,7 @@ import type { IAhkoOptions, IScheduleOptions } from "./models/options.model.js";
2
2
  import type { IAhkoStats } from "./models/stats.model.js";
3
3
  import type { ITask } from "./models/task.model.js";
4
4
  /**
5
- * Ahko — Low-energy, production-grade asynchronous task scheduler.
5
+ * Ahko — Low-energy asynchronous task scheduler.
6
6
  *
7
7
  * Coordinates execution timing, enforces concurrency limits, and cooperates
8
8
  * natively with AbortSignal cancellation.
@@ -58,6 +58,30 @@ export declare class Ahko {
58
58
  * ```
59
59
  */
60
60
  schedule<T>(task: ITask<T>, options?: IScheduleOptions): Promise<T>;
61
+ /**
62
+ * Convenience method to schedule a task during platform idle opportunities.
63
+ *
64
+ * Equivalent to calling `schedule(task, { ...options, strategy: "idle" })`.
65
+ * In browsers, uses `requestIdleCallback` when available.
66
+ * In Node.js, uses `setImmediate`.
67
+ * Falls back to `setTimeout(..., 0)` if neither is available.
68
+ *
69
+ * @template T - Inferred return type of the task.
70
+ * @param task - Task function to run when idle.
71
+ * @param options - Scheduling options (excluding strategy).
72
+ * @returns A promise resolving to the task's return value.
73
+ *
74
+ * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.
75
+ * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * const result = await ahko.idle(async ({ signal }) => {
80
+ * return computeAnalytics();
81
+ * });
82
+ * ```
83
+ */
84
+ idle<T>(task: ITask<T>, options?: Omit<IScheduleOptions, "strategy">): Promise<T>;
61
85
  /**
62
86
  * Retrieves real-time telemetry metrics from the scheduler.
63
87
  *
package/dist/index.cjs CHANGED
@@ -62,6 +62,14 @@ var AhkoConfigurationError = class extends AhkoError {
62
62
  }
63
63
  };
64
64
 
65
+ // src/models/strategy.model.ts
66
+ var EScheduleStrategy = /* @__PURE__ */ ((EScheduleStrategy2) => {
67
+ EScheduleStrategy2["IMMEDIATE"] = "immediate";
68
+ EScheduleStrategy2["DELAY"] = "delay";
69
+ EScheduleStrategy2["IDLE"] = "idle";
70
+ return EScheduleStrategy2;
71
+ })(EScheduleStrategy || {});
72
+
65
73
  // src/models/state.model.ts
66
74
  var ETaskState = /* @__PURE__ */ ((ETaskState2) => {
67
75
  ETaskState2["PENDING"] = "pending";
@@ -73,12 +81,44 @@ var ETaskState = /* @__PURE__ */ ((ETaskState2) => {
73
81
  return ETaskState2;
74
82
  })(ETaskState || {});
75
83
 
76
- // src/models/strategy.model.ts
77
- var EScheduleStrategy = /* @__PURE__ */ ((EScheduleStrategy2) => {
78
- EScheduleStrategy2["IMMEDIATE"] = "immediate";
79
- EScheduleStrategy2["DELAY"] = "delay";
80
- return EScheduleStrategy2;
81
- })(EScheduleStrategy || {});
84
+ // src/scheduler/idle-scheduler.ts
85
+ var IdleScheduler = class {
86
+ /**
87
+ * Schedules a callback to execute during the next idle opportunity.
88
+ *
89
+ * @param callback - Function to invoke when idle opportunity arises.
90
+ * @param timeout - Optional max deadline in milliseconds to wait before invoking (browser only).
91
+ * @param runtime - Target runtime scope providing scheduling primitives (defaults to globalThis).
92
+ * @returns An {@link IIdleHandle} with a `cancel()` method for cleanup.
93
+ */
94
+ static schedule(callback, timeout, runtime = globalThis) {
95
+ if (typeof runtime.requestIdleCallback === "function" && typeof runtime.cancelIdleCallback === "function") {
96
+ const requestFn = runtime.requestIdleCallback;
97
+ const cancelFn = runtime.cancelIdleCallback;
98
+ const id = requestFn(
99
+ () => callback(),
100
+ typeof timeout === "number" && !Number.isNaN(timeout) && timeout >= 0 ? { timeout } : void 0
101
+ );
102
+ return {
103
+ cancel: () => cancelFn(id)
104
+ };
105
+ }
106
+ if (typeof runtime.setImmediate === "function" && typeof runtime.clearImmediate === "function") {
107
+ const setImmFn = runtime.setImmediate;
108
+ const clearImmFn = runtime.clearImmediate;
109
+ const handle = setImmFn(() => callback());
110
+ return {
111
+ cancel: () => clearImmFn(handle)
112
+ };
113
+ }
114
+ const setTimerFn = runtime.setTimeout.bind(runtime);
115
+ const clearTimerFn = runtime.clearTimeout.bind(runtime);
116
+ const timerId = setTimerFn(() => callback(), 0);
117
+ return {
118
+ cancel: () => clearTimerFn(timerId)
119
+ };
120
+ }
121
+ };
82
122
 
83
123
  // src/scheduler/task-queue.ts
84
124
  var TaskQueue = class {
@@ -90,6 +130,8 @@ var TaskQueue = class {
90
130
  activeRunners = /* @__PURE__ */ new Set();
91
131
  /** Set of tasks currently in delay phase */
92
132
  delayedEntries = /* @__PURE__ */ new Set();
133
+ /** Set of tasks currently awaiting an idle opportunity */
134
+ idleEntries = /* @__PURE__ */ new Set();
93
135
  /** Cumulative completed tasks counter */
94
136
  completedTasks = 0;
95
137
  /** Cumulative failed tasks counter */
@@ -123,9 +165,9 @@ var TaskQueue = class {
123
165
  */
124
166
  enqueue(runner, options) {
125
167
  const strategy = options?.strategy ?? "immediate" /* IMMEDIATE */;
126
- if (strategy !== "immediate" /* IMMEDIATE */ && strategy !== "delay" /* DELAY */) {
168
+ if (strategy !== "immediate" /* IMMEDIATE */ && strategy !== "delay" /* DELAY */ && strategy !== "idle" /* IDLE */) {
127
169
  throw new AhkoConfigurationError(
128
- `Unsupported schedule strategy "${String(strategy)}". Supported strategies in 0.1.0: "immediate", "delay".`
170
+ `Unsupported schedule strategy "${String(strategy)}". Supported strategies: "immediate", "delay", "idle".`
129
171
  );
130
172
  }
131
173
  if (runner.state === "cancelled" /* CANCELLED */) {
@@ -142,6 +184,15 @@ var TaskQueue = class {
142
184
  this.scheduleDelayed(runner, delayMs);
143
185
  return runner.promise;
144
186
  }
187
+ if (strategy === "idle" /* IDLE */) {
188
+ if (options?.idleTimeout !== void 0 && (typeof options.idleTimeout !== "number" || Number.isNaN(options.idleTimeout) || options.idleTimeout < 0)) {
189
+ throw new AhkoConfigurationError(
190
+ `Invalid idleTimeout "${options.idleTimeout}". idleTimeout must be a non-negative number in milliseconds.`
191
+ );
192
+ }
193
+ this.scheduleIdle(runner, options?.idleTimeout);
194
+ return runner.promise;
195
+ }
145
196
  runner.onCancel = () => {
146
197
  const index = this.queue.indexOf(runner);
147
198
  if (index !== -1) {
@@ -185,6 +236,37 @@ var TaskQueue = class {
185
236
  }
186
237
  };
187
238
  }
239
+ /**
240
+ * Schedules a task to be placed into the queue during an idle opportunity,
241
+ * handling early cancellation safely.
242
+ */
243
+ scheduleIdle(runner, idleTimeout) {
244
+ let idleEntry;
245
+ const handle = IdleScheduler.schedule(() => {
246
+ this.idleEntries.delete(idleEntry);
247
+ if (runner.state === "cancelled" /* CANCELLED */) {
248
+ return;
249
+ }
250
+ runner.onCancel = () => {
251
+ const index = this.queue.indexOf(runner);
252
+ if (index !== -1) {
253
+ this.queue.splice(index, 1);
254
+ this.cancelledTasks++;
255
+ }
256
+ };
257
+ this.queue.push(runner);
258
+ this.pump();
259
+ }, idleTimeout);
260
+ idleEntry = { runner, handle };
261
+ this.idleEntries.add(idleEntry);
262
+ runner.onCancel = () => {
263
+ if (this.idleEntries.has(idleEntry)) {
264
+ handle.cancel();
265
+ this.idleEntries.delete(idleEntry);
266
+ this.cancelledTasks++;
267
+ }
268
+ };
269
+ }
188
270
  /**
189
271
  * Pumps the queue by picking pending tasks and executing them
190
272
  * as long as concurrency capacity is available.
@@ -234,7 +316,7 @@ var TaskQueue = class {
234
316
  getStats() {
235
317
  return Object.freeze({
236
318
  activeTasks: this.activeRunners.size,
237
- pendingTasks: this.queue.length + this.delayedEntries.size,
319
+ pendingTasks: this.queue.length + this.delayedEntries.size + this.idleEntries.size,
238
320
  completedTasks: this.completedTasks,
239
321
  failedTasks: this.failedTasks,
240
322
  cancelledTasks: this.cancelledTasks,
@@ -454,6 +536,35 @@ var Ahko = class {
454
536
  const runner = new TaskRunner(task, options?.signal);
455
537
  return this.queue.enqueue(runner, options);
456
538
  }
539
+ /**
540
+ * Convenience method to schedule a task during platform idle opportunities.
541
+ *
542
+ * Equivalent to calling `schedule(task, { ...options, strategy: "idle" })`.
543
+ * In browsers, uses `requestIdleCallback` when available.
544
+ * In Node.js, uses `setImmediate`.
545
+ * Falls back to `setTimeout(..., 0)` if neither is available.
546
+ *
547
+ * @template T - Inferred return type of the task.
548
+ * @param task - Task function to run when idle.
549
+ * @param options - Scheduling options (excluding strategy).
550
+ * @returns A promise resolving to the task's return value.
551
+ *
552
+ * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.
553
+ * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.
554
+ *
555
+ * @example
556
+ * ```typescript
557
+ * const result = await ahko.idle(async ({ signal }) => {
558
+ * return computeAnalytics();
559
+ * });
560
+ * ```
561
+ */
562
+ idle(task, options) {
563
+ return this.schedule(task, {
564
+ ...options,
565
+ strategy: "idle" /* IDLE */
566
+ });
567
+ }
457
568
  /**
458
569
  * Retrieves real-time telemetry metrics from the scheduler.
459
570
  *
@@ -471,7 +582,7 @@ var Ahko = class {
471
582
  };
472
583
 
473
584
  // src/version.ts
474
- var VERSION = "0.1.0";
585
+ var VERSION = "0.2.0";
475
586
 
476
587
  // src/errors/queue.error.ts
477
588
  var AhkoQueueError = class extends AhkoError {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/errors/ahko.error.ts","../src/errors/configuration.error.ts","../src/models/state.model.ts","../src/models/strategy.model.ts","../src/scheduler/task-queue.ts","../src/errors/cancellation.error.ts","../src/scheduler/task-runner.ts","../src/ahko.ts","../src/version.ts","../src/errors/queue.error.ts","../src/errors/timeout.error.ts"],"sourcesContent":["export { Ahko } from \"./ahko.js\";\nexport { VERSION } from \"./version.js\";\n\n// Errors\nexport {\n AhkoError,\n AhkoCancellationError,\n AhkoConfigurationError,\n AhkoQueueError,\n AhkoTimeoutError,\n} from \"./errors/index.js\";\n\n// Models and interfaces\nexport {\n ETaskState,\n EScheduleStrategy,\n} from \"./models/index.js\";\n\nexport type {\n ITask,\n ITaskContext,\n IScheduleOptions,\n IAhkoOptions,\n IAhkoStats,\n TScheduleStrategy,\n} from \"./models/index.js\";\n","/**\n * Base error class for all errors originating from the Ahko scheduler.\n */\nexport class AhkoError extends Error {\n /**\n * Creates a new AhkoError instance.\n *\n * @param message - Descriptive error message.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when invalid configuration or scheduling options are provided.\n */\nexport class AhkoConfigurationError extends AhkoError {\n /**\n * Creates a new AhkoConfigurationError.\n *\n * @param message - Explanation of the invalid configuration parameter.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoConfigurationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","/**\n * Represents the discrete lifecycle states of an Ahko task.\n */\nexport enum ETaskState {\n /** Task has been scheduled and is awaiting execution in queue or timer */\n PENDING = \"pending\",\n /** Task is currently executing within an allocated concurrency slot */\n RUNNING = \"running\",\n /** Task successfully finished execution */\n COMPLETED = \"completed\",\n /** Task execution threw an error or rejected */\n FAILED = \"failed\",\n /** Task was cancelled via AbortSignal before or during execution */\n CANCELLED = \"cancelled\",\n /** Task was terminated because its execution exceeded the timeout */\n TIMED_OUT = \"timed_out\",\n}\n","/**\n * Fundamental scheduling strategies supported by the Ahko scheduler.\n */\nexport enum EScheduleStrategy {\n /** Execute as soon as a concurrency slot is available */\n IMMEDIATE = \"immediate\",\n /** Delay execution for a designated duration before queuing */\n DELAY = \"delay\",\n}\n\n/**\n * Union type representing valid scheduling strategy identifiers.\n */\nexport type TScheduleStrategy = EScheduleStrategy | \"immediate\" | \"delay\";\n","import { AhkoConfigurationError } from \"../errors/configuration.error.js\";\nimport type { IScheduleOptions } from \"../models/options.model.js\";\nimport type { IAhkoStats } from \"../models/stats.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport { EScheduleStrategy } from \"../models/strategy.model.js\";\nimport { TaskRunner } from \"./task-runner.js\";\n\n/**\n * Entry tracking delayed task timers for deterministic cancellation and memory cleanup.\n */\ninterface IDelayedEntry {\n runner: TaskRunner<unknown>;\n timerId: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Memory-safe FIFO task queue managing concurrency allocation,\n * delayed scheduling, and task lifecycle counters.\n */\nexport class TaskQueue {\n /** Maximum concurrent active tasks */\n public readonly concurrency: number;\n\n /** Queue of pending task runners waiting for a concurrency slot */\n private readonly queue: TaskRunner<unknown>[] = [];\n\n /** Set of task runners currently executing */\n private readonly activeRunners = new Set<TaskRunner<unknown>>();\n\n /** Set of tasks currently in delay phase */\n private readonly delayedEntries = new Set<IDelayedEntry>();\n\n /** Cumulative completed tasks counter */\n private completedTasks = 0;\n\n /** Cumulative failed tasks counter */\n private failedTasks = 0;\n\n /** Cumulative cancelled tasks counter */\n private cancelledTasks = 0;\n\n /** Cumulative timed out tasks counter */\n private timedOutTasks = 0;\n\n /**\n * Creates a new TaskQueue.\n *\n * @param concurrency - Maximum concurrent tasks (defaults to Infinity).\n * @throws {AhkoConfigurationError} If concurrency is less than 1 or not a valid number.\n */\n constructor(concurrency = Infinity) {\n if (Number.isNaN(concurrency) || concurrency < 1) {\n throw new AhkoConfigurationError(\n `Invalid concurrency \"${concurrency}\". Must be a number greater than or equal to 1.`\n );\n }\n this.concurrency = concurrency;\n }\n\n /**\n * Enqueues a task runner according to the specified schedule options.\n *\n * @template T - The return type produced by the task.\n * @param runner - The task runner instance.\n * @param options - Scheduling options.\n * @returns The deferred promise associated with the task runner.\n * @throws {AhkoConfigurationError} If scheduling options are invalid.\n */\n public enqueue<T>(runner: TaskRunner<T>, options?: IScheduleOptions): Promise<T> {\n const strategy = options?.strategy ?? EScheduleStrategy.IMMEDIATE;\n\n if (strategy !== EScheduleStrategy.IMMEDIATE && strategy !== EScheduleStrategy.DELAY) {\n throw new AhkoConfigurationError(\n `Unsupported schedule strategy \"${String(strategy)}\". Supported strategies in 0.1.0: \"immediate\", \"delay\".`\n );\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n return runner.promise;\n }\n\n if (strategy === EScheduleStrategy.DELAY) {\n const delayMs = options?.delay ?? 0;\n if (typeof delayMs !== \"number\" || Number.isNaN(delayMs) || delayMs < 0) {\n throw new AhkoConfigurationError(\n `Invalid delay \"${delayMs}\". Delay must be a non-negative number in milliseconds.`\n );\n }\n\n this.scheduleDelayed(runner as TaskRunner<unknown>, delayMs);\n return runner.promise;\n }\n\n // Attach immediate onCancel handler to dequeue without consuming concurrency\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner as TaskRunner<unknown>);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n // Immediate strategy: add to pending queue and pump\n this.queue.push(runner as TaskRunner<unknown>);\n this.pump();\n\n return runner.promise;\n }\n\n /**\n * Schedules a task to be placed into the queue after a delay,\n * handling early cancellation safely.\n */\n private scheduleDelayed(runner: TaskRunner<unknown>, delayMs: number): void {\n const delayedEntry: IDelayedEntry = {\n runner,\n timerId: setTimeout(() => {\n this.delayedEntries.delete(delayedEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, delayMs),\n };\n\n this.delayedEntries.add(delayedEntry);\n\n runner.onCancel = () => {\n if (this.delayedEntries.has(delayedEntry)) {\n clearTimeout(delayedEntry.timerId);\n this.delayedEntries.delete(delayedEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Pumps the queue by picking pending tasks and executing them\n * as long as concurrency capacity is available.\n */\n private pump(): void {\n while (this.activeRunners.size < this.concurrency && this.queue.length > 0) {\n const runner = this.queue.shift();\n if (!runner) {\n break;\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n continue;\n }\n\n this.activeRunners.add(runner);\n\n // Execute runner without unhandled rejection risk\n void this.executeRunner(runner);\n }\n }\n\n /**\n * Internal execution of an active task runner.\n * Settle caller promise strictly after stats and active status are updated.\n */\n private async executeRunner(runner: TaskRunner<unknown>): Promise<void> {\n try {\n const result = await runner.run();\n this.completedTasks++;\n this.activeRunners.delete(runner);\n runner.resolve(result);\n } catch (error) {\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n } else if (runner.state === ETaskState.TIMED_OUT) {\n this.timedOutTasks++;\n } else {\n this.failedTasks++;\n }\n this.activeRunners.delete(runner);\n runner.reject(error);\n } finally {\n this.pump();\n }\n }\n\n /**\n * Returns telemetry snapshot for the scheduler.\n *\n * @returns Frozen snapshot of current task metrics.\n */\n public getStats(): IAhkoStats {\n return Object.freeze({\n activeTasks: this.activeRunners.size,\n pendingTasks: this.queue.length + this.delayedEntries.size,\n completedTasks: this.completedTasks,\n failedTasks: this.failedTasks,\n cancelledTasks: this.cancelledTasks,\n timedOutTasks: this.timedOutTasks,\n capacity: this.concurrency,\n });\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when a task is cancelled before or during execution.\n */\nexport class AhkoCancellationError extends AhkoError {\n /**\n * Creates a new AhkoCancellationError.\n *\n * @param message - Reason for cancellation.\n * @param options - Standard Error options including cause.\n */\n constructor(message = \"Task was cancelled\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoCancellationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoCancellationError } from \"../errors/cancellation.error.js\";\nimport type { ITaskContext } from \"../models/context.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport type { ITask } from \"../models/task.model.js\";\n\nlet taskIdCounter = 0;\n\n/**\n * Internal task lifecycle manager responsible for execution, state transitions,\n * AbortSignal coordination, and deterministic resource cleanup.\n *\n * @template T - The return type produced by the underlying task.\n */\nexport class TaskRunner<T> {\n /** Unique task identifier */\n public readonly taskId: string;\n\n /** Current lifecycle state */\n private _state: ETaskState = ETaskState.PENDING;\n\n /** Internal AbortController whose signal is passed to the task context */\n private readonly abortController: AbortController;\n\n /** The user task function to execute */\n private readonly task: ITask<T>;\n\n /** User-supplied AbortSignal for external cancellation */\n private readonly externalSignal?: AbortSignal;\n\n /** Abort event listener reference for clean detachment */\n private readonly abortListener?: () => void;\n\n /** Promise resolve handler */\n private resolvePromise!: (value: T | PromiseLike<T>) => void;\n\n /** Promise reject handler */\n private rejectPromise!: (reason?: unknown) => void;\n\n /** Deferred promise exposed to the caller */\n public readonly promise: Promise<T>;\n\n /** Callback invoked when runner is cancelled while pending */\n public onCancel?: (runner: TaskRunner<T>) => void;\n\n /**\n * Creates a new TaskRunner instance.\n *\n * @param task - The asynchronous work unit to run.\n * @param externalSignal - Optional external AbortSignal to propagate.\n */\n constructor(task: ITask<T>, externalSignal?: AbortSignal) {\n this.taskId = `task_${Date.now().toString(36)}_${(++taskIdCounter).toString(36)}_${Math.random().toString(36).slice(2, 6)}`;\n this.task = task;\n this.externalSignal = externalSignal;\n this.abortController = new AbortController();\n\n this.promise = new Promise<T>((resolve, reject) => {\n this.resolvePromise = resolve;\n this.rejectPromise = reject;\n });\n\n if (this.externalSignal) {\n if (this.externalSignal.aborted) {\n this._state = ETaskState.CANCELLED;\n const reason = this.externalSignal.reason;\n const cancelError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.rejectPromise(cancelError);\n } else {\n this.abortListener = () => {\n this.handleExternalAbort();\n };\n this.externalSignal.addEventListener(\"abort\", this.abortListener, { once: true });\n }\n }\n }\n\n /**\n * Gets the current lifecycle state of the task.\n */\n public get state(): ETaskState {\n return this._state;\n }\n\n /**\n * Resolves the deferred promise.\n *\n * @param value - Value to resolve with.\n */\n public resolve(value: T): void {\n this.resolvePromise(value);\n }\n\n /**\n * Rejects the deferred promise.\n *\n * @param reason - Reason to reject with.\n */\n public reject(reason: unknown): void {\n this.rejectPromise(reason);\n }\n\n /**\n * Executes the task within an allocated concurrency slot.\n *\n * @returns A promise resolving to the task result or rejecting on failure/cancellation.\n */\n public async run(): Promise<T> {\n if (this._state === ETaskState.CANCELLED) {\n throw new AhkoCancellationError(\"Task was cancelled prior to execution\");\n }\n\n this._state = ETaskState.RUNNING;\n\n const context: ITaskContext = {\n signal: this.abortController.signal,\n taskId: this.taskId,\n };\n\n try {\n const result = await this.task(context);\n this._state = ETaskState.COMPLETED;\n this.cleanup();\n return result;\n } catch (error) {\n this.cleanup();\n\n const isCancelled =\n (this._state as ETaskState) === ETaskState.CANCELLED ||\n this.abortController.signal.aborted;\n\n if (isCancelled) {\n this._state = ETaskState.CANCELLED;\n throw new AhkoCancellationError(\"Task was cancelled during execution\", {\n cause: error instanceof Error ? error : undefined,\n });\n }\n\n this._state = ETaskState.FAILED;\n throw error;\n }\n }\n\n /**\n * Cancels the task, aborting pending or running execution.\n *\n * @param reason - Optional cancellation reason.\n */\n public cancel(reason?: unknown): void {\n if (\n this._state === ETaskState.COMPLETED ||\n this._state === ETaskState.FAILED ||\n this._state === ETaskState.CANCELLED ||\n this._state === ETaskState.TIMED_OUT\n ) {\n return;\n }\n\n const wasPending = this._state === ETaskState.PENDING;\n this._state = ETaskState.CANCELLED;\n this.abortController.abort(reason);\n this.cleanup();\n\n if (wasPending) {\n const cancellationError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.rejectPromise(cancellationError);\n this.onCancel?.(this);\n }\n }\n\n /**\n * Handles external AbortSignal trigger.\n */\n private handleExternalAbort(): void {\n this.cancel(this.externalSignal?.reason);\n }\n\n /**\n * Detaches event listeners from external signal to guarantee memory safety.\n */\n public cleanup(): void {\n if (this.externalSignal && this.abortListener) {\n this.externalSignal.removeEventListener(\"abort\", this.abortListener);\n }\n }\n}\n","import { AhkoConfigurationError } from \"./errors/configuration.error.js\";\nimport type { IAhkoOptions, IScheduleOptions } from \"./models/options.model.js\";\nimport type { IAhkoStats } from \"./models/stats.model.js\";\nimport type { ITask } from \"./models/task.model.js\";\nimport { TaskQueue } from \"./scheduler/task-queue.js\";\nimport { TaskRunner } from \"./scheduler/task-runner.js\";\n\n/**\n * Ahko — Low-energy, production-grade asynchronous task scheduler.\n *\n * Coordinates execution timing, enforces concurrency limits, and cooperates\n * natively with AbortSignal cancellation.\n *\n * @example\n * ```typescript\n * import { Ahko } from \"@mrjacket/ahko\";\n *\n * const ahko = new Ahko({ concurrency: 2 });\n *\n * const result = await ahko.schedule(async ({ signal, taskId }) => {\n * const res = await fetch(\"https://api.example.com\", { signal });\n * return res.json();\n * });\n * ```\n */\nexport class Ahko {\n /** Internal queue and concurrency manager */\n private readonly queue: TaskQueue;\n\n /**\n * Initializes a new Ahko scheduler instance.\n *\n * @param options - Optional scheduler configuration.\n * @throws {AhkoConfigurationError} If concurrency is invalid (less than 1 or NaN).\n *\n * @example\n * ```typescript\n * const ahko = new Ahko({ concurrency: 4 });\n * ```\n */\n constructor(options?: IAhkoOptions) {\n this.queue = new TaskQueue(options?.concurrency);\n }\n\n /**\n * Schedules a task for execution with full return type inference.\n *\n * @template T - Inferred return type of the task.\n * @param task - Asynchronous or synchronous task function accepting an {@link ITaskContext}.\n * @param options - Task-specific scheduling options such as strategy, delay, and cancellation signal.\n * @returns A promise that resolves with the task's return value.\n *\n * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.\n * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.\n *\n * @example\n * ```typescript\n * // Immediate execution (subject to concurrency)\n * const count = await ahko.schedule(async () => 42);\n *\n * // Delayed execution\n * await ahko.schedule(\n * async ({ signal }) => doWork({ signal }),\n * { strategy: \"delay\", delay: 1000 }\n * );\n * ```\n */\n public schedule<T>(task: ITask<T>, options?: IScheduleOptions): Promise<T> {\n if (typeof task !== \"function\") {\n throw new AhkoConfigurationError(\"Task must be a valid function.\");\n }\n\n const runner = new TaskRunner<T>(task, options?.signal);\n return this.queue.enqueue(runner, options);\n }\n\n /**\n * Retrieves real-time telemetry metrics from the scheduler.\n *\n * @returns An {@link IAhkoStats} snapshot of active, pending, completed, failed, cancelled, and timed out tasks.\n *\n * @example\n * ```typescript\n * const stats = ahko.stats();\n * console.log(`Active: ${stats.activeTasks}, Pending: ${stats.pendingTasks}`);\n * ```\n */\n public stats(): IAhkoStats {\n return this.queue.getStats();\n }\n}\n","/**\n * Current version of @mrjacket/ahko package.\n */\nexport const VERSION = \"0.1.0\";\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when an internal queue invariant is violated or queue limits are breached.\n */\nexport class AhkoQueueError extends AhkoError {\n /**\n * Creates a new AhkoQueueError.\n *\n * @param message - Explanation of the queue failure.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoQueueError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when a task exceeds its allotted timeout duration.\n */\nexport class AhkoTimeoutError extends AhkoError {\n /**\n * Creates a new AhkoTimeoutError.\n *\n * @param message - Explanation of timeout expiry.\n * @param options - Standard Error options including cause.\n */\n constructor(message = \"Task execution timed out\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoTimeoutError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,YAAN,cAAwB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnC,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACVO,IAAM,yBAAN,cAAqC,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOpD,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACdO,IAAK,aAAL,kBAAKA,gBAAL;AAEL,EAAAA,YAAA,aAAU;AAEV,EAAAA,YAAA,aAAU;AAEV,EAAAA,YAAA,eAAY;AAEZ,EAAAA,YAAA,YAAS;AAET,EAAAA,YAAA,eAAY;AAE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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAyBO,SAAY,MAAgB,SAAwC;AACzE,QAAI,OAAO,SAAS,YAAY;AAC9B,YAAM,IAAI,uBAAuB,gCAAgC;AAAA,IACnE;AAEA,UAAM,SAAS,IAAI,WAAc,MAAM,SAAS,MAAM;AACtD,WAAO,KAAK,MAAM,QAAQ,QAAQ,OAAO;AAAA,EAC3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaO,QAAoB;AACzB,WAAO,KAAK,MAAM,SAAS;AAAA,EAC7B;AACF;;;ACvFO,IAAM,UAAU;;;ACEhB,IAAM,iBAAN,cAA6B,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO5C,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACZO,IAAM,mBAAN,cAA+B,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO9C,YAAY,UAAU,4BAA4B,SAAwB;AACxE,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;","names":["ETaskState","EScheduleStrategy"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/errors/ahko.error.ts","../src/errors/configuration.error.ts","../src/models/strategy.model.ts","../src/models/state.model.ts","../src/scheduler/idle-scheduler.ts","../src/scheduler/task-queue.ts","../src/errors/cancellation.error.ts","../src/scheduler/task-runner.ts","../src/ahko.ts","../src/version.ts","../src/errors/queue.error.ts","../src/errors/timeout.error.ts"],"sourcesContent":["export { Ahko } from \"./ahko.js\";\nexport { VERSION } from \"./version.js\";\n\n// Errors\nexport {\n AhkoError,\n AhkoCancellationError,\n AhkoConfigurationError,\n AhkoQueueError,\n AhkoTimeoutError,\n} from \"./errors/index.js\";\n\n// Models and interfaces\nexport {\n ETaskState,\n EScheduleStrategy,\n} from \"./models/index.js\";\n\nexport type {\n ITask,\n ITaskContext,\n IScheduleOptions,\n IAhkoOptions,\n IAhkoStats,\n TScheduleStrategy,\n} from \"./models/index.js\";\n","/**\n * Base error class for all errors originating from the Ahko scheduler.\n */\nexport class AhkoError extends Error {\n /**\n * Creates a new AhkoError instance.\n *\n * @param message - Descriptive error message.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when invalid configuration or scheduling options are provided.\n */\nexport class AhkoConfigurationError extends AhkoError {\n /**\n * Creates a new AhkoConfigurationError.\n *\n * @param message - Explanation of the invalid configuration parameter.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoConfigurationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","/**\n * Fundamental scheduling strategies supported by the Ahko scheduler.\n */\nexport enum EScheduleStrategy {\n /** Execute as soon as a concurrency slot is available */\n IMMEDIATE = \"immediate\",\n /** Delay execution for a designated duration before queuing */\n DELAY = \"delay\",\n /** Execute during platform idle opportunities (requestIdleCallback in browser, setImmediate in Node.js) */\n IDLE = \"idle\",\n}\n\n/**\n * Union type representing valid scheduling strategy identifiers.\n */\nexport type TScheduleStrategy = EScheduleStrategy | \"immediate\" | \"delay\" | \"idle\";\n","/**\n * Represents the discrete lifecycle states of an Ahko task.\n */\nexport enum ETaskState {\n /** Task has been scheduled and is awaiting execution in queue or timer */\n PENDING = \"pending\",\n /** Task is currently executing within an allocated concurrency slot */\n RUNNING = \"running\",\n /** Task successfully finished execution */\n COMPLETED = \"completed\",\n /** Task execution threw an error or rejected */\n FAILED = \"failed\",\n /** Task was cancelled via AbortSignal before or during execution */\n CANCELLED = \"cancelled\",\n /** Task was terminated because its execution exceeded the timeout */\n TIMED_OUT = \"timed_out\",\n}\n","/**\n * Handle returned by the IdleScheduler allowing cancellation of an idle request.\n */\nexport interface IIdleHandle {\n /**\n * Cancels the scheduled idle callback and cleans up platform resources.\n */\n cancel(): void;\n}\n\n/**\n * Platform-agnostic scheduler for opportunistic idle task execution.\n *\n * Automatically detects and selects platform capabilities:\n * 1. Browser: `requestIdleCallback` / `cancelIdleCallback` (with optional timeout)\n * 2. Node.js: `setImmediate` / `clearImmediate` as low-priority primitive\n * 3. Fallback: `setTimeout(..., 0)` / `clearTimeout`\n */\nexport class IdleScheduler {\n /**\n * Schedules a callback to execute during the next idle opportunity.\n *\n * @param callback - Function to invoke when idle opportunity arises.\n * @param timeout - Optional max deadline in milliseconds to wait before invoking (browser only).\n * @param runtime - Target runtime scope providing scheduling primitives (defaults to globalThis).\n * @returns An {@link IIdleHandle} with a `cancel()` method for cleanup.\n */\n public static schedule(\n callback: () => void,\n timeout?: number,\n runtime: typeof globalThis = globalThis\n ): IIdleHandle {\n // 1. Browser requestIdleCallback\n if (\n typeof (runtime as Record<string, unknown>).requestIdleCallback === \"function\" &&\n typeof (runtime as Record<string, unknown>).cancelIdleCallback === \"function\"\n ) {\n const requestFn = (runtime as Record<string, unknown>).requestIdleCallback as (\n cb: (deadline?: unknown) => void,\n opts?: { timeout?: number }\n ) => number;\n\n const cancelFn = (runtime as Record<string, unknown>).cancelIdleCallback as (\n handle: number\n ) => void;\n\n const id = requestFn(\n () => callback(),\n typeof timeout === \"number\" && !Number.isNaN(timeout) && timeout >= 0\n ? { timeout }\n : undefined\n );\n\n return {\n cancel: () => cancelFn(id),\n };\n }\n\n // 2. Node.js setImmediate\n if (\n typeof (runtime as Record<string, unknown>).setImmediate === \"function\" &&\n typeof (runtime as Record<string, unknown>).clearImmediate === \"function\"\n ) {\n const setImmFn = (runtime as Record<string, unknown>).setImmediate as (\n cb: () => void\n ) => ReturnType<typeof setImmediate>;\n\n const clearImmFn = (runtime as Record<string, unknown>).clearImmediate as (\n handle: ReturnType<typeof setImmediate>\n ) => void;\n\n const handle = setImmFn(() => callback());\n\n return {\n cancel: () => clearImmFn(handle),\n };\n }\n\n // 3. Universal fallback setTimeout(0)\n const setTimerFn = runtime.setTimeout.bind(runtime);\n const clearTimerFn = runtime.clearTimeout.bind(runtime);\n\n const timerId = setTimerFn(() => callback(), 0);\n\n return {\n cancel: () => clearTimerFn(timerId),\n };\n }\n}\n","import { AhkoConfigurationError } from \"../errors/configuration.error.js\";\nimport type { IScheduleOptions } from \"../models/options.model.js\";\nimport type { IAhkoStats } from \"../models/stats.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport { EScheduleStrategy } from \"../models/strategy.model.js\";\nimport { IdleScheduler, type IIdleHandle } from \"./idle-scheduler.js\";\nimport { TaskRunner } from \"./task-runner.js\";\n\n/**\n * Entry tracking delayed task timers for deterministic cancellation and memory cleanup.\n */\ninterface IDelayedEntry {\n runner: TaskRunner<unknown>;\n timerId: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Entry tracking idle callback handles for deterministic cancellation and cleanup.\n */\ninterface IIdleEntry {\n runner: TaskRunner<unknown>;\n handle: IIdleHandle;\n}\n\n/**\n * Memory-safe FIFO task queue managing concurrency allocation,\n * delayed scheduling, and task lifecycle counters.\n */\nexport class TaskQueue {\n /** Maximum concurrent active tasks */\n public readonly concurrency: number;\n\n /** Queue of pending task runners waiting for a concurrency slot */\n private readonly queue: TaskRunner<unknown>[] = [];\n\n /** Set of task runners currently executing */\n private readonly activeRunners = new Set<TaskRunner<unknown>>();\n\n /** Set of tasks currently in delay phase */\n private readonly delayedEntries = new Set<IDelayedEntry>();\n\n /** Set of tasks currently awaiting an idle opportunity */\n private readonly idleEntries = new Set<IIdleEntry>();\n\n /** Cumulative completed tasks counter */\n private completedTasks = 0;\n\n /** Cumulative failed tasks counter */\n private failedTasks = 0;\n\n /** Cumulative cancelled tasks counter */\n private cancelledTasks = 0;\n\n /** Cumulative timed out tasks counter */\n private timedOutTasks = 0;\n\n /**\n * Creates a new TaskQueue.\n *\n * @param concurrency - Maximum concurrent tasks (defaults to Infinity).\n * @throws {AhkoConfigurationError} If concurrency is less than 1 or not a valid number.\n */\n constructor(concurrency = Infinity) {\n if (Number.isNaN(concurrency) || concurrency < 1) {\n throw new AhkoConfigurationError(\n `Invalid concurrency \"${concurrency}\". Must be a number greater than or equal to 1.`\n );\n }\n this.concurrency = concurrency;\n }\n\n /**\n * Enqueues a task runner according to the specified schedule options.\n *\n * @template T - The return type produced by the task.\n * @param runner - The task runner instance.\n * @param options - Scheduling options.\n * @returns The deferred promise associated with the task runner.\n * @throws {AhkoConfigurationError} If scheduling options are invalid.\n */\n public enqueue<T>(runner: TaskRunner<T>, options?: IScheduleOptions): Promise<T> {\n const strategy = options?.strategy ?? EScheduleStrategy.IMMEDIATE;\n\n if (\n strategy !== EScheduleStrategy.IMMEDIATE &&\n strategy !== EScheduleStrategy.DELAY &&\n strategy !== EScheduleStrategy.IDLE\n ) {\n throw new AhkoConfigurationError(\n `Unsupported schedule strategy \"${String(strategy)}\". Supported strategies: \"immediate\", \"delay\", \"idle\".`\n );\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n return runner.promise;\n }\n\n if (strategy === EScheduleStrategy.DELAY) {\n const delayMs = options?.delay ?? 0;\n if (typeof delayMs !== \"number\" || Number.isNaN(delayMs) || delayMs < 0) {\n throw new AhkoConfigurationError(\n `Invalid delay \"${delayMs}\". Delay must be a non-negative number in milliseconds.`\n );\n }\n\n this.scheduleDelayed(runner as TaskRunner<unknown>, delayMs);\n return runner.promise;\n }\n\n if (strategy === EScheduleStrategy.IDLE) {\n if (\n options?.idleTimeout !== undefined &&\n (typeof options.idleTimeout !== \"number\" ||\n Number.isNaN(options.idleTimeout) ||\n options.idleTimeout < 0)\n ) {\n throw new AhkoConfigurationError(\n `Invalid idleTimeout \"${options.idleTimeout}\". idleTimeout must be a non-negative number in milliseconds.`\n );\n }\n\n this.scheduleIdle(runner as TaskRunner<unknown>, options?.idleTimeout);\n return runner.promise;\n }\n\n // Attach immediate onCancel handler to dequeue without consuming concurrency\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner as TaskRunner<unknown>);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n // Immediate strategy: add to pending queue and pump\n this.queue.push(runner as TaskRunner<unknown>);\n this.pump();\n\n return runner.promise;\n }\n\n /**\n * Schedules a task to be placed into the queue after a delay,\n * handling early cancellation safely.\n */\n private scheduleDelayed(runner: TaskRunner<unknown>, delayMs: number): void {\n const delayedEntry: IDelayedEntry = {\n runner,\n timerId: setTimeout(() => {\n this.delayedEntries.delete(delayedEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, delayMs),\n };\n\n this.delayedEntries.add(delayedEntry);\n\n runner.onCancel = () => {\n if (this.delayedEntries.has(delayedEntry)) {\n clearTimeout(delayedEntry.timerId);\n this.delayedEntries.delete(delayedEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Schedules a task to be placed into the queue during an idle opportunity,\n * handling early cancellation safely.\n */\n private scheduleIdle(runner: TaskRunner<unknown>, idleTimeout?: number): void {\n let idleEntry!: IIdleEntry;\n\n const handle = IdleScheduler.schedule(() => {\n this.idleEntries.delete(idleEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, idleTimeout);\n\n idleEntry = { runner, handle };\n this.idleEntries.add(idleEntry);\n\n runner.onCancel = () => {\n if (this.idleEntries.has(idleEntry)) {\n handle.cancel();\n this.idleEntries.delete(idleEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Pumps the queue by picking pending tasks and executing them\n * as long as concurrency capacity is available.\n */\n private pump(): void {\n while (this.activeRunners.size < this.concurrency && this.queue.length > 0) {\n const runner = this.queue.shift();\n if (!runner) {\n break;\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n continue;\n }\n\n this.activeRunners.add(runner);\n\n // Execute runner without unhandled rejection risk\n void this.executeRunner(runner);\n }\n }\n\n /**\n * Internal execution of an active task runner.\n * Settle caller promise strictly after stats and active status are updated.\n */\n private async executeRunner(runner: TaskRunner<unknown>): Promise<void> {\n try {\n const result = await runner.run();\n this.completedTasks++;\n this.activeRunners.delete(runner);\n runner.resolve(result);\n } catch (error) {\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n } else if (runner.state === ETaskState.TIMED_OUT) {\n this.timedOutTasks++;\n } else {\n this.failedTasks++;\n }\n this.activeRunners.delete(runner);\n runner.reject(error);\n } finally {\n this.pump();\n }\n }\n\n /**\n * Returns telemetry snapshot for the scheduler.\n *\n * @returns Frozen snapshot of current task metrics.\n */\n public getStats(): IAhkoStats {\n return Object.freeze({\n activeTasks: this.activeRunners.size,\n pendingTasks: this.queue.length + this.delayedEntries.size + this.idleEntries.size,\n completedTasks: this.completedTasks,\n failedTasks: this.failedTasks,\n cancelledTasks: this.cancelledTasks,\n timedOutTasks: this.timedOutTasks,\n capacity: this.concurrency,\n });\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when a task is cancelled before or during execution.\n */\nexport class AhkoCancellationError extends AhkoError {\n /**\n * Creates a new AhkoCancellationError.\n *\n * @param message - Reason for cancellation.\n * @param options - Standard Error options including cause.\n */\n constructor(message = \"Task was cancelled\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoCancellationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoCancellationError } from \"../errors/cancellation.error.js\";\nimport type { ITaskContext } from \"../models/context.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport type { ITask } from \"../models/task.model.js\";\n\nlet taskIdCounter = 0;\n\n/**\n * Internal task lifecycle manager responsible for execution, state transitions,\n * AbortSignal coordination, and deterministic resource cleanup.\n *\n * @template T - The return type produced by the underlying task.\n */\nexport class TaskRunner<T> {\n /** Unique task identifier */\n public readonly taskId: string;\n\n /** Current lifecycle state */\n private _state: ETaskState = ETaskState.PENDING;\n\n /** Internal AbortController whose signal is passed to the task context */\n private readonly abortController: AbortController;\n\n /** The user task function to execute */\n private readonly task: ITask<T>;\n\n /** User-supplied AbortSignal for external cancellation */\n private readonly externalSignal?: AbortSignal;\n\n /** Abort event listener reference for clean detachment */\n private readonly abortListener?: () => void;\n\n /** Promise resolve handler */\n private resolvePromise!: (value: T | PromiseLike<T>) => void;\n\n /** Promise reject handler */\n private rejectPromise!: (reason?: unknown) => void;\n\n /** Deferred promise exposed to the caller */\n public readonly promise: Promise<T>;\n\n /** Callback invoked when runner is cancelled while pending */\n public onCancel?: (runner: TaskRunner<T>) => void;\n\n /**\n * Creates a new TaskRunner instance.\n *\n * @param task - The asynchronous work unit to run.\n * @param externalSignal - Optional external AbortSignal to propagate.\n */\n constructor(task: ITask<T>, externalSignal?: AbortSignal) {\n this.taskId = `task_${Date.now().toString(36)}_${(++taskIdCounter).toString(36)}_${Math.random().toString(36).slice(2, 6)}`;\n this.task = task;\n this.externalSignal = externalSignal;\n this.abortController = new AbortController();\n\n this.promise = new Promise<T>((resolve, reject) => {\n this.resolvePromise = resolve;\n this.rejectPromise = reject;\n });\n\n if (this.externalSignal) {\n if (this.externalSignal.aborted) {\n this._state = ETaskState.CANCELLED;\n const reason = this.externalSignal.reason;\n const cancelError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.rejectPromise(cancelError);\n } else {\n this.abortListener = () => {\n this.handleExternalAbort();\n };\n this.externalSignal.addEventListener(\"abort\", this.abortListener, { once: true });\n }\n }\n }\n\n /**\n * Gets the current lifecycle state of the task.\n */\n public get state(): ETaskState {\n return this._state;\n }\n\n /**\n * Resolves the deferred promise.\n *\n * @param value - Value to resolve with.\n */\n public resolve(value: T): void {\n this.resolvePromise(value);\n }\n\n /**\n * Rejects the deferred promise.\n *\n * @param reason - Reason to reject with.\n */\n public reject(reason: unknown): void {\n this.rejectPromise(reason);\n }\n\n /**\n * Executes the task within an allocated concurrency slot.\n *\n * @returns A promise resolving to the task result or rejecting on failure/cancellation.\n */\n public async run(): Promise<T> {\n if (this._state === ETaskState.CANCELLED) {\n throw new AhkoCancellationError(\"Task was cancelled prior to execution\");\n }\n\n this._state = ETaskState.RUNNING;\n\n const context: ITaskContext = {\n signal: this.abortController.signal,\n taskId: this.taskId,\n };\n\n try {\n const result = await this.task(context);\n this._state = ETaskState.COMPLETED;\n this.cleanup();\n return result;\n } catch (error) {\n this.cleanup();\n\n const isCancelled =\n (this._state as ETaskState) === ETaskState.CANCELLED ||\n this.abortController.signal.aborted;\n\n if (isCancelled) {\n this._state = ETaskState.CANCELLED;\n throw new AhkoCancellationError(\"Task was cancelled during execution\", {\n cause: error instanceof Error ? error : undefined,\n });\n }\n\n this._state = ETaskState.FAILED;\n throw error;\n }\n }\n\n /**\n * Cancels the task, aborting pending or running execution.\n *\n * @param reason - Optional cancellation reason.\n */\n public cancel(reason?: unknown): void {\n if (\n this._state === ETaskState.COMPLETED ||\n this._state === ETaskState.FAILED ||\n this._state === ETaskState.CANCELLED ||\n this._state === ETaskState.TIMED_OUT\n ) {\n return;\n }\n\n const wasPending = this._state === ETaskState.PENDING;\n this._state = ETaskState.CANCELLED;\n this.abortController.abort(reason);\n this.cleanup();\n\n if (wasPending) {\n const cancellationError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.rejectPromise(cancellationError);\n this.onCancel?.(this);\n }\n }\n\n /**\n * Handles external AbortSignal trigger.\n */\n private handleExternalAbort(): void {\n this.cancel(this.externalSignal?.reason);\n }\n\n /**\n * Detaches event listeners from external signal to guarantee memory safety.\n */\n public cleanup(): void {\n if (this.externalSignal && this.abortListener) {\n this.externalSignal.removeEventListener(\"abort\", this.abortListener);\n }\n }\n}\n","import { AhkoConfigurationError } from \"./errors/configuration.error.js\";\nimport type { IAhkoOptions, IScheduleOptions } from \"./models/options.model.js\";\nimport type { IAhkoStats } from \"./models/stats.model.js\";\nimport { EScheduleStrategy } from \"./models/strategy.model.js\";\nimport type { ITask } from \"./models/task.model.js\";\nimport { TaskQueue } from \"./scheduler/task-queue.js\";\nimport { TaskRunner } from \"./scheduler/task-runner.js\";\n\n/**\n * Ahko — Low-energy asynchronous task scheduler.\n *\n * Coordinates execution timing, enforces concurrency limits, and cooperates\n * natively with AbortSignal cancellation.\n *\n * @example\n * ```typescript\n * import { Ahko } from \"@mrjacket/ahko\";\n *\n * const ahko = new Ahko({ concurrency: 2 });\n *\n * const result = await ahko.schedule(async ({ signal, taskId }) => {\n * const res = await fetch(\"https://api.example.com\", { signal });\n * return res.json();\n * });\n * ```\n */\nexport class Ahko {\n /** Internal queue and concurrency manager */\n private readonly queue: TaskQueue;\n\n /**\n * Initializes a new Ahko scheduler instance.\n *\n * @param options - Optional scheduler configuration.\n * @throws {AhkoConfigurationError} If concurrency is invalid (less than 1 or NaN).\n *\n * @example\n * ```typescript\n * const ahko = new Ahko({ concurrency: 4 });\n * ```\n */\n constructor(options?: IAhkoOptions) {\n this.queue = new TaskQueue(options?.concurrency);\n }\n\n /**\n * Schedules a task for execution with full return type inference.\n *\n * @template T - Inferred return type of the task.\n * @param task - Asynchronous or synchronous task function accepting an {@link ITaskContext}.\n * @param options - Task-specific scheduling options such as strategy, delay, and cancellation signal.\n * @returns A promise that resolves with the task's return value.\n *\n * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.\n * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.\n *\n * @example\n * ```typescript\n * // Immediate execution (subject to concurrency)\n * const count = await ahko.schedule(async () => 42);\n *\n * // Delayed execution\n * await ahko.schedule(\n * async ({ signal }) => doWork({ signal }),\n * { strategy: \"delay\", delay: 1000 }\n * );\n * ```\n */\n public schedule<T>(task: ITask<T>, options?: IScheduleOptions): Promise<T> {\n if (typeof task !== \"function\") {\n throw new AhkoConfigurationError(\"Task must be a valid function.\");\n }\n\n const runner = new TaskRunner<T>(task, options?.signal);\n return this.queue.enqueue(runner, options);\n }\n\n /**\n * Convenience method to schedule a task during platform idle opportunities.\n *\n * Equivalent to calling `schedule(task, { ...options, strategy: \"idle\" })`.\n * In browsers, uses `requestIdleCallback` when available.\n * In Node.js, uses `setImmediate`.\n * Falls back to `setTimeout(..., 0)` if neither is available.\n *\n * @template T - Inferred return type of the task.\n * @param task - Task function to run when idle.\n * @param options - Scheduling options (excluding strategy).\n * @returns A promise resolving to the task's return value.\n *\n * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.\n * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.\n *\n * @example\n * ```typescript\n * const result = await ahko.idle(async ({ signal }) => {\n * return computeAnalytics();\n * });\n * ```\n */\n public idle<T>(\n task: ITask<T>,\n options?: Omit<IScheduleOptions, \"strategy\">\n ): Promise<T> {\n return this.schedule(task, {\n ...options,\n strategy: EScheduleStrategy.IDLE,\n });\n }\n\n /**\n * Retrieves real-time telemetry metrics from the scheduler.\n *\n * @returns An {@link IAhkoStats} snapshot of active, pending, completed, failed, cancelled, and timed out tasks.\n *\n * @example\n * ```typescript\n * const stats = ahko.stats();\n * console.log(`Active: ${stats.activeTasks}, Pending: ${stats.pendingTasks}`);\n * ```\n */\n public stats(): IAhkoStats {\n return this.queue.getStats();\n }\n}\n","/**\n * Current version of @mrjacket/ahko package.\n */\nexport const VERSION = \"0.2.0\";\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when an internal queue invariant is violated or queue limits are breached.\n */\nexport class AhkoQueueError extends AhkoError {\n /**\n * Creates a new AhkoQueueError.\n *\n * @param message - Explanation of the queue failure.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoQueueError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when a task exceeds its allotted timeout duration.\n */\nexport class AhkoTimeoutError extends AhkoError {\n /**\n * Creates a new AhkoTimeoutError.\n *\n * @param message - Explanation of timeout expiry.\n * @param options - Standard Error options including cause.\n */\n constructor(message = \"Task execution timed out\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoTimeoutError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,YAAN,cAAwB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnC,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACVO,IAAM,yBAAN,cAAqC,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOpD,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACdO,IAAK,oBAAL,kBAAKA,uBAAL;AAEL,EAAAA,mBAAA,eAAY;AAEZ,EAAAA,mBAAA,WAAQ;AAER,EAAAA,mBAAA,UAAO;AANG,SAAAA;AAAA,GAAA;;;ACAL,IAAK,aAAL,kBAAKC,gBAAL;AAEL,EAAAA,YAAA,aAAU;AAEV,EAAA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A;AAAA;AAAA;AAAA;AAAA,EAaO,QAAoB;AACzB,WAAO,KAAK,MAAM,SAAS;AAAA,EAC7B;AACF;;;ACzHO,IAAM,UAAU;;;ACEhB,IAAM,iBAAN,cAA6B,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO5C,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACZO,IAAM,mBAAN,cAA+B,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO9C,YAAY,UAAU,4BAA4B,SAAwB;AACxE,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;","names":["EScheduleStrategy","ETaskState"]}
package/dist/index.js CHANGED
@@ -28,6 +28,14 @@ var AhkoConfigurationError = class extends AhkoError {
28
28
  }
29
29
  };
30
30
 
31
+ // src/models/strategy.model.ts
32
+ var EScheduleStrategy = /* @__PURE__ */ ((EScheduleStrategy2) => {
33
+ EScheduleStrategy2["IMMEDIATE"] = "immediate";
34
+ EScheduleStrategy2["DELAY"] = "delay";
35
+ EScheduleStrategy2["IDLE"] = "idle";
36
+ return EScheduleStrategy2;
37
+ })(EScheduleStrategy || {});
38
+
31
39
  // src/models/state.model.ts
32
40
  var ETaskState = /* @__PURE__ */ ((ETaskState2) => {
33
41
  ETaskState2["PENDING"] = "pending";
@@ -39,12 +47,44 @@ var ETaskState = /* @__PURE__ */ ((ETaskState2) => {
39
47
  return ETaskState2;
40
48
  })(ETaskState || {});
41
49
 
42
- // src/models/strategy.model.ts
43
- var EScheduleStrategy = /* @__PURE__ */ ((EScheduleStrategy2) => {
44
- EScheduleStrategy2["IMMEDIATE"] = "immediate";
45
- EScheduleStrategy2["DELAY"] = "delay";
46
- return EScheduleStrategy2;
47
- })(EScheduleStrategy || {});
50
+ // src/scheduler/idle-scheduler.ts
51
+ var IdleScheduler = class {
52
+ /**
53
+ * Schedules a callback to execute during the next idle opportunity.
54
+ *
55
+ * @param callback - Function to invoke when idle opportunity arises.
56
+ * @param timeout - Optional max deadline in milliseconds to wait before invoking (browser only).
57
+ * @param runtime - Target runtime scope providing scheduling primitives (defaults to globalThis).
58
+ * @returns An {@link IIdleHandle} with a `cancel()` method for cleanup.
59
+ */
60
+ static schedule(callback, timeout, runtime = globalThis) {
61
+ if (typeof runtime.requestIdleCallback === "function" && typeof runtime.cancelIdleCallback === "function") {
62
+ const requestFn = runtime.requestIdleCallback;
63
+ const cancelFn = runtime.cancelIdleCallback;
64
+ const id = requestFn(
65
+ () => callback(),
66
+ typeof timeout === "number" && !Number.isNaN(timeout) && timeout >= 0 ? { timeout } : void 0
67
+ );
68
+ return {
69
+ cancel: () => cancelFn(id)
70
+ };
71
+ }
72
+ if (typeof runtime.setImmediate === "function" && typeof runtime.clearImmediate === "function") {
73
+ const setImmFn = runtime.setImmediate;
74
+ const clearImmFn = runtime.clearImmediate;
75
+ const handle = setImmFn(() => callback());
76
+ return {
77
+ cancel: () => clearImmFn(handle)
78
+ };
79
+ }
80
+ const setTimerFn = runtime.setTimeout.bind(runtime);
81
+ const clearTimerFn = runtime.clearTimeout.bind(runtime);
82
+ const timerId = setTimerFn(() => callback(), 0);
83
+ return {
84
+ cancel: () => clearTimerFn(timerId)
85
+ };
86
+ }
87
+ };
48
88
 
49
89
  // src/scheduler/task-queue.ts
50
90
  var TaskQueue = class {
@@ -56,6 +96,8 @@ var TaskQueue = class {
56
96
  activeRunners = /* @__PURE__ */ new Set();
57
97
  /** Set of tasks currently in delay phase */
58
98
  delayedEntries = /* @__PURE__ */ new Set();
99
+ /** Set of tasks currently awaiting an idle opportunity */
100
+ idleEntries = /* @__PURE__ */ new Set();
59
101
  /** Cumulative completed tasks counter */
60
102
  completedTasks = 0;
61
103
  /** Cumulative failed tasks counter */
@@ -89,9 +131,9 @@ var TaskQueue = class {
89
131
  */
90
132
  enqueue(runner, options) {
91
133
  const strategy = options?.strategy ?? "immediate" /* IMMEDIATE */;
92
- if (strategy !== "immediate" /* IMMEDIATE */ && strategy !== "delay" /* DELAY */) {
134
+ if (strategy !== "immediate" /* IMMEDIATE */ && strategy !== "delay" /* DELAY */ && strategy !== "idle" /* IDLE */) {
93
135
  throw new AhkoConfigurationError(
94
- `Unsupported schedule strategy "${String(strategy)}". Supported strategies in 0.1.0: "immediate", "delay".`
136
+ `Unsupported schedule strategy "${String(strategy)}". Supported strategies: "immediate", "delay", "idle".`
95
137
  );
96
138
  }
97
139
  if (runner.state === "cancelled" /* CANCELLED */) {
@@ -108,6 +150,15 @@ var TaskQueue = class {
108
150
  this.scheduleDelayed(runner, delayMs);
109
151
  return runner.promise;
110
152
  }
153
+ if (strategy === "idle" /* IDLE */) {
154
+ if (options?.idleTimeout !== void 0 && (typeof options.idleTimeout !== "number" || Number.isNaN(options.idleTimeout) || options.idleTimeout < 0)) {
155
+ throw new AhkoConfigurationError(
156
+ `Invalid idleTimeout "${options.idleTimeout}". idleTimeout must be a non-negative number in milliseconds.`
157
+ );
158
+ }
159
+ this.scheduleIdle(runner, options?.idleTimeout);
160
+ return runner.promise;
161
+ }
111
162
  runner.onCancel = () => {
112
163
  const index = this.queue.indexOf(runner);
113
164
  if (index !== -1) {
@@ -151,6 +202,37 @@ var TaskQueue = class {
151
202
  }
152
203
  };
153
204
  }
205
+ /**
206
+ * Schedules a task to be placed into the queue during an idle opportunity,
207
+ * handling early cancellation safely.
208
+ */
209
+ scheduleIdle(runner, idleTimeout) {
210
+ let idleEntry;
211
+ const handle = IdleScheduler.schedule(() => {
212
+ this.idleEntries.delete(idleEntry);
213
+ if (runner.state === "cancelled" /* CANCELLED */) {
214
+ return;
215
+ }
216
+ runner.onCancel = () => {
217
+ const index = this.queue.indexOf(runner);
218
+ if (index !== -1) {
219
+ this.queue.splice(index, 1);
220
+ this.cancelledTasks++;
221
+ }
222
+ };
223
+ this.queue.push(runner);
224
+ this.pump();
225
+ }, idleTimeout);
226
+ idleEntry = { runner, handle };
227
+ this.idleEntries.add(idleEntry);
228
+ runner.onCancel = () => {
229
+ if (this.idleEntries.has(idleEntry)) {
230
+ handle.cancel();
231
+ this.idleEntries.delete(idleEntry);
232
+ this.cancelledTasks++;
233
+ }
234
+ };
235
+ }
154
236
  /**
155
237
  * Pumps the queue by picking pending tasks and executing them
156
238
  * as long as concurrency capacity is available.
@@ -200,7 +282,7 @@ var TaskQueue = class {
200
282
  getStats() {
201
283
  return Object.freeze({
202
284
  activeTasks: this.activeRunners.size,
203
- pendingTasks: this.queue.length + this.delayedEntries.size,
285
+ pendingTasks: this.queue.length + this.delayedEntries.size + this.idleEntries.size,
204
286
  completedTasks: this.completedTasks,
205
287
  failedTasks: this.failedTasks,
206
288
  cancelledTasks: this.cancelledTasks,
@@ -420,6 +502,35 @@ var Ahko = class {
420
502
  const runner = new TaskRunner(task, options?.signal);
421
503
  return this.queue.enqueue(runner, options);
422
504
  }
505
+ /**
506
+ * Convenience method to schedule a task during platform idle opportunities.
507
+ *
508
+ * Equivalent to calling `schedule(task, { ...options, strategy: "idle" })`.
509
+ * In browsers, uses `requestIdleCallback` when available.
510
+ * In Node.js, uses `setImmediate`.
511
+ * Falls back to `setTimeout(..., 0)` if neither is available.
512
+ *
513
+ * @template T - Inferred return type of the task.
514
+ * @param task - Task function to run when idle.
515
+ * @param options - Scheduling options (excluding strategy).
516
+ * @returns A promise resolving to the task's return value.
517
+ *
518
+ * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.
519
+ * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.
520
+ *
521
+ * @example
522
+ * ```typescript
523
+ * const result = await ahko.idle(async ({ signal }) => {
524
+ * return computeAnalytics();
525
+ * });
526
+ * ```
527
+ */
528
+ idle(task, options) {
529
+ return this.schedule(task, {
530
+ ...options,
531
+ strategy: "idle" /* IDLE */
532
+ });
533
+ }
423
534
  /**
424
535
  * Retrieves real-time telemetry metrics from the scheduler.
425
536
  *
@@ -437,7 +548,7 @@ var Ahko = class {
437
548
  };
438
549
 
439
550
  // src/version.ts
440
- var VERSION = "0.1.0";
551
+ var VERSION = "0.2.0";
441
552
 
442
553
  // src/errors/queue.error.ts
443
554
  var AhkoQueueError = class extends AhkoError {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors/ahko.error.ts","../src/errors/configuration.error.ts","../src/models/state.model.ts","../src/models/strategy.model.ts","../src/scheduler/task-queue.ts","../src/errors/cancellation.error.ts","../src/scheduler/task-runner.ts","../src/ahko.ts","../src/version.ts","../src/errors/queue.error.ts","../src/errors/timeout.error.ts"],"sourcesContent":["/**\n * Base error class for all errors originating from the Ahko scheduler.\n */\nexport class AhkoError extends Error {\n /**\n * Creates a new AhkoError instance.\n *\n * @param message - Descriptive error message.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when invalid configuration or scheduling options are provided.\n */\nexport class AhkoConfigurationError extends AhkoError {\n /**\n * Creates a new AhkoConfigurationError.\n *\n * @param message - Explanation of the invalid configuration parameter.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoConfigurationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","/**\n * Represents the discrete lifecycle states of an Ahko task.\n */\nexport enum ETaskState {\n /** Task has been scheduled and is awaiting execution in queue or timer */\n PENDING = \"pending\",\n /** Task is currently executing within an allocated concurrency slot */\n RUNNING = \"running\",\n /** Task successfully finished execution */\n COMPLETED = \"completed\",\n /** Task execution threw an error or rejected */\n FAILED = \"failed\",\n /** Task was cancelled via AbortSignal before or during execution */\n CANCELLED = \"cancelled\",\n /** Task was terminated because its execution exceeded the timeout */\n TIMED_OUT = \"timed_out\",\n}\n","/**\n * Fundamental scheduling strategies supported by the Ahko scheduler.\n */\nexport enum EScheduleStrategy {\n /** Execute as soon as a concurrency slot is available */\n IMMEDIATE = \"immediate\",\n /** Delay execution for a designated duration before queuing */\n DELAY = \"delay\",\n}\n\n/**\n * Union type representing valid scheduling strategy identifiers.\n */\nexport type TScheduleStrategy = EScheduleStrategy | \"immediate\" | \"delay\";\n","import { AhkoConfigurationError } from \"../errors/configuration.error.js\";\nimport type { IScheduleOptions } from \"../models/options.model.js\";\nimport type { IAhkoStats } from \"../models/stats.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport { EScheduleStrategy } from \"../models/strategy.model.js\";\nimport { TaskRunner } from \"./task-runner.js\";\n\n/**\n * Entry tracking delayed task timers for deterministic cancellation and memory cleanup.\n */\ninterface IDelayedEntry {\n runner: TaskRunner<unknown>;\n timerId: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Memory-safe FIFO task queue managing concurrency allocation,\n * delayed scheduling, and task lifecycle counters.\n */\nexport class TaskQueue {\n /** Maximum concurrent active tasks */\n public readonly concurrency: number;\n\n /** Queue of pending task runners waiting for a concurrency slot */\n private readonly queue: TaskRunner<unknown>[] = [];\n\n /** Set of task runners currently executing */\n private readonly activeRunners = new Set<TaskRunner<unknown>>();\n\n /** Set of tasks currently in delay phase */\n private readonly delayedEntries = new Set<IDelayedEntry>();\n\n /** Cumulative completed tasks counter */\n private completedTasks = 0;\n\n /** Cumulative failed tasks counter */\n private failedTasks = 0;\n\n /** Cumulative cancelled tasks counter */\n private cancelledTasks = 0;\n\n /** Cumulative timed out tasks counter */\n private timedOutTasks = 0;\n\n /**\n * Creates a new TaskQueue.\n *\n * @param concurrency - Maximum concurrent tasks (defaults to Infinity).\n * @throws {AhkoConfigurationError} If concurrency is less than 1 or not a valid number.\n */\n constructor(concurrency = Infinity) {\n if (Number.isNaN(concurrency) || concurrency < 1) {\n throw new AhkoConfigurationError(\n `Invalid concurrency \"${concurrency}\". Must be a number greater than or equal to 1.`\n );\n }\n this.concurrency = concurrency;\n }\n\n /**\n * Enqueues a task runner according to the specified schedule options.\n *\n * @template T - The return type produced by the task.\n * @param runner - The task runner instance.\n * @param options - Scheduling options.\n * @returns The deferred promise associated with the task runner.\n * @throws {AhkoConfigurationError} If scheduling options are invalid.\n */\n public enqueue<T>(runner: TaskRunner<T>, options?: IScheduleOptions): Promise<T> {\n const strategy = options?.strategy ?? EScheduleStrategy.IMMEDIATE;\n\n if (strategy !== EScheduleStrategy.IMMEDIATE && strategy !== EScheduleStrategy.DELAY) {\n throw new AhkoConfigurationError(\n `Unsupported schedule strategy \"${String(strategy)}\". Supported strategies in 0.1.0: \"immediate\", \"delay\".`\n );\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n return runner.promise;\n }\n\n if (strategy === EScheduleStrategy.DELAY) {\n const delayMs = options?.delay ?? 0;\n if (typeof delayMs !== \"number\" || Number.isNaN(delayMs) || delayMs < 0) {\n throw new AhkoConfigurationError(\n `Invalid delay \"${delayMs}\". Delay must be a non-negative number in milliseconds.`\n );\n }\n\n this.scheduleDelayed(runner as TaskRunner<unknown>, delayMs);\n return runner.promise;\n }\n\n // Attach immediate onCancel handler to dequeue without consuming concurrency\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner as TaskRunner<unknown>);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n // Immediate strategy: add to pending queue and pump\n this.queue.push(runner as TaskRunner<unknown>);\n this.pump();\n\n return runner.promise;\n }\n\n /**\n * Schedules a task to be placed into the queue after a delay,\n * handling early cancellation safely.\n */\n private scheduleDelayed(runner: TaskRunner<unknown>, delayMs: number): void {\n const delayedEntry: IDelayedEntry = {\n runner,\n timerId: setTimeout(() => {\n this.delayedEntries.delete(delayedEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, delayMs),\n };\n\n this.delayedEntries.add(delayedEntry);\n\n runner.onCancel = () => {\n if (this.delayedEntries.has(delayedEntry)) {\n clearTimeout(delayedEntry.timerId);\n this.delayedEntries.delete(delayedEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Pumps the queue by picking pending tasks and executing them\n * as long as concurrency capacity is available.\n */\n private pump(): void {\n while (this.activeRunners.size < this.concurrency && this.queue.length > 0) {\n const runner = this.queue.shift();\n if (!runner) {\n break;\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n continue;\n }\n\n this.activeRunners.add(runner);\n\n // Execute runner without unhandled rejection risk\n void this.executeRunner(runner);\n }\n }\n\n /**\n * Internal execution of an active task runner.\n * Settle caller promise strictly after stats and active status are updated.\n */\n private async executeRunner(runner: TaskRunner<unknown>): Promise<void> {\n try {\n const result = await runner.run();\n this.completedTasks++;\n this.activeRunners.delete(runner);\n runner.resolve(result);\n } catch (error) {\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n } else if (runner.state === ETaskState.TIMED_OUT) {\n this.timedOutTasks++;\n } else {\n this.failedTasks++;\n }\n this.activeRunners.delete(runner);\n runner.reject(error);\n } finally {\n this.pump();\n }\n }\n\n /**\n * Returns telemetry snapshot for the scheduler.\n *\n * @returns Frozen snapshot of current task metrics.\n */\n public getStats(): IAhkoStats {\n return Object.freeze({\n activeTasks: this.activeRunners.size,\n pendingTasks: this.queue.length + this.delayedEntries.size,\n completedTasks: this.completedTasks,\n failedTasks: this.failedTasks,\n cancelledTasks: this.cancelledTasks,\n timedOutTasks: this.timedOutTasks,\n capacity: this.concurrency,\n });\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when a task is cancelled before or during execution.\n */\nexport class AhkoCancellationError extends AhkoError {\n /**\n * Creates a new AhkoCancellationError.\n *\n * @param message - Reason for cancellation.\n * @param options - Standard Error options including cause.\n */\n constructor(message = \"Task was cancelled\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoCancellationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoCancellationError } from \"../errors/cancellation.error.js\";\nimport type { ITaskContext } from \"../models/context.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport type { ITask } from \"../models/task.model.js\";\n\nlet taskIdCounter = 0;\n\n/**\n * Internal task lifecycle manager responsible for execution, state transitions,\n * AbortSignal coordination, and deterministic resource cleanup.\n *\n * @template T - The return type produced by the underlying task.\n */\nexport class TaskRunner<T> {\n /** Unique task identifier */\n public readonly taskId: string;\n\n /** Current lifecycle state */\n private _state: ETaskState = ETaskState.PENDING;\n\n /** Internal AbortController whose signal is passed to the task context */\n private readonly abortController: AbortController;\n\n /** The user task function to execute */\n private readonly task: ITask<T>;\n\n /** User-supplied AbortSignal for external cancellation */\n private readonly externalSignal?: AbortSignal;\n\n /** Abort event listener reference for clean detachment */\n private readonly abortListener?: () => void;\n\n /** Promise resolve handler */\n private resolvePromise!: (value: T | PromiseLike<T>) => void;\n\n /** Promise reject handler */\n private rejectPromise!: (reason?: unknown) => void;\n\n /** Deferred promise exposed to the caller */\n public readonly promise: Promise<T>;\n\n /** Callback invoked when runner is cancelled while pending */\n public onCancel?: (runner: TaskRunner<T>) => void;\n\n /**\n * Creates a new TaskRunner instance.\n *\n * @param task - The asynchronous work unit to run.\n * @param externalSignal - Optional external AbortSignal to propagate.\n */\n constructor(task: ITask<T>, externalSignal?: AbortSignal) {\n this.taskId = `task_${Date.now().toString(36)}_${(++taskIdCounter).toString(36)}_${Math.random().toString(36).slice(2, 6)}`;\n this.task = task;\n this.externalSignal = externalSignal;\n this.abortController = new AbortController();\n\n this.promise = new Promise<T>((resolve, reject) => {\n this.resolvePromise = resolve;\n this.rejectPromise = reject;\n });\n\n if (this.externalSignal) {\n if (this.externalSignal.aborted) {\n this._state = ETaskState.CANCELLED;\n const reason = this.externalSignal.reason;\n const cancelError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.rejectPromise(cancelError);\n } else {\n this.abortListener = () => {\n this.handleExternalAbort();\n };\n this.externalSignal.addEventListener(\"abort\", this.abortListener, { once: true });\n }\n }\n }\n\n /**\n * Gets the current lifecycle state of the task.\n */\n public get state(): ETaskState {\n return this._state;\n }\n\n /**\n * Resolves the deferred promise.\n *\n * @param value - Value to resolve with.\n */\n public resolve(value: T): void {\n this.resolvePromise(value);\n }\n\n /**\n * Rejects the deferred promise.\n *\n * @param reason - Reason to reject with.\n */\n public reject(reason: unknown): void {\n this.rejectPromise(reason);\n }\n\n /**\n * Executes the task within an allocated concurrency slot.\n *\n * @returns A promise resolving to the task result or rejecting on failure/cancellation.\n */\n public async run(): Promise<T> {\n if (this._state === ETaskState.CANCELLED) {\n throw new AhkoCancellationError(\"Task was cancelled prior to execution\");\n }\n\n this._state = ETaskState.RUNNING;\n\n const context: ITaskContext = {\n signal: this.abortController.signal,\n taskId: this.taskId,\n };\n\n try {\n const result = await this.task(context);\n this._state = ETaskState.COMPLETED;\n this.cleanup();\n return result;\n } catch (error) {\n this.cleanup();\n\n const isCancelled =\n (this._state as ETaskState) === ETaskState.CANCELLED ||\n this.abortController.signal.aborted;\n\n if (isCancelled) {\n this._state = ETaskState.CANCELLED;\n throw new AhkoCancellationError(\"Task was cancelled during execution\", {\n cause: error instanceof Error ? error : undefined,\n });\n }\n\n this._state = ETaskState.FAILED;\n throw error;\n }\n }\n\n /**\n * Cancels the task, aborting pending or running execution.\n *\n * @param reason - Optional cancellation reason.\n */\n public cancel(reason?: unknown): void {\n if (\n this._state === ETaskState.COMPLETED ||\n this._state === ETaskState.FAILED ||\n this._state === ETaskState.CANCELLED ||\n this._state === ETaskState.TIMED_OUT\n ) {\n return;\n }\n\n const wasPending = this._state === ETaskState.PENDING;\n this._state = ETaskState.CANCELLED;\n this.abortController.abort(reason);\n this.cleanup();\n\n if (wasPending) {\n const cancellationError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.rejectPromise(cancellationError);\n this.onCancel?.(this);\n }\n }\n\n /**\n * Handles external AbortSignal trigger.\n */\n private handleExternalAbort(): void {\n this.cancel(this.externalSignal?.reason);\n }\n\n /**\n * Detaches event listeners from external signal to guarantee memory safety.\n */\n public cleanup(): void {\n if (this.externalSignal && this.abortListener) {\n this.externalSignal.removeEventListener(\"abort\", this.abortListener);\n }\n }\n}\n","import { AhkoConfigurationError } from \"./errors/configuration.error.js\";\nimport type { IAhkoOptions, IScheduleOptions } from \"./models/options.model.js\";\nimport type { IAhkoStats } from \"./models/stats.model.js\";\nimport type { ITask } from \"./models/task.model.js\";\nimport { TaskQueue } from \"./scheduler/task-queue.js\";\nimport { TaskRunner } from \"./scheduler/task-runner.js\";\n\n/**\n * Ahko — Low-energy, production-grade asynchronous task scheduler.\n *\n * Coordinates execution timing, enforces concurrency limits, and cooperates\n * natively with AbortSignal cancellation.\n *\n * @example\n * ```typescript\n * import { Ahko } from \"@mrjacket/ahko\";\n *\n * const ahko = new Ahko({ concurrency: 2 });\n *\n * const result = await ahko.schedule(async ({ signal, taskId }) => {\n * const res = await fetch(\"https://api.example.com\", { signal });\n * return res.json();\n * });\n * ```\n */\nexport class Ahko {\n /** Internal queue and concurrency manager */\n private readonly queue: TaskQueue;\n\n /**\n * Initializes a new Ahko scheduler instance.\n *\n * @param options - Optional scheduler configuration.\n * @throws {AhkoConfigurationError} If concurrency is invalid (less than 1 or NaN).\n *\n * @example\n * ```typescript\n * const ahko = new Ahko({ concurrency: 4 });\n * ```\n */\n constructor(options?: IAhkoOptions) {\n this.queue = new TaskQueue(options?.concurrency);\n }\n\n /**\n * Schedules a task for execution with full return type inference.\n *\n * @template T - Inferred return type of the task.\n * @param task - Asynchronous or synchronous task function accepting an {@link ITaskContext}.\n * @param options - Task-specific scheduling options such as strategy, delay, and cancellation signal.\n * @returns A promise that resolves with the task's return value.\n *\n * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.\n * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.\n *\n * @example\n * ```typescript\n * // Immediate execution (subject to concurrency)\n * const count = await ahko.schedule(async () => 42);\n *\n * // Delayed execution\n * await ahko.schedule(\n * async ({ signal }) => doWork({ signal }),\n * { strategy: \"delay\", delay: 1000 }\n * );\n * ```\n */\n public schedule<T>(task: ITask<T>, options?: IScheduleOptions): Promise<T> {\n if (typeof task !== \"function\") {\n throw new AhkoConfigurationError(\"Task must be a valid function.\");\n }\n\n const runner = new TaskRunner<T>(task, options?.signal);\n return this.queue.enqueue(runner, options);\n }\n\n /**\n * Retrieves real-time telemetry metrics from the scheduler.\n *\n * @returns An {@link IAhkoStats} snapshot of active, pending, completed, failed, cancelled, and timed out tasks.\n *\n * @example\n * ```typescript\n * const stats = ahko.stats();\n * console.log(`Active: ${stats.activeTasks}, Pending: ${stats.pendingTasks}`);\n * ```\n */\n public stats(): IAhkoStats {\n return this.queue.getStats();\n }\n}\n","/**\n * Current version of @mrjacket/ahko package.\n */\nexport const VERSION = \"0.1.0\";\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when an internal queue invariant is violated or queue limits are breached.\n */\nexport class AhkoQueueError extends AhkoError {\n /**\n * Creates a new AhkoQueueError.\n *\n * @param message - Explanation of the queue failure.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoQueueError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when a task exceeds its allotted timeout duration.\n */\nexport class AhkoTimeoutError extends AhkoError {\n /**\n * Creates a new AhkoTimeoutError.\n *\n * @param message - Explanation of timeout expiry.\n * @param options - Standard Error options including cause.\n */\n constructor(message = \"Task execution timed out\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"Ahko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,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACZO,IAAM,mBAAN,cAA+B,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO9C,YAAY,UAAU,4BAA4B,SAAwB;AACxE,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;","names":["ETaskState","EScheduleStrategy"]}
1
+ {"version":3,"sources":["../src/errors/ahko.error.ts","../src/errors/configuration.error.ts","../src/models/strategy.model.ts","../src/models/state.model.ts","../src/scheduler/idle-scheduler.ts","../src/scheduler/task-queue.ts","../src/errors/cancellation.error.ts","../src/scheduler/task-runner.ts","../src/ahko.ts","../src/version.ts","../src/errors/queue.error.ts","../src/errors/timeout.error.ts"],"sourcesContent":["/**\n * Base error class for all errors originating from the Ahko scheduler.\n */\nexport class AhkoError extends Error {\n /**\n * Creates a new AhkoError instance.\n *\n * @param message - Descriptive error message.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when invalid configuration or scheduling options are provided.\n */\nexport class AhkoConfigurationError extends AhkoError {\n /**\n * Creates a new AhkoConfigurationError.\n *\n * @param message - Explanation of the invalid configuration parameter.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoConfigurationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","/**\n * Fundamental scheduling strategies supported by the Ahko scheduler.\n */\nexport enum EScheduleStrategy {\n /** Execute as soon as a concurrency slot is available */\n IMMEDIATE = \"immediate\",\n /** Delay execution for a designated duration before queuing */\n DELAY = \"delay\",\n /** Execute during platform idle opportunities (requestIdleCallback in browser, setImmediate in Node.js) */\n IDLE = \"idle\",\n}\n\n/**\n * Union type representing valid scheduling strategy identifiers.\n */\nexport type TScheduleStrategy = EScheduleStrategy | \"immediate\" | \"delay\" | \"idle\";\n","/**\n * Represents the discrete lifecycle states of an Ahko task.\n */\nexport enum ETaskState {\n /** Task has been scheduled and is awaiting execution in queue or timer */\n PENDING = \"pending\",\n /** Task is currently executing within an allocated concurrency slot */\n RUNNING = \"running\",\n /** Task successfully finished execution */\n COMPLETED = \"completed\",\n /** Task execution threw an error or rejected */\n FAILED = \"failed\",\n /** Task was cancelled via AbortSignal before or during execution */\n CANCELLED = \"cancelled\",\n /** Task was terminated because its execution exceeded the timeout */\n TIMED_OUT = \"timed_out\",\n}\n","/**\n * Handle returned by the IdleScheduler allowing cancellation of an idle request.\n */\nexport interface IIdleHandle {\n /**\n * Cancels the scheduled idle callback and cleans up platform resources.\n */\n cancel(): void;\n}\n\n/**\n * Platform-agnostic scheduler for opportunistic idle task execution.\n *\n * Automatically detects and selects platform capabilities:\n * 1. Browser: `requestIdleCallback` / `cancelIdleCallback` (with optional timeout)\n * 2. Node.js: `setImmediate` / `clearImmediate` as low-priority primitive\n * 3. Fallback: `setTimeout(..., 0)` / `clearTimeout`\n */\nexport class IdleScheduler {\n /**\n * Schedules a callback to execute during the next idle opportunity.\n *\n * @param callback - Function to invoke when idle opportunity arises.\n * @param timeout - Optional max deadline in milliseconds to wait before invoking (browser only).\n * @param runtime - Target runtime scope providing scheduling primitives (defaults to globalThis).\n * @returns An {@link IIdleHandle} with a `cancel()` method for cleanup.\n */\n public static schedule(\n callback: () => void,\n timeout?: number,\n runtime: typeof globalThis = globalThis\n ): IIdleHandle {\n // 1. Browser requestIdleCallback\n if (\n typeof (runtime as Record<string, unknown>).requestIdleCallback === \"function\" &&\n typeof (runtime as Record<string, unknown>).cancelIdleCallback === \"function\"\n ) {\n const requestFn = (runtime as Record<string, unknown>).requestIdleCallback as (\n cb: (deadline?: unknown) => void,\n opts?: { timeout?: number }\n ) => number;\n\n const cancelFn = (runtime as Record<string, unknown>).cancelIdleCallback as (\n handle: number\n ) => void;\n\n const id = requestFn(\n () => callback(),\n typeof timeout === \"number\" && !Number.isNaN(timeout) && timeout >= 0\n ? { timeout }\n : undefined\n );\n\n return {\n cancel: () => cancelFn(id),\n };\n }\n\n // 2. Node.js setImmediate\n if (\n typeof (runtime as Record<string, unknown>).setImmediate === \"function\" &&\n typeof (runtime as Record<string, unknown>).clearImmediate === \"function\"\n ) {\n const setImmFn = (runtime as Record<string, unknown>).setImmediate as (\n cb: () => void\n ) => ReturnType<typeof setImmediate>;\n\n const clearImmFn = (runtime as Record<string, unknown>).clearImmediate as (\n handle: ReturnType<typeof setImmediate>\n ) => void;\n\n const handle = setImmFn(() => callback());\n\n return {\n cancel: () => clearImmFn(handle),\n };\n }\n\n // 3. Universal fallback setTimeout(0)\n const setTimerFn = runtime.setTimeout.bind(runtime);\n const clearTimerFn = runtime.clearTimeout.bind(runtime);\n\n const timerId = setTimerFn(() => callback(), 0);\n\n return {\n cancel: () => clearTimerFn(timerId),\n };\n }\n}\n","import { AhkoConfigurationError } from \"../errors/configuration.error.js\";\nimport type { IScheduleOptions } from \"../models/options.model.js\";\nimport type { IAhkoStats } from \"../models/stats.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport { EScheduleStrategy } from \"../models/strategy.model.js\";\nimport { IdleScheduler, type IIdleHandle } from \"./idle-scheduler.js\";\nimport { TaskRunner } from \"./task-runner.js\";\n\n/**\n * Entry tracking delayed task timers for deterministic cancellation and memory cleanup.\n */\ninterface IDelayedEntry {\n runner: TaskRunner<unknown>;\n timerId: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Entry tracking idle callback handles for deterministic cancellation and cleanup.\n */\ninterface IIdleEntry {\n runner: TaskRunner<unknown>;\n handle: IIdleHandle;\n}\n\n/**\n * Memory-safe FIFO task queue managing concurrency allocation,\n * delayed scheduling, and task lifecycle counters.\n */\nexport class TaskQueue {\n /** Maximum concurrent active tasks */\n public readonly concurrency: number;\n\n /** Queue of pending task runners waiting for a concurrency slot */\n private readonly queue: TaskRunner<unknown>[] = [];\n\n /** Set of task runners currently executing */\n private readonly activeRunners = new Set<TaskRunner<unknown>>();\n\n /** Set of tasks currently in delay phase */\n private readonly delayedEntries = new Set<IDelayedEntry>();\n\n /** Set of tasks currently awaiting an idle opportunity */\n private readonly idleEntries = new Set<IIdleEntry>();\n\n /** Cumulative completed tasks counter */\n private completedTasks = 0;\n\n /** Cumulative failed tasks counter */\n private failedTasks = 0;\n\n /** Cumulative cancelled tasks counter */\n private cancelledTasks = 0;\n\n /** Cumulative timed out tasks counter */\n private timedOutTasks = 0;\n\n /**\n * Creates a new TaskQueue.\n *\n * @param concurrency - Maximum concurrent tasks (defaults to Infinity).\n * @throws {AhkoConfigurationError} If concurrency is less than 1 or not a valid number.\n */\n constructor(concurrency = Infinity) {\n if (Number.isNaN(concurrency) || concurrency < 1) {\n throw new AhkoConfigurationError(\n `Invalid concurrency \"${concurrency}\". Must be a number greater than or equal to 1.`\n );\n }\n this.concurrency = concurrency;\n }\n\n /**\n * Enqueues a task runner according to the specified schedule options.\n *\n * @template T - The return type produced by the task.\n * @param runner - The task runner instance.\n * @param options - Scheduling options.\n * @returns The deferred promise associated with the task runner.\n * @throws {AhkoConfigurationError} If scheduling options are invalid.\n */\n public enqueue<T>(runner: TaskRunner<T>, options?: IScheduleOptions): Promise<T> {\n const strategy = options?.strategy ?? EScheduleStrategy.IMMEDIATE;\n\n if (\n strategy !== EScheduleStrategy.IMMEDIATE &&\n strategy !== EScheduleStrategy.DELAY &&\n strategy !== EScheduleStrategy.IDLE\n ) {\n throw new AhkoConfigurationError(\n `Unsupported schedule strategy \"${String(strategy)}\". Supported strategies: \"immediate\", \"delay\", \"idle\".`\n );\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n return runner.promise;\n }\n\n if (strategy === EScheduleStrategy.DELAY) {\n const delayMs = options?.delay ?? 0;\n if (typeof delayMs !== \"number\" || Number.isNaN(delayMs) || delayMs < 0) {\n throw new AhkoConfigurationError(\n `Invalid delay \"${delayMs}\". Delay must be a non-negative number in milliseconds.`\n );\n }\n\n this.scheduleDelayed(runner as TaskRunner<unknown>, delayMs);\n return runner.promise;\n }\n\n if (strategy === EScheduleStrategy.IDLE) {\n if (\n options?.idleTimeout !== undefined &&\n (typeof options.idleTimeout !== \"number\" ||\n Number.isNaN(options.idleTimeout) ||\n options.idleTimeout < 0)\n ) {\n throw new AhkoConfigurationError(\n `Invalid idleTimeout \"${options.idleTimeout}\". idleTimeout must be a non-negative number in milliseconds.`\n );\n }\n\n this.scheduleIdle(runner as TaskRunner<unknown>, options?.idleTimeout);\n return runner.promise;\n }\n\n // Attach immediate onCancel handler to dequeue without consuming concurrency\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner as TaskRunner<unknown>);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n // Immediate strategy: add to pending queue and pump\n this.queue.push(runner as TaskRunner<unknown>);\n this.pump();\n\n return runner.promise;\n }\n\n /**\n * Schedules a task to be placed into the queue after a delay,\n * handling early cancellation safely.\n */\n private scheduleDelayed(runner: TaskRunner<unknown>, delayMs: number): void {\n const delayedEntry: IDelayedEntry = {\n runner,\n timerId: setTimeout(() => {\n this.delayedEntries.delete(delayedEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, delayMs),\n };\n\n this.delayedEntries.add(delayedEntry);\n\n runner.onCancel = () => {\n if (this.delayedEntries.has(delayedEntry)) {\n clearTimeout(delayedEntry.timerId);\n this.delayedEntries.delete(delayedEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Schedules a task to be placed into the queue during an idle opportunity,\n * handling early cancellation safely.\n */\n private scheduleIdle(runner: TaskRunner<unknown>, idleTimeout?: number): void {\n let idleEntry!: IIdleEntry;\n\n const handle = IdleScheduler.schedule(() => {\n this.idleEntries.delete(idleEntry);\n if (runner.state === ETaskState.CANCELLED) {\n return;\n }\n\n runner.onCancel = () => {\n const index = this.queue.indexOf(runner);\n if (index !== -1) {\n this.queue.splice(index, 1);\n this.cancelledTasks++;\n }\n };\n\n this.queue.push(runner);\n this.pump();\n }, idleTimeout);\n\n idleEntry = { runner, handle };\n this.idleEntries.add(idleEntry);\n\n runner.onCancel = () => {\n if (this.idleEntries.has(idleEntry)) {\n handle.cancel();\n this.idleEntries.delete(idleEntry);\n this.cancelledTasks++;\n }\n };\n }\n\n /**\n * Pumps the queue by picking pending tasks and executing them\n * as long as concurrency capacity is available.\n */\n private pump(): void {\n while (this.activeRunners.size < this.concurrency && this.queue.length > 0) {\n const runner = this.queue.shift();\n if (!runner) {\n break;\n }\n\n if (runner.state === ETaskState.CANCELLED) {\n continue;\n }\n\n this.activeRunners.add(runner);\n\n // Execute runner without unhandled rejection risk\n void this.executeRunner(runner);\n }\n }\n\n /**\n * Internal execution of an active task runner.\n * Settle caller promise strictly after stats and active status are updated.\n */\n private async executeRunner(runner: TaskRunner<unknown>): Promise<void> {\n try {\n const result = await runner.run();\n this.completedTasks++;\n this.activeRunners.delete(runner);\n runner.resolve(result);\n } catch (error) {\n if (runner.state === ETaskState.CANCELLED) {\n this.cancelledTasks++;\n } else if (runner.state === ETaskState.TIMED_OUT) {\n this.timedOutTasks++;\n } else {\n this.failedTasks++;\n }\n this.activeRunners.delete(runner);\n runner.reject(error);\n } finally {\n this.pump();\n }\n }\n\n /**\n * Returns telemetry snapshot for the scheduler.\n *\n * @returns Frozen snapshot of current task metrics.\n */\n public getStats(): IAhkoStats {\n return Object.freeze({\n activeTasks: this.activeRunners.size,\n pendingTasks: this.queue.length + this.delayedEntries.size + this.idleEntries.size,\n completedTasks: this.completedTasks,\n failedTasks: this.failedTasks,\n cancelledTasks: this.cancelledTasks,\n timedOutTasks: this.timedOutTasks,\n capacity: this.concurrency,\n });\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when a task is cancelled before or during execution.\n */\nexport class AhkoCancellationError extends AhkoError {\n /**\n * Creates a new AhkoCancellationError.\n *\n * @param message - Reason for cancellation.\n * @param options - Standard Error options including cause.\n */\n constructor(message = \"Task was cancelled\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoCancellationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoCancellationError } from \"../errors/cancellation.error.js\";\nimport type { ITaskContext } from \"../models/context.model.js\";\nimport { ETaskState } from \"../models/state.model.js\";\nimport type { ITask } from \"../models/task.model.js\";\n\nlet taskIdCounter = 0;\n\n/**\n * Internal task lifecycle manager responsible for execution, state transitions,\n * AbortSignal coordination, and deterministic resource cleanup.\n *\n * @template T - The return type produced by the underlying task.\n */\nexport class TaskRunner<T> {\n /** Unique task identifier */\n public readonly taskId: string;\n\n /** Current lifecycle state */\n private _state: ETaskState = ETaskState.PENDING;\n\n /** Internal AbortController whose signal is passed to the task context */\n private readonly abortController: AbortController;\n\n /** The user task function to execute */\n private readonly task: ITask<T>;\n\n /** User-supplied AbortSignal for external cancellation */\n private readonly externalSignal?: AbortSignal;\n\n /** Abort event listener reference for clean detachment */\n private readonly abortListener?: () => void;\n\n /** Promise resolve handler */\n private resolvePromise!: (value: T | PromiseLike<T>) => void;\n\n /** Promise reject handler */\n private rejectPromise!: (reason?: unknown) => void;\n\n /** Deferred promise exposed to the caller */\n public readonly promise: Promise<T>;\n\n /** Callback invoked when runner is cancelled while pending */\n public onCancel?: (runner: TaskRunner<T>) => void;\n\n /**\n * Creates a new TaskRunner instance.\n *\n * @param task - The asynchronous work unit to run.\n * @param externalSignal - Optional external AbortSignal to propagate.\n */\n constructor(task: ITask<T>, externalSignal?: AbortSignal) {\n this.taskId = `task_${Date.now().toString(36)}_${(++taskIdCounter).toString(36)}_${Math.random().toString(36).slice(2, 6)}`;\n this.task = task;\n this.externalSignal = externalSignal;\n this.abortController = new AbortController();\n\n this.promise = new Promise<T>((resolve, reject) => {\n this.resolvePromise = resolve;\n this.rejectPromise = reject;\n });\n\n if (this.externalSignal) {\n if (this.externalSignal.aborted) {\n this._state = ETaskState.CANCELLED;\n const reason = this.externalSignal.reason;\n const cancelError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.rejectPromise(cancelError);\n } else {\n this.abortListener = () => {\n this.handleExternalAbort();\n };\n this.externalSignal.addEventListener(\"abort\", this.abortListener, { once: true });\n }\n }\n }\n\n /**\n * Gets the current lifecycle state of the task.\n */\n public get state(): ETaskState {\n return this._state;\n }\n\n /**\n * Resolves the deferred promise.\n *\n * @param value - Value to resolve with.\n */\n public resolve(value: T): void {\n this.resolvePromise(value);\n }\n\n /**\n * Rejects the deferred promise.\n *\n * @param reason - Reason to reject with.\n */\n public reject(reason: unknown): void {\n this.rejectPromise(reason);\n }\n\n /**\n * Executes the task within an allocated concurrency slot.\n *\n * @returns A promise resolving to the task result or rejecting on failure/cancellation.\n */\n public async run(): Promise<T> {\n if (this._state === ETaskState.CANCELLED) {\n throw new AhkoCancellationError(\"Task was cancelled prior to execution\");\n }\n\n this._state = ETaskState.RUNNING;\n\n const context: ITaskContext = {\n signal: this.abortController.signal,\n taskId: this.taskId,\n };\n\n try {\n const result = await this.task(context);\n this._state = ETaskState.COMPLETED;\n this.cleanup();\n return result;\n } catch (error) {\n this.cleanup();\n\n const isCancelled =\n (this._state as ETaskState) === ETaskState.CANCELLED ||\n this.abortController.signal.aborted;\n\n if (isCancelled) {\n this._state = ETaskState.CANCELLED;\n throw new AhkoCancellationError(\"Task was cancelled during execution\", {\n cause: error instanceof Error ? error : undefined,\n });\n }\n\n this._state = ETaskState.FAILED;\n throw error;\n }\n }\n\n /**\n * Cancels the task, aborting pending or running execution.\n *\n * @param reason - Optional cancellation reason.\n */\n public cancel(reason?: unknown): void {\n if (\n this._state === ETaskState.COMPLETED ||\n this._state === ETaskState.FAILED ||\n this._state === ETaskState.CANCELLED ||\n this._state === ETaskState.TIMED_OUT\n ) {\n return;\n }\n\n const wasPending = this._state === ETaskState.PENDING;\n this._state = ETaskState.CANCELLED;\n this.abortController.abort(reason);\n this.cleanup();\n\n if (wasPending) {\n const cancellationError = new AhkoCancellationError(\n typeof reason === \"string\" ? reason : \"Task was cancelled prior to execution\",\n { cause: reason instanceof Error ? reason : undefined }\n );\n this.rejectPromise(cancellationError);\n this.onCancel?.(this);\n }\n }\n\n /**\n * Handles external AbortSignal trigger.\n */\n private handleExternalAbort(): void {\n this.cancel(this.externalSignal?.reason);\n }\n\n /**\n * Detaches event listeners from external signal to guarantee memory safety.\n */\n public cleanup(): void {\n if (this.externalSignal && this.abortListener) {\n this.externalSignal.removeEventListener(\"abort\", this.abortListener);\n }\n }\n}\n","import { AhkoConfigurationError } from \"./errors/configuration.error.js\";\nimport type { IAhkoOptions, IScheduleOptions } from \"./models/options.model.js\";\nimport type { IAhkoStats } from \"./models/stats.model.js\";\nimport { EScheduleStrategy } from \"./models/strategy.model.js\";\nimport type { ITask } from \"./models/task.model.js\";\nimport { TaskQueue } from \"./scheduler/task-queue.js\";\nimport { TaskRunner } from \"./scheduler/task-runner.js\";\n\n/**\n * Ahko — Low-energy asynchronous task scheduler.\n *\n * Coordinates execution timing, enforces concurrency limits, and cooperates\n * natively with AbortSignal cancellation.\n *\n * @example\n * ```typescript\n * import { Ahko } from \"@mrjacket/ahko\";\n *\n * const ahko = new Ahko({ concurrency: 2 });\n *\n * const result = await ahko.schedule(async ({ signal, taskId }) => {\n * const res = await fetch(\"https://api.example.com\", { signal });\n * return res.json();\n * });\n * ```\n */\nexport class Ahko {\n /** Internal queue and concurrency manager */\n private readonly queue: TaskQueue;\n\n /**\n * Initializes a new Ahko scheduler instance.\n *\n * @param options - Optional scheduler configuration.\n * @throws {AhkoConfigurationError} If concurrency is invalid (less than 1 or NaN).\n *\n * @example\n * ```typescript\n * const ahko = new Ahko({ concurrency: 4 });\n * ```\n */\n constructor(options?: IAhkoOptions) {\n this.queue = new TaskQueue(options?.concurrency);\n }\n\n /**\n * Schedules a task for execution with full return type inference.\n *\n * @template T - Inferred return type of the task.\n * @param task - Asynchronous or synchronous task function accepting an {@link ITaskContext}.\n * @param options - Task-specific scheduling options such as strategy, delay, and cancellation signal.\n * @returns A promise that resolves with the task's return value.\n *\n * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.\n * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.\n *\n * @example\n * ```typescript\n * // Immediate execution (subject to concurrency)\n * const count = await ahko.schedule(async () => 42);\n *\n * // Delayed execution\n * await ahko.schedule(\n * async ({ signal }) => doWork({ signal }),\n * { strategy: \"delay\", delay: 1000 }\n * );\n * ```\n */\n public schedule<T>(task: ITask<T>, options?: IScheduleOptions): Promise<T> {\n if (typeof task !== \"function\") {\n throw new AhkoConfigurationError(\"Task must be a valid function.\");\n }\n\n const runner = new TaskRunner<T>(task, options?.signal);\n return this.queue.enqueue(runner, options);\n }\n\n /**\n * Convenience method to schedule a task during platform idle opportunities.\n *\n * Equivalent to calling `schedule(task, { ...options, strategy: \"idle\" })`.\n * In browsers, uses `requestIdleCallback` when available.\n * In Node.js, uses `setImmediate`.\n * Falls back to `setTimeout(..., 0)` if neither is available.\n *\n * @template T - Inferred return type of the task.\n * @param task - Task function to run when idle.\n * @param options - Scheduling options (excluding strategy).\n * @returns A promise resolving to the task's return value.\n *\n * @throws {AhkoConfigurationError} If the task is not a function or options are invalid.\n * @throws {AhkoCancellationError} If the task is cancelled prior to or during execution.\n *\n * @example\n * ```typescript\n * const result = await ahko.idle(async ({ signal }) => {\n * return computeAnalytics();\n * });\n * ```\n */\n public idle<T>(\n task: ITask<T>,\n options?: Omit<IScheduleOptions, \"strategy\">\n ): Promise<T> {\n return this.schedule(task, {\n ...options,\n strategy: EScheduleStrategy.IDLE,\n });\n }\n\n /**\n * Retrieves real-time telemetry metrics from the scheduler.\n *\n * @returns An {@link IAhkoStats} snapshot of active, pending, completed, failed, cancelled, and timed out tasks.\n *\n * @example\n * ```typescript\n * const stats = ahko.stats();\n * console.log(`Active: ${stats.activeTasks}, Pending: ${stats.pendingTasks}`);\n * ```\n */\n public stats(): IAhkoStats {\n return this.queue.getStats();\n }\n}\n","/**\n * Current version of @mrjacket/ahko package.\n */\nexport const VERSION = \"0.2.0\";\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when an internal queue invariant is violated or queue limits are breached.\n */\nexport class AhkoQueueError extends AhkoError {\n /**\n * Creates a new AhkoQueueError.\n *\n * @param message - Explanation of the queue failure.\n * @param options - Standard Error options including cause.\n */\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoQueueError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { AhkoError } from \"./ahko.error.js\";\n\n/**\n * Thrown when a task exceeds its allotted timeout duration.\n */\nexport class AhkoTimeoutError extends AhkoError {\n /**\n * Creates a new AhkoTimeoutError.\n *\n * @param message - Explanation of timeout expiry.\n * @param options - Standard Error options including cause.\n */\n constructor(message = \"Task execution timed out\", options?: ErrorOptions) {\n super(message, options);\n this.name = \"AhkoTimeoutError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n"],"mappings":";AAGO,IAAM,YAAN,cAAwB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnC,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACVO,IAAM,yBAAN,cAAqC,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOpD,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACdO,IAAK,oB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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAyBO,KACL,MACA,SACY;AACZ,WAAO,KAAK,SAAS,MAAM;AAAA,MACzB,GAAG;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaO,QAAoB;AACzB,WAAO,KAAK,MAAM,SAAS;AAAA,EAC7B;AACF;;;ACzHO,IAAM,UAAU;;;ACEhB,IAAM,iBAAN,cAA6B,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO5C,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;;;ACZO,IAAM,mBAAN,cAA+B,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO9C,YAAY,UAAU,4BAA4B,SAAwB;AACxE,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;","names":["EScheduleStrategy","ETaskState"]}
@@ -13,6 +13,12 @@ export interface IScheduleOptions {
13
13
  * Applicable when strategy is "delay".
14
14
  */
15
15
  delay?: number;
16
+ /**
17
+ * Maximum time in milliseconds to wait for an idle opportunity before
18
+ * forcing execution into the queue. Applicable when strategy is "idle".
19
+ * Forwards to requestIdleCallback({ timeout }) when running in browser runtimes.
20
+ */
21
+ idleTimeout?: number;
16
22
  /**
17
23
  * External cancellation signal.
18
24
  * If aborted before start, the task is removed from the queue without execution.
@@ -5,9 +5,11 @@ export declare enum EScheduleStrategy {
5
5
  /** Execute as soon as a concurrency slot is available */
6
6
  IMMEDIATE = "immediate",
7
7
  /** Delay execution for a designated duration before queuing */
8
- DELAY = "delay"
8
+ DELAY = "delay",
9
+ /** Execute during platform idle opportunities (requestIdleCallback in browser, setImmediate in Node.js) */
10
+ IDLE = "idle"
9
11
  }
10
12
  /**
11
13
  * Union type representing valid scheduling strategy identifiers.
12
14
  */
13
- export type TScheduleStrategy = EScheduleStrategy | "immediate" | "delay";
15
+ export type TScheduleStrategy = EScheduleStrategy | "immediate" | "delay" | "idle";
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Handle returned by the IdleScheduler allowing cancellation of an idle request.
3
+ */
4
+ export interface IIdleHandle {
5
+ /**
6
+ * Cancels the scheduled idle callback and cleans up platform resources.
7
+ */
8
+ cancel(): void;
9
+ }
10
+ /**
11
+ * Platform-agnostic scheduler for opportunistic idle task execution.
12
+ *
13
+ * Automatically detects and selects platform capabilities:
14
+ * 1. Browser: `requestIdleCallback` / `cancelIdleCallback` (with optional timeout)
15
+ * 2. Node.js: `setImmediate` / `clearImmediate` as low-priority primitive
16
+ * 3. Fallback: `setTimeout(..., 0)` / `clearTimeout`
17
+ */
18
+ export declare class IdleScheduler {
19
+ /**
20
+ * Schedules a callback to execute during the next idle opportunity.
21
+ *
22
+ * @param callback - Function to invoke when idle opportunity arises.
23
+ * @param timeout - Optional max deadline in milliseconds to wait before invoking (browser only).
24
+ * @param runtime - Target runtime scope providing scheduling primitives (defaults to globalThis).
25
+ * @returns An {@link IIdleHandle} with a `cancel()` method for cleanup.
26
+ */
27
+ static schedule(callback: () => void, timeout?: number, runtime?: typeof globalThis): IIdleHandle;
28
+ }
@@ -14,6 +14,8 @@ export declare class TaskQueue {
14
14
  private readonly activeRunners;
15
15
  /** Set of tasks currently in delay phase */
16
16
  private readonly delayedEntries;
17
+ /** Set of tasks currently awaiting an idle opportunity */
18
+ private readonly idleEntries;
17
19
  /** Cumulative completed tasks counter */
18
20
  private completedTasks;
19
21
  /** Cumulative failed tasks counter */
@@ -44,6 +46,11 @@ export declare class TaskQueue {
44
46
  * handling early cancellation safely.
45
47
  */
46
48
  private scheduleDelayed;
49
+ /**
50
+ * Schedules a task to be placed into the queue during an idle opportunity,
51
+ * handling early cancellation safely.
52
+ */
53
+ private scheduleIdle;
47
54
  /**
48
55
  * Pumps the queue by picking pending tasks and executing them
49
56
  * as long as concurrency capacity is available.
package/dist/version.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /**
2
2
  * Current version of @mrjacket/ahko package.
3
3
  */
4
- export declare const VERSION = "0.1.0";
4
+ export declare const VERSION = "0.2.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrjacket/ahko",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A low-energy task scheduler for JavaScript and TypeScript. Let your code chill.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -54,9 +54,9 @@
54
54
  "async"
55
55
  ],
56
56
  "devDependencies": {
57
- "@types/node": "^22.13.0",
57
+ "@types/node": "^26.6.2",
58
58
  "tsup": "^8.3.6",
59
- "typescript": "^5.7.3",
60
- "vitest": "^3.0.5"
59
+ "typescript": "^7.0.2",
60
+ "vitest": "^5.0.1"
61
61
  }
62
62
  }