@muhkoo/cli 0.15.0-alpha.0 → 0.15.0-alpha.11
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 +1 -0
- package/bin/muhkoo.js +4 -1
- package/package.json +11 -4
- package/src/commands/kv.js +65 -0
- package/src/commands/vfs.js +118 -14
- package/src/index.js +2 -0
- package/src/lib/drain.js +60 -0
- package/src/lib/mount.js +608 -135
- package/src/lib/syncPlan.js +73 -3
- package/src/lib/vfs.js +29 -14
package/README.md
CHANGED
|
@@ -109,6 +109,7 @@ Backend provision · tables · agents · functions
|
|
|
109
109
|
Files vfs cd|pwd|ls|stat|tree|cat|put|get|mkdir|rm|cp|mv|find|history|restore
|
|
110
110
|
vfs import|mount|ignore · vfs sweep|use-app|app
|
|
111
111
|
vcs status|commit|log|show|diff|branch|switch|checkout|merge|restore · vcs merge --abort
|
|
112
|
+
kv ls [prefix]
|
|
112
113
|
Hosting deploy · promote · hosting status|rollback|rm-release|unpublish · domains
|
|
113
114
|
Tools logs · eject
|
|
114
115
|
```
|
package/bin/muhkoo.js
CHANGED
|
@@ -9,10 +9,12 @@
|
|
|
9
9
|
|
|
10
10
|
import { run } from "../src/index.js";
|
|
11
11
|
import { printable } from "../src/lib/ui.js";
|
|
12
|
+
import { drained } from "../src/lib/drain.js";
|
|
12
13
|
|
|
13
14
|
run(process.argv.slice(2))
|
|
15
|
+
.then(() => drained())
|
|
14
16
|
.then(() => process.exit(0))
|
|
15
|
-
.catch((e) => {
|
|
17
|
+
.catch(async (e) => {
|
|
16
18
|
// Escaped like everything else printed: an error's message can carry a
|
|
17
19
|
// name or a server's words. The message is one line; the stack's frames
|
|
18
20
|
// are Node's own lines.
|
|
@@ -20,5 +22,6 @@ run(process.argv.slice(2))
|
|
|
20
22
|
const stack = e instanceof Error && typeof e.stack === "string" ? e.stack : "";
|
|
21
23
|
const frames = stack.startsWith(head) ? stack.slice(head.length).split("\n").filter(Boolean) : [];
|
|
22
24
|
console.error(["", `✗ ${printable(head)}`, ...frames.map(printable), ""].join("\n"));
|
|
25
|
+
await drained();
|
|
23
26
|
process.exit(1);
|
|
24
27
|
});
|
package/package.json
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@muhkoo/cli",
|
|
3
|
-
"version": "0.15.0-alpha.
|
|
3
|
+
"version": "0.15.0-alpha.11",
|
|
4
4
|
"description": "Command-line interface for the Muhkoo platform — provision backends, deploy apps, and manage agents, functions, databases, and domains.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "muhkoo",
|
|
8
|
-
"repository":
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/muhkoo/cli.git"
|
|
11
|
+
},
|
|
9
12
|
"homepage": "https://docs.muhkoo.dev",
|
|
10
13
|
"bugs": "https://github.com/muhkoo/cli/issues",
|
|
11
14
|
"keywords": [
|
|
@@ -40,11 +43,15 @@
|
|
|
40
43
|
"release": "npm publish --tag alpha && npm dist-tag add @muhkoo/cli@$npm_package_version latest"
|
|
41
44
|
},
|
|
42
45
|
"dependencies": {
|
|
43
|
-
"@muhkoo/connect": "0.15.0-alpha.
|
|
46
|
+
"@muhkoo/connect": "0.15.0-alpha.11",
|
|
44
47
|
"snarkjs": "^0.7.0"
|
|
45
48
|
},
|
|
46
49
|
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",
|
|
47
50
|
"devDependencies": {
|
|
48
|
-
"vitest": "^
|
|
51
|
+
"vitest": "^4.1.11"
|
|
52
|
+
},
|
|
53
|
+
"overrides": {
|
|
54
|
+
"jsonpath": "^1.3.0",
|
|
55
|
+
"underscore": "^1.13.8"
|
|
49
56
|
}
|
|
50
57
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `muhkoo kv` — the keys in your personal key/value store.
|
|
3
|
+
*
|
|
4
|
+
* The store is shared by every app you sign into: `client.kv` collections
|
|
5
|
+
* (`todos/…`), your filesystem (`vfs/…`), version control (`vcs/…`) and the
|
|
6
|
+
* SDK's own keys. This lists NAMES only and never reads a value, so it needs a
|
|
7
|
+
* session but not an unlocked vault. (`client.kv` encrypts values by default,
|
|
8
|
+
* but an app may store one with `encrypt: false`, so nothing here says every
|
|
9
|
+
* value is encrypted.)
|
|
10
|
+
* Keys come from whoever wrote them, so they are printed escaped (`info`,
|
|
11
|
+
* `json`), never raw.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { openSession } from "../lib/vfs.js";
|
|
15
|
+
import { json, info, die } from "../lib/ui.js";
|
|
16
|
+
|
|
17
|
+
export const help = `muhkoo kv — the keys in your personal key/value store
|
|
18
|
+
|
|
19
|
+
Usage:
|
|
20
|
+
muhkoo kv ls [<prefix>] [--json] keys that start with <prefix> (default: all)
|
|
21
|
+
|
|
22
|
+
Options:
|
|
23
|
+
--app <slug> the app the read is made as (default: the one from
|
|
24
|
+
\`muhkoo vfs use-app\`); reads work without one
|
|
25
|
+
--json a JSON array of keys
|
|
26
|
+
|
|
27
|
+
Keys only: this command never reads a value. Put --json after "ls".
|
|
28
|
+
|
|
29
|
+
Examples:
|
|
30
|
+
muhkoo kv ls todos/ one client.kv collection
|
|
31
|
+
muhkoo kv ls vfs/d/ your filesystem's directory records`;
|
|
32
|
+
|
|
33
|
+
export default async function kv(args) {
|
|
34
|
+
// The shared parser gives `--json` the word after it, so `kv ls --json todos/`
|
|
35
|
+
// arrives as `json: "todos/"`. That word goes back on the END of the
|
|
36
|
+
// positionals, as `vfs`'s `booleanFlags` does. So `--json` works anywhere
|
|
37
|
+
// after the subcommand, but not before it: `kv --json ls todos/` reads as
|
|
38
|
+
// `kv todos/ ls` and is refused as an unknown subcommand.
|
|
39
|
+
const words = [...args._.slice(1), ...(typeof args.json === "string" ? [args.json] : [])];
|
|
40
|
+
const sub = words[0] ?? "ls";
|
|
41
|
+
|
|
42
|
+
switch (sub) {
|
|
43
|
+
case "ls": {
|
|
44
|
+
if (words.length > 2) return die("Usage: muhkoo kv ls [<prefix>] [--json]");
|
|
45
|
+
const prefix = words[1] ?? "";
|
|
46
|
+
const client = await openSession(args);
|
|
47
|
+
const keys = await client.kv.keys(prefix);
|
|
48
|
+
if (args.json) return json(keys);
|
|
49
|
+
// A human hint, not data: stderr, so `kv ls todos/ | while read k; do …`
|
|
50
|
+
// never reads this sentence as a key. Stdout stays empty and the exit
|
|
51
|
+
// code stays 0.
|
|
52
|
+
if (!keys.length)
|
|
53
|
+
return void process.stderr.write(
|
|
54
|
+
`${prefix ? `No keys start with "${prefix}".` : "Your personal store is empty."}\n`,
|
|
55
|
+
);
|
|
56
|
+
// One key a line, a thousand lines a call: a large space can hold more
|
|
57
|
+
// keys than one function call takes arguments.
|
|
58
|
+
for (let i = 0; i < keys.length; i += 1000) info(...keys.slice(i, i + 1000));
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
default:
|
|
63
|
+
return die(`Unknown subcommand "kv ${sub}". See \`muhkoo kv --help\`.`);
|
|
64
|
+
}
|
|
65
|
+
}
|
package/src/commands/vfs.js
CHANGED
|
@@ -7,10 +7,10 @@
|
|
|
7
7
|
* keep byte-exact — and the first one to drift would corrupt real files.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import { readFile, stat, writeFile } from "node:fs/promises";
|
|
11
|
-
import { basename, resolve } from "node:path";
|
|
10
|
+
import { lstat, readFile, stat, writeFile } from "node:fs/promises";
|
|
11
|
+
import { basename, dirname, isAbsolute, resolve } from "node:path";
|
|
12
12
|
import { openClient, explainWriteFailure } from "../lib/vfs.js";
|
|
13
|
-
import { mount as mountDir, importOnce, previewMount, heldBack, acceptIgnores, diskIgnoreTexts, assertMountable } from "../lib/mount.js";
|
|
13
|
+
import { mount as mountDir, importOnce, previewMount, heldBack, acceptIgnores, diskIgnoreTexts, assertMountable, mountTarget } from "../lib/mount.js";
|
|
14
14
|
import { draftIgnores, ignoreFileProblem } from "../lib/ignore.js";
|
|
15
15
|
import { loadConfig, saveConfig } from "../lib/config.js";
|
|
16
16
|
import { table, json, ok, info, warn, die, writeText, prompt } from "../lib/ui.js";
|
|
@@ -48,9 +48,16 @@ Usage:
|
|
|
48
48
|
.git/info/exclude on disk (it replaces them
|
|
49
49
|
all); --write saves it (--force to replace),
|
|
50
50
|
unless it is past an ignore file's limits
|
|
51
|
-
muhkoo vfs import <dir…> [--path <p>] upload whole projects, once.
|
|
52
|
-
|
|
53
|
-
|
|
51
|
+
muhkoo vfs import <dir…> [--path <p>] upload whole projects, once. Each <dir> is a
|
|
52
|
+
folder on this computer; --path is the Muhkoo
|
|
53
|
+
path it goes to (default /apps/<its name>).
|
|
54
|
+
Upload only: never writes or deletes
|
|
55
|
+
anything here
|
|
56
|
+
muhkoo vfs mount <dir> [--path <p>] sync a subtree to disk and keep it live.
|
|
57
|
+
<dir> is the folder on this computer, made
|
|
58
|
+
if missing (but not the folders above it);
|
|
59
|
+
--path is the Muhkoo path to sync, e.g.
|
|
60
|
+
/apps/my-app (default /)
|
|
54
61
|
(dot-files skipped; deletes need --allow-delete;
|
|
55
62
|
Ctrl-C or closing the terminal stops it after
|
|
56
63
|
the current file; a second Ctrl-C quits now)
|
|
@@ -124,6 +131,15 @@ export default async function vfs(args) {
|
|
|
124
131
|
// limiter long before it finishes.
|
|
125
132
|
if (sub === "ignore") return ignoreCommand(args);
|
|
126
133
|
|
|
134
|
+
// Where to sync is checked before the session opens, which can ask for a
|
|
135
|
+
// password: `vfs mount /apps/x --path ./`, the two swapped, unlocked the
|
|
136
|
+
// vault and then set about creating /apps at the top of this disk.
|
|
137
|
+
const mounting = sub === "mount" ? await mountArgs(args) : null;
|
|
138
|
+
if ((sub === "import" || sub === "push") && args.path !== undefined) {
|
|
139
|
+
const problem = pathProblem(args.path);
|
|
140
|
+
if (problem) return die(pathError("import into", problem));
|
|
141
|
+
}
|
|
142
|
+
|
|
127
143
|
// A dry run writes nothing, and that includes ~/.muhkoo: unlocking would
|
|
128
144
|
// otherwise pair a machine not paired yet (a device enrolled on the server,
|
|
129
145
|
// its key saved) and reset a stale working directory. It unlocks for this
|
|
@@ -299,7 +315,7 @@ export default async function vfs(args) {
|
|
|
299
315
|
const opts = { hidden: flags.hidden, allowDelete: flags["allow-delete"], dryRun: flags["dry-run"] };
|
|
300
316
|
let failed = 0;
|
|
301
317
|
for (const d of dirs) {
|
|
302
|
-
const root = normalizeRoot(args.path ?? `/apps/${await slugFor(resolve(d))}`);
|
|
318
|
+
const root = normalizeRoot(args.path ?? `/apps/${await slugFor(resolve(d))}`); // --path checked above
|
|
303
319
|
try {
|
|
304
320
|
await importOnce({ client, dir: resolve(d), root, opts });
|
|
305
321
|
} catch (err) {
|
|
@@ -316,12 +332,9 @@ export default async function vfs(args) {
|
|
|
316
332
|
}
|
|
317
333
|
|
|
318
334
|
case "mount": {
|
|
319
|
-
const {
|
|
320
|
-
if (positionals.length > 1) return die(`vfs mount takes one directory, not ${positionals.length}: ${positionals.join(", ")}`);
|
|
321
|
-
const dir = required(positionals[0], "mount <dir> [--path /apps]");
|
|
322
|
-
const root = normalizeRoot(args.path ?? "/");
|
|
335
|
+
const { dir, root, flags } = mounting;
|
|
323
336
|
if (flags["dry-run"]) {
|
|
324
|
-
return previewMount({ client, dir
|
|
337
|
+
return previewMount({ client, dir, root, opts: { allowDelete: flags["allow-delete"], hidden: flags.hidden } });
|
|
325
338
|
}
|
|
326
339
|
// Ctrl-C is the way out of a foreground watcher, so it has to be a clean
|
|
327
340
|
// stop that flushes state — not a process kill mid-write.
|
|
@@ -333,7 +346,7 @@ export default async function vfs(args) {
|
|
|
333
346
|
for (const sig of signals) process.on(sig, stop);
|
|
334
347
|
try {
|
|
335
348
|
await mountDir({
|
|
336
|
-
client, dir
|
|
349
|
+
client, dir, root, signal: controller.signal,
|
|
337
350
|
opts: { allowDelete: flags["allow-delete"], hidden: flags.hidden },
|
|
338
351
|
});
|
|
339
352
|
} finally {
|
|
@@ -515,6 +528,94 @@ async function slugFor(dir) {
|
|
|
515
528
|
return declared || basename(dir);
|
|
516
529
|
}
|
|
517
530
|
|
|
531
|
+
/**
|
|
532
|
+
* `vfs mount`'s folder, Muhkoo path and switches, checked before the session
|
|
533
|
+
* opens: `{ dir, root, flags }`, with `dir` resolved.
|
|
534
|
+
*
|
|
535
|
+
* `<dir>` is the folder on this computer and `--path` the Muhkoo path. When
|
|
536
|
+
* `<dir>` reads as a Muhkoo path instead — absolute, starting at a folder this
|
|
537
|
+
* computer does not have (`/apps`), and --path either not given or refused —
|
|
538
|
+
* the error carries the command with the two swapped. A folder mistyped here,
|
|
539
|
+
* such as /Users/me/GitHub/tpyo/app, starts at one it has, and gets no
|
|
540
|
+
* suggestion. It is only ever suggested, never run: a mount writes into the
|
|
541
|
+
* folder, and with --allow-delete deletes there, so a guess is not acted on.
|
|
542
|
+
*/
|
|
543
|
+
async function mountArgs(args) {
|
|
544
|
+
const { flags, positionals } = booleanFlags(args, ["hidden", "allow-delete", "dry-run", "no-pair"]);
|
|
545
|
+
if (positionals.length > 1) return die(`vfs mount takes one directory, not ${positionals.length}: ${positionals.join(", ")}`);
|
|
546
|
+
const dir = required(positionals[0], "mount <dir> [--path /apps]");
|
|
547
|
+
const given = args.path !== undefined;
|
|
548
|
+
const problem = given ? pathProblem(args.path) : null;
|
|
549
|
+
const suggestion = async () => {
|
|
550
|
+
if ((given && !problem) || !isAbsolute(dir)) return [];
|
|
551
|
+
const here = await lstat(topFolder(dir)).then(() => true, (err) => err.code !== "ENOENT");
|
|
552
|
+
if (here) return [];
|
|
553
|
+
return [` Did you mean: ${swappedCommand(args, flags, problem?.local ? args.path : null, dir)}`];
|
|
554
|
+
};
|
|
555
|
+
if (problem) return die(pathError("mount", problem), ...(await suggestion()));
|
|
556
|
+
try {
|
|
557
|
+
await mountTarget(resolve(dir));
|
|
558
|
+
} catch (err) {
|
|
559
|
+
return die(err?.message ?? String(err), ...(await suggestion()));
|
|
560
|
+
}
|
|
561
|
+
return { dir: resolve(dir), root: normalizeRoot(args.path ?? "/"), flags };
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** The folder at the top of absolute `path`: /apps for /apps/my-app. */
|
|
565
|
+
function topFolder(path) {
|
|
566
|
+
let top = resolve(path);
|
|
567
|
+
while (dirname(top) !== dirname(dirname(top))) top = dirname(top);
|
|
568
|
+
return top;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Why `value`, given as --path, cannot be a Muhkoo path, or null when it can.
|
|
573
|
+
*
|
|
574
|
+
* --path names a place in your Muhkoo filesystem, never a folder here, so what
|
|
575
|
+
* reads as one is refused: a `.` or `..` segment, or a leading `~`. `./` used
|
|
576
|
+
* to become the Muhkoo root "/.", accepted without a word. No value at all is
|
|
577
|
+
* refused too: an empty one read as "/". A missing leading slash is still
|
|
578
|
+
* forgiven, as before: `apps/x` is /apps/x.
|
|
579
|
+
*/
|
|
580
|
+
function pathProblem(value) {
|
|
581
|
+
if (typeof value !== "string" || value === "") return { why: "It was given no value." };
|
|
582
|
+
if (value.startsWith("~") || value.split("/").some((part) => part === "." || part === "..")) {
|
|
583
|
+
return { why: `"${value}" looks like a folder on this computer.`, local: true };
|
|
584
|
+
}
|
|
585
|
+
return null;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** The one error for a refused --path. `verb`: what the Muhkoo path is for. */
|
|
589
|
+
function pathError(verb, { why }) {
|
|
590
|
+
return `--path is the Muhkoo path to ${verb}, starting with / (for example --path /apps/my-app). ${why}`;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* `muhkoo vfs mount <folder> --path <dir>`: the command given, with the folder
|
|
595
|
+
* and the Muhkoo path the other way round. `folder` is the refused --path
|
|
596
|
+
* when it read as a folder here, or a placeholder. The other options come
|
|
597
|
+
* along, so a dry run stays one; a key is never printed.
|
|
598
|
+
*/
|
|
599
|
+
function swappedCommand(args, flags, folder, dir) {
|
|
600
|
+
const words = ["muhkoo", "vfs", "mount", folder === null ? "<folder>" : shellWord(folder), "--path", shellWord(dir)];
|
|
601
|
+
for (const [name, value] of Object.entries(args)) {
|
|
602
|
+
if (name === "_" || name === "path") continue;
|
|
603
|
+
if (name in flags) {
|
|
604
|
+
if (flags[name]) words.push(`--${name}`);
|
|
605
|
+
} else if (name === "key") {
|
|
606
|
+
words.push("--key <key>");
|
|
607
|
+
} else {
|
|
608
|
+
words.push(value === true ? `--${name}` : `--${name} ${shellWord(String(value))}`);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
return words.join(" ");
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** `word` as a shell reads it back: quoted unless it is made of the plainest characters. */
|
|
615
|
+
function shellWord(word) {
|
|
616
|
+
return /^[\w@%+=:,./~-]+$/.test(word) ? word : `'${word.replace(/'/g, "'\\''")}'`;
|
|
617
|
+
}
|
|
618
|
+
|
|
518
619
|
/**
|
|
519
620
|
* `names` read as on/off switches, and the positionals from index 2 on.
|
|
520
621
|
*
|
|
@@ -631,7 +732,10 @@ async function readLocal(path) {
|
|
|
631
732
|
}
|
|
632
733
|
}
|
|
633
734
|
|
|
634
|
-
/**
|
|
735
|
+
/**
|
|
736
|
+
* A mount root is always an absolute directory path, with no trailing slash.
|
|
737
|
+
* A --path reaches here only once `pathProblem` has passed it.
|
|
738
|
+
*/
|
|
635
739
|
function normalizeRoot(path) {
|
|
636
740
|
const p = ("/" + path).replace(/\/+/g, "/").replace(/\/$/, "");
|
|
637
741
|
return p === "" ? "/" : p;
|
package/src/index.js
CHANGED
|
@@ -22,6 +22,7 @@ const COMMANDS = {
|
|
|
22
22
|
promote: () => import("./commands/promote.js"),
|
|
23
23
|
vfs: () => import("./commands/vfs.js"),
|
|
24
24
|
vcs: () => import("./commands/vcs.js"),
|
|
25
|
+
kv: () => import("./commands/kv.js"),
|
|
25
26
|
devices: () => import("./commands/devices.js"),
|
|
26
27
|
hosting: () => import("./commands/hosting.js"),
|
|
27
28
|
domains: () => import("./commands/domains.js"),
|
|
@@ -63,6 +64,7 @@ Files
|
|
|
63
64
|
vfs sweep|use-app|app reclaim records; pick the app writes are made as
|
|
64
65
|
vcs status|commit|log|show|diff|branch|switch|checkout|merge|restore
|
|
65
66
|
version control over it
|
|
67
|
+
kv ls [prefix] keys in your personal key/value store
|
|
66
68
|
|
|
67
69
|
Hosting
|
|
68
70
|
deploy deploy a built client to Muhkoo hosting (test env)
|
package/src/lib/drain.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolves once everything already written to stdout and stderr has left the
|
|
3
|
+
* process. On macOS a write to a pipe is asynchronous, so exiting straight
|
|
4
|
+
* after a large write dropped everything past the pipe's buffer (64 KiB or
|
|
5
|
+
* less): `muhkoo kv ls vfs/ | wc -l` lost keys and still exited 0. An empty
|
|
6
|
+
* write's callback runs after every write queued before it. It also runs when
|
|
7
|
+
* the reader has gone away (`| head`), and so does the `error` listener, so
|
|
8
|
+
* this never waits on a closed pipe and a closed pipe does not crash the exit.
|
|
9
|
+
*
|
|
10
|
+
* The `error` listener must not set off Node's listener-leak warning. A ZK
|
|
11
|
+
* login leaves the prover's worker threads alive, one per core, and Node pipes
|
|
12
|
+
* each one's stdout and stderr into the process's own: one `error` listener
|
|
13
|
+
* each, added without a warning because Node raises the limit around the pipe.
|
|
14
|
+
* On a 14-core Mac this listener was the 15th, past the default limit of 10,
|
|
15
|
+
* and `muhkoo login` ended with the warning printed twice. So the limit is
|
|
16
|
+
* raised as Node raises it, only while the listener is added, and only as far
|
|
17
|
+
* as it must be: by one is not enough when the count is already past it. The
|
|
18
|
+
* listener goes again once the write has gone through. After a failed write on
|
|
19
|
+
* a stream that was live before the write it stays: that stream emits its
|
|
20
|
+
* `error` only after the write's callback, and with no listener the error
|
|
21
|
+
* would go unhandled. It comes off when that `error` arrives. A stream already
|
|
22
|
+
* destroyed before the write emits no `error` for it, so there the listener
|
|
23
|
+
* goes with the callback.
|
|
24
|
+
*/
|
|
25
|
+
export const drained = (streams = [process.stdout, process.stderr]) =>
|
|
26
|
+
Promise.all(
|
|
27
|
+
streams.map(
|
|
28
|
+
(stream) =>
|
|
29
|
+
new Promise((resolve) => {
|
|
30
|
+
const onError = () => resolve();
|
|
31
|
+
const live = !stream.destroyed;
|
|
32
|
+
withRoomFor(stream, "error", () => stream.once("error", onError));
|
|
33
|
+
stream.write("", (err) => {
|
|
34
|
+
if (!err || !live) stream.removeListener("error", onError);
|
|
35
|
+
resolve();
|
|
36
|
+
});
|
|
37
|
+
}),
|
|
38
|
+
),
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Run `add`, which adds one `event` listener to `emitter`, with the limit
|
|
43
|
+
* raised just enough not to warn. The limit is put back as it was found, as
|
|
44
|
+
* Node's own pipe puts it back: a stream with no limit of its own, such as
|
|
45
|
+
* process.stdout, goes on following `EventEmitter.defaultMaxListeners` rather
|
|
46
|
+
* than being pinned at its value.
|
|
47
|
+
*/
|
|
48
|
+
function withRoomFor(emitter, event, add) {
|
|
49
|
+
const max = emitter.getMaxListeners();
|
|
50
|
+
const needed = emitter.listenerCount(event) + 1;
|
|
51
|
+
// 0 means no limit; Infinity, or a limit already high enough, needs nothing.
|
|
52
|
+
if (max === 0 || max >= needed) return add();
|
|
53
|
+
const own = emitter._maxListeners; // undefined: none of its own
|
|
54
|
+
emitter.setMaxListeners(needed);
|
|
55
|
+
try {
|
|
56
|
+
return add();
|
|
57
|
+
} finally {
|
|
58
|
+
emitter._maxListeners = own;
|
|
59
|
+
}
|
|
60
|
+
}
|