qpass 1.0.0 β†’ 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,160 +1,187 @@
1
- # Qpass
2
-
3
- Qpass is a JavaScript/TypeScript queue library for processing tasks sequentially.
4
- It supports batch execution, error handling options, and progress callbacks.
5
-
6
- ## πŸ“Œ Getting started
7
-
8
- ```js
9
- npm install qpass
10
- ```
11
-
12
- ## πŸ“Œ Usage
13
-
14
- ### Basic usage
15
-
16
- ```js
17
- import Qpass from "qpass";
18
-
19
- const queue = new Qpass();
20
-
21
- const job1 = () => Promise.resolve("job1 completed");
22
- const job2 = () => Promise.resolve("job2 completed");
23
-
24
- queue.add([job1, job2]);
25
- ```
26
-
27
- ### Option
28
-
29
- You can configure options when creating a Qpass instance.
30
-
31
- ```ts
32
- const queue = new Qpass({
33
- breakWhenError?: boolean;
34
- onProgress?: (progress: {
35
- batchToProcess: number; // Total number of batches remaining
36
- itemsToProcess: number; // Total remaining tasks
37
- completed?: any[]; // Array of completed task results
38
- }) => void;
39
- batchSize?: number; // must be β‰₯ 1, default is 1
40
- });
41
- ```
42
-
43
- ### πŸ” OnProgress
44
-
45
- The onProgress callback runs when the queue starts and after each batch is completed.
46
-
47
- ```js
48
- const queue = new Qpass({
49
- batchSize: 2,
50
- onProgress: (progress) => {
51
- console.log(progress);
52
- },
53
- });
54
-
55
- await queue.add([
56
- () => Promise.resolve("Job 1"),
57
- () => Promise.resolve("Job 2"),
58
- () => Promise.resolve("Job 3"),
59
- () => Promise.resolve("Job 4"),
60
- ]);
61
-
62
- // Example output:
63
- // { batchToProcess: 1, itemsToProcess: 2, completed: ["Job 1", "Job 2"] }
64
- // { batchToProcess: 0, itemsToProcess: 0, completed: ["Job 3", "Job 4"] }
65
- ```
66
-
67
- ## ❗Handling Errors
68
-
69
- Qpass lets you choose whether to stop on error or continue execution when an error occurs.
70
- <br>
71
- This behavior is controlled via the breakWhenError option.
72
-
73
- ### βœ… Continue execution even on errors (breakWhenError: false)
74
-
75
- ```js
76
- const queue = new Qpass({
77
- breakWhenError: false, // default
78
- onProgress: (progress) => {
79
- console.log("Completed jobs: ", progress.completed);
80
- },
81
- });
82
-
83
- const jobs = [
84
- () => Promise.resolve("First success"),
85
- () => Promise.reject("Second failed ❌"),
86
- () => Promise.resolve("Third success βœ…"),
87
- ];
88
-
89
- await queue.add(jobs);
90
- ```
91
-
92
- Result
93
-
94
- ```js
95
- Completed jobs: ["First success"]
96
- Completed jobs: ["First success", "Second failed ❌", "Third success βœ…"]
97
- // Errors are stored as error objects and execution continues.
98
- ```
99
-
100
- ### πŸ›‘ Stop immediately on error (breakWhenError: true)
101
-
102
- ```js
103
- const queue = new Qpass({
104
- breakWhenError: true,
105
- onProgress: (progress) => {
106
- console.log(`Completed jobs:: `, progress.completed);
107
- },
108
- });
109
-
110
- const jobs = [
111
- () => Promise.resolve("First success"),
112
- () => Promise.reject("Second failed ❌"),
113
- () => Promise.resolve("Third will not run 🚫"),
114
- ];
115
-
116
- try {
117
- await queue.add(jobs);
118
- } catch (err) {
119
- console.error("Execution stopped: ", err);
120
- }
121
- ```
122
-
123
- Result
124
-
125
- ```js
126
- Completed jobs: ["First success"]
127
- Execution stopped: Second failed ❌
128
- // Stops immediately on error, so the third job is never executed.
129
- ```
130
-
131
- ## πŸ“Œ Practical Example
132
-
133
- ```js
134
- const queue = new Qpass({
135
- batchSize: 5,
136
- onProgress: (progress) => {
137
- console.log(
138
- `Remaining batches: ${progress.batchToProcess}, Remaining tasks: ${progress.itemsToProcess}`
139
- );
140
- },
141
- });
142
-
143
- const jobs = [];
144
-
145
- for (let i = 0; i < 100; i++) {
146
- jobs.push(() => fetch(`/api/data/${i}`).then((res) => res.json()));
147
- }
148
-
149
- queue.add(jobs);
150
- ```
151
-
152
- ## πŸ“Œ Features
153
-
154
- β€’ Batch processing (batchSize) β€” control how many jobs run in parallel
155
- <br>
156
- β€’ Error control (breakWhenError) β€” choose whether to stop or continue on failure
157
- <br>
158
- β€’ Progress tracking (onProgress) β€” monitor task progress in real time
159
- <br>
160
- β€’ Execution state (isRunning) β€” check whether the queue is currently running
1
+ # Qpass
2
+
3
+ Qpass is a lightweight promise-job queue for JavaScript/TypeScript.
4
+ It runs jobs in cycles with configurable parallelism (`batchSize`) and reports progress after each cycle.
5
+
6
+ ## Platform support
7
+
8
+ - Node.js ESM (`import`) via `qpass`
9
+ - Node.js CommonJS (`require`) via `qpass`
10
+ - Browser bundlers (Vite/Webpack/Rollup) via `qpass`
11
+ - Browser script tag/global build via `dist/qpass.js`
12
+
13
+ Version is sourced from `package.json` at build time, so you only update it in one place.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install qpass
19
+ ```
20
+
21
+ ## Quick start
22
+
23
+ ```js
24
+ import Qpass from "qpass";
25
+
26
+ const queue = new Qpass({
27
+ batchSize: 3,
28
+ onProgress: ({ batchToProcess, itemsToProcess, completed }) => {
29
+ console.log({ batchToProcess, itemsToProcess, completed });
30
+ },
31
+ });
32
+
33
+ const jobs = [
34
+ () => Promise.resolve("A"),
35
+ () => Promise.resolve("B"),
36
+ () => Promise.resolve("C"),
37
+ () => Promise.resolve("D"),
38
+ ];
39
+
40
+ queue.add(jobs);
41
+ ```
42
+
43
+ ## Import by platform
44
+
45
+ ### Node.js ESM
46
+
47
+ ```js
48
+ import Qpass from "qpass";
49
+ ```
50
+
51
+ ### Node.js CommonJS
52
+
53
+ ```js
54
+ const Qpass = require("qpass").default;
55
+ ```
56
+
57
+ ### Browser bundler
58
+
59
+ ```js
60
+ import Qpass from "qpass";
61
+ ```
62
+
63
+ ### Browser script tag (global)
64
+
65
+ Use the global build from your package output or CDN:
66
+
67
+ ```html
68
+ <script src="https://cdn.jsdelivr.net/npm/qpass/dist/qpass.js"></script>
69
+ <script>
70
+ const queue = new Qpass();
71
+ </script>
72
+ ```
73
+
74
+ ## API
75
+
76
+ ### `new Qpass(options?)`
77
+
78
+ ```ts
79
+ new Qpass({
80
+ breakWhenError?: boolean;
81
+ batchSize?: number; // >= 1, default: 1
82
+ onProgress?: (progress: {
83
+ batchToProcess: number;
84
+ itemsToProcess: number;
85
+ completed: any[];
86
+ }) => void;
87
+ })
88
+ ```
89
+
90
+ #### Options
91
+
92
+ - `batchSize` (default `1`): number of jobs to run in parallel per cycle.
93
+ - `breakWhenError` (default `false`): when `true`, queued jobs are cleared after an error is seen.
94
+ - `onProgress`: called after each cycle finishes.
95
+
96
+ ### `add(jobs)`
97
+
98
+ ```ts
99
+ add(jobs: (() => Promise<any>)[] | (() => Promise<any>)): void
100
+ ```
101
+
102
+ - Adds one or many jobs to the queue.
103
+ - Starts processing automatically.
104
+ - `add` is not `async` and does not return a promise.
105
+
106
+ ### `terminate()`
107
+
108
+ ```ts
109
+ terminate(): void
110
+ ```
111
+
112
+ - Clears all queued (not-yet-started) jobs.
113
+ - Already running jobs continue until they settle.
114
+
115
+ ## Progress callback behavior
116
+
117
+ `onProgress` receives:
118
+
119
+ - `completed`: results (or errors) from the cycle that just finished.
120
+ - `itemsToProcess`: queued jobs still waiting to start.
121
+ - `batchToProcess`: `Math.ceil(itemsToProcess / batchSize)`.
122
+
123
+ Notes:
124
+
125
+ - Progress is reported per cycle, not per individual job completion.
126
+ - If you call `add` repeatedly (for example, inside a loop), the first cycle may be smaller than `batchSize` because processing starts immediately.
127
+
128
+ ## Error handling
129
+
130
+ ### Continue on error (`breakWhenError: false`)
131
+
132
+ ```js
133
+ const queue = new Qpass({
134
+ breakWhenError: false,
135
+ batchSize: 2,
136
+ onProgress: ({ completed }) => {
137
+ console.log(
138
+ completed.map((x) => (x instanceof Error ? `Error: ${x.message}` : x))
139
+ );
140
+ },
141
+ });
142
+
143
+ queue.add([
144
+ () => Promise.resolve("ok-1"),
145
+ () => Promise.reject(new Error("failed-2")),
146
+ () => Promise.resolve("ok-3"),
147
+ ]);
148
+ ```
149
+
150
+ ### Stop queueing after error (`breakWhenError: true`)
151
+
152
+ ```js
153
+ const queue = new Qpass({
154
+ breakWhenError: true,
155
+ batchSize: 3,
156
+ onProgress: ({ itemsToProcess, completed }) => {
157
+ console.log({ itemsToProcess, completed });
158
+ },
159
+ });
160
+
161
+ queue.add([
162
+ () => Promise.resolve("ok-1"),
163
+ () => Promise.reject(new Error("failed-2")),
164
+ () => Promise.resolve("ok-3"),
165
+ () => Promise.resolve("queued-but-may-be-cleared"),
166
+ ]);
167
+ ```
168
+
169
+ With `breakWhenError: true`, Qpass clears jobs still waiting in the queue after an error is observed. Jobs already running in the same cycle still settle.
170
+
171
+ ## Practical pattern: queue all jobs at once
172
+
173
+ If you want predictable `itemsToProcess` values in `onProgress`, build the job array first and call `add` once:
174
+
175
+ ```js
176
+ const jobs = [];
177
+
178
+ for (let i = 1; i <= 14; i++) {
179
+ jobs.push(() => Promise.resolve(`Job ${i}`));
180
+ }
181
+
182
+ queue.add(jobs);
183
+ ```
184
+
185
+ ## License
186
+
187
+ ISC
package/dist/index.cjs ADDED
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ default: () => index_default
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+ var QPASS_VERSION = true ? "1.1.0" : "0.0.0";
27
+ var Qpass = class {
28
+ version = QPASS_VERSION;
29
+ // version info
30
+ items = [];
31
+ // job queue
32
+ breakWhenError = false;
33
+ // whether to stop on error
34
+ batchSize = 1;
35
+ // number of jobs to process at once
36
+ onProgress;
37
+ // progress callback
38
+ activeCount = 0;
39
+ // number of jobs currently running
40
+ currentCycleCompleted = [];
41
+ // completed results for current cycle
42
+ stopProcessing = false;
43
+ // stop scheduling new jobs when true
44
+ get batchToProcess() {
45
+ return Math.ceil(this.items.length / this.batchSize);
46
+ }
47
+ constructor(option) {
48
+ this.breakWhenError = !!option?.breakWhenError;
49
+ this.batchSize = option?.batchSize ?? 1;
50
+ if (typeof this.batchSize !== "number" || this.batchSize < 1) {
51
+ throw new Error("batchSize must be at least 1");
52
+ }
53
+ if (option?.onProgress) {
54
+ if (typeof option.onProgress === "function") {
55
+ this.onProgress = option.onProgress;
56
+ } else {
57
+ throw new Error("onProgress must be a function");
58
+ }
59
+ }
60
+ }
61
+ // add jobs to the queue at once
62
+ add(jobs) {
63
+ const jobsArray = Array.isArray(jobs) ? jobs : [jobs];
64
+ for (const job of jobsArray) {
65
+ if (typeof job !== "function") {
66
+ throw new Error(
67
+ "Each job must be a function that returns a Promise"
68
+ );
69
+ }
70
+ this.items.push(job);
71
+ }
72
+ this.processNext();
73
+ }
74
+ // process next batch of jobs
75
+ processNext() {
76
+ if (this.stopProcessing || this.items.length === 0 || this.activeCount > 0) {
77
+ return;
78
+ }
79
+ const jobsToRun = this.items.splice(0, this.batchSize);
80
+ this.activeCount = jobsToRun.length;
81
+ this.currentCycleCompleted = new Array(jobsToRun.length);
82
+ jobsToRun.forEach((job, index) => {
83
+ Promise.resolve().then(() => job()).then((result) => {
84
+ this.finalizeJob(index, result, false);
85
+ return result;
86
+ }).catch((err) => {
87
+ this.finalizeJob(index, err, true);
88
+ return err;
89
+ });
90
+ });
91
+ }
92
+ finalizeJob(index, value, isError) {
93
+ this.currentCycleCompleted[index] = value;
94
+ this.activeCount -= 1;
95
+ if (isError && this.breakWhenError) {
96
+ this.stopProcessing = true;
97
+ this.items = [];
98
+ }
99
+ if (this.activeCount !== 0) {
100
+ return;
101
+ }
102
+ const completed = this.currentCycleCompleted.slice();
103
+ this.currentCycleCompleted = [];
104
+ if (this.onProgress) {
105
+ this.onProgress({
106
+ batchToProcess: this.batchToProcess,
107
+ itemsToProcess: this.items.length,
108
+ completed
109
+ });
110
+ }
111
+ this.processNext();
112
+ }
113
+ terminate() {
114
+ this.items = [];
115
+ }
116
+ };
117
+ var index_default = Qpass;
118
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../index.ts"],"sourcesContent":["declare const __QPASS_VERSION__: string;\r\n\r\nconst QPASS_VERSION =\r\n typeof __QPASS_VERSION__ === \"string\" ? __QPASS_VERSION__ : \"0.0.0\";\r\n\r\nclass Qpass {\r\n version = QPASS_VERSION; // version info\r\n\r\n private items: (() => Promise<any>)[] = []; // job queue\r\n private breakWhenError: boolean = false; // whether to stop on error\r\n private batchSize: number = 1; // number of jobs to process at once\r\n private onProgress?: (progress: {\r\n batchToProcess: number; // remaining batch count\r\n itemsToProcess: number; // remaining job count\r\n completed: any[]; // completed job results array\r\n }) => void; // progress callback\r\n\r\n private activeCount: number = 0; // number of jobs currently running\r\n private currentCycleCompleted: any[] = []; // completed results for current cycle\r\n private stopProcessing: boolean = false; // stop scheduling new jobs when true\r\n\r\n private get batchToProcess() {\r\n // calculate total batch count\r\n return Math.ceil(this.items.length / this.batchSize);\r\n }\r\n\r\n constructor(option?: {\r\n breakWhenError?: boolean;\r\n onProgress?: (progress: {\r\n batchToProcess: number;\r\n itemsToProcess: number;\r\n completed: any[];\r\n }) => void;\r\n batchSize?: number; // must be at least 1, default is 1\r\n }) {\r\n this.breakWhenError = !!option?.breakWhenError;\r\n this.batchSize = option?.batchSize ?? 1;\r\n\r\n if (typeof this.batchSize !== \"number\" || this.batchSize < 1) {\r\n throw new Error(\"batchSize must be at least 1\");\r\n }\r\n\r\n if (option?.onProgress) {\r\n if (typeof option.onProgress === \"function\") {\r\n this.onProgress = option.onProgress;\r\n } else {\r\n throw new Error(\"onProgress must be a function\");\r\n }\r\n }\r\n }\r\n\r\n // add jobs to the queue at once\r\n add(jobs: (() => Promise<any>)[] | (() => Promise<any>)) {\r\n // check if jobs is an array, if not convert to array\r\n const jobsArray = Array.isArray(jobs) ? jobs : [jobs];\r\n\r\n // check if each job is a function, if so add to queue\r\n for (const job of jobsArray) {\r\n if (typeof job !== \"function\") {\r\n throw new Error(\r\n \"Each job must be a function that returns a Promise\"\r\n );\r\n }\r\n this.items.push(job);\r\n }\r\n\r\n this.processNext();\r\n }\r\n\r\n // process next batch of jobs\r\n private processNext() {\r\n // exit if queue is empty, processing is stopped, or a cycle is still running\r\n if (\r\n this.stopProcessing ||\r\n this.items.length === 0 ||\r\n this.activeCount > 0\r\n ) {\r\n return;\r\n }\r\n\r\n const jobsToRun = this.items.splice(0, this.batchSize);\r\n this.activeCount = jobsToRun.length;\r\n this.currentCycleCompleted = new Array(jobsToRun.length);\r\n\r\n jobsToRun.forEach((job, index) => {\r\n Promise.resolve()\r\n .then(() => job())\r\n .then((result) => {\r\n this.finalizeJob(index, result, false);\r\n return result;\r\n })\r\n .catch((err) => {\r\n this.finalizeJob(index, err, true);\r\n return err;\r\n });\r\n });\r\n }\r\n\r\n private finalizeJob(index: number, value: any, isError: boolean) {\r\n this.currentCycleCompleted[index] = value;\r\n this.activeCount -= 1;\r\n\r\n if (isError && this.breakWhenError) {\r\n this.stopProcessing = true;\r\n this.items = [];\r\n }\r\n\r\n if (this.activeCount !== 0) {\r\n return;\r\n }\r\n\r\n const completed = this.currentCycleCompleted.slice();\r\n this.currentCycleCompleted = [];\r\n\r\n if (this.onProgress) {\r\n this.onProgress({\r\n batchToProcess: this.batchToProcess,\r\n itemsToProcess: this.items.length,\r\n completed: completed,\r\n });\r\n }\r\n\r\n this.processNext();\r\n }\r\n\r\n terminate()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AA,IACJ;AAEA,UAAM,YAAY,KAAK,MAAM,OAAO,GAAG,KAAK,SAAS;AACrD,SAAK,cAAc,UAAU;AAC7B,SAAK,wBAAwB,IAAI,MAAM,UAAU,MAAM;AAEvD,cAAU,QAAQ,CAAC,KAAK,UAAU;AAC9B,cAAQ,QAAQ,EACX,KAAK,MAAM,IAAI,CAAC,EAChB,KAAK,CAAC,WAAW;AACd,aAAK,YAAY,OAAO,QAAQ,KAAK;AACrC,eAAO;AAAA,MACX,CAAC,EACA,MAAM,CAAC,QAAQ;AACZ,aAAK,YAAY,OAAO,KAAK,IAAI;AACjC,eAAO;AAAA,MACX,CAAC;AAAA,IACT,CAAC;AAAA,EACL;AAAA,EAEQ,YAAY,OAAe,OAAY,SAAkB;AAC7D,SAAK,sBAAsB,KAAK,IAAI;AACpC,SAAK,eAAe;AAEpB,QAAI,WAAW,KAAK,gBAAgB;AAChC,WAAK,iBAAiB;AACtB,WAAK,QAAQ,CAAC;AAAA,IAClB;AAEA,QAAI,KAAK,gBAAgB,GAAG;AACxB;AAAA,IACJ;AAEA,UAAM,YAAY,KAAK,sBAAsB,MAAM;AACnD,SAAK,wBAAwB,CAAC;AAE9B,QAAI,KAAK,YAAY;AACjB,WAAK,WAAW;AAAA,QACZ,gBAAgB,KAAK;AAAA,QACrB,gBAAgB,KAAK,MAAM;AAAA,QAC3B;AAAA,MACJ,CAAC;AAAA,IACL;AAEA,SAAK,YAAY;AAAA,EACrB;AAAA,EAEA,YAAY;AAER,SAAK,QAAQ,CAAC;AAAA,EAClB;AACJ;AAEA,IAAO,gBAAQ;","names":[]}
@@ -0,0 +1,27 @@
1
+ declare class Qpass {
2
+ version: string;
3
+ private items;
4
+ private breakWhenError;
5
+ private batchSize;
6
+ private onProgress?;
7
+ private activeCount;
8
+ private currentCycleCompleted;
9
+ private stopProcessing;
10
+ private get batchToProcess();
11
+ constructor(option?: {
12
+ breakWhenError?: boolean;
13
+ onProgress?: (progress: {
14
+ batchToProcess: number;
15
+ itemsToProcess: number;
16
+ completed: any[];
17
+ }) => void;
18
+ batchSize?: number;
19
+ });
20
+ add(jobs: (() => Promise<any>)[] | (() => Promise<any>)): void;
21
+ private processNext;
22
+ private finalizeJob;
23
+ terminate(): void;
24
+ }
25
+ //# sourceMappingURL=index.d.ts.map
26
+
27
+ export { Qpass as default };
@@ -0,0 +1,27 @@
1
+ declare class Qpass {
2
+ version: string;
3
+ private items;
4
+ private breakWhenError;
5
+ private batchSize;
6
+ private onProgress?;
7
+ private activeCount;
8
+ private currentCycleCompleted;
9
+ private stopProcessing;
10
+ private get batchToProcess();
11
+ constructor(option?: {
12
+ breakWhenError?: boolean;
13
+ onProgress?: (progress: {
14
+ batchToProcess: number;
15
+ itemsToProcess: number;
16
+ completed: any[];
17
+ }) => void;
18
+ batchSize?: number;
19
+ });
20
+ add(jobs: (() => Promise<any>)[] | (() => Promise<any>)): void;
21
+ private processNext;
22
+ private finalizeJob;
23
+ terminate(): void;
24
+ }
25
+ //# sourceMappingURL=index.d.ts.map
26
+
27
+ export { Qpass as default };
package/dist/index.js ADDED
@@ -0,0 +1,97 @@
1
+ // index.ts
2
+ var QPASS_VERSION = true ? "1.1.0" : "0.0.0";
3
+ var Qpass = class {
4
+ version = QPASS_VERSION;
5
+ // version info
6
+ items = [];
7
+ // job queue
8
+ breakWhenError = false;
9
+ // whether to stop on error
10
+ batchSize = 1;
11
+ // number of jobs to process at once
12
+ onProgress;
13
+ // progress callback
14
+ activeCount = 0;
15
+ // number of jobs currently running
16
+ currentCycleCompleted = [];
17
+ // completed results for current cycle
18
+ stopProcessing = false;
19
+ // stop scheduling new jobs when true
20
+ get batchToProcess() {
21
+ return Math.ceil(this.items.length / this.batchSize);
22
+ }
23
+ constructor(option) {
24
+ this.breakWhenError = !!option?.breakWhenError;
25
+ this.batchSize = option?.batchSize ?? 1;
26
+ if (typeof this.batchSize !== "number" || this.batchSize < 1) {
27
+ throw new Error("batchSize must be at least 1");
28
+ }
29
+ if (option?.onProgress) {
30
+ if (typeof option.onProgress === "function") {
31
+ this.onProgress = option.onProgress;
32
+ } else {
33
+ throw new Error("onProgress must be a function");
34
+ }
35
+ }
36
+ }
37
+ // add jobs to the queue at once
38
+ add(jobs) {
39
+ const jobsArray = Array.isArray(jobs) ? jobs : [jobs];
40
+ for (const job of jobsArray) {
41
+ if (typeof job !== "function") {
42
+ throw new Error(
43
+ "Each job must be a function that returns a Promise"
44
+ );
45
+ }
46
+ this.items.push(job);
47
+ }
48
+ this.processNext();
49
+ }
50
+ // process next batch of jobs
51
+ processNext() {
52
+ if (this.stopProcessing || this.items.length === 0 || this.activeCount > 0) {
53
+ return;
54
+ }
55
+ const jobsToRun = this.items.splice(0, this.batchSize);
56
+ this.activeCount = jobsToRun.length;
57
+ this.currentCycleCompleted = new Array(jobsToRun.length);
58
+ jobsToRun.forEach((job, index) => {
59
+ Promise.resolve().then(() => job()).then((result) => {
60
+ this.finalizeJob(index, result, false);
61
+ return result;
62
+ }).catch((err) => {
63
+ this.finalizeJob(index, err, true);
64
+ return err;
65
+ });
66
+ });
67
+ }
68
+ finalizeJob(index, value, isError) {
69
+ this.currentCycleCompleted[index] = value;
70
+ this.activeCount -= 1;
71
+ if (isError && this.breakWhenError) {
72
+ this.stopProcessing = true;
73
+ this.items = [];
74
+ }
75
+ if (this.activeCount !== 0) {
76
+ return;
77
+ }
78
+ const completed = this.currentCycleCompleted.slice();
79
+ this.currentCycleCompleted = [];
80
+ if (this.onProgress) {
81
+ this.onProgress({
82
+ batchToProcess: this.batchToProcess,
83
+ itemsToProcess: this.items.length,
84
+ completed
85
+ });
86
+ }
87
+ this.processNext();
88
+ }
89
+ terminate() {
90
+ this.items = [];
91
+ }
92
+ };
93
+ var index_default = Qpass;
94
+ export {
95
+ index_default as default
96
+ };
97
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../index.ts"],"sourcesContent":["declare const __QPASS_VERSION__: string;\r\n\r\nconst QPASS_VERSION =\r\n typeof __QPASS_VERSION__ === \"string\" ? __QPASS_VERSION__ : \"0.0.0\";\r\n\r\nclass Qpass {\r\n version = QPASS_VERSION; // version info\r\n\r\n private items: (() => Promise<any>)[] = []; // job queue\r\n private breakWhenError: boolean = false; // whether to stop on error\r\n private batchSize: number = 1; // number of jobs to process at once\r\n private onProgress?: (progress: {\r\n batchToProcess: number; // remaining batch count\r\n itemsToProcess: number; // remaining job count\r\n completed: any[]; // completed job results array\r\n }) => void; // progress callback\r\n\r\n private activeCount: number = 0; // number of jobs currently running\r\n private currentCycleCompleted: any[] = []; // completed results for current cycle\r\n private stopProcessing: boolean = false; // stop scheduling new jobs when true\r\n\r\n private get batchToProcess() {\r\n // calculate total batch count\r\n return Math.ceil(this.items.length / this.batchSize);\r\n }\r\n\r\n constructor(option?: {\r\n breakWhenError?: boolean;\r\n onProgress?: (progress: {\r\n batchToProcess: number;\r\n itemsToProcess: number;\r\n completed: any[];\r\n }) => void;\r\n batchSize?: number; // must be at least 1, default is 1\r\n }) {\r\n this.breakWhenError = !!option?.breakWhenError;\r\n this.batchSize = option?.batchSize ?? 1;\r\n\r\n if (typeof this.batchSize !== \"number\" || this.batchSize < 1) {\r\n throw new Error(\"batchSize must be at least 1\");\r\n }\r\n\r\n if (option?.onProgress) {\r\n if (typeof option.onProgress === \"function\") {\r\n this.onProgress = option.onProgress;\r\n } else {\r\n throw new Error(\"onProgress must be a function\");\r\n }\r\n }\r\n }\r\n\r\n // add jobs to the queue at once\r\n add(jobs: (() => Promise<any>)[] | (() => Promise<any>)) {\r\n // check if jobs is an array, if not convert to array\r\n const jobsArray = Array.isArray(jobs) ? jobs : [jobs];\r\n\r\n // check if each job is a function, if so add to queue\r\n for (const job of jobsArray) {\r\n if (typeof job !== \"function\") {\r\n throw new Error(\r\n \"Each job must be a function that returns a Promise\"\r\n );\r\n }\r\n this.items.push(job);\r\n }\r\n\r\n this.processNext();\r\n }\r\n\r\n // process next batch of jobs\r\n private processNext() {\r\n // exit if queue is empty, processing is stopped, or a cycle is still running\r\n if (\r\n this.stopProcessing ||\r\n this.items.length === 0 ||\r\n this.activeCount > 0\r\n ) {\r\n return;\r\n }\r\n\r\n const jobsToRun = this.items.splice(0, this.batchSize);\r\n this.activeCount = jobsToRun.length;\r\n this.currentCycleCompleted = new Array(jobsToRun.length);\r\n\r\n jobsToRun.forEach((job, index) => {\r\n Promise.resolve()\r\n .then(() => job())\r\n .then((result) => {\r\n this.finalizeJob(index, result, false);\r\n return result;\r\n })\r\n .catch((err) => {\r\n this.finalizeJob(index, err, true);\r\n return err;\r\n });\r\n });\r\n }\r\n\r\n private finalizeJob(index: number, value: any, isError: boolean) {\r\n this.currentCycleCompleted[index] = value;\r\n this.activeCount -= 1;\r\n\r\n if (isError && this.breakWhenError) {\r\n this.stopProcessing = true;\r\n this.items = [];\r\n }\r\n\r\n if (this.activeCount !== 0) {\r\n return;\r\n }\r\n\r\n const completed = this.currentCycleCompleted.slice();\r\n this.currentCycleCompleted = [];\r\n\r\n if (this.onProgress) {\r\n this.onProgress({\r\n batchToProcess: this.batchToProcess,\r\n itemsToProcess: this.items.length,\r\n completed: completed,\r\n });\r\n }\r\n\r\n this.processNext();\r\n }\r\n\r\n terminate() {\r\n // remove all remaining jobs from queue\r\n this.items = [];\r\n }\r\n}\r\n\r\nexport default Qpass;\r\n"],"mappings":";AAEA,IAAM,gBACF,OAAwC,UAAoB;AAEhE,IAAM,QAAN,MAAY;AAAA,EACR,UAAU;AAAA;AAAA,EAEF,QAAgC,CAAC;AAAA;AAAA,EACjC,iBAA0B;AAAA;AAAA,EAC1B,YAAoB;AAAA;AAAA,EACpB;AAAA;AAAA,EAMA,cAAsB;AAAA;AAAA,EACtB,wBAA+B,CAAC;AAAA;AAAA,EAChC,iBAA0B;AAAA;AAAA,EAElC,IAAY,iBAAiB;AAEzB,WAAO,KAAK,KAAK,KAAK,MAAM,SAAS,KAAK,SAAS;AAAA,EACvD;AAAA,EAEA,YAAY,QAQT;AACC,SAAK,iBAAiB,CAAC,CAAC,Q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B;AAChC,WAAK,iBAAiB;AACtB,WAAK,QAAQ,CAAC;AAAA,IAClB;AAEA,QAAI,KAAK,gBAAgB,GAAG;AACxB;AAAA,IACJ;AAEA,UAAM,YAAY,KAAK,sBAAsB,MAAM;AACnD,SAAK,wBAAwB,CAAC;AAE9B,QAAI,KAAK,YAAY;AACjB,WAAK,WAAW;AAAA,QACZ,gBAAgB,KAAK;AAAA,QACrB,gBAAgB,KAAK,MAAM;AAAA,QAC3B;AAAA,MACJ,CAAC;AAAA,IACL;AAEA,SAAK,YAAY;AAAA,EACrB;AAAA,EAEA,YAAY;AAER,SAAK,QAAQ,CAAC;AAAA,EAClB;AACJ;AAEA,IAAO,gBAAQ;","names":[]}
package/dist/qpass.js ADDED
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ var Qpass = (() => {
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ default: () => index_default
25
+ });
26
+ var QPASS_VERSION = true ? "1.1.0" : "0.0.0";
27
+ var Qpass = class {
28
+ version = QPASS_VERSION;
29
+ // version info
30
+ items = [];
31
+ // job queue
32
+ breakWhenError = false;
33
+ // whether to stop on error
34
+ batchSize = 1;
35
+ // number of jobs to process at once
36
+ onProgress;
37
+ // progress callback
38
+ activeCount = 0;
39
+ // number of jobs currently running
40
+ currentCycleCompleted = [];
41
+ // completed results for current cycle
42
+ stopProcessing = false;
43
+ // stop scheduling new jobs when true
44
+ get batchToProcess() {
45
+ return Math.ceil(this.items.length / this.batchSize);
46
+ }
47
+ constructor(option) {
48
+ this.breakWhenError = !!option?.breakWhenError;
49
+ this.batchSize = option?.batchSize ?? 1;
50
+ if (typeof this.batchSize !== "number" || this.batchSize < 1) {
51
+ throw new Error("batchSize must be at least 1");
52
+ }
53
+ if (option?.onProgress) {
54
+ if (typeof option.onProgress === "function") {
55
+ this.onProgress = option.onProgress;
56
+ } else {
57
+ throw new Error("onProgress must be a function");
58
+ }
59
+ }
60
+ }
61
+ // add jobs to the queue at once
62
+ add(jobs) {
63
+ const jobsArray = Array.isArray(jobs) ? jobs : [jobs];
64
+ for (const job of jobsArray) {
65
+ if (typeof job !== "function") {
66
+ throw new Error(
67
+ "Each job must be a function that returns a Promise"
68
+ );
69
+ }
70
+ this.items.push(job);
71
+ }
72
+ this.processNext();
73
+ }
74
+ // process next batch of jobs
75
+ processNext() {
76
+ if (this.stopProcessing || this.items.length === 0 || this.activeCount > 0) {
77
+ return;
78
+ }
79
+ const jobsToRun = this.items.splice(0, this.batchSize);
80
+ this.activeCount = jobsToRun.length;
81
+ this.currentCycleCompleted = new Array(jobsToRun.length);
82
+ jobsToRun.forEach((job, index) => {
83
+ Promise.resolve().then(() => job()).then((result) => {
84
+ this.finalizeJob(index, result, false);
85
+ return result;
86
+ }).catch((err) => {
87
+ this.finalizeJob(index, err, true);
88
+ return err;
89
+ });
90
+ });
91
+ }
92
+ finalizeJob(index, value, isError) {
93
+ this.currentCycleCompleted[index] = value;
94
+ this.activeCount -= 1;
95
+ if (isError && this.breakWhenError) {
96
+ this.stopProcessing = true;
97
+ this.items = [];
98
+ }
99
+ if (this.activeCount !== 0) {
100
+ return;
101
+ }
102
+ const completed = this.currentCycleCompleted.slice();
103
+ this.currentCycleCompleted = [];
104
+ if (this.onProgress) {
105
+ this.onProgress({
106
+ batchToProcess: this.batchToProcess,
107
+ itemsToProcess: this.items.length,
108
+ completed
109
+ });
110
+ }
111
+ this.processNext();
112
+ }
113
+ terminate() {
114
+ this.items = [];
115
+ }
116
+ };
117
+ var index_default = Qpass;
118
+ return __toCommonJS(index_exports);
119
+ })();
120
+ //# sourceMappingURL=qpass.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../index.ts"],"sourcesContent":["declare const __QPASS_VERSION__: string;\r\n\r\nconst QPASS_VERSION =\r\n typeof __QPASS_VERSION__ === \"string\" ? __QPASS_VERSION__ : \"0.0.0\";\r\n\r\nclass Qpass {\r\n version = QPASS_VERSION; // version info\r\n\r\n private items: (() => Promise<any>)[] = []; // job queue\r\n private breakWhenError: boolean = false; // whether to stop on error\r\n private batchSize: number = 1; // number of jobs to process at once\r\n private onProgress?: (progress: {\r\n batchToProcess: number; // remaining batch count\r\n itemsToProcess: number; // remaining job count\r\n completed: any[]; // completed job results array\r\n }) => void; // progress callback\r\n\r\n private activeCount: number = 0; // number of jobs currently running\r\n private currentCycleCompleted: any[] = []; // completed results for current cycle\r\n private stopProcessing: boolean = false; // stop scheduling new jobs when true\r\n\r\n private get batchToProcess() {\r\n // calculate total batch count\r\n return Math.ceil(this.items.length / this.batchSize);\r\n }\r\n\r\n constructor(option?: {\r\n breakWhenError?: boolean;\r\n onProgress?: (progress: {\r\n batchToProcess: number;\r\n itemsToProcess: number;\r\n completed: any[];\r\n }) => void;\r\n batchSize?: number; // must be at least 1, default is 1\r\n }) {\r\n this.breakWhenError = !!option?.breakWhenError;\r\n this.batchSize = option?.batchSize ?? 1;\r\n\r\n if (typeof this.batchSize !== \"number\" || this.batchSize < 1) {\r\n throw new Error(\"batchSize must be at least 1\");\r\n }\r\n\r\n if (option?.onProgress) {\r\n if (typeof option.onProgress === \"function\") {\r\n this.onProgress = option.onProgress;\r\n } else {\r\n throw new Error(\"onProgress must be a function\");\r\n }\r\n }\r\n }\r\n\r\n // add jobs to the queue at once\r\n add(jobs: (() => Promise<any>)[] | (() => Promise<any>)) {\r\n // check if jobs is an array, if not convert to array\r\n const jobsArray = Array.isArray(jobs) ? jobs : [jobs];\r\n\r\n // check if each job is a function, if so add to queue\r\n for (const job of jobsArray) {\r\n if (typeof job !== \"function\") {\r\n throw new Error(\r\n \"Each job must be a function that returns a Promise\"\r\n );\r\n }\r\n this.items.push(job);\r\n }\r\n\r\n this.processNext();\r\n }\r\n\r\n // process next batch of jobs\r\n private processNext() {\r\n // exit if queue is empty, processing is stopped, or a cycle is still running\r\n if (\r\n this.stopProcessing ||\r\n this.items.length === 0 ||\r\n this.activeCount > 0\r\n ) {\r\n return;\r\n }\r\n\r\n const jobsToRun = this.items.splice(0, this.batchSize);\r\n this.activeCount = jobsToRun.length;\r\n this.currentCycleCompleted = new Array(jobsToRun.length);\r\n\r\n jobsToRun.forEach((job, index) => {\r\n Promise.resolve()\r\n .then(() => job())\r\n .then((result) => {\r\n this.finalizeJob(index, result, false);\r\n return result;\r\n })\r\n .catch((err) => {\r\n this.finalizeJob(index, err, true);\r\n return err;\r\n });\r\n });\r\n }\r\n\r\n private finalizeJob(index: number, value: any, isError: boolean) {\r\n this.currentCycleCompleted[index] = value;\r\n this.activeCount -= 1;\r\n\r\n if (isError && this.breakWhenError) {\r\n this.stopProcessing = true;\r\n this.items = [];\r\n }\r\n\r\n if (this.activeCount !== 0) {\r\n return;\r\n }\r\n\r\n const completed = this.currentCycleCompleted.slice();\r\n this.currentCycleCompleted = [];\r\n\r\n if (this.onProgress) {\r\n this.onProgress({\r\n batchToProcess: this.batchToProcess,\r\n itemsToProcess: this.items.length,\r\n completed: completed,\r\n });\r\n }\r\n\r\n this.processNext();\r\n }\r\n\r\n terminate() {\r\n // remove all remaining jobs from queue\r\n this.items = [];\r\n }\r\n}\r\n\r\nexport default Qpass;\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AA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U,MAAM;AAEvD,gBAAU,QAAQ,CAAC,KAAK,UAAU;AAC9B,gBAAQ,QAAQ,EACX,KAAK,MAAM,IAAI,CAAC,EAChB,KAAK,CAAC,WAAW;AACd,eAAK,YAAY,OAAO,QAAQ,KAAK;AACrC,iBAAO;AAAA,QACX,CAAC,EACA,MAAM,CAAC,QAAQ;AACZ,eAAK,YAAY,OAAO,KAAK,IAAI;AACjC,iBAAO;AAAA,QACX,CAAC;AAAA,MACT,CAAC;AAAA,IACL;AAAA,IAEQ,YAAY,OAAe,OAAY,SAAkB;AAC7D,WAAK,sBAAsB,KAAK,IAAI;AACpC,WAAK,eAAe;AAEpB,UAAI,WAAW,KAAK,gBAAgB;AAChC,aAAK,iBAAiB;AACtB,aAAK,QAAQ,CAAC;AAAA,MAClB;AAEA,UAAI,KAAK,gBAAgB,GAAG;AACxB;AAAA,MACJ;AAEA,YAAM,YAAY,KAAK,sBAAsB,MAAM;AACnD,WAAK,wBAAwB,CAAC;AAE9B,UAAI,KAAK,YAAY;AACjB,aAAK,WAAW;AAAA,UACZ,gBAAgB,KAAK;AAAA,UACrB,gBAAgB,KAAK,MAAM;AAAA,UAC3B;AAAA,QACJ,CAAC;AAAA,MACL;AAEA,WAAK,YAAY;AAAA,IACrB;AAAA,IAEA,YAAY;AAER,WAAK,QAAQ,CAAC;AAAA,IAClB;AAAA,EACJ;AAEA,MAAO,gBAAQ;","names":[]}
package/package.json CHANGED
@@ -1,16 +1,36 @@
1
- {
2
- "name": "qpass",
3
- "version": "1.0.0",
4
- "description": "Asynchronous function handler with adjustable concurrency",
5
- "main": "index.js",
6
- "type": "module",
7
- "scripts": {
8
- "test": "echo \"Error: no test specified\" && exit 1",
9
- "build": "npx tsc --project tsconfig.json"
10
- },
11
- "author": "",
12
- "license": "ISC",
13
- "devDependencies": {
14
- "typescript": "^5.9.3"
15
- }
16
- }
1
+ {
2
+ "name": "qpass",
3
+ "version": "1.1.0",
4
+ "description": "Asynchronous function handler with adjustable concurrency",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./package.json": "./package.json"
16
+ },
17
+ "browser": "./dist/index.js",
18
+ "unpkg": "./dist/qpass.js",
19
+ "jsdelivr": "./dist/qpass.js",
20
+ "files": [
21
+ "dist",
22
+ "README.md"
23
+ ],
24
+ "type": "module",
25
+ "scripts": {
26
+ "test": "npm run build && node ./test.js",
27
+ "typecheck": "tsc --noEmit --project tsconfig.json",
28
+ "build": "tsup --config tsup.config.mjs"
29
+ },
30
+ "author": "",
31
+ "license": "ISC",
32
+ "devDependencies": {
33
+ "tsup": "^8.5.0",
34
+ "typescript": "^5.9.3"
35
+ }
36
+ }
package/index.js DELETED
@@ -1,109 +0,0 @@
1
- class Qpass {
2
- version = "1.0.0"; // version info
3
- items = []; // job queue
4
- breakWhenError = false; // whether to stop on error
5
- batchSize = 1; // number of jobs to process at once
6
- onProgress; // progress callback
7
- completed = []; // completed job results array
8
- runningBatches = []; // currently running batch count
9
- runningSlots = []; // running slot status array
10
- get batchToProcess() {
11
- // calculate total batch count
12
- return Math.ceil(this.items.length / this.batchSize);
13
- }
14
- get batchProcessFinished() {
15
- let completedCount = Object.keys(this.completed).length;
16
- let isFinished = completedCount === this.runningBatches.length;
17
- if (isFinished) {
18
- const completed = this.completed; // copy
19
- // reset state before calling callback
20
- this.completed = [];
21
- this.runningBatches = [];
22
- this.runningSlots = [];
23
- if (this.onProgress) {
24
- this.onProgress({
25
- batchToProcess: this.batchToProcess,
26
- itemsToProcess: this.items.length,
27
- completed: completed,
28
- });
29
- }
30
- }
31
- return isFinished;
32
- }
33
- constructor(option) {
34
- this.breakWhenError = !!option?.breakWhenError;
35
- this.batchSize = option?.batchSize ?? 1;
36
- if (typeof this.batchSize !== "number" || this.batchSize < 1) {
37
- throw new Error("batchSize must be at least 1");
38
- }
39
- if (option?.onProgress) {
40
- if (typeof option.onProgress === "function") {
41
- this.onProgress = option.onProgress;
42
- }
43
- else {
44
- throw new Error("onProgress must be a function");
45
- }
46
- }
47
- }
48
- // add jobs to the queue at once
49
- add(jobs) {
50
- // check if jobs is an array, if not convert to array
51
- const jobsArray = Array.isArray(jobs) ? jobs : [jobs];
52
- // check if each job is a function, if so add to queue
53
- for (const job of jobsArray) {
54
- if (typeof job !== "function") {
55
- throw new Error("Each job must be a function that returns a Promise");
56
- }
57
- this.items.push(job);
58
- }
59
- this.processNext();
60
- }
61
- // process next batch of jobs
62
- processNext() {
63
- // exit if queue is empty
64
- if (this.items.length === 0) {
65
- return;
66
- }
67
- const batchToRun = this.batchSize - this.runningBatches.length;
68
- if (batchToRun <= 0) {
69
- // exit if current running batches reached maximum
70
- return;
71
- }
72
- // extract batchToRun amount of jobs
73
- this.runningBatches.push(...this.items.splice(0, batchToRun));
74
- for (let i = 0; i < this.runningBatches.length; i++) {
75
- if (this.runningSlots?.[i]) {
76
- continue;
77
- }
78
- this.runningSlots[i] = true;
79
- this.runningBatches[i]()
80
- .then((result) => {
81
- if (this.completed[i]) {
82
- return result;
83
- }
84
- this.completed[i] = result;
85
- if (this.batchProcessFinished) {
86
- return this.processNext();
87
- }
88
- return result;
89
- })
90
- .catch((err) => {
91
- // error handling
92
- if (this.breakWhenError) {
93
- throw err;
94
- }
95
- this.completed[i] = err;
96
- if (this.batchProcessFinished) {
97
- return this.processNext();
98
- }
99
- return err;
100
- });
101
- }
102
- }
103
- terminate() {
104
- // remove all remaining jobs from queue
105
- this.items = [];
106
- }
107
- }
108
- export default Qpass;
109
- //# sourceMappingURL=index.js.map
package/index.ts DELETED
@@ -1,148 +0,0 @@
1
- class Qpass {
2
- version = "1.0.0"; // version info
3
-
4
- private items: (() => Promise<any>)[] = []; // job queue
5
- private breakWhenError: boolean = false; // whether to stop on error
6
- private batchSize: number = 1; // number of jobs to process at once
7
- private onProgress?: (progress: {
8
- batchToProcess: number; // remaining batch count
9
- itemsToProcess: number; // remaining job count
10
- completed: any[]; // completed job results array
11
- }) => void; // progress callback
12
-
13
- private completed: any[] = []; // completed job results array
14
- private runningBatches: (() => Promise<any>)[] = []; // currently running batch count
15
- private runningSlots: boolean[] = []; // running slot status array
16
-
17
- private get batchToProcess() {
18
- // calculate total batch count
19
- return Math.ceil(this.items.length / this.batchSize);
20
- }
21
-
22
- private get batchProcessFinished() {
23
- let completedCount = Object.keys(this.completed).length;
24
- let isFinished = completedCount === this.runningBatches.length;
25
-
26
- if (isFinished) {
27
- const completed = this.completed; // copy
28
-
29
- // reset state before calling callback
30
- this.completed = [];
31
- this.runningBatches = [];
32
- this.runningSlots = [];
33
-
34
- if (this.onProgress) {
35
- this.onProgress({
36
- batchToProcess: this.batchToProcess,
37
- itemsToProcess: this.items.length,
38
- completed: completed,
39
- });
40
- }
41
- }
42
-
43
- return isFinished;
44
- }
45
-
46
- constructor(option?: {
47
- breakWhenError?: boolean;
48
- onProgress?: (progress: {
49
- batchToProcess: number;
50
- itemsToProcess: number;
51
- completed: any[];
52
- }) => void;
53
- batchSize?: number; // must be at least 1, default is 1
54
- }) {
55
- this.breakWhenError = !!option?.breakWhenError;
56
- this.batchSize = option?.batchSize ?? 1;
57
-
58
- if (typeof this.batchSize !== "number" || this.batchSize < 1) {
59
- throw new Error("batchSize must be at least 1");
60
- }
61
-
62
- if (option?.onProgress) {
63
- if (typeof option.onProgress === "function") {
64
- this.onProgress = option.onProgress;
65
- } else {
66
- throw new Error("onProgress must be a function");
67
- }
68
- }
69
- }
70
-
71
- // add jobs to the queue at once
72
- add(jobs: (() => Promise<any>)[] | (() => Promise<any>)) {
73
- // check if jobs is an array, if not convert to array
74
- const jobsArray = Array.isArray(jobs) ? jobs : [jobs];
75
-
76
- // check if each job is a function, if so add to queue
77
- for (const job of jobsArray) {
78
- if (typeof job !== "function") {
79
- throw new Error(
80
- "Each job must be a function that returns a Promise"
81
- );
82
- }
83
- this.items.push(job);
84
- }
85
-
86
- this.processNext();
87
- }
88
-
89
- // process next batch of jobs
90
- private processNext() {
91
- // exit if queue is empty
92
- if (this.items.length === 0) {
93
- return;
94
- }
95
-
96
- const batchToRun = this.batchSize - this.runningBatches.length;
97
- if (batchToRun <= 0) {
98
- // exit if current running batches reached maximum
99
- return;
100
- }
101
-
102
- // extract batchToRun amount of jobs
103
- this.runningBatches.push(...this.items.splice(0, batchToRun));
104
-
105
- for (let i = 0; i < this.runningBatches.length; i++) {
106
- if (this.runningSlots?.[i]) {
107
- continue;
108
- }
109
-
110
- this.runningSlots[i] = true;
111
- (this.runningBatches[i] as () => Promise<any>)()
112
- .then((result) => {
113
- if (this.completed[i]) {
114
- return result;
115
- }
116
-
117
- this.completed[i] = result;
118
-
119
- if (this.batchProcessFinished) {
120
- return this.processNext();
121
- }
122
-
123
- return result;
124
- })
125
- .catch((err) => {
126
- // error handling
127
- if (this.breakWhenError) {
128
- throw err;
129
- }
130
-
131
- this.completed[i] = err;
132
-
133
- if (this.batchProcessFinished) {
134
- return this.processNext();
135
- }
136
-
137
- return err;
138
- });
139
- }
140
- }
141
-
142
- terminate() {
143
- // remove all remaining jobs from queue
144
- this.items = [];
145
- }
146
- }
147
-
148
- export default Qpass;
package/test.js DELETED
@@ -1,68 +0,0 @@
1
- import Qpass from "./index.js";
2
-
3
- // job creator
4
- const createJob =
5
- (id, duration, shouldFail = false) =>
6
- () => {
7
- return new Promise((resolve, reject) => {
8
- setTimeout(() => {
9
- if (shouldFail) {
10
- reject(new Error(`Job ${id} failed`));
11
- } else {
12
- resolve(`Job ${id} completed`);
13
- }
14
- }, duration);
15
- });
16
- };
17
-
18
- // test code
19
- console.log("πŸš€ Qpass test started\n");
20
-
21
- let did2ndTest = false;
22
-
23
- const onProgress = ({ batchToProcess, itemsToProcess, completed }) => {
24
- console.log(`Remaining batches: ${batchToProcess}`);
25
- console.log(`Remaining jobs: ${itemsToProcess}`);
26
- if(itemsToProcess === 5) {
27
- queue.terminate();
28
- }
29
- console.log(
30
- "Completed:",
31
- completed.map((r) => (r instanceof Error ? `Error: ${r.message}` : r))
32
- );
33
-
34
- console.log("---");
35
-
36
- if (itemsToProcess === 0) {
37
- console.log("πŸš€ Qpass test completed");
38
-
39
- if (!did2ndTest) {
40
- console.log("\nπŸš€ Qpass array addition 2nd test started\n");
41
-
42
- did2ndTest = true;
43
- testArray();
44
- }
45
- }
46
- };
47
-
48
- const queue = new Qpass({
49
- breakWhenError: false,
50
- batchSize: 3,
51
- onProgress: onProgress,
52
- });
53
-
54
- const testLoop = () => {
55
- for (let i = 1; i <= 14; i++) {
56
- queue.add(createJob(i, 800, i % 3 === 0)); // multiples of 3 will fail
57
- }
58
- };
59
-
60
- testLoop();
61
-
62
- const testArray = () => {
63
- let jobs = [];
64
- for (let i = 1; i <= 14; i++) {
65
- jobs.push(createJob(i, 800, i % 3 === 0)); // multiples of 3 will fail
66
- }
67
- queue.add(jobs);
68
- };
package/tsconfig.json DELETED
@@ -1,47 +0,0 @@
1
- {
2
- // Visit https://aka.ms/tsconfig to read more about this file
3
- "compilerOptions": {
4
- // File Layout
5
- // "rootDir": "./src",
6
- // "outDir": "./dist",
7
-
8
- // Environment Settings
9
- // See also https://aka.ms/tsconfig/module
10
- "module": "nodenext",
11
- "target": "esnext",
12
- "types": [],
13
- // For nodejs:
14
- // "lib": ["esnext"],
15
- // "types": ["node"],
16
- // and npm install -D @types/node
17
-
18
- // Other Outputs
19
- "sourceMap": true,
20
- "declaration": true,
21
- "declarationMap": true,
22
-
23
- // Stricter Typechecking Options
24
- "noUncheckedIndexedAccess": true,
25
- "exactOptionalPropertyTypes": true,
26
-
27
- // Style Options
28
- // "noImplicitReturns": true,
29
- // "noImplicitOverride": true,
30
- // "noUnusedLocals": true,
31
- // "noUnusedParameters": true,
32
- // "noFallthroughCasesInSwitch": true,
33
- // "noPropertyAccessFromIndexSignature": true,
34
-
35
- // Recommended Options
36
- "strict": true,
37
- "jsx": "react-jsx",
38
- "verbatimModuleSyntax": true,
39
- "isolatedModules": true,
40
- "noUncheckedSideEffectImports": true,
41
- "moduleDetection": "force",
42
- "skipLibCheck": true,
43
-
44
- // "target": "ES2015", // λ˜λŠ” "ES6"
45
- "lib": ["ES2015", "DOM"] // Promise와 λΈŒλΌμš°μ € κ΄€λ ¨ APIλ₯Ό 지원
46
- }
47
- }