@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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Intellectual Frontiers
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @intellectual-frontiers/system
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The host system as one typed library: files, paths, the folders of a program, one run at a time, file watching, programs found by prefix, processes and their streams, Git, a program built into one binary, the operating system's scheduled jobs, and the terminal's streams; the same code on Bun and Node 26.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
bun add @intellectual-frontiers/system # or: npm install @intellectual-frontiers/system
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Sources and specifications: https://github.com/intellectual-frontiers/.github/tree/main/commons/system
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A program built into one binary with the pinned Bun (commons 0005-typescript-runtime FR-062): `bun build --compile`, for this computer or
|
|
3
|
+
* for a target given (`linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `windows-x64`), with the files it embeds, giving the
|
|
4
|
+
* binary's path and SHA-256. Bun is found as `bun` on `PATH`, or given by its path; where an expected version is given, a Bun of another
|
|
5
|
+
* version is refused, so a build is made only by the pinned one. Everything that can go wrong is a `CompileError` in a `Result`.
|
|
6
|
+
*
|
|
7
|
+
* The argument vector is made by `compileArgv`, a pure function, so what is asked of Bun can be checked without running it; a program
|
|
8
|
+
* built this way runs itself again with `proc.selfCommand()` (FR-053).
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { compile } from "./compile.js";
|
|
13
|
+
* const r = await compile({ entry: "src/main.ts", outfile: "dist/tool", target: "windows-x64" });
|
|
14
|
+
* if (r.kind === "ok") console.log(r.value.path, r.value.sha256); // dist/tool.exe, its SHA-256
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* @module
|
|
18
|
+
*/
|
|
19
|
+
import { type Result } from "@intellectual-frontiers/core";
|
|
20
|
+
import type { Sha256 } from "@intellectual-frontiers/crypto/sha256";
|
|
21
|
+
import { type Arch, type Os } from "./proc.js";
|
|
22
|
+
/** A system Bun builds a binary for. */
|
|
23
|
+
export type Target = "linux-x64" | "linux-arm64" | "darwin-x64" | "darwin-arm64" | "windows-x64";
|
|
24
|
+
/** Every target, in a fixed order. */
|
|
25
|
+
export declare const TARGETS: readonly Target[];
|
|
26
|
+
/** The target of a system, by `proc.build`'s names; undefined where Bun builds for no such system. */
|
|
27
|
+
export declare function targetOf(os: Os, arch: Arch): Target | undefined;
|
|
28
|
+
/** The target of this computer; undefined where Bun builds for no such system. */
|
|
29
|
+
export declare function hostTarget(): Target | undefined;
|
|
30
|
+
/** Whether a target's binaries are Windows programs, named with `.exe`. */
|
|
31
|
+
export declare function isWindows(target: Target): boolean;
|
|
32
|
+
/** What to build. */
|
|
33
|
+
export type CompileOptions = {
|
|
34
|
+
/** The program's entry point (a `.ts` or `.js` file). */
|
|
35
|
+
readonly entry: string;
|
|
36
|
+
/** Where the binary goes; `.exe` is added for Windows where it is not there, as Bun adds it. */
|
|
37
|
+
readonly outfile: string;
|
|
38
|
+
/** The system to build for; this computer where it is not given. */
|
|
39
|
+
readonly target?: Target;
|
|
40
|
+
/** Files embedded in the binary, beside the code its imports bring in. */
|
|
41
|
+
readonly files?: readonly string[];
|
|
42
|
+
/** Bun's path; `bun` on `PATH` where it is not given. */
|
|
43
|
+
readonly bun?: string;
|
|
44
|
+
/** The version Bun must be (the pin, such as `1.4.4`); any version where it is not given. */
|
|
45
|
+
readonly bunVersion?: string;
|
|
46
|
+
/** The folder the build runs in, against which relative paths are read; the process's working folder by default. */
|
|
47
|
+
readonly cwd?: string;
|
|
48
|
+
/** More of `bun build`'s options, put before the entry point (`--minify`, `--define=...`). */
|
|
49
|
+
readonly extraArgs?: readonly string[];
|
|
50
|
+
/** Stopping the build. */
|
|
51
|
+
readonly signal?: AbortSignal;
|
|
52
|
+
};
|
|
53
|
+
/** A binary built. */
|
|
54
|
+
export type Compiled = {
|
|
55
|
+
/** Its path, absolute. */
|
|
56
|
+
readonly path: string;
|
|
57
|
+
/** Its SHA-256. */
|
|
58
|
+
readonly sha256: Sha256;
|
|
59
|
+
/** The system it is for. */
|
|
60
|
+
readonly target: Target;
|
|
61
|
+
/** The version of Bun that built it. */
|
|
62
|
+
readonly bunVersion: string;
|
|
63
|
+
};
|
|
64
|
+
/** Why a binary was not built. */
|
|
65
|
+
export type CompileError = {
|
|
66
|
+
readonly kind: "no-bun";
|
|
67
|
+
readonly message: string;
|
|
68
|
+
} | {
|
|
69
|
+
readonly kind: "wrong-bun";
|
|
70
|
+
readonly expected: string;
|
|
71
|
+
readonly found: string;
|
|
72
|
+
} | {
|
|
73
|
+
readonly kind: "no-target";
|
|
74
|
+
readonly message: string;
|
|
75
|
+
} | {
|
|
76
|
+
readonly kind: "failed";
|
|
77
|
+
readonly code: number;
|
|
78
|
+
readonly stderr: string;
|
|
79
|
+
} | {
|
|
80
|
+
readonly kind: "no-binary";
|
|
81
|
+
readonly path: string;
|
|
82
|
+
};
|
|
83
|
+
/** A sentence for a `CompileError`. */
|
|
84
|
+
export declare function describeCompileError(e: CompileError): string;
|
|
85
|
+
/** The binary's path for a target: `outfile`, with `.exe` added for Windows where it is not there. */
|
|
86
|
+
export declare function binaryPath(outfile: string, target: Target): string;
|
|
87
|
+
/**
|
|
88
|
+
* The argument vector that builds the binary (pure): `bun build --compile [--target=bun-<target>] --outfile=<path> [extra...] <entry>
|
|
89
|
+
* [files...]`. A target is named only where one is given; without it Bun builds for the computer it runs on. The files after the entry
|
|
90
|
+
* point are embedded in the binary.
|
|
91
|
+
*/
|
|
92
|
+
export declare function compileArgv(bun: string, options: CompileOptions, outfile: string): readonly string[];
|
|
93
|
+
/** Builds a program into one binary with Bun (FR-062) and gives its path and SHA-256; a `CompileError` where it cannot. */
|
|
94
|
+
export declare function compile(options: CompileOptions): Promise<Result<Compiled, CompileError>>;
|
package/dist/compile.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Spec: 0001-system FR-013
|
|
2
|
+
/**
|
|
3
|
+
* A program built into one binary with the pinned Bun (commons 0005-typescript-runtime FR-062): `bun build --compile`, for this computer or
|
|
4
|
+
* for a target given (`linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `windows-x64`), with the files it embeds, giving the
|
|
5
|
+
* binary's path and SHA-256. Bun is found as `bun` on `PATH`, or given by its path; where an expected version is given, a Bun of another
|
|
6
|
+
* version is refused, so a build is made only by the pinned one. Everything that can go wrong is a `CompileError` in a `Result`.
|
|
7
|
+
*
|
|
8
|
+
* The argument vector is made by `compileArgv`, a pure function, so what is asked of Bun can be checked without running it; a program
|
|
9
|
+
* built this way runs itself again with `proc.selfCommand()` (FR-053).
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { compile } from "./compile.ts";
|
|
14
|
+
* const r = await compile({ entry: "src/main.ts", outfile: "dist/tool", target: "windows-x64" });
|
|
15
|
+
* if (r.kind === "ok") console.log(r.value.path, r.value.sha256); // dist/tool.exe, its SHA-256
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
import { absurd, err, ok } from "@intellectual-frontiers/core";
|
|
21
|
+
import { exists, sha256File } from "./fs.js";
|
|
22
|
+
import { resolve } from "./path.js";
|
|
23
|
+
import { build, cwd as processCwd, output, which } from "./proc.js";
|
|
24
|
+
/** Every target, in a fixed order. */
|
|
25
|
+
export const TARGETS = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64", "windows-x64"];
|
|
26
|
+
/** The target of a system, by `proc.build`'s names; undefined where Bun builds for no such system. */
|
|
27
|
+
export function targetOf(os, arch) {
|
|
28
|
+
const key = `${os}/${arch}`;
|
|
29
|
+
switch (key) {
|
|
30
|
+
case "linux/x86_64":
|
|
31
|
+
return "linux-x64";
|
|
32
|
+
case "linux/aarch64":
|
|
33
|
+
return "linux-arm64";
|
|
34
|
+
case "darwin/x86_64":
|
|
35
|
+
return "darwin-x64";
|
|
36
|
+
case "darwin/aarch64":
|
|
37
|
+
return "darwin-arm64";
|
|
38
|
+
case "windows/x86_64":
|
|
39
|
+
return "windows-x64";
|
|
40
|
+
default:
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** The target of this computer; undefined where Bun builds for no such system. */
|
|
45
|
+
export function hostTarget() {
|
|
46
|
+
return targetOf(build.os, build.arch);
|
|
47
|
+
}
|
|
48
|
+
/** Whether a target's binaries are Windows programs, named with `.exe`. */
|
|
49
|
+
export function isWindows(target) {
|
|
50
|
+
switch (target) {
|
|
51
|
+
case "windows-x64":
|
|
52
|
+
return true;
|
|
53
|
+
case "linux-x64":
|
|
54
|
+
case "linux-arm64":
|
|
55
|
+
case "darwin-x64":
|
|
56
|
+
case "darwin-arm64":
|
|
57
|
+
return false;
|
|
58
|
+
default:
|
|
59
|
+
return absurd(target);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** A sentence for a `CompileError`. */
|
|
63
|
+
export function describeCompileError(e) {
|
|
64
|
+
switch (e.kind) {
|
|
65
|
+
case "no-bun":
|
|
66
|
+
return e.message;
|
|
67
|
+
case "wrong-bun":
|
|
68
|
+
return `Bun ${e.found} is not the pinned ${e.expected}`;
|
|
69
|
+
case "no-target":
|
|
70
|
+
return e.message;
|
|
71
|
+
case "failed":
|
|
72
|
+
return `bun build --compile failed (${e.code}): ${e.stderr.trim()}`;
|
|
73
|
+
case "no-binary":
|
|
74
|
+
return `bun build --compile wrote no binary at ${e.path}`;
|
|
75
|
+
default:
|
|
76
|
+
return absurd(e);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** The binary's path for a target: `outfile`, with `.exe` added for Windows where it is not there. */
|
|
80
|
+
export function binaryPath(outfile, target) {
|
|
81
|
+
return isWindows(target) && !/\.exe$/i.test(outfile) ? `${outfile}.exe` : outfile;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The argument vector that builds the binary (pure): `bun build --compile [--target=bun-<target>] --outfile=<path> [extra...] <entry>
|
|
85
|
+
* [files...]`. A target is named only where one is given; without it Bun builds for the computer it runs on. The files after the entry
|
|
86
|
+
* point are embedded in the binary.
|
|
87
|
+
*/
|
|
88
|
+
export function compileArgv(bun, options, outfile) {
|
|
89
|
+
return [
|
|
90
|
+
bun,
|
|
91
|
+
"build",
|
|
92
|
+
"--compile",
|
|
93
|
+
...(options.target === undefined ? [] : [`--target=bun-${options.target}`]),
|
|
94
|
+
`--outfile=${outfile}`,
|
|
95
|
+
...(options.extraArgs ?? []),
|
|
96
|
+
options.entry,
|
|
97
|
+
...(options.files ?? []),
|
|
98
|
+
];
|
|
99
|
+
}
|
|
100
|
+
/** Builds a program into one binary with Bun (FR-062) and gives its path and SHA-256; a `CompileError` where it cannot. */
|
|
101
|
+
export async function compile(options) {
|
|
102
|
+
const target = options.target ?? hostTarget();
|
|
103
|
+
if (target === undefined)
|
|
104
|
+
return err({ kind: "no-target", message: `Bun builds no binary for ${build.os}/${build.arch}` });
|
|
105
|
+
const bun = options.bun ?? which("bun");
|
|
106
|
+
if (bun === undefined)
|
|
107
|
+
return err({ kind: "no-bun", message: "no bun on PATH" });
|
|
108
|
+
const where = options.cwd ?? processCwd();
|
|
109
|
+
const run = { cwd: where, ...(options.signal === undefined ? {} : { signal: options.signal }) };
|
|
110
|
+
let version;
|
|
111
|
+
try {
|
|
112
|
+
const v = await output([bun, "--version"], run);
|
|
113
|
+
version = new TextDecoder().decode(v.stdout).trim();
|
|
114
|
+
if (!v.success || version === "")
|
|
115
|
+
return err({ kind: "no-bun", message: `${bun} --version failed (${v.code})` });
|
|
116
|
+
}
|
|
117
|
+
catch (e) {
|
|
118
|
+
return err({ kind: "no-bun", message: `${bun}: ${e instanceof Error ? e.message : String(e)}` });
|
|
119
|
+
}
|
|
120
|
+
if (options.bunVersion !== undefined && version !== options.bunVersion) {
|
|
121
|
+
return err({ kind: "wrong-bun", expected: options.bunVersion, found: version });
|
|
122
|
+
}
|
|
123
|
+
const path = resolve(where, binaryPath(options.outfile, target));
|
|
124
|
+
const built = await output(compileArgv(bun, options, path), run);
|
|
125
|
+
if (!built.success)
|
|
126
|
+
return err({ kind: "failed", code: built.code, stderr: new TextDecoder().decode(built.stderr) });
|
|
127
|
+
if (!(await exists(path)))
|
|
128
|
+
return err({ kind: "no-binary", path });
|
|
129
|
+
return ok({ path, sha256: await sha256File(path), target, bunVersion: version });
|
|
130
|
+
}
|
package/dist/dirs.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** An operating system, by the names `proc.build.os` gives. */
|
|
2
|
+
export type Os = "linux" | "darwin" | "windows";
|
|
3
|
+
/** A variable's value, or `undefined`. */
|
|
4
|
+
export type Env = (name: string) => string | undefined;
|
|
5
|
+
/** The folders a program keeps its files in; each is undefined where it cannot be found. */
|
|
6
|
+
export type Dirs = {
|
|
7
|
+
readonly config: string | undefined;
|
|
8
|
+
readonly data: string | undefined;
|
|
9
|
+
readonly state: string | undefined;
|
|
10
|
+
readonly cache: string | undefined;
|
|
11
|
+
/** For locks and sockets: undefined where `XDG_RUNTIME_DIR` is not set, and the caller uses `state`. */
|
|
12
|
+
readonly runtime: string | undefined;
|
|
13
|
+
/** Where a program a person installs is put: `~/.local/bin`; undefined on Windows. */
|
|
14
|
+
readonly bin: string | undefined;
|
|
15
|
+
};
|
|
16
|
+
/** The home folder: `HOME`, and on Windows `USERPROFILE` first. */
|
|
17
|
+
export declare function homeOf(env: Env, os: Os): string | undefined;
|
|
18
|
+
/** The folders of the program `app` on the system `os`, from the variables `env` gives. */
|
|
19
|
+
export declare function dirsOf(app: string, env: Env, os: Os): Dirs;
|
package/dist/dirs.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
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.js";
|
|
27
|
+
const rulesOf = (os) => (os === "windows" ? win32 : posix);
|
|
28
|
+
/** The home folder: `HOME`, and on Windows `USERPROFILE` first. */
|
|
29
|
+
export function homeOf(env, os) {
|
|
30
|
+
const h = os === "windows" ? (env("USERPROFILE") ?? env("HOME")) : env("HOME");
|
|
31
|
+
return h === undefined || h === "" ? undefined : h;
|
|
32
|
+
}
|
|
33
|
+
/** An XDG variable's value where it is set to an absolute path, as the specification says to read it. */
|
|
34
|
+
function xdg(env, name, os) {
|
|
35
|
+
const v = env(name);
|
|
36
|
+
return v !== undefined && v !== "" && (rulesOf(os).isAbsolute(v) || (os === "windows" && posix.isAbsolute(v))) ? v : undefined;
|
|
37
|
+
}
|
|
38
|
+
/** The folders of the program `app` on the system `os`, from the variables `env` gives. */
|
|
39
|
+
export function dirsOf(app, env, os) {
|
|
40
|
+
const r = rulesOf(os);
|
|
41
|
+
const home = homeOf(env, os);
|
|
42
|
+
const under = (base, ...rest) => base === undefined ? undefined : r.join(base, ...rest);
|
|
43
|
+
const fromHome = (...parts) => (home === undefined ? undefined : r.join(home, ...parts));
|
|
44
|
+
if (os === "windows") {
|
|
45
|
+
const local = env("LOCALAPPDATA") ?? fromHome("AppData", "Local");
|
|
46
|
+
const roaming = env("APPDATA") ?? fromHome("AppData", "Roaming");
|
|
47
|
+
return {
|
|
48
|
+
config: under(xdg(env, "XDG_CONFIG_HOME", os) ?? roaming, app),
|
|
49
|
+
data: under(xdg(env, "XDG_DATA_HOME", os) ?? local, app),
|
|
50
|
+
state: xdg(env, "XDG_STATE_HOME", os) === undefined ? under(local, app, "state") : under(xdg(env, "XDG_STATE_HOME", os), app),
|
|
51
|
+
cache: xdg(env, "XDG_CACHE_HOME", os) === undefined ? under(local, app, "cache") : under(xdg(env, "XDG_CACHE_HOME", os), app),
|
|
52
|
+
runtime: under(xdg(env, "XDG_RUNTIME_DIR", os), app),
|
|
53
|
+
bin: undefined,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
config: under(xdg(env, "XDG_CONFIG_HOME", os) ?? fromHome(".config"), app),
|
|
58
|
+
data: under(xdg(env, "XDG_DATA_HOME", os) ?? fromHome(".local", "share"), app),
|
|
59
|
+
state: under(xdg(env, "XDG_STATE_HOME", os) ?? fromHome(".local", "state"), app),
|
|
60
|
+
cache: under(xdg(env, "XDG_CACHE_HOME", os) ?? fromHome(".cache"), app),
|
|
61
|
+
runtime: under(xdg(env, "XDG_RUNTIME_DIR", os), app),
|
|
62
|
+
bin: fromHome(".local", "bin"),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** The rules a search follows: Windows' (`;`, `\`, PATHEXT) or POSIX's (`:`, `/`, the mode's execute bits). */
|
|
2
|
+
export type SearchPlatform = "windows" | "posix";
|
|
3
|
+
/** What a search is given; each is read from this process where it is not. */
|
|
4
|
+
export type DiscoverOptions = {
|
|
5
|
+
/** The search path, `PATH` by default. */
|
|
6
|
+
readonly path?: string;
|
|
7
|
+
/** The extensions of programs on Windows, `PATHEXT` by default, `.EXE;.CMD;.BAT;.COM` where that is not set. */
|
|
8
|
+
readonly pathext?: string;
|
|
9
|
+
/** The platform whose rules apply, this one's by default. */
|
|
10
|
+
readonly platform?: SearchPlatform;
|
|
11
|
+
};
|
|
12
|
+
/** A program found: its name after the prefix (on Windows without its extension) and its file. */
|
|
13
|
+
export type FoundProgram = {
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly file: string;
|
|
16
|
+
};
|
|
17
|
+
/** Why a file whose name begins with the prefix was not taken. */
|
|
18
|
+
export type SkipReason = {
|
|
19
|
+
readonly kind: "directory";
|
|
20
|
+
} | {
|
|
21
|
+
readonly kind: "not-executable";
|
|
22
|
+
} | {
|
|
23
|
+
readonly kind: "shadowed";
|
|
24
|
+
readonly by: string;
|
|
25
|
+
};
|
|
26
|
+
/** A file passed over, and why. */
|
|
27
|
+
export type SkippedProgram = {
|
|
28
|
+
readonly file: string;
|
|
29
|
+
readonly why: SkipReason;
|
|
30
|
+
};
|
|
31
|
+
/** What a search found, in the order of the path and then of the names in each folder. */
|
|
32
|
+
export type Discovered = {
|
|
33
|
+
readonly found: readonly FoundProgram[];
|
|
34
|
+
readonly skipped: readonly SkippedProgram[];
|
|
35
|
+
};
|
|
36
|
+
/** The platform this process runs on, as the search names it. */
|
|
37
|
+
export declare function searchPlatform(): SearchPlatform;
|
|
38
|
+
/** The extensions of PATHEXT, upper case, in their order. */
|
|
39
|
+
export declare function pathExtensions(pathext: string | undefined): readonly string[];
|
|
40
|
+
/** A reason as words, for a `--verbose` line. */
|
|
41
|
+
export declare function skipReasonText(why: SkipReason): string;
|
|
42
|
+
/** Every program on the search path whose name begins with `prefix`, and every file of that name passed over. */
|
|
43
|
+
export declare function discoverPrograms(prefix: string, options?: DiscoverOptions): Promise<Discovered>;
|
package/dist/discover.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
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
|
+
/** The platform this process runs on, as the search names it. */
|
|
28
|
+
export function searchPlatform() {
|
|
29
|
+
return process.platform === "win32" ? "windows" : "posix";
|
|
30
|
+
}
|
|
31
|
+
/** The extensions of PATHEXT, upper case, in their order. */
|
|
32
|
+
export function pathExtensions(pathext) {
|
|
33
|
+
return (pathext ?? ".EXE;.CMD;.BAT;.COM")
|
|
34
|
+
.split(";")
|
|
35
|
+
.map((e) => e.trim().toUpperCase())
|
|
36
|
+
.filter((e) => e !== "");
|
|
37
|
+
}
|
|
38
|
+
/** A reason as words, for a `--verbose` line. */
|
|
39
|
+
export function skipReasonText(why) {
|
|
40
|
+
switch (why.kind) {
|
|
41
|
+
case "directory":
|
|
42
|
+
return "a directory";
|
|
43
|
+
case "not-executable":
|
|
44
|
+
return "not a program this account may run";
|
|
45
|
+
case "shadowed":
|
|
46
|
+
return `shadowed by ${why.by}`;
|
|
47
|
+
default:
|
|
48
|
+
return absurd(why);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Every program on the search path whose name begins with `prefix`, and every file of that name passed over. */
|
|
52
|
+
export async function discoverPrograms(prefix, options = {}) {
|
|
53
|
+
const platform = options.platform ?? searchPlatform();
|
|
54
|
+
const rules = platform === "windows" ? win32 : posix;
|
|
55
|
+
const search = options.path ?? process.env["PATH"] ?? "";
|
|
56
|
+
const exts = pathExtensions(options.pathext ?? process.env["PATHEXT"]);
|
|
57
|
+
const found = [];
|
|
58
|
+
const skipped = [];
|
|
59
|
+
const byName = new Map();
|
|
60
|
+
const folders = search.split(rules.delimiter).filter((d) => d !== "");
|
|
61
|
+
for (const folder of folders) {
|
|
62
|
+
let names;
|
|
63
|
+
try {
|
|
64
|
+
names = (await readdir(folder)).filter((n) => n.startsWith(prefix));
|
|
65
|
+
// In a folder, Windows takes a name's extensions in PATHEXT's order; elsewhere names are taken in byte order.
|
|
66
|
+
const rank = (n) => {
|
|
67
|
+
const i = exts.indexOf(rules.extname(n).toUpperCase());
|
|
68
|
+
return i < 0 ? exts.length : i;
|
|
69
|
+
};
|
|
70
|
+
const stem = (n) => (platform === "windows" ? n.slice(0, n.length - rules.extname(n).length).toLowerCase() : n);
|
|
71
|
+
names.sort((a, b) => (stem(a) < stem(b) ? -1 : stem(a) > stem(b) ? 1 : platform === "windows" ? rank(a) - rank(b) : 0));
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
for (const entry of names) {
|
|
77
|
+
const file = join(folder, entry);
|
|
78
|
+
let isDir;
|
|
79
|
+
let mode;
|
|
80
|
+
try {
|
|
81
|
+
const s = await stat(file);
|
|
82
|
+
isDir = s.isDirectory();
|
|
83
|
+
mode = s.mode;
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (isDir) {
|
|
89
|
+
skipped.push({ file, why: { kind: "directory" } });
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
let name = entry.slice(prefix.length);
|
|
93
|
+
if (platform === "windows") {
|
|
94
|
+
const ext = rules.extname(entry).toUpperCase();
|
|
95
|
+
if (ext === "" || !exts.includes(ext)) {
|
|
96
|
+
skipped.push({ file, why: { kind: "not-executable" } });
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
name = name.slice(0, name.length - ext.length);
|
|
100
|
+
}
|
|
101
|
+
else if ((mode & 0o111) === 0) {
|
|
102
|
+
skipped.push({ file, why: { kind: "not-executable" } });
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (name === "")
|
|
106
|
+
continue;
|
|
107
|
+
const key = platform === "windows" ? name.toLowerCase() : name;
|
|
108
|
+
const first = byName.get(key);
|
|
109
|
+
if (first !== undefined) {
|
|
110
|
+
skipped.push({ file, why: { kind: "shadowed", by: first } });
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
byName.set(key, file);
|
|
114
|
+
found.push({ name, file });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return { found, skipped };
|
|
118
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 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
|
|
3
|
+
* (`ENOENT`, `EEXIST`, `EACCES`, ...), keeping that code, the path or address where there is one, and the original error as its `cause`.
|
|
4
|
+
* The runtime throws; `Result` belongs to the layers above, which turn these into their own errors.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* import { errors } from "./errors.js";
|
|
9
|
+
* import { readTextFile } from "./fs.js";
|
|
10
|
+
* try {
|
|
11
|
+
* await readTextFile("/no/such/file");
|
|
12
|
+
* } catch (e) {
|
|
13
|
+
* if (e instanceof errors.NotFound) console.log("not there");
|
|
14
|
+
* else throw e;
|
|
15
|
+
* }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
/** What every error of the runtime carries: the code the host gave and, for a file or an address, where. */
|
|
21
|
+
export declare class RuntimeError extends Error {
|
|
22
|
+
/** The host's error code (`ENOENT`, `EACCES`, ...), or `""` where it gave none. */
|
|
23
|
+
readonly code: string;
|
|
24
|
+
/** The path, or the address, the failed call was about, where there was one. */
|
|
25
|
+
readonly path: string | undefined;
|
|
26
|
+
/** Make one from a message, the host's code, the path and the error it stands for. */
|
|
27
|
+
constructor(message: string, code: string, path?: string, cause?: unknown);
|
|
28
|
+
/** The class's own name, so a stack trace says `NotFound` and not `Error`. */
|
|
29
|
+
get name(): string;
|
|
30
|
+
}
|
|
31
|
+
/** Nothing is at the path, or no such program (`ENOENT`). */
|
|
32
|
+
export declare class NotFound extends RuntimeError {
|
|
33
|
+
}
|
|
34
|
+
/** Something is already at the path (`EEXIST`). */
|
|
35
|
+
export declare class AlreadyExists extends RuntimeError {
|
|
36
|
+
}
|
|
37
|
+
/** The account may not do this (`EACCES`, `EPERM`). */
|
|
38
|
+
export declare class PermissionDenied extends RuntimeError {
|
|
39
|
+
}
|
|
40
|
+
/** A folder was given where a file was needed (`EISDIR`). */
|
|
41
|
+
export declare class IsADirectory extends RuntimeError {
|
|
42
|
+
}
|
|
43
|
+
/** A file was given where a folder was needed (`ENOTDIR`). */
|
|
44
|
+
export declare class NotADirectory extends RuntimeError {
|
|
45
|
+
}
|
|
46
|
+
/** A folder that must be empty is not (`ENOTEMPTY`). */
|
|
47
|
+
export declare class DirectoryNotEmpty extends RuntimeError {
|
|
48
|
+
}
|
|
49
|
+
/** Links point at each other with no end (`ELOOP`). */
|
|
50
|
+
export declare class FilesystemLoop extends RuntimeError {
|
|
51
|
+
}
|
|
52
|
+
/** The resource is in use (`EBUSY`, `ETXTBSY`). */
|
|
53
|
+
export declare class Busy extends RuntimeError {
|
|
54
|
+
}
|
|
55
|
+
/** The address is already in use (`EADDRINUSE`). */
|
|
56
|
+
export declare class AddrInUse extends RuntimeError {
|
|
57
|
+
}
|
|
58
|
+
/** The address cannot be used on this computer (`EADDRNOTAVAIL`). */
|
|
59
|
+
export declare class AddrNotAvailable extends RuntimeError {
|
|
60
|
+
}
|
|
61
|
+
/** Nothing listens at the address (`ECONNREFUSED`). */
|
|
62
|
+
export declare class ConnectionRefused extends RuntimeError {
|
|
63
|
+
}
|
|
64
|
+
/** The other end reset the connection (`ECONNRESET`). */
|
|
65
|
+
export declare class ConnectionReset extends RuntimeError {
|
|
66
|
+
}
|
|
67
|
+
/** The connection was aborted (`ECONNABORTED`). */
|
|
68
|
+
export declare class ConnectionAborted extends RuntimeError {
|
|
69
|
+
}
|
|
70
|
+
/** The other end of a pipe was closed (`EPIPE`). */
|
|
71
|
+
export declare class BrokenPipe extends RuntimeError {
|
|
72
|
+
}
|
|
73
|
+
/** The call took too long (`ETIMEDOUT`). */
|
|
74
|
+
export declare class TimedOut extends RuntimeError {
|
|
75
|
+
}
|
|
76
|
+
/** A signal interrupted the call (`EINTR`). */
|
|
77
|
+
export declare class Interrupted extends RuntimeError {
|
|
78
|
+
}
|
|
79
|
+
/** The network cannot be reached (`ENETUNREACH`, `EHOSTUNREACH`). */
|
|
80
|
+
export declare class NetworkUnreachable extends RuntimeError {
|
|
81
|
+
}
|
|
82
|
+
/** The data was not what was expected (`EINVAL` on data, a bad archive or encoding). */
|
|
83
|
+
export declare class InvalidData extends RuntimeError {
|
|
84
|
+
}
|
|
85
|
+
/** This platform or file system cannot do it (`ENOSYS`, `ENOTSUP`, `EXDEV` across devices). */
|
|
86
|
+
export declare class NotSupported extends RuntimeError {
|
|
87
|
+
}
|
|
88
|
+
/** The end of the data came before what was needed. */
|
|
89
|
+
export declare class UnexpectedEof extends RuntimeError {
|
|
90
|
+
}
|
|
91
|
+
/** The error classes by name. */
|
|
92
|
+
export declare const errors: {
|
|
93
|
+
readonly RuntimeError: typeof RuntimeError;
|
|
94
|
+
readonly NotFound: typeof NotFound;
|
|
95
|
+
readonly AlreadyExists: typeof AlreadyExists;
|
|
96
|
+
readonly PermissionDenied: typeof PermissionDenied;
|
|
97
|
+
readonly IsADirectory: typeof IsADirectory;
|
|
98
|
+
readonly NotADirectory: typeof NotADirectory;
|
|
99
|
+
readonly DirectoryNotEmpty: typeof DirectoryNotEmpty;
|
|
100
|
+
readonly FilesystemLoop: typeof FilesystemLoop;
|
|
101
|
+
readonly Busy: typeof Busy;
|
|
102
|
+
readonly AddrInUse: typeof AddrInUse;
|
|
103
|
+
readonly AddrNotAvailable: typeof AddrNotAvailable;
|
|
104
|
+
readonly ConnectionRefused: typeof ConnectionRefused;
|
|
105
|
+
readonly ConnectionReset: typeof ConnectionReset;
|
|
106
|
+
readonly ConnectionAborted: typeof ConnectionAborted;
|
|
107
|
+
readonly BrokenPipe: typeof BrokenPipe;
|
|
108
|
+
readonly TimedOut: typeof TimedOut;
|
|
109
|
+
readonly Interrupted: typeof Interrupted;
|
|
110
|
+
readonly NetworkUnreachable: typeof NetworkUnreachable;
|
|
111
|
+
readonly InvalidData: typeof InvalidData;
|
|
112
|
+
readonly NotSupported: typeof NotSupported;
|
|
113
|
+
readonly UnexpectedEof: typeof UnexpectedEof;
|
|
114
|
+
};
|
|
115
|
+
type ErrorClass = new (message: string, code: string, path?: string, cause?: unknown) => RuntimeError;
|
|
116
|
+
/** The class each Node error code becomes. */
|
|
117
|
+
export declare const BY_CODE: Readonly<Record<string, ErrorClass>>;
|
|
118
|
+
/** What was thrown or rejected, as an `Error`: an `Error` as it is, anything else wrapped, kept as the cause. */
|
|
119
|
+
export declare function toError(thrown: unknown, message?: string): Error;
|
|
120
|
+
/**
|
|
121
|
+
* What the host threw, as an error of the runtime: an error that carries a known `code` becomes its class (keeping the message, code,
|
|
122
|
+
* 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
|
|
123
|
+
* {@link toError}.
|
|
124
|
+
*/
|
|
125
|
+
export declare function mapError(thrown: unknown, path?: string): Error;
|
|
126
|
+
/** Run a call on the host and throw what it throws as an error of the runtime. */
|
|
127
|
+
export declare function hostCall<T>(path: string | undefined, f: () => Promise<T>): Promise<T>;
|
|
128
|
+
/** The same, for a call that does not wait. */
|
|
129
|
+
export declare function hostCallSync<T>(path: string | undefined, f: () => T): T;
|
|
130
|
+
export {};
|