in-parallel-lit 1.0.0 → 3.0.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/LICENSE CHANGED
File without changes
package/README.md CHANGED
@@ -6,8 +6,6 @@ A CLI tool to run multiple processes in parallel.
6
6
 
7
7
  ```bash
8
8
  $ npm i -g in-parallel-lit
9
- # or
10
- $ yarn global add in-parallel-lit
11
9
  ```
12
10
 
13
11
  ## Usage
@@ -151,9 +149,3 @@ $ ./Taskfile.sh validate
151
149
 
152
150
  (3) Start developing. See [`./Taskfile.sh`](./Taskfile.sh) for more tasks to
153
151
  help you develop.
154
-
155
- ---
156
-
157
- _This project was set up by @jvdx/core_
158
-
159
- [install-node]: https://github.com/nvm-sh/nvm
package/dist/bin.cjs ADDED
@@ -0,0 +1,438 @@
1
+ #!/usr/bin/env node
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let node_module = require("node:module");
25
+ let sade = require("sade");
26
+ sade = __toESM(sade);
27
+ let node_stream = require("node:stream");
28
+ let node_string_decoder = require("node:string_decoder");
29
+ let cross_spawn = require("cross-spawn");
30
+ let node_os = require("node:os");
31
+ node_os = __toESM(node_os);
32
+ //#region src/lib/get-signal-num.ts
33
+ var signals = {
34
+ SIGABRT: 6,
35
+ SIGALRM: 14,
36
+ SIGBUS: 10,
37
+ SIGCHLD: 20,
38
+ SIGCONT: 19,
39
+ SIGFPE: 8,
40
+ SIGHUP: 1,
41
+ SIGILL: 4,
42
+ SIGINT: 2,
43
+ SIGKILL: 9,
44
+ SIGPIPE: 13,
45
+ SIGQUIT: 3,
46
+ SIGSEGV: 11,
47
+ SIGSTOP: 17,
48
+ SIGTERM: 15,
49
+ SIGTRAP: 5,
50
+ SIGTSTP: 18,
51
+ SIGTTIN: 21,
52
+ SIGTTOU: 22,
53
+ SIGUSR1: 30,
54
+ SIGUSR2: 31
55
+ };
56
+ /**
57
+ * Converts a signal name to a number.
58
+ */
59
+ function getSignalNumber(signal) {
60
+ return signals[signal] || 0;
61
+ }
62
+ //#endregion
63
+ //#region src/lib/get-stream-kind.ts
64
+ /**
65
+ * Converts a given stream to an option for `child_process.spawn`.
66
+ */
67
+ function getStreamKind(stream, std) {
68
+ if (stream == null) return "ignore";
69
+ if (stream !== std || !std.isTTY) return "pipe";
70
+ return stream;
71
+ }
72
+ //#endregion
73
+ //#region src/lib/in-parallel-error.ts
74
+ var InParallelError = class extends Error {
75
+ code;
76
+ results;
77
+ constructor(causeResult, allResults) {
78
+ super(`"${causeResult.name}" exited with ${causeResult.code}.`);
79
+ this.name = causeResult.name;
80
+ this.code = causeResult.code;
81
+ this.results = allResults;
82
+ }
83
+ };
84
+ //#endregion
85
+ //#region src/lib/memory-writable.ts
86
+ var noop = () => {};
87
+ var MemoryWritable = class extends node_stream.Writable {
88
+ queue = [];
89
+ data;
90
+ constructor(data = null) {
91
+ super();
92
+ this.data = Array.isArray(data) ? data : [data];
93
+ this.queue = [];
94
+ for (let chunk of this.data) {
95
+ if (chunk == null) continue;
96
+ if (!(chunk instanceof Buffer)) chunk = Buffer.from(chunk);
97
+ this.queue.push(chunk);
98
+ }
99
+ }
100
+ _write(chunk, enc, cb = noop) {
101
+ let decoder = null;
102
+ try {
103
+ decoder = enc && enc !== "buffer" ? new node_string_decoder.StringDecoder(enc) : null;
104
+ } catch (err) {
105
+ return cb(err);
106
+ }
107
+ let decodedChunk = decoder != null ? decoder.write(chunk) : chunk;
108
+ this.queue.push(Buffer.isBuffer(decodedChunk) ? decodedChunk : Buffer.from(decodedChunk));
109
+ cb();
110
+ }
111
+ _getQueueSize() {
112
+ let size = 0;
113
+ for (let i = 0; i < this.queue.length; i++) size += this.queue[i].length;
114
+ return size;
115
+ }
116
+ toString() {
117
+ let str = "";
118
+ for (const chunk of this.queue) str += chunk.toString();
119
+ return str;
120
+ }
121
+ toBuffer() {
122
+ const buffer = Buffer.alloc(this._getQueueSize());
123
+ let currentOffset = 0;
124
+ for (const chunk of this.queue) {
125
+ chunk.copy(buffer, currentOffset);
126
+ currentOffset += chunk.length;
127
+ }
128
+ return buffer;
129
+ }
130
+ };
131
+ //#endregion
132
+ //#region src/lib/remove-from-arr.ts
133
+ /**
134
+ * removeFromArr removes an `item` from `arr`.
135
+ */
136
+ function removeFromArr(arr, item) {
137
+ const index = arr.indexOf(item);
138
+ if (index !== -1) arr.splice(index, 1);
139
+ }
140
+ //#endregion
141
+ //#region src/lib/kill-pids.ts
142
+ /**
143
+ * Wrap crossSpawn in a Promise
144
+ */
145
+ function crossSpawnPromise(cmd, args = [], options = {}) {
146
+ return new Promise((resolve, reject) => {
147
+ let stdout = "";
148
+ let stderr = "";
149
+ const ch = (0, cross_spawn.spawn)(cmd, args, options);
150
+ if (ch.stdout === null || ch.stderr === null) return reject("stdout/stderr is null");
151
+ ch.stdout.on("data", (d) => {
152
+ stdout += d.toString();
153
+ });
154
+ ch.stderr.on("data", (d) => {
155
+ stderr += d.toString();
156
+ });
157
+ ch.on("error", (err) => reject(err));
158
+ ch.on("close", (code) => {
159
+ if (stderr) return reject(stderr);
160
+ if (code !== 0) return reject(`${cmd} exited with code ${code}`);
161
+ return resolve(stdout);
162
+ });
163
+ });
164
+ }
165
+ /**
166
+ * Kills a process by ID and all its subprocesses.
167
+ */
168
+ async function killPids(pid, platform = process.platform) {
169
+ if (platform === "win32") {
170
+ (0, cross_spawn.spawn)("taskkill", [
171
+ "/F",
172
+ "/T",
173
+ "/PID",
174
+ String(pid)
175
+ ]);
176
+ return;
177
+ }
178
+ try {
179
+ const stdoutRows = (await crossSpawnPromise("ps", [
180
+ "-A",
181
+ "-o",
182
+ "ppid,pid"
183
+ ])).split(node_os.default.EOL);
184
+ let pidExists = false;
185
+ const pidTree = {};
186
+ for (let i = 1; i < stdoutRows.length; i++) {
187
+ stdoutRows[i] = stdoutRows[i].trim();
188
+ if (!stdoutRows[i]) continue;
189
+ const stdoutTuple = stdoutRows[i].split(/\s+/);
190
+ const stdoutPpid = parseInt(stdoutTuple[0], 10);
191
+ const stdoutPid = parseInt(stdoutTuple[1], 10);
192
+ if (!pidExists && stdoutPid === pid || !pidExists && stdoutPpid === pid) pidExists = true;
193
+ if (pidTree[stdoutPpid]) pidTree[stdoutPpid].push(stdoutPid);
194
+ else pidTree[stdoutPpid] = [stdoutPid];
195
+ }
196
+ if (!pidExists) return;
197
+ let idx = 0;
198
+ const pids = [pid];
199
+ while (idx < pids.length) {
200
+ const curpid = pids[idx++];
201
+ if (!pidTree[curpid]) continue;
202
+ for (let j = 0; j < pidTree[curpid].length; j++) pids.push(pidTree[curpid][j]);
203
+ delete pidTree[curpid];
204
+ }
205
+ for (const pid of pids) process.kill(pid);
206
+ } catch {}
207
+ }
208
+ //#endregion
209
+ //#region src/lib/spawn.ts
210
+ /**
211
+ * Launches a new process with the given command.
212
+ * This is almost same as `child_process.spawn`, but it adds a `kill` method
213
+ * that kills the instance process and its sub processes.
214
+ */
215
+ function spawn(command, args, options) {
216
+ const child = (0, cross_spawn.spawn)(command, args, options);
217
+ child.kill = function kill() {
218
+ killPids(this.pid);
219
+ return true;
220
+ };
221
+ return child;
222
+ }
223
+ //#endregion
224
+ //#region src/lib/prefix-transform.ts
225
+ var ALL_BR = /\n/g;
226
+ var PrefixTransform = class extends node_stream.Transform {
227
+ prefix;
228
+ lastPrefix;
229
+ lastIsLinebreak;
230
+ constructor(prefix) {
231
+ super();
232
+ this.prefix = prefix;
233
+ this.lastPrefix = null;
234
+ this.lastIsLinebreak = true;
235
+ }
236
+ _transform(chunk, _enc, cb) {
237
+ const prefixed = `${this.lastIsLinebreak ? this.prefix : this.lastPrefix !== this.prefix ? "\n" : ""}${chunk}`.replace(ALL_BR, `\n${this.prefix}`);
238
+ const index = prefixed.indexOf(this.prefix, Math.max(0, prefixed.length - this.prefix.length));
239
+ this.lastPrefix = this.prefix;
240
+ this.lastIsLinebreak = index !== -1;
241
+ cb(null, index !== -1 ? prefixed.slice(0, index) : prefixed);
242
+ }
243
+ };
244
+ //#endregion
245
+ //#region src/lib/select-color.ts
246
+ var FORCE_COLOR;
247
+ var NODE_DISABLE_COLORS;
248
+ var NO_COLOR;
249
+ var TERM;
250
+ var isTTY = true;
251
+ var enabled;
252
+ /**
253
+ * Check if color support is enabled.
254
+ */
255
+ function checkColorSupport() {
256
+ if (enabled != null) return;
257
+ ({FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM} = process.env);
258
+ isTTY = process.stdout?.isTTY;
259
+ enabled = !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY);
260
+ }
261
+ /**
262
+ * Returns functions that wrap a given string with color char codes.
263
+ */
264
+ function createColor(x, y) {
265
+ const rgx = new RegExp(`\\x1b\\[${y}m`, "g");
266
+ const open = `\x1b[${x}m`;
267
+ const close = `\x1b[${y}m`;
268
+ return function(txt) {
269
+ checkColorSupport();
270
+ if (!enabled) return txt;
271
+ return open + (~`${txt}`.indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;
272
+ };
273
+ }
274
+ var colors = [
275
+ createColor(36, 39),
276
+ createColor(32, 39),
277
+ createColor(35, 39),
278
+ createColor(33, 39),
279
+ createColor(31, 39)
280
+ ];
281
+ var colorIndex = 0;
282
+ var taskNamesToColors = /* @__PURE__ */ new Map();
283
+ /**
284
+ * Select a color from given task name.
285
+ */
286
+ function selectColor(taskName) {
287
+ let color = taskNamesToColors.get(taskName);
288
+ if (color == null) {
289
+ color = colors[colorIndex];
290
+ colorIndex = (colorIndex + 1) % colors.length;
291
+ taskNamesToColors.set(taskName, color);
292
+ }
293
+ return color;
294
+ }
295
+ //#endregion
296
+ //#region src/lib/wrap-stream-with-label.ts
297
+ /**
298
+ * Wraps stdout/stderr with a transform stream to add the task name as prefix.
299
+ */
300
+ function wrapStreamWithLabel(source, label) {
301
+ if (source == null) return source;
302
+ const target = new PrefixTransform((source.isTTY ? selectColor(label) : (x) => x)(`[${label}] `));
303
+ target.pipe(source);
304
+ return target;
305
+ }
306
+ //#endregion
307
+ //#region src/index.ts
308
+ /**
309
+ * prog represents the main program logic.
310
+ */
311
+ function prog(opts, proc) {
312
+ const { _: tasks, ...options } = opts;
313
+ const customTaskNames = options.names != null ? options.names.split(",").map((n) => n.trim()) : [];
314
+ return new Promise((resolve, reject) => {
315
+ let results = [];
316
+ let queue = [];
317
+ let promises = [];
318
+ let error = null;
319
+ let aborted = false;
320
+ if (tasks.length === 0) return done();
321
+ for (let i = 0; i < tasks.length; i++) {
322
+ results.push({
323
+ name: tasks[i],
324
+ code: void 0
325
+ });
326
+ queue.push({
327
+ name: tasks[i],
328
+ index: i
329
+ });
330
+ }
331
+ function done() {
332
+ if (error == null) return resolve(results);
333
+ return reject(error);
334
+ }
335
+ function abort() {
336
+ if (aborted) return;
337
+ aborted = true;
338
+ if (promises.length === 0) return done();
339
+ for (const p of promises) p.abort();
340
+ return Promise.all(promises).then(done, reject);
341
+ }
342
+ function next() {
343
+ if (aborted) return;
344
+ if (queue.length === 0) {
345
+ if (promises.length === 0) return done();
346
+ return;
347
+ }
348
+ const task = queue.shift();
349
+ if (task == null) return;
350
+ const originalOutputStream = proc.stdout;
351
+ const optionsClone = {
352
+ stdout: proc.stdout,
353
+ stderr: proc.stderr,
354
+ stdin: proc.stdin,
355
+ customName: customTaskNames[task.index]
356
+ };
357
+ const writer = new MemoryWritable();
358
+ if (options["aggregate-output"]) optionsClone.stdout = writer;
359
+ const promise = runTask(task.name, optionsClone);
360
+ promises.push(promise);
361
+ promise.then((result) => {
362
+ removeFromArr(promises, promise);
363
+ if (aborted) return;
364
+ if (options["aggregate-output"]) originalOutputStream.write(writer.toString());
365
+ if (result.code === null && result.signal !== null) result.code = 128 + getSignalNumber(result.signal);
366
+ results[task.index].code = result.code;
367
+ if (result.code) {
368
+ error = new InParallelError(result, results);
369
+ if (!options["continue-on-error"]) return abort();
370
+ }
371
+ next();
372
+ }, (err) => {
373
+ removeFromArr(promises, promise);
374
+ if (!options["continue-on-error"]) {
375
+ error = err;
376
+ return abort();
377
+ }
378
+ next();
379
+ });
380
+ }
381
+ let end = tasks.length;
382
+ if (typeof options["max-parallel"] === "number" && options["max-parallel"] > 0) end = Math.min(tasks.length, options["max-parallel"]);
383
+ for (let i = 0; i < end; ++i) next();
384
+ });
385
+ }
386
+ /**
387
+ * runTask executes a single task as a child process.
388
+ */
389
+ function runTask(name, opts) {
390
+ let proc = null;
391
+ const task = new Promise((resolve, reject) => {
392
+ const stdin = opts.stdin;
393
+ const stdout = wrapStreamWithLabel(opts.stdout, opts.customName || name);
394
+ const stderr = wrapStreamWithLabel(opts.stderr, opts.customName || name);
395
+ const stdinKind = getStreamKind(stdin, process.stdin);
396
+ const stdoutKind = getStreamKind(stdout, process.stdout);
397
+ const stderrKind = getStreamKind(stderr, process.stderr);
398
+ const [spawnName, ...spawnArgs] = name.split(" ");
399
+ proc = spawn(spawnName, spawnArgs, { stdio: [
400
+ stdinKind,
401
+ stdoutKind,
402
+ stderrKind
403
+ ] });
404
+ if (proc == null) return reject("Failed to spawn process");
405
+ if (stdinKind === "pipe") stdin.pipe(proc.stdin);
406
+ if (stdoutKind === "pipe") proc.stdout.pipe(stdout, { end: false });
407
+ if (stderrKind === "pipe") proc.stderr.pipe(stderr, { end: false });
408
+ proc.on("error", (err) => {
409
+ proc = null;
410
+ return reject(err);
411
+ });
412
+ proc.on("close", (code, signal) => {
413
+ proc = null;
414
+ return resolve({
415
+ name,
416
+ code,
417
+ signal
418
+ });
419
+ });
420
+ });
421
+ task.abort = () => {
422
+ if (proc == null) return;
423
+ proc.kill();
424
+ proc = null;
425
+ };
426
+ return task;
427
+ }
428
+ //#endregion
429
+ //#region src/bin.ts
430
+ async function run(argv) {
431
+ const packageJson = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)("../package.json");
432
+ process.stdout.setMaxListeners(0);
433
+ process.stderr.setMaxListeners(0);
434
+ process.stdin.setMaxListeners(0);
435
+ (0, sade.default)("in-parallel", true).version(packageJson.version).describe(packageJson.description).option(`-n, --names`, `List of custom names to be used in prefix template.`).example(`-n "first,second" "ping google.com" "ping 172.0.0.1"`).option(`-c, --continue-on-error`, `Set the flag to continue executing other/subsequent tasks even if a task threw an error. 'in-parallel' itself will exit with non-zero code if one or more tasks threw error(s).`).option(`--max-parallel`, `Set the maximum number of parallelism. Default is unlimited.`, 0).option(`--aggregate-output`, `Avoid interleaving output by delaying printing of each command's output until it has finished.`, false).action((opts) => prog(opts, process)).parse(argv);
436
+ }
437
+ run(process.argv);
438
+ //#endregion