@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/src/dirs.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Spec: 0001-system FR-008
|
|
2
|
+
/**
|
|
3
|
+
* Where a program keeps its files on each system, by the conventions the system and the tools we depend on already have, never by one of ours (commons 0031-install-locations): the XDG Base Directory
|
|
4
|
+
* Specification on Linux and macOS (as `git` and `gh` do on both), and Windows' known folders on Windows (as `gh` does), with the `XDG_*` variables honored on every system where they are set. Every function takes the
|
|
5
|
+
* environment and the system as values, so that a test on one system proves the paths of another; nothing here reads the host.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* Config is `$XDG_CONFIG_HOME/<app>` (else `~/.config/<app>`) and `%APPDATA%\<app>`; data is `$XDG_DATA_HOME/<app>` (else `~/.local/share/<app>`) and `%LOCALAPPDATA%\<app>`; state, which is what a program
|
|
9
|
+
* remembers between runs and a person would not want to back up, is `$XDG_STATE_HOME/<app>` (else `~/.local/state/<app>`) and `%LOCALAPPDATA%\<app>\state`; cache is `$XDG_CACHE_HOME/<app>` (else `~/.cache/<app>`)
|
|
10
|
+
* and `%LOCALAPPDATA%\<app>\cache`; the runtime folder (locks and sockets) is `$XDG_RUNTIME_DIR/<app>` where the variable is set and there is none otherwise, and the caller uses its state folder; user programs go in
|
|
11
|
+
* `~/.local/bin`, which the XDG specification names for them, and Windows has no such folder (WinGet links the programs it installs into its own, which is already on the path, and a runtime's global install has its
|
|
12
|
+
* own). A value of an `XDG_*` variable that is not an absolute path is ignored, as the specification says.
|
|
13
|
+
*
|
|
14
|
+
* @limits
|
|
15
|
+
* It makes no folder and reads none. Where no home folder can be found and no variable names the folder, the folder is `undefined`, never a guess.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { dirsOf } from "./dirs.ts";
|
|
20
|
+
* const env = (n: string): string | undefined => ({ HOME: "/home/a" })[n];
|
|
21
|
+
* dirsOf("ergonex", env, "linux").config; // "/home/a/.config/ergonex"
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* @module
|
|
25
|
+
*/
|
|
26
|
+
import { posix, win32 } from "./path.ts";
|
|
27
|
+
|
|
28
|
+
/** An operating system, by the names `proc.build.os` gives. */
|
|
29
|
+
export type Os = "linux" | "darwin" | "windows";
|
|
30
|
+
|
|
31
|
+
/** A variable's value, or `undefined`. */
|
|
32
|
+
export type Env = (name: string) => string | undefined;
|
|
33
|
+
|
|
34
|
+
/** The folders a program keeps its files in; each is undefined where it cannot be found. */
|
|
35
|
+
export type Dirs = {
|
|
36
|
+
readonly config: string | undefined;
|
|
37
|
+
readonly data: string | undefined;
|
|
38
|
+
readonly state: string | undefined;
|
|
39
|
+
readonly cache: string | undefined;
|
|
40
|
+
/** For locks and sockets: undefined where `XDG_RUNTIME_DIR` is not set, and the caller uses `state`. */
|
|
41
|
+
readonly runtime: string | undefined;
|
|
42
|
+
/** Where a program a person installs is put: `~/.local/bin`; undefined on Windows. */
|
|
43
|
+
readonly bin: string | undefined;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const rulesOf = (os: Os): typeof posix => (os === "windows" ? win32 : posix);
|
|
47
|
+
|
|
48
|
+
/** The home folder: `HOME`, and on Windows `USERPROFILE` first. */
|
|
49
|
+
export function homeOf(env: Env, os: Os): string | undefined {
|
|
50
|
+
const h = os === "windows" ? (env("USERPROFILE") ?? env("HOME")) : env("HOME");
|
|
51
|
+
return h === undefined || h === "" ? undefined : h;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** An XDG variable's value where it is set to an absolute path, as the specification says to read it. */
|
|
55
|
+
function xdg(env: Env, name: string, os: Os): string | undefined {
|
|
56
|
+
const v = env(name);
|
|
57
|
+
return v !== undefined && v !== "" && (rulesOf(os).isAbsolute(v) || (os === "windows" && posix.isAbsolute(v))) ? v : undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The folders of the program `app` on the system `os`, from the variables `env` gives. */
|
|
61
|
+
export function dirsOf(app: string, env: Env, os: Os): Dirs {
|
|
62
|
+
const r = rulesOf(os);
|
|
63
|
+
const home = homeOf(env, os);
|
|
64
|
+
const under = (base: string | undefined, ...rest: readonly string[]): string | undefined =>
|
|
65
|
+
base === undefined ? undefined : r.join(base, ...rest);
|
|
66
|
+
const fromHome = (...parts: readonly string[]): string | undefined => (home === undefined ? undefined : r.join(home, ...parts));
|
|
67
|
+
if (os === "windows") {
|
|
68
|
+
const local = env("LOCALAPPDATA") ?? fromHome("AppData", "Local");
|
|
69
|
+
const roaming = env("APPDATA") ?? fromHome("AppData", "Roaming");
|
|
70
|
+
return {
|
|
71
|
+
config: under(xdg(env, "XDG_CONFIG_HOME", os) ?? roaming, app),
|
|
72
|
+
data: under(xdg(env, "XDG_DATA_HOME", os) ?? local, app),
|
|
73
|
+
state: xdg(env, "XDG_STATE_HOME", os) === undefined ? under(local, app, "state") : under(xdg(env, "XDG_STATE_HOME", os), app),
|
|
74
|
+
cache: xdg(env, "XDG_CACHE_HOME", os) === undefined ? under(local, app, "cache") : under(xdg(env, "XDG_CACHE_HOME", os), app),
|
|
75
|
+
runtime: under(xdg(env, "XDG_RUNTIME_DIR", os), app),
|
|
76
|
+
bin: undefined,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
config: under(xdg(env, "XDG_CONFIG_HOME", os) ?? fromHome(".config"), app),
|
|
81
|
+
data: under(xdg(env, "XDG_DATA_HOME", os) ?? fromHome(".local", "share"), app),
|
|
82
|
+
state: under(xdg(env, "XDG_STATE_HOME", os) ?? fromHome(".local", "state"), app),
|
|
83
|
+
cache: under(xdg(env, "XDG_CACHE_HOME", os) ?? fromHome(".cache"), app),
|
|
84
|
+
runtime: under(xdg(env, "XDG_RUNTIME_DIR", os), app),
|
|
85
|
+
bin: fromHome(".local", "bin"),
|
|
86
|
+
};
|
|
87
|
+
}
|
package/src/discover.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Spec: 0001-system FR-012
|
|
2
|
+
/**
|
|
3
|
+
* Programs found by the prefix of their name on a search path, as Git finds `git-<word>` (commons 0005-typescript-runtime FR-071): each
|
|
4
|
+
* folder of the path in order, the first program of a name winning; a directory, a file that may not be run and a program shadowed by an
|
|
5
|
+
* earlier one of the same name each kept with why it was not taken. On Windows a program is a file whose extension `PATHEXT` lists,
|
|
6
|
+
* compared without regard to case, and its name is given without that extension.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* The search path, the extensions and the platform can be given rather than read from this process, so that Windows' rules are proven on
|
|
10
|
+
* any system; the separator between folders is that platform's (`path.win32` or `path.posix`), and a folder and a name are joined by the
|
|
11
|
+
* running system's rules, since the files are this system's.
|
|
12
|
+
* A folder of the path that cannot be read is passed over, as a shell passes it over.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* import { discoverPrograms } from "./discover.ts";
|
|
17
|
+
* const { found } = await discoverPrograms("git-");
|
|
18
|
+
* found.map((p) => p.name); // ["lfs", ...]: the words `git` would take as commands
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* @module
|
|
22
|
+
*/
|
|
23
|
+
import { readdir, stat } from "node:fs/promises";
|
|
24
|
+
import { join, posix, win32 } from "node:path";
|
|
25
|
+
import process from "node:process";
|
|
26
|
+
import { absurd } from "@intellectual-frontiers/core";
|
|
27
|
+
|
|
28
|
+
/** The rules a search follows: Windows' (`;`, `\`, PATHEXT) or POSIX's (`:`, `/`, the mode's execute bits). */
|
|
29
|
+
export type SearchPlatform = "windows" | "posix";
|
|
30
|
+
|
|
31
|
+
/** What a search is given; each is read from this process where it is not. */
|
|
32
|
+
export type DiscoverOptions = {
|
|
33
|
+
/** The search path, `PATH` by default. */
|
|
34
|
+
readonly path?: string;
|
|
35
|
+
/** The extensions of programs on Windows, `PATHEXT` by default, `.EXE;.CMD;.BAT;.COM` where that is not set. */
|
|
36
|
+
readonly pathext?: string;
|
|
37
|
+
/** The platform whose rules apply, this one's by default. */
|
|
38
|
+
readonly platform?: SearchPlatform;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** A program found: its name after the prefix (on Windows without its extension) and its file. */
|
|
42
|
+
export type FoundProgram = { readonly name: string; readonly file: string };
|
|
43
|
+
|
|
44
|
+
/** Why a file whose name begins with the prefix was not taken. */
|
|
45
|
+
export type SkipReason =
|
|
46
|
+
{ readonly kind: "directory" } | { readonly kind: "not-executable" } | { readonly kind: "shadowed"; readonly by: string };
|
|
47
|
+
|
|
48
|
+
/** A file passed over, and why. */
|
|
49
|
+
export type SkippedProgram = { readonly file: string; readonly why: SkipReason };
|
|
50
|
+
|
|
51
|
+
/** What a search found, in the order of the path and then of the names in each folder. */
|
|
52
|
+
export type Discovered = { readonly found: readonly FoundProgram[]; readonly skipped: readonly SkippedProgram[] };
|
|
53
|
+
|
|
54
|
+
/** The platform this process runs on, as the search names it. */
|
|
55
|
+
export function searchPlatform(): SearchPlatform {
|
|
56
|
+
return process.platform === "win32" ? "windows" : "posix";
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The extensions of PATHEXT, upper case, in their order. */
|
|
60
|
+
export function pathExtensions(pathext: string | undefined): readonly string[] {
|
|
61
|
+
return (pathext ?? ".EXE;.CMD;.BAT;.COM")
|
|
62
|
+
.split(";")
|
|
63
|
+
.map((e) => e.trim().toUpperCase())
|
|
64
|
+
.filter((e) => e !== "");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A reason as words, for a `--verbose` line. */
|
|
68
|
+
export function skipReasonText(why: SkipReason): string {
|
|
69
|
+
switch (why.kind) {
|
|
70
|
+
case "directory":
|
|
71
|
+
return "a directory";
|
|
72
|
+
case "not-executable":
|
|
73
|
+
return "not a program this account may run";
|
|
74
|
+
case "shadowed":
|
|
75
|
+
return `shadowed by ${why.by}`;
|
|
76
|
+
default:
|
|
77
|
+
return absurd(why);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Every program on the search path whose name begins with `prefix`, and every file of that name passed over. */
|
|
82
|
+
export async function discoverPrograms(prefix: string, options: DiscoverOptions = {}): Promise<Discovered> {
|
|
83
|
+
const platform = options.platform ?? searchPlatform();
|
|
84
|
+
const rules = platform === "windows" ? win32 : posix;
|
|
85
|
+
const search = options.path ?? process.env["PATH"] ?? "";
|
|
86
|
+
const exts = pathExtensions(options.pathext ?? process.env["PATHEXT"]);
|
|
87
|
+
const found: FoundProgram[] = [];
|
|
88
|
+
const skipped: SkippedProgram[] = [];
|
|
89
|
+
const byName = new Map<string, string>();
|
|
90
|
+
const folders = search.split(rules.delimiter).filter((d) => d !== "");
|
|
91
|
+
for (const folder of folders) {
|
|
92
|
+
let names: string[];
|
|
93
|
+
try {
|
|
94
|
+
names = (await readdir(folder)).filter((n) => n.startsWith(prefix));
|
|
95
|
+
// In a folder, Windows takes a name's extensions in PATHEXT's order; elsewhere names are taken in byte order.
|
|
96
|
+
const rank = (n: string): number => {
|
|
97
|
+
const i = exts.indexOf(rules.extname(n).toUpperCase());
|
|
98
|
+
return i < 0 ? exts.length : i;
|
|
99
|
+
};
|
|
100
|
+
const stem = (n: string): string => (platform === "windows" ? n.slice(0, n.length - rules.extname(n).length).toLowerCase() : n);
|
|
101
|
+
names.sort((a, b) => (stem(a) < stem(b) ? -1 : stem(a) > stem(b) ? 1 : platform === "windows" ? rank(a) - rank(b) : 0));
|
|
102
|
+
} catch {
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
for (const entry of names) {
|
|
106
|
+
const file = join(folder, entry);
|
|
107
|
+
let isDir: boolean;
|
|
108
|
+
let mode: number;
|
|
109
|
+
try {
|
|
110
|
+
const s = await stat(file);
|
|
111
|
+
isDir = s.isDirectory();
|
|
112
|
+
mode = s.mode;
|
|
113
|
+
} catch {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (isDir) {
|
|
117
|
+
skipped.push({ file, why: { kind: "directory" } });
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
let name = entry.slice(prefix.length);
|
|
121
|
+
if (platform === "windows") {
|
|
122
|
+
const ext = rules.extname(entry).toUpperCase();
|
|
123
|
+
if (ext === "" || !exts.includes(ext)) {
|
|
124
|
+
skipped.push({ file, why: { kind: "not-executable" } });
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
name = name.slice(0, name.length - ext.length);
|
|
128
|
+
} else if ((mode & 0o111) === 0) {
|
|
129
|
+
skipped.push({ file, why: { kind: "not-executable" } });
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (name === "") continue;
|
|
133
|
+
const key = platform === "windows" ? name.toLowerCase() : name;
|
|
134
|
+
const first = byName.get(key);
|
|
135
|
+
if (first !== undefined) {
|
|
136
|
+
skipped.push({ file, why: { kind: "shadowed", by: first } });
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
byName.set(key, file);
|
|
140
|
+
found.push({ name, file });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return { found, skipped };
|
|
144
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// Spec: 0001-system FR-001
|
|
2
|
+
/**
|
|
3
|
+
* The errors the runtime throws (commons 0005-typescript-runtime FR-019): one class for each kind a caller acts on, by plain names (`errors.NotFound`), each made from the `code` Node gives
|
|
4
|
+
* (`ENOENT`, `EEXIST`, `EACCES`, ...), keeping that code, the path or address where there is one, and the original error as its `cause`.
|
|
5
|
+
* The runtime throws; `Result` belongs to the layers above, which turn these into their own errors.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { errors } from "./errors.ts";
|
|
10
|
+
* import { readTextFile } from "./fs.ts";
|
|
11
|
+
* try {
|
|
12
|
+
* await readTextFile("/no/such/file");
|
|
13
|
+
* } catch (e) {
|
|
14
|
+
* if (e instanceof errors.NotFound) console.log("not there");
|
|
15
|
+
* else throw e;
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** What every error of the runtime carries: the code the host gave and, for a file or an address, where. */
|
|
23
|
+
export class RuntimeError extends Error {
|
|
24
|
+
/** The host's error code (`ENOENT`, `EACCES`, ...), or `""` where it gave none. */
|
|
25
|
+
readonly code: string;
|
|
26
|
+
/** The path, or the address, the failed call was about, where there was one. */
|
|
27
|
+
readonly path: string | undefined;
|
|
28
|
+
/** Make one from a message, the host's code, the path and the error it stands for. */
|
|
29
|
+
constructor(message: string, code: string, path?: string, cause?: unknown) {
|
|
30
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
31
|
+
this.code = code;
|
|
32
|
+
this.path = path;
|
|
33
|
+
}
|
|
34
|
+
/** The class's own name, so a stack trace says `NotFound` and not `Error`. */
|
|
35
|
+
override get name(): string {
|
|
36
|
+
return this.constructor.name;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Nothing is at the path, or no such program (`ENOENT`). */
|
|
41
|
+
export class NotFound extends RuntimeError {}
|
|
42
|
+
/** Something is already at the path (`EEXIST`). */
|
|
43
|
+
export class AlreadyExists extends RuntimeError {}
|
|
44
|
+
/** The account may not do this (`EACCES`, `EPERM`). */
|
|
45
|
+
export class PermissionDenied extends RuntimeError {}
|
|
46
|
+
/** A folder was given where a file was needed (`EISDIR`). */
|
|
47
|
+
export class IsADirectory extends RuntimeError {}
|
|
48
|
+
/** A file was given where a folder was needed (`ENOTDIR`). */
|
|
49
|
+
export class NotADirectory extends RuntimeError {}
|
|
50
|
+
/** A folder that must be empty is not (`ENOTEMPTY`). */
|
|
51
|
+
export class DirectoryNotEmpty extends RuntimeError {}
|
|
52
|
+
/** Links point at each other with no end (`ELOOP`). */
|
|
53
|
+
export class FilesystemLoop extends RuntimeError {}
|
|
54
|
+
/** The resource is in use (`EBUSY`, `ETXTBSY`). */
|
|
55
|
+
export class Busy extends RuntimeError {}
|
|
56
|
+
/** The address is already in use (`EADDRINUSE`). */
|
|
57
|
+
export class AddrInUse extends RuntimeError {}
|
|
58
|
+
/** The address cannot be used on this computer (`EADDRNOTAVAIL`). */
|
|
59
|
+
export class AddrNotAvailable extends RuntimeError {}
|
|
60
|
+
/** Nothing listens at the address (`ECONNREFUSED`). */
|
|
61
|
+
export class ConnectionRefused extends RuntimeError {}
|
|
62
|
+
/** The other end reset the connection (`ECONNRESET`). */
|
|
63
|
+
export class ConnectionReset extends RuntimeError {}
|
|
64
|
+
/** The connection was aborted (`ECONNABORTED`). */
|
|
65
|
+
export class ConnectionAborted extends RuntimeError {}
|
|
66
|
+
/** The other end of a pipe was closed (`EPIPE`). */
|
|
67
|
+
export class BrokenPipe extends RuntimeError {}
|
|
68
|
+
/** The call took too long (`ETIMEDOUT`). */
|
|
69
|
+
export class TimedOut extends RuntimeError {}
|
|
70
|
+
/** A signal interrupted the call (`EINTR`). */
|
|
71
|
+
export class Interrupted extends RuntimeError {}
|
|
72
|
+
/** The network cannot be reached (`ENETUNREACH`, `EHOSTUNREACH`). */
|
|
73
|
+
export class NetworkUnreachable extends RuntimeError {}
|
|
74
|
+
/** The data was not what was expected (`EINVAL` on data, a bad archive or encoding). */
|
|
75
|
+
export class InvalidData extends RuntimeError {}
|
|
76
|
+
/** This platform or file system cannot do it (`ENOSYS`, `ENOTSUP`, `EXDEV` across devices). */
|
|
77
|
+
export class NotSupported extends RuntimeError {}
|
|
78
|
+
/** The end of the data came before what was needed. */
|
|
79
|
+
export class UnexpectedEof extends RuntimeError {}
|
|
80
|
+
|
|
81
|
+
/** The error classes by name. */
|
|
82
|
+
export const errors = {
|
|
83
|
+
RuntimeError,
|
|
84
|
+
NotFound,
|
|
85
|
+
AlreadyExists,
|
|
86
|
+
PermissionDenied,
|
|
87
|
+
IsADirectory,
|
|
88
|
+
NotADirectory,
|
|
89
|
+
DirectoryNotEmpty,
|
|
90
|
+
FilesystemLoop,
|
|
91
|
+
Busy,
|
|
92
|
+
AddrInUse,
|
|
93
|
+
AddrNotAvailable,
|
|
94
|
+
ConnectionRefused,
|
|
95
|
+
ConnectionReset,
|
|
96
|
+
ConnectionAborted,
|
|
97
|
+
BrokenPipe,
|
|
98
|
+
TimedOut,
|
|
99
|
+
Interrupted,
|
|
100
|
+
NetworkUnreachable,
|
|
101
|
+
InvalidData,
|
|
102
|
+
NotSupported,
|
|
103
|
+
UnexpectedEof,
|
|
104
|
+
} as const;
|
|
105
|
+
|
|
106
|
+
type ErrorClass = new (message: string, code: string, path?: string, cause?: unknown) => RuntimeError;
|
|
107
|
+
|
|
108
|
+
/** The class each Node error code becomes. */
|
|
109
|
+
export const BY_CODE: Readonly<Record<string, ErrorClass>> = {
|
|
110
|
+
ENOENT: NotFound,
|
|
111
|
+
EEXIST: AlreadyExists,
|
|
112
|
+
EACCES: PermissionDenied,
|
|
113
|
+
EPERM: PermissionDenied,
|
|
114
|
+
EISDIR: IsADirectory,
|
|
115
|
+
ENOTDIR: NotADirectory,
|
|
116
|
+
ENOTEMPTY: DirectoryNotEmpty,
|
|
117
|
+
ELOOP: FilesystemLoop,
|
|
118
|
+
EBUSY: Busy,
|
|
119
|
+
ETXTBSY: Busy,
|
|
120
|
+
EADDRINUSE: AddrInUse,
|
|
121
|
+
EADDRNOTAVAIL: AddrNotAvailable,
|
|
122
|
+
ECONNREFUSED: ConnectionRefused,
|
|
123
|
+
ECONNRESET: ConnectionReset,
|
|
124
|
+
ECONNABORTED: ConnectionAborted,
|
|
125
|
+
EPIPE: BrokenPipe,
|
|
126
|
+
ETIMEDOUT: TimedOut,
|
|
127
|
+
EINTR: Interrupted,
|
|
128
|
+
ENETUNREACH: NetworkUnreachable,
|
|
129
|
+
EHOSTUNREACH: NetworkUnreachable,
|
|
130
|
+
EINVAL: InvalidData,
|
|
131
|
+
ENOSYS: NotSupported,
|
|
132
|
+
ENOTSUP: NotSupported,
|
|
133
|
+
EXDEV: NotSupported,
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const field = (e: object, key: string): string | undefined => {
|
|
137
|
+
const v: unknown = Reflect.get(e, key);
|
|
138
|
+
return typeof v === "string" ? v : undefined;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** What was thrown or rejected, as an `Error`: an `Error` as it is, anything else wrapped, kept as the cause. */
|
|
142
|
+
export function toError(thrown: unknown, message = "a value that is not an Error was thrown"): Error {
|
|
143
|
+
return thrown instanceof Error ? thrown : new Error(message, { cause: thrown });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* What the host threw, as an error of the runtime: an error that carries a known `code` becomes its class (keeping the message, code,
|
|
148
|
+
* path and the original as its cause); any other `Error`, a runtime error among them, is returned as it is; anything else is wrapped by
|
|
149
|
+
* {@link toError}.
|
|
150
|
+
*/
|
|
151
|
+
export function mapError(thrown: unknown, path?: string): Error {
|
|
152
|
+
if (thrown instanceof RuntimeError || typeof thrown !== "object" || thrown === null) return toError(thrown);
|
|
153
|
+
const code = field(thrown, "code");
|
|
154
|
+
const Class = code === undefined ? undefined : BY_CODE[code];
|
|
155
|
+
if (code === undefined || Class === undefined) return toError(thrown);
|
|
156
|
+
const message = thrown instanceof Error ? thrown.message : (field(thrown, "message") ?? code);
|
|
157
|
+
return new Class(message, code, field(thrown, "path") ?? field(thrown, "address") ?? path, thrown);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Run a call on the host and throw what it throws as an error of the runtime. */
|
|
161
|
+
export async function hostCall<T>(path: string | undefined, f: () => Promise<T>): Promise<T> {
|
|
162
|
+
try {
|
|
163
|
+
return await f();
|
|
164
|
+
} catch (e) {
|
|
165
|
+
throw mapError(e, path);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The same, for a call that does not wait. */
|
|
170
|
+
export function hostCallSync<T>(path: string | undefined, f: () => T): T {
|
|
171
|
+
try {
|
|
172
|
+
return f();
|
|
173
|
+
} catch (e) {
|
|
174
|
+
throw mapError(e, path);
|
|
175
|
+
}
|
|
176
|
+
}
|