@intellectual-frontiers/system 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +8 -2
- package/dist/compile.d.ts +94 -0
- package/dist/compile.js +130 -0
- package/dist/dirs.d.ts +19 -0
- package/dist/dirs.js +64 -0
- package/dist/discover.d.ts +43 -0
- package/dist/discover.js +118 -0
- package/dist/errors.d.ts +130 -0
- package/dist/errors.js +189 -0
- package/dist/fs.d.ts +263 -0
- package/dist/fs.js +826 -0
- package/dist/git.d.ts +63 -0
- package/dist/git.js +144 -0
- package/dist/job-plan.d.ts +207 -0
- package/dist/job-plan.js +563 -0
- package/dist/lock.d.ts +41 -0
- package/dist/lock.js +130 -0
- package/dist/mod.d.ts +28 -0
- package/dist/mod.js +29 -0
- package/dist/path.d.ts +47 -0
- package/dist/path.js +55 -0
- package/dist/proc.d.ts +257 -0
- package/dist/proc.js +589 -0
- package/dist/schedule.d.ts +99 -0
- package/dist/schedule.js +131 -0
- package/dist/stdio.d.ts +31 -0
- package/dist/stdio.js +170 -0
- package/dist/tty.d.ts +34 -0
- package/dist/tty.js +71 -0
- package/dist/watch.d.ts +42 -0
- package/dist/watch.js +342 -0
- package/package.json +113 -4
- package/src/compile.ts +178 -0
- package/src/dirs.ts +87 -0
- package/src/discover.ts +144 -0
- package/src/errors.ts +176 -0
- package/src/fs.ts +967 -0
- package/src/git.ts +163 -0
- package/src/job-plan.ts +660 -0
- package/src/lock.ts +149 -0
- package/src/mod.ts +29 -0
- package/src/path.ts +59 -0
- package/src/proc.ts +786 -0
- package/src/schedule.ts +173 -0
- package/src/stdio.ts +204 -0
- package/src/tty.ts +94 -0
- package/src/watch.ts +338 -0
package/dist/schedule.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Spec: 0001-system FR-017
|
|
2
|
+
/**
|
|
3
|
+
* The operating system's own scheduled job, installed and removed (commons 0005-typescript-runtime FR-046): `installJob` plans the job
|
|
4
|
+
* with the kernel's `planJob`, writes its files under the home folder (making their folders, with their modes) and runs the commands that
|
|
5
|
+
* load it; `removeJob` runs the commands that unload it, removes its files and runs what follows (systemd's `daemon-reload`). Each file and
|
|
6
|
+
* each command is reported as an outcome, and the first failure that matters is a typed error carrying the outcomes until then; a
|
|
7
|
+
* command marked `mayFail` (nothing to unload) never stops the rest. The scheduler, the home folder, the user's id and the program that
|
|
8
|
+
* runs a command are parameters, defaulting to this computer's (`build.os`, `homeDir()`, `uid()`, `run`), so a test plans and installs any
|
|
9
|
+
* scheduler's job in a temporary folder with a fake runner, and no real systemctl, launchctl or schtasks runs. Taken from Stolos's
|
|
10
|
+
* `src/archon/export/schedule.ts` (`installJob`, `uninstallJob`), which took its file and command functions as dependencies and threw;
|
|
11
|
+
* here the files go through `./fs.ts`, the commands through `./proc.ts` or a given runner, and errors are values.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { jobName, schedule } from "./job-plan.ts";
|
|
16
|
+
* import { installJob } from "./schedule.ts";
|
|
17
|
+
* const name = jobName("backup");
|
|
18
|
+
* const when = schedule({ kind: "weekly", day: "sun", hour: 3, minute: 30 });
|
|
19
|
+
* if (name.kind === "ok" && when.kind === "ok") {
|
|
20
|
+
* const r = await installJob({ name: name.value, owner: { domain: "org.example", folder: "Example" }, argv: ["/usr/bin/backup"], workdir: "/srv", when: when.value });
|
|
21
|
+
* if (r.kind === "err") console.error(r.error.kind);
|
|
22
|
+
* }
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* @module
|
|
26
|
+
*/
|
|
27
|
+
import { absurd, err, ok } from "@intellectual-frontiers/core";
|
|
28
|
+
import { planJob } from "./job-plan.js";
|
|
29
|
+
import { NotFound } from "./errors.js";
|
|
30
|
+
import { mkdir, remove, writeTextFile } from "./fs.js";
|
|
31
|
+
import { dirname, join } from "./path.js";
|
|
32
|
+
import { build, homeDir, run, uid } from "./proc.js";
|
|
33
|
+
/** The default runner: the program run with `run`, never through a shell; one that cannot be started gives status 127 and the reason. */
|
|
34
|
+
export const runStep = async (argv) => {
|
|
35
|
+
try {
|
|
36
|
+
const r = await run(argv);
|
|
37
|
+
return { code: r.code, output: r.stderr.trim() === "" ? r.stdout.trim() : r.stderr.trim() };
|
|
38
|
+
}
|
|
39
|
+
catch (e) {
|
|
40
|
+
return { code: 127, output: e instanceof Error ? e.message : String(e) };
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
/** A job error as one line. */
|
|
44
|
+
export function formatJobError(e) {
|
|
45
|
+
switch (e.kind) {
|
|
46
|
+
case "unsupported":
|
|
47
|
+
return `this OS (${e.os}) has no scheduler this module knows: Linux, macOS or Windows`;
|
|
48
|
+
case "plan":
|
|
49
|
+
return `${e.error.field}: ${e.error.message}`;
|
|
50
|
+
case "write":
|
|
51
|
+
return `could not write ${e.path}: ${e.message}`;
|
|
52
|
+
case "remove":
|
|
53
|
+
return `could not remove ${e.path}: ${e.message}`;
|
|
54
|
+
case "step":
|
|
55
|
+
return `${e.argv.join(" ")} failed (${e.code})${e.output === "" ? "" : `: ${e.output}`}`;
|
|
56
|
+
default:
|
|
57
|
+
return absurd(e);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const SCHEDULERS = ["linux", "darwin", "windows"];
|
|
61
|
+
const isScheduler = (os) => SCHEDULERS.includes(os);
|
|
62
|
+
function prepare(job, options) {
|
|
63
|
+
const os = options.os ?? build.os;
|
|
64
|
+
if (!isScheduler(os))
|
|
65
|
+
return err({ kind: "unsupported", os, outcomes: [] });
|
|
66
|
+
const home = options.home ?? homeDir();
|
|
67
|
+
const id = options.uid ?? uid();
|
|
68
|
+
const plan = planJob(job, { os, home, ...(id === undefined ? {} : { uid: id }) });
|
|
69
|
+
if (plan.kind === "err")
|
|
70
|
+
return err({ kind: "plan", error: plan.error, outcomes: [] });
|
|
71
|
+
return ok({ plan: plan.value, home, runner: options.runner ?? runStep });
|
|
72
|
+
}
|
|
73
|
+
const message = (e) => (e instanceof Error ? e.message : String(e));
|
|
74
|
+
/** The commands run in turn, each an outcome; the first that fails and may not is the error. */
|
|
75
|
+
async function runSteps(steps, runner, outcomes) {
|
|
76
|
+
for (const s of steps) {
|
|
77
|
+
const r = await runner(s.argv);
|
|
78
|
+
outcomes.push({ kind: "ran", argv: s.argv, code: r.code, output: r.output, mayFail: s.mayFail });
|
|
79
|
+
if (r.code !== 0 && !s.mayFail)
|
|
80
|
+
return err({ kind: "step", argv: s.argv, code: r.code, output: r.output, outcomes: [...outcomes] });
|
|
81
|
+
}
|
|
82
|
+
return ok(undefined);
|
|
83
|
+
}
|
|
84
|
+
/** A planned file's absolute path on this computer: the home folder and the parts of its relative path. */
|
|
85
|
+
const hostPath = (home, rel) => join(home, ...rel.split("/"));
|
|
86
|
+
/** A job scheduled: planned, its files written (their folders made, their modes set), then the commands that load it run. */
|
|
87
|
+
export async function installJob(job, options = {}) {
|
|
88
|
+
const p = prepare(job, options);
|
|
89
|
+
if (p.kind === "err")
|
|
90
|
+
return p;
|
|
91
|
+
const { plan, home, runner } = p.value;
|
|
92
|
+
const outcomes = [];
|
|
93
|
+
for (const f of plan.files) {
|
|
94
|
+
const path = hostPath(home, f.path);
|
|
95
|
+
try {
|
|
96
|
+
await mkdir(dirname(path), { recursive: true });
|
|
97
|
+
await writeTextFile(path, f.content, f.mode === undefined ? {} : { mode: f.mode });
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
return err({ kind: "write", path, message: message(e), outcomes });
|
|
101
|
+
}
|
|
102
|
+
outcomes.push({ kind: "wrote", path });
|
|
103
|
+
}
|
|
104
|
+
const steps = await runSteps(plan.install, runner, outcomes);
|
|
105
|
+
return steps.kind === "err" ? steps : ok({ plan, outcomes });
|
|
106
|
+
}
|
|
107
|
+
/** A job unscheduled: the commands that unload it run, its files removed (one already gone is no error), then what follows run. */
|
|
108
|
+
export async function removeJob(job, options = {}) {
|
|
109
|
+
const p = prepare(job, options);
|
|
110
|
+
if (p.kind === "err")
|
|
111
|
+
return p;
|
|
112
|
+
const { plan, home, runner } = p.value;
|
|
113
|
+
const outcomes = [];
|
|
114
|
+
const before = await runSteps(plan.remove, runner, outcomes);
|
|
115
|
+
if (before.kind === "err")
|
|
116
|
+
return before;
|
|
117
|
+
for (const f of plan.files) {
|
|
118
|
+
const path = hostPath(home, f.path);
|
|
119
|
+
try {
|
|
120
|
+
await remove(path);
|
|
121
|
+
outcomes.push({ kind: "removed", path, existed: true });
|
|
122
|
+
}
|
|
123
|
+
catch (e) {
|
|
124
|
+
if (!(e instanceof NotFound))
|
|
125
|
+
return err({ kind: "remove", path, message: message(e), outcomes });
|
|
126
|
+
outcomes.push({ kind: "removed", path, existed: false });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const after = await runSteps(plan.afterRemove, runner, outcomes);
|
|
130
|
+
return after.kind === "err" ? after : ok({ plan, outcomes });
|
|
131
|
+
}
|
package/dist/stdio.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Standard input. */
|
|
2
|
+
export type Stdin = {
|
|
3
|
+
/** The whole of standard input as a web stream; made once, on first use. Bytes `read` took but did not give come first. */
|
|
4
|
+
readonly readable: ReadableStream<Uint8Array>;
|
|
5
|
+
/** Reads into `buffer` and gives how many bytes it read, or null at the end of the input. */
|
|
6
|
+
read(buffer: Uint8Array): Promise<number | null>;
|
|
7
|
+
/** The rest of standard input, to its end, as bytes. */
|
|
8
|
+
bytes(): Promise<Uint8Array>;
|
|
9
|
+
/** The rest of standard input, to its end, as text (UTF-8). */
|
|
10
|
+
text(): Promise<string>;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Standard input over a source stream, made on first use: `read` keeps what did not fit in its buffer for the next `read`, and `readable`
|
|
14
|
+
* gives that first. Exported so a test can drive it with a stream of its own.
|
|
15
|
+
*/
|
|
16
|
+
export declare function stdinOf(source: () => ReadableStream<Uint8Array>): Stdin;
|
|
17
|
+
/** This process's standard input. */
|
|
18
|
+
export declare const stdin: Stdin;
|
|
19
|
+
/** Standard output or standard error, for output a program reads. */
|
|
20
|
+
export type Stdout = {
|
|
21
|
+
/** Writes bytes, or text as UTF-8, and gives how many bytes were written, once they are handed to the system. */
|
|
22
|
+
write(data: Uint8Array | string): Promise<number>;
|
|
23
|
+
/** Writes bytes, or text as UTF-8, all of them, before it returns; gives how many bytes were written. */
|
|
24
|
+
writeSync(data: Uint8Array | string): number;
|
|
25
|
+
/** A web stream onto it; closing the stream leaves the file descriptor open, as other writers may still use it. */
|
|
26
|
+
readonly writable: WritableStream<Uint8Array>;
|
|
27
|
+
};
|
|
28
|
+
/** This process's standard output, for what a program reads. */
|
|
29
|
+
export declare const stdout: Stdout;
|
|
30
|
+
/** This process's standard error, for what a program reads (a person's messages go through `runtime/console.ts`). */
|
|
31
|
+
export declare const stderr: Stdout;
|
package/dist/stdio.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// Spec: 0001-system FR-019
|
|
2
|
+
/**
|
|
3
|
+
* Standard input, output and error for what a program reads (commons 0005-typescript-runtime FR-054): JSON, a protocol on standard input
|
|
4
|
+
* and output, bytes passed along a pipe. The names are plain (`read`, `readable`, `write`,
|
|
5
|
+
* `writeSync`, `writable`). This file and `runtime/console.ts` are the only files of the runtime that write to
|
|
6
|
+
* standard output or standard error: what a person reads goes through the console (0006-signals FR-026), what a program reads through here.
|
|
7
|
+
*
|
|
8
|
+
* Writes: `write` waits until the bytes are handed to the system and gives their length; `writeSync` writes them all to the file
|
|
9
|
+
* descriptor before it returns (retrying while a non-blocking pipe is full), so it suits the last words of a process that is about to
|
|
10
|
+
* exit. Both write the whole of what they are given. A closed pipe (`EPIPE`) rejects `write` and throws from `writeSync` as the runtime's
|
|
11
|
+
* error; it never ends the process as an uncaught error.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { stdin, stdout } from "./stdio.ts";
|
|
16
|
+
* const request = JSON.parse(await stdin.text());
|
|
17
|
+
* await stdout.write(`${JSON.stringify({ ok: true, request })}\n`);
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* @module
|
|
21
|
+
*/
|
|
22
|
+
import { writeSync as fdWriteSync } from "node:fs";
|
|
23
|
+
import process from "node:process";
|
|
24
|
+
import { Readable } from "node:stream";
|
|
25
|
+
import { mapError } from "./errors.js";
|
|
26
|
+
/** Byte arrays joined into one. */
|
|
27
|
+
function joined(parts) {
|
|
28
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
29
|
+
let at = 0;
|
|
30
|
+
for (const p of parts) {
|
|
31
|
+
out.set(p, at);
|
|
32
|
+
at += p.length;
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Standard input over a source stream, made on first use: `read` keeps what did not fit in its buffer for the next `read`, and `readable`
|
|
38
|
+
* gives that first. Exported so a test can drive it with a stream of its own.
|
|
39
|
+
*/
|
|
40
|
+
export function stdinOf(source) {
|
|
41
|
+
let base;
|
|
42
|
+
let whole;
|
|
43
|
+
let left = new Uint8Array(0);
|
|
44
|
+
const opened = () => (base ??= source());
|
|
45
|
+
const read = async (buffer) => {
|
|
46
|
+
if (buffer.length === 0)
|
|
47
|
+
return 0;
|
|
48
|
+
if (left.length === 0) {
|
|
49
|
+
const reader = opened().getReader();
|
|
50
|
+
try {
|
|
51
|
+
const r = await reader.read();
|
|
52
|
+
if (r.done)
|
|
53
|
+
return null;
|
|
54
|
+
left = r.value;
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
reader.releaseLock();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const n = Math.min(buffer.length, left.length);
|
|
61
|
+
buffer.set(left.subarray(0, n));
|
|
62
|
+
left = left.subarray(n);
|
|
63
|
+
return n;
|
|
64
|
+
};
|
|
65
|
+
const readable = () => {
|
|
66
|
+
if (whole !== undefined)
|
|
67
|
+
return whole;
|
|
68
|
+
const reader = opened().getReader();
|
|
69
|
+
whole = new ReadableStream({
|
|
70
|
+
pull: async (controller) => {
|
|
71
|
+
if (left.length > 0) {
|
|
72
|
+
controller.enqueue(left);
|
|
73
|
+
left = new Uint8Array(0);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const r = await reader.read();
|
|
77
|
+
if (r.done)
|
|
78
|
+
controller.close();
|
|
79
|
+
else
|
|
80
|
+
controller.enqueue(r.value);
|
|
81
|
+
},
|
|
82
|
+
cancel: async (reason) => reader.cancel(reason),
|
|
83
|
+
});
|
|
84
|
+
return whole;
|
|
85
|
+
};
|
|
86
|
+
const bytes = async () => {
|
|
87
|
+
const parts = [];
|
|
88
|
+
const reader = readable().getReader();
|
|
89
|
+
try {
|
|
90
|
+
for (;;) {
|
|
91
|
+
const r = await reader.read();
|
|
92
|
+
if (r.done)
|
|
93
|
+
break;
|
|
94
|
+
parts.push(r.value);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
reader.releaseLock();
|
|
99
|
+
}
|
|
100
|
+
return joined(parts);
|
|
101
|
+
};
|
|
102
|
+
return {
|
|
103
|
+
get readable() {
|
|
104
|
+
return readable();
|
|
105
|
+
},
|
|
106
|
+
read,
|
|
107
|
+
bytes,
|
|
108
|
+
text: async () => new TextDecoder().decode(await bytes()),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/** This process's standard input. */
|
|
112
|
+
export const stdin = stdinOf(
|
|
113
|
+
// Node's stream becomes a web stream; its type is `node:stream/web`'s, which is the same class as the global one.
|
|
114
|
+
() => Readable.toWeb(process.stdin));
|
|
115
|
+
const encoder = new TextEncoder();
|
|
116
|
+
const bytesOf = (data) => (typeof data === "string" ? encoder.encode(data) : data);
|
|
117
|
+
/** Waits about a millisecond without giving way to the event loop, while a non-blocking pipe is full. */
|
|
118
|
+
function pause() {
|
|
119
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1);
|
|
120
|
+
}
|
|
121
|
+
function stdoutOf(sink) {
|
|
122
|
+
let guarded = false;
|
|
123
|
+
const stream = () => {
|
|
124
|
+
const s = sink.stream();
|
|
125
|
+
if (!guarded) {
|
|
126
|
+
guarded = true;
|
|
127
|
+
// A closed pipe is reported to the writer that wrote, not as an uncaught error that ends the process.
|
|
128
|
+
s.on("error", () => undefined);
|
|
129
|
+
}
|
|
130
|
+
return s;
|
|
131
|
+
};
|
|
132
|
+
const write = (data) => {
|
|
133
|
+
const bytes = bytesOf(data);
|
|
134
|
+
return new Promise((resolve, reject) => {
|
|
135
|
+
stream().write(bytes, (e) => (e === undefined || e === null ? resolve(bytes.length) : reject(mapError(e))));
|
|
136
|
+
});
|
|
137
|
+
};
|
|
138
|
+
const writeSync = (data) => {
|
|
139
|
+
const bytes = bytesOf(data);
|
|
140
|
+
let at = 0;
|
|
141
|
+
while (at < bytes.length) {
|
|
142
|
+
try {
|
|
143
|
+
at += fdWriteSync(sink.fd, bytes, at, bytes.length - at);
|
|
144
|
+
}
|
|
145
|
+
catch (e) {
|
|
146
|
+
if (typeof e === "object" && e !== null && "code" in e && e.code === "EAGAIN")
|
|
147
|
+
pause();
|
|
148
|
+
else
|
|
149
|
+
throw mapError(e);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return bytes.length;
|
|
153
|
+
};
|
|
154
|
+
let writable;
|
|
155
|
+
return {
|
|
156
|
+
write,
|
|
157
|
+
writeSync,
|
|
158
|
+
get writable() {
|
|
159
|
+
return (writable ??= new WritableStream({
|
|
160
|
+
write: async (chunk) => {
|
|
161
|
+
await write(chunk);
|
|
162
|
+
},
|
|
163
|
+
}));
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/** This process's standard output, for what a program reads. */
|
|
168
|
+
export const stdout = stdoutOf({ fd: 1, stream: () => process.stdout });
|
|
169
|
+
/** This process's standard error, for what a program reads (a person's messages go through `runtime/console.ts`). */
|
|
170
|
+
export const stderr = stdoutOf({ fd: 2, stream: () => process.stderr });
|
package/dist/tty.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type Os } from "./proc.js";
|
|
2
|
+
/** A standard stream of the process. */
|
|
3
|
+
export type StdStream = "stdin" | "stdout" | "stderr";
|
|
4
|
+
/** Whether a standard stream is a terminal. */
|
|
5
|
+
export declare function isTerminal(stream: StdStream): boolean;
|
|
6
|
+
/** The size of the terminal on standard output or, failing that, standard error; undefined where neither is one. */
|
|
7
|
+
export declare function consoleSize(): {
|
|
8
|
+
readonly columns: number;
|
|
9
|
+
readonly rows: number;
|
|
10
|
+
} | undefined;
|
|
11
|
+
/** Raw mode on standard input turned on (every key as it is pressed, no echo) or off; `NotSupported` where standard input is not a terminal. */
|
|
12
|
+
export declare function setRaw(on: boolean): void;
|
|
13
|
+
/** How output should look. */
|
|
14
|
+
export type Look = {
|
|
15
|
+
readonly tty: boolean;
|
|
16
|
+
readonly colour: boolean;
|
|
17
|
+
readonly emoji: boolean;
|
|
18
|
+
readonly columns: number;
|
|
19
|
+
};
|
|
20
|
+
/** What the choice of a look depends on. */
|
|
21
|
+
export type LookFacts = {
|
|
22
|
+
/** The environment's variables. */
|
|
23
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
24
|
+
/** Whether the stream written to is a terminal. */
|
|
25
|
+
readonly terminal: boolean;
|
|
26
|
+
/** The operating system. */
|
|
27
|
+
readonly os: Os;
|
|
28
|
+
/** The terminal's width, where known. */
|
|
29
|
+
readonly columns?: number;
|
|
30
|
+
};
|
|
31
|
+
/** The look the facts call for: see the module's rules. The width is the terminal's where it is at least 40, else 80. */
|
|
32
|
+
export declare function lookOf(facts: LookFacts): Look;
|
|
33
|
+
/** The look for writing to a standard stream (standard error by default) of this process. */
|
|
34
|
+
export declare function currentLook(stream?: StdStream): Look;
|
package/dist/tty.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Spec: 0001-system FR-018
|
|
2
|
+
/**
|
|
3
|
+
* The terminal (commons 0005-typescript-runtime FR-023): whether a stream is one, its size, raw mode, and the choice of colour and emoji the
|
|
4
|
+
* three `ui` modules each made (Stolos's `core/ui.ts`, the setup's `ui.ts`, erga's console). The choice is a pure function of the
|
|
5
|
+
* environment and the facts about the terminal (`lookOf`), so it is tested without one; `currentLook` reads them from the host.
|
|
6
|
+
*
|
|
7
|
+
* Rules: colour only where `NO_COLOR` is unset or empty, and only at a terminal unless `FORCE_COLOR` is set; a terminal whose `TERM` is
|
|
8
|
+
* `dumb` counts as none; emoji where the locale is UTF-8, or on Windows in a terminal that says so (`WT_SESSION`, `TERM_PROGRAM`,
|
|
9
|
+
* `ConEmuANSI=ON`), or on a Mac with `TERM_PROGRAM`.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { lookOf } from "./tty.ts";
|
|
14
|
+
* lookOf({ env: { LANG: "en_US.UTF-8" }, terminal: true, os: "linux", columns: 120 });
|
|
15
|
+
* // { tty: true, colour: true, emoji: true, columns: 120 }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
import { isatty } from "node:tty";
|
|
21
|
+
import process from "node:process";
|
|
22
|
+
import { NotSupported } from "./errors.js";
|
|
23
|
+
import { build, env } from "./proc.js";
|
|
24
|
+
const FD = { stdin: 0, stdout: 1, stderr: 2 };
|
|
25
|
+
/** Whether a standard stream is a terminal. */
|
|
26
|
+
export function isTerminal(stream) {
|
|
27
|
+
try {
|
|
28
|
+
return isatty(FD[stream]);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** The size of the terminal on standard output or, failing that, standard error; undefined where neither is one. */
|
|
35
|
+
export function consoleSize() {
|
|
36
|
+
for (const s of [process.stdout, process.stderr]) {
|
|
37
|
+
if (s.isTTY === true && typeof s.columns === "number" && typeof s.rows === "number")
|
|
38
|
+
return { columns: s.columns, rows: s.rows };
|
|
39
|
+
}
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
/** Raw mode on standard input turned on (every key as it is pressed, no echo) or off; `NotSupported` where standard input is not a terminal. */
|
|
43
|
+
export function setRaw(on) {
|
|
44
|
+
const stdin = process.stdin;
|
|
45
|
+
if (stdin.isTTY !== true || typeof stdin.setRawMode !== "function")
|
|
46
|
+
throw new NotSupported("standard input is not a terminal", "ENOTTY");
|
|
47
|
+
stdin.setRawMode(on);
|
|
48
|
+
}
|
|
49
|
+
const set = (v) => v !== undefined && v !== "";
|
|
50
|
+
/** The look the facts call for: see the module's rules. The width is the terminal's where it is at least 40, else 80. */
|
|
51
|
+
export function lookOf(facts) {
|
|
52
|
+
const e = facts.env;
|
|
53
|
+
const tty = facts.terminal && (e["TERM"] ?? "") !== "dumb";
|
|
54
|
+
const colour = !set(e["NO_COLOR"]) && (tty || set(e["FORCE_COLOR"]));
|
|
55
|
+
const utf8 = /utf-?8/i.test(e["LC_ALL"] || e["LC_CTYPE"] || e["LANG"] || "");
|
|
56
|
+
const emoji = utf8 ||
|
|
57
|
+
(facts.os === "windows" && (set(e["WT_SESSION"]) || set(e["TERM_PROGRAM"]) || e["ConEmuANSI"] === "ON")) ||
|
|
58
|
+
(facts.os === "darwin" && set(e["TERM_PROGRAM"]));
|
|
59
|
+
const columns = tty && facts.columns !== undefined && facts.columns >= 40 ? facts.columns : 80;
|
|
60
|
+
return { tty, colour, emoji, columns };
|
|
61
|
+
}
|
|
62
|
+
/** The look for writing to a standard stream (standard error by default) of this process. */
|
|
63
|
+
export function currentLook(stream = "stderr") {
|
|
64
|
+
const size = consoleSize();
|
|
65
|
+
return lookOf({
|
|
66
|
+
env: env.toObject(),
|
|
67
|
+
terminal: isTerminal(stream),
|
|
68
|
+
os: build.os,
|
|
69
|
+
...(size === undefined ? {} : { columns: size.columns }),
|
|
70
|
+
});
|
|
71
|
+
}
|
package/dist/watch.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** What happened to a path: made, changed, removed, or moved from the first path to the second. */
|
|
2
|
+
export type FsEventKind = "create" | "modify" | "remove" | "rename";
|
|
3
|
+
/** One event, after the join: a path made, changed or removed, or one moved (`paths` is then `[from, to]`). Paths are absolute. */
|
|
4
|
+
export type FsEvent = {
|
|
5
|
+
readonly kind: "create" | "modify" | "remove";
|
|
6
|
+
readonly paths: readonly [string];
|
|
7
|
+
} | {
|
|
8
|
+
readonly kind: "rename";
|
|
9
|
+
readonly paths: readonly [from: string, to: string];
|
|
10
|
+
};
|
|
11
|
+
/** How to watch: folders with everything under them (`recursive`), the window over which reports are joined (`debounceMs`, 100), and a signal that stops it. */
|
|
12
|
+
export type WatchOptions = {
|
|
13
|
+
readonly recursive?: boolean;
|
|
14
|
+
readonly debounceMs?: number;
|
|
15
|
+
readonly signal?: AbortSignal;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* A running watch: an async iterable of {@link FsEvent}s, ended by `close`, the signal, `using`, `await using` or leaving a `for await`
|
|
19
|
+
* loop. A watch that fails (other than by its folder being removed) throws from the loop as an error of `./errors.ts`. Made by {@link watchFs}.
|
|
20
|
+
*/
|
|
21
|
+
export declare class FsWatcher implements AsyncIterableIterator<FsEvent>, Disposable, AsyncDisposable {
|
|
22
|
+
#private;
|
|
23
|
+
/** A watch of the paths; use {@link watchFs}. */
|
|
24
|
+
constructor(paths: readonly string[], options: WatchOptions);
|
|
25
|
+
/** The next event, waiting for one; done once the watch is closed. */
|
|
26
|
+
next(): Promise<IteratorResult<FsEvent>>;
|
|
27
|
+
/** The watch closed, as leaving a `for await` loop does. */
|
|
28
|
+
return(): Promise<IteratorResult<FsEvent>>;
|
|
29
|
+
/** The watch itself, to iterate. */
|
|
30
|
+
[Symbol.asyncIterator](): FsWatcher;
|
|
31
|
+
/** The watch stopped: no more events; a loop over it ends. Closing it again does nothing. */
|
|
32
|
+
close(): void;
|
|
33
|
+
/** Closed at the end of a `using` block. */
|
|
34
|
+
[Symbol.dispose](): void;
|
|
35
|
+
/** Closed at the end of an `await using` block. */
|
|
36
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Files and folders watched, (see the module's documentation): each path a file, or a folder whose entries
|
|
40
|
+
* (with `recursive`, everything under it) are watched. `NotFound` where a path is not there.
|
|
41
|
+
*/
|
|
42
|
+
export declare function watchFs(paths: string | URL | readonly (string | URL)[], options?: WatchOptions): FsWatcher;
|