@socketsecurity/lib
Version:
Core utilities and infrastructure for Socket.dev security tools
112 lines (111 loc) • 3.22 kB
JavaScript
;
/* Socket Lib - Built with esbuild */
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var promise_queue_exports = {};
__export(promise_queue_exports, {
PromiseQueue: () => PromiseQueue
});
module.exports = __toCommonJS(promise_queue_exports);
class PromiseQueue {
queue = [];
running = 0;
maxConcurrency;
maxQueueLength;
/**
* Creates a new PromiseQueue
* @param maxConcurrency - Maximum number of promises that can run concurrently
* @param maxQueueLength - Maximum queue size (older tasks are dropped if exceeded)
*/
constructor(maxConcurrency, maxQueueLength) {
this.maxConcurrency = maxConcurrency;
this.maxQueueLength = maxQueueLength;
if (maxConcurrency < 1) {
throw new Error("maxConcurrency must be at least 1");
}
}
/**
* Add a task to the queue
* @param fn - Async function to execute
* @returns Promise that resolves with the function's result
*/
async add(fn) {
return await new Promise((resolve, reject) => {
const task = { fn, resolve, reject };
if (this.maxQueueLength && this.queue.length >= this.maxQueueLength) {
const droppedTask = this.queue.shift();
if (droppedTask) {
droppedTask.reject(new Error("Task dropped: queue length exceeded"));
}
}
this.queue.push(task);
this.runNext();
});
}
runNext() {
if (this.running >= this.maxConcurrency || this.queue.length === 0) {
return;
}
const task = this.queue.shift();
if (!task) {
return;
}
this.running++;
task.fn().then(task.resolve).catch(task.reject).finally(() => {
this.running--;
this.runNext();
});
}
/**
* Wait for all queued and running tasks to complete
*/
async onIdle() {
return await new Promise((resolve) => {
const check = () => {
if (this.running === 0 && this.queue.length === 0) {
resolve();
} else {
setImmediate(check);
}
};
check();
});
}
/**
* Get the number of tasks currently running
*/
get activeCount() {
return this.running;
}
/**
* Get the number of tasks waiting in the queue
*/
get pendingCount() {
return this.queue.length;
}
/**
* Clear all pending tasks from the queue (does not affect running tasks)
*/
clear() {
this.queue = [];
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
PromiseQueue
});