@better-fs-tools/node 0.0.0-tegami-trusted-publish-setup → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +149 -6
- package/dist/command-runner.d.ts +16 -0
- package/dist/command-runner.js +159 -0
- package/dist/create-node-bash-tool.d.ts +10 -0
- package/dist/create-node-bash-tool.js +31 -0
- package/dist/create-node-fs-tools.d.ts +75 -0
- package/dist/create-node-fs-tools.js +112 -0
- package/dist/create-node-read-tool.d.ts +9 -0
- package/dist/create-node-read-tool.js +22 -0
- package/dist/create-node-write-tools.d.ts +19 -0
- package/dist/create-node-write-tools.js +42 -0
- package/dist/digest.d.ts +3 -0
- package/dist/digest.js +21 -0
- package/dist/filesystem.d.ts +15 -0
- package/dist/filesystem.js +226 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +7 -0
- package/dist/policy.d.ts +73 -0
- package/dist/policy.js +219 -0
- package/dist/stat.d.ts +3 -0
- package/dist/stat.js +121 -0
- package/dist/write.d.ts +20 -0
- package/dist/write.js +341 -0
- package/package.json +37 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gareth Andrew
|
|
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,6 +1,149 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
# @better-fs-tools/node
|
|
2
|
+
|
|
3
|
+
The Node filesystem for Better FS Tools, a SHA-256 digest, `createNodeReadTool()`, the zero-config local read tool, and `createNodeFsTools()`, which adds `edit`, `write`, and `apply_patch` over the same filesystem and read store, and `bash` when you ask for it. It works on Node 24 or later, and on Bun.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @better-fs-tools/node @better-fs-tools/read @better-fs-tools/write
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
The package has no peers. It needs Node 24 or later (`engines.node` is `>=24`), or Bun.
|
|
12
|
+
|
|
13
|
+
## Example
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createNodeReadTool, nodeFileSystem } from "@better-fs-tools/node";
|
|
17
|
+
import { textOf } from "@better-fs-tools/read";
|
|
18
|
+
|
|
19
|
+
// Zero config: rooted at process.cwd(), with SHA-256 observations.
|
|
20
|
+
const read = createNodeReadTool();
|
|
21
|
+
console.log(textOf(await read({ path: "package.json", limit: 1 }))); // "1|{" and a continue note
|
|
22
|
+
|
|
23
|
+
// Your own roots and policy.
|
|
24
|
+
export const docsOnly = createNodeReadTool({
|
|
25
|
+
fs: nodeFileSystem({
|
|
26
|
+
cwd: "/srv/app",
|
|
27
|
+
allowedRoots: ["/srv/app/docs"],
|
|
28
|
+
denyRoots: ["/srv/app/docs/private"],
|
|
29
|
+
symlinks: "reject",
|
|
30
|
+
}),
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
All four tools, with one read store, so `edit` and `write` need a read first:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { createNodeFsTools } from "@better-fs-tools/node";
|
|
38
|
+
import { textOf } from "@better-fs-tools/read";
|
|
39
|
+
import { protectPaths } from "@better-fs-tools/write";
|
|
40
|
+
|
|
41
|
+
// read, edit, write, and apply_patch over one nodeFileSystem rooted at
|
|
42
|
+
// process.cwd(), with one read store, one SHA-256 digest, and one lock manager.
|
|
43
|
+
const tools = createNodeFsTools({
|
|
44
|
+
edit: { authorize: protectPaths() },
|
|
45
|
+
write: { authorize: protectPaths() },
|
|
46
|
+
applyPatch: { authorize: protectPaths() },
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
export async function bump(path: string): Promise<string> {
|
|
50
|
+
await tools.read({ path });
|
|
51
|
+
const result = await tools.edit({ path, edits: [{ oldText: "a = 1", newText: "a = 2" }] });
|
|
52
|
+
return textOf(result);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// A shell tool changed the file: the next edit must read it first.
|
|
56
|
+
export async function afterShell(path: string): Promise<boolean> {
|
|
57
|
+
const outcome = await tools.invalidate(path);
|
|
58
|
+
// ok: false means the stat or the store failed, and a record may still be there.
|
|
59
|
+
return outcome.ok;
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Contents
|
|
64
|
+
|
|
65
|
+
| Export | Use |
|
|
66
|
+
| -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
67
|
+
| `createNodeReadTool(options?)` | `createReadTool()` from `@better-fs-tools/read` with Node defaults. `fs` defaults to `nodeFileSystem` rooted at `process.cwd()`. `digest` defaults to `nodeDigest()`. Pass `digest: null` to turn observations off. Every other option goes to the core. |
|
|
68
|
+
| `createNodeFsTools(options?)` | `createFsTools()` from `@better-fs-tools/write` over one `nodeFileSystem`, with `nodeDigest()`: `read`, `edit`, `write`, and `apply_patch` share one `memoryStore({ clock })`, one digest, one `memoryLocks()`, and one clock. Options: `cwd`, `allowedRoots` (default `[cwd]`), `denyRoots`, `symlinks`, `hardLinks`, `newFileMode`, `newDirectoryMode`, `state` (`null` turns read-before-write off), `digest`, `locks`, `clock`, per-tool options under `read`, `edit`, `write`, and `applyPatch`, and `bash`. Bash is off unless `bash` is `true` or an options object. The result also has `bash` (`null` when off), `fs`, `state`, `digest`, `locks`, `clock`, and `invalidate(path, call?)`, which returns an `InvalidateOutcome`. The Node filesystem is fixed, so `call` is not needed. An unknown option key, or `fs`, `state`, `digest`, `locks`, or `clock` inside a per-tool object (`digest` or `clock` inside `bash`), throws `TypeError` |
|
|
69
|
+
| `createNodeEditTool(deps?)`, `createNodeWriteTool(deps?)`, `createNodeApplyPatchTool(deps?)` | One write tool each. `fs` defaults to `nodeFileSystem` rooted at `process.cwd()`, `digest` to `nodeDigest()`. `state` stays `null`, so every update carries a `read-before-write-off` note |
|
|
70
|
+
| `createNodeBashTool(deps?)` | The local `bash` tool. See [Bash tool](#bash-tool) |
|
|
71
|
+
| `nodeCommandRunner(options?)` | The command runner that `createNodeBashTool()` uses: `bash -c` in its own process group. POSIX only |
|
|
72
|
+
| `nodeFileSystem(options)` | A `WritableFileSystem` over Node file descriptors |
|
|
73
|
+
| `nodeDigest()` | SHA-256 over `node:crypto`. Values look like `sha256:<hex>`, the same as `sha256Digest()` from `@better-fs-tools/read`. |
|
|
74
|
+
|
|
75
|
+
`nodeFileSystem` options. The first six are the shared `FileSystemRootOptions` from `@better-fs-tools/fs`. The filesystem also exposes the resolved `cwd`, `allowedRoots`, `denyRoots`, `symlinks`, and `identity`:
|
|
76
|
+
|
|
77
|
+
| Option | Default | Meaning |
|
|
78
|
+
| ------------------ | ----------------------- | ------------------------------------------------------------------------------------------------------ |
|
|
79
|
+
| `allowedRoots` | required | At least one root. A path outside every root gives `OUTSIDE_ALLOWED_ROOTS`. |
|
|
80
|
+
| `cwd` | `process.cwd()` | Base for relative paths. A relative `cwd` resolves against `process.cwd()` |
|
|
81
|
+
| `denyRoots` | none | Refused as `DANGEROUS_PATH`, in addition to `/dev`, `/proc`, and `/sys` |
|
|
82
|
+
| `symlinks` | `"follow-within-roots"` | `"reject"` refuses every symlink |
|
|
83
|
+
| `identity` | `"required"` | The only value: Node always reports device and inode |
|
|
84
|
+
| `id` | `"node"` | Appears in `result.file.backend` |
|
|
85
|
+
| `hardLinks` | `"refuse"` | A replace of a file with more than one hard link. `"in-place"` writes through the link, not atomically |
|
|
86
|
+
| `newFileMode` | `0o666` less the umask | Mode of a new file. A mode you set is exact: the umask does not apply to it |
|
|
87
|
+
| `newDirectoryMode` | `0o777` less the umask | Mode of a directory that `createParents` makes. A mode you set is exact |
|
|
88
|
+
|
|
89
|
+
## How it opens a file
|
|
90
|
+
|
|
91
|
+
`open()` resolves the path, checks the roots, and opens one descriptor with `O_NOFOLLOW | O_NONBLOCK`. It then checks the type on that descriptor, so a FIFO cannot block the call and a swapped path cannot change what is read. Directories, FIFOs, sockets, and devices are refused before any content byte is read. `verify()` stats the same descriptor after the read, and compares its device, inode, size, and change times.
|
|
92
|
+
|
|
93
|
+
## How it writes a file
|
|
94
|
+
|
|
95
|
+
`stat()`, `write()`, `stage()`, and `remove()` apply the same roots, deny roots, and symlink policy as `open()`. A link inside the roots is followed, so the real file changes and the link stays. A link out of the roots and a dangling link are refused. Directories, FIFOs, sockets, and devices are refused without being opened.
|
|
96
|
+
|
|
97
|
+
A write goes to a `0o600` temp file next to the target. The bytes are written and synced, and the file gets the old mode or the new-file mode. Publishing takes an in-process lock for the real path and checks the precondition against a fresh `lstat`. A create is published with `link()`, so a concurrent creator makes it fail with `exists`. A replace is published with `rename()`. Any failure removes the temp file and the directories the write created. The version token is the read identity: device, inode, size, and both change times. `EROFS` gives `read-only`, and `ENOSPC` and `EDQUOT` give `no-space`.
|
|
98
|
+
|
|
99
|
+
`writeCapabilities` is `{ atomic: true, compareAndSwap: true, preserveMode: true }`, and `stage()` and `remove()` exist. Some of this holds with limits:
|
|
100
|
+
|
|
101
|
+
- `compareAndSwap` holds inside one process only. The lock orders writes inside one process. Another process can still change the file between the final check and the rename, and that change is then lost.
|
|
102
|
+
- A replace keeps the permission bits only. The owner, the group, extended attributes, and ACLs are not kept, because `rename()` publishes a new file owned by the writing user.
|
|
103
|
+
- A process that dies between `stage()` and `publish()` leaves a `.<name>.<random>.tmp` file next to the target. Nothing removes it later. An `apply_patch` call stages every file first, so a process killed during its commit can leave several.
|
|
104
|
+
- A create links the temp file to the target, then removes the temp name. For those two system calls the new file has two links.
|
|
105
|
+
|
|
106
|
+
## Bash tool
|
|
107
|
+
|
|
108
|
+
`createNodeBashTool()` is the zero-config local `bash` tool from [`@better-fs-tools/shell`](https://www.npmjs.com/package/@better-fs-tools/shell). It uses `nodeCommandRunner()`: `bash -c` in its own process group, stdin on `/dev/null`, SIGTERM to the group on a stop, and SIGKILL after the grace time. The environment is `process.env`, read on each call, with the pager and colour defaults over it. `createNodeFsTools()` starts no process unless you ask: `bash: true`, or a `bash` options object, adds the same tool as `bash`, in the same cwd, with the bundle's digest and clock. Its `env` also defaults to `process.env`, since a host that turns on a local bash in a Node bundle asks for a local shell. Pass `env` to narrow it, for example `shellEnv({ PATH: process.env.PATH })`. With your own `bash.runner`, an explicit `cwd` still applies: it becomes the bash `cwd` dependency. `bash.cwd` wins over both. `nodeCommandRunner({ cwd })` resolves a relative `cwd` against `process.cwd()`, as `nodeFileSystem` does. So does the `cwd` dependency of `createNodeBashTool({ cwd })` and `bash.cwd`; the portable core keeps its absolute rule.
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
import { createNodeFsTools, nodeCommandRunner } from "@better-fs-tools/node";
|
|
112
|
+
import type { NodeFsToolsWithBash } from "@better-fs-tools/node";
|
|
113
|
+
|
|
114
|
+
// bash is created only because `bash` is set. The hook makes the next edit of
|
|
115
|
+
// package.json need a read first, since a command may have changed it.
|
|
116
|
+
let tools: NodeFsToolsWithBash | undefined;
|
|
117
|
+
tools = createNodeFsTools({
|
|
118
|
+
cwd: "/srv/project",
|
|
119
|
+
bash: {
|
|
120
|
+
runner: nodeCommandRunner({ cwd: "/srv/project", shell: "/bin/bash" }),
|
|
121
|
+
afterRun: [
|
|
122
|
+
{
|
|
123
|
+
id: "invalidate-package-json",
|
|
124
|
+
afterRun: async (outcome) => {
|
|
125
|
+
const invalidated = await tools?.invalidate("package.json");
|
|
126
|
+
// An empty update keeps the output and the notes.
|
|
127
|
+
if (invalidated === undefined || invalidated.ok) return {};
|
|
128
|
+
const warning = {
|
|
129
|
+
code: "invalidate-failed",
|
|
130
|
+
severity: "warning" as const,
|
|
131
|
+
message: "Read package.json again before you edit it.",
|
|
132
|
+
};
|
|
133
|
+
return { notes: [...outcome.notes, warning] };
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
],
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
export const { read, edit, bash } = tools;
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
The allowed roots do not limit what a command touches. The runner is POSIX only.
|
|
144
|
+
|
|
145
|
+
## Links
|
|
146
|
+
|
|
147
|
+
- `docs/hosts.md` in [`@better-fs-tools/write`](https://www.npmjs.com/package/@better-fs-tools/write): the defaults of every host and bundle, and what each backend can do
|
|
148
|
+
- [`@better-fs-tools/read`](https://www.npmjs.com/package/@better-fs-tools/read): every read option
|
|
149
|
+
- [`@better-fs-tools/pi`](https://www.npmjs.com/package/@better-fs-tools/pi): the Pi tool, which builds on `nodeFileSystem`
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { CommandRunner } from "@better-fs-tools/shell";
|
|
2
|
+
export interface NodeCommandRunnerOptions {
|
|
3
|
+
/** Default process.cwd(). A relative path resolves against process.cwd(). */
|
|
4
|
+
readonly cwd?: string;
|
|
5
|
+
/** The shell, run as `<shell> -c <command>`. Default "bash". */
|
|
6
|
+
readonly shell?: string;
|
|
7
|
+
/** Default "node". */
|
|
8
|
+
readonly id?: string;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A command runner that runs `bash -c <command>` on the local machine, with
|
|
12
|
+
* stdin closed. Stopping a command sends SIGTERM to its process group, then
|
|
13
|
+
* SIGKILL after killGraceMs. A background child that outlives the shell keeps
|
|
14
|
+
* running, but its output is no longer captured. POSIX only.
|
|
15
|
+
*/
|
|
16
|
+
export declare function nodeCommandRunner(options?: NodeCommandRunnerOptions): CommandRunner;
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
const BACKGROUND_CHILD_PIPE_GRACE_MS = 100;
|
|
5
|
+
/**
|
|
6
|
+
* A command runner that runs `bash -c <command>` on the local machine, with
|
|
7
|
+
* stdin closed. Stopping a command sends SIGTERM to its process group, then
|
|
8
|
+
* SIGKILL after killGraceMs. A background child that outlives the shell keeps
|
|
9
|
+
* running, but its output is no longer captured. POSIX only.
|
|
10
|
+
*/
|
|
11
|
+
export function nodeCommandRunner(options = {}) {
|
|
12
|
+
if (options === null || typeof options !== "object" || Array.isArray(options)) {
|
|
13
|
+
throw new TypeError("nodeCommandRunner options must be an object");
|
|
14
|
+
}
|
|
15
|
+
const { cwd: given = process.cwd(), shell = "bash", id = "node" } = options;
|
|
16
|
+
if (typeof given !== "string" || given === "" || given.includes("\0")) {
|
|
17
|
+
throw new TypeError("cwd must be a non-empty path without NUL");
|
|
18
|
+
}
|
|
19
|
+
const cwd = path.resolve(given);
|
|
20
|
+
if (typeof shell !== "string" || shell === "")
|
|
21
|
+
throw new TypeError("shell must be a string");
|
|
22
|
+
if (typeof id !== "string" || id === "")
|
|
23
|
+
throw new TypeError("id must be a string");
|
|
24
|
+
return Object.freeze({
|
|
25
|
+
id,
|
|
26
|
+
cwd,
|
|
27
|
+
run: (request) => runNode(shell, request),
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
function runNode(shell, request) {
|
|
31
|
+
const queue = new ChunkQueue();
|
|
32
|
+
const exit = start(shell, request, queue);
|
|
33
|
+
return { output: queue, exit };
|
|
34
|
+
}
|
|
35
|
+
async function start(shell, request, queue) {
|
|
36
|
+
const problem = await checkCwd(request.cwd);
|
|
37
|
+
if (problem !== null) {
|
|
38
|
+
queue.end();
|
|
39
|
+
return { code: null, signal: null, error: { reason: problem } };
|
|
40
|
+
}
|
|
41
|
+
if (request.signal.aborted) {
|
|
42
|
+
queue.end();
|
|
43
|
+
return { code: null, signal: "SIGTERM" };
|
|
44
|
+
}
|
|
45
|
+
return new Promise((resolve) => {
|
|
46
|
+
const child = spawn(shell, ["-c", request.command], {
|
|
47
|
+
cwd: request.cwd,
|
|
48
|
+
env: { ...request.env },
|
|
49
|
+
detached: true,
|
|
50
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
51
|
+
});
|
|
52
|
+
let settled = false;
|
|
53
|
+
let forceTimer;
|
|
54
|
+
const stopTree = () => {
|
|
55
|
+
signalGroup(child.pid, "SIGTERM");
|
|
56
|
+
forceTimer = setTimeout(() => signalGroup(child.pid, "SIGKILL"), request.killGraceMs);
|
|
57
|
+
forceTimer.unref();
|
|
58
|
+
};
|
|
59
|
+
request.signal.addEventListener("abort", stopTree, { once: true });
|
|
60
|
+
let open = 2;
|
|
61
|
+
const closed = () => {
|
|
62
|
+
open -= 1;
|
|
63
|
+
if (open === 0)
|
|
64
|
+
queue.end();
|
|
65
|
+
};
|
|
66
|
+
for (const [name, stream] of [
|
|
67
|
+
["stdout", child.stdout],
|
|
68
|
+
["stderr", child.stderr],
|
|
69
|
+
]) {
|
|
70
|
+
stream.on("data", (bytes) => queue.push({ stream: name, bytes }));
|
|
71
|
+
stream.on("close", closed);
|
|
72
|
+
stream.on("error", () => undefined);
|
|
73
|
+
}
|
|
74
|
+
const finish = (value) => {
|
|
75
|
+
if (settled)
|
|
76
|
+
return;
|
|
77
|
+
settled = true;
|
|
78
|
+
request.signal.removeEventListener("abort", stopTree);
|
|
79
|
+
const releasePipesHeldByBackgroundChild = setTimeout(() => {
|
|
80
|
+
child.stdout.destroy();
|
|
81
|
+
child.stderr.destroy();
|
|
82
|
+
queue.end();
|
|
83
|
+
}, BACKGROUND_CHILD_PIPE_GRACE_MS);
|
|
84
|
+
releasePipesHeldByBackgroundChild.unref();
|
|
85
|
+
// A stopped tree still gets its SIGKILL: grandchildren may outlive the shell.
|
|
86
|
+
if (!request.signal.aborted)
|
|
87
|
+
clearTimeout(forceTimer);
|
|
88
|
+
resolve(value);
|
|
89
|
+
};
|
|
90
|
+
child.on("error", (error) => {
|
|
91
|
+
queue.end();
|
|
92
|
+
finish({
|
|
93
|
+
code: null,
|
|
94
|
+
signal: null,
|
|
95
|
+
error: { reason: "spawn-failed", detail: error.message },
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
child.on("exit", (code, signal) => finish({ code, signal }));
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
async function checkCwd(cwd) {
|
|
102
|
+
try {
|
|
103
|
+
return (await stat(cwd)).isDirectory() ? null : "cwd-not-a-directory";
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
const code = error.code;
|
|
107
|
+
return code === "ENOTDIR" ? "cwd-not-a-directory" : "cwd-not-found";
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function signalGroup(pid, signal) {
|
|
111
|
+
if (pid === undefined)
|
|
112
|
+
return;
|
|
113
|
+
try {
|
|
114
|
+
process.kill(-pid, signal);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
// ESRCH: the group is gone.
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
class ChunkQueue {
|
|
121
|
+
#items = [];
|
|
122
|
+
#ended = false;
|
|
123
|
+
#wake;
|
|
124
|
+
push(chunk) {
|
|
125
|
+
if (this.#ended)
|
|
126
|
+
return;
|
|
127
|
+
this.#items.push(chunk);
|
|
128
|
+
this.#notify();
|
|
129
|
+
}
|
|
130
|
+
end() {
|
|
131
|
+
this.#ended = true;
|
|
132
|
+
this.#notify();
|
|
133
|
+
}
|
|
134
|
+
#notify() {
|
|
135
|
+
this.#wake?.();
|
|
136
|
+
this.#wake = undefined;
|
|
137
|
+
}
|
|
138
|
+
[Symbol.asyncIterator]() {
|
|
139
|
+
return {
|
|
140
|
+
next: async () => {
|
|
141
|
+
for (;;) {
|
|
142
|
+
const item = this.#items.shift();
|
|
143
|
+
if (item !== undefined)
|
|
144
|
+
return { done: false, value: item };
|
|
145
|
+
if (this.#ended)
|
|
146
|
+
return { done: true, value: undefined };
|
|
147
|
+
await new Promise((resolve) => {
|
|
148
|
+
this.#wake = resolve;
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
return: async () => {
|
|
153
|
+
this.#items = [];
|
|
154
|
+
this.end();
|
|
155
|
+
return { done: true, value: undefined };
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { BashTool, ShellToolDeps } from "@better-fs-tools/shell";
|
|
2
|
+
/**
|
|
3
|
+
* Creates a bash tool that runs commands on the local machine. `runner`
|
|
4
|
+
* defaults to nodeCommandRunner() at process.cwd(). `env` defaults to
|
|
5
|
+
* process.env, read on each call, with defaultShellEnv over it. A relative
|
|
6
|
+
* `cwd` resolves against process.cwd(). There is no authorizer, hook, or
|
|
7
|
+
* spill unless you pass one.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createNodeBashTool<THost = undefined>(deps?: Partial<ShellToolDeps<THost>>): BashTool<THost>;
|
|
10
|
+
export declare function withNodeShellDefaults<THost>(deps: Partial<ShellToolDeps<THost>>, cwd?: string): ShellToolDeps<THost>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { createBashTool, shellEnv } from "@better-fs-tools/shell";
|
|
3
|
+
import { nodeCommandRunner } from "./command-runner.js";
|
|
4
|
+
/**
|
|
5
|
+
* Creates a bash tool that runs commands on the local machine. `runner`
|
|
6
|
+
* defaults to nodeCommandRunner() at process.cwd(). `env` defaults to
|
|
7
|
+
* process.env, read on each call, with defaultShellEnv over it. A relative
|
|
8
|
+
* `cwd` resolves against process.cwd(). There is no authorizer, hook, or
|
|
9
|
+
* spill unless you pass one.
|
|
10
|
+
*/
|
|
11
|
+
export function createNodeBashTool(deps = {}) {
|
|
12
|
+
if (deps === null || typeof deps !== "object" || Array.isArray(deps)) {
|
|
13
|
+
throw new TypeError("bash tool dependencies must be an object");
|
|
14
|
+
}
|
|
15
|
+
return createBashTool(withNodeShellDefaults(deps));
|
|
16
|
+
}
|
|
17
|
+
export function withNodeShellDefaults(deps, cwd) {
|
|
18
|
+
const given = deps.cwd;
|
|
19
|
+
return {
|
|
20
|
+
...deps,
|
|
21
|
+
...(isValidRelativePath(given) ? { cwd: path.resolve(given) } : {}),
|
|
22
|
+
runner: deps.runner ?? nodeCommandRunner(cwd === undefined ? {} : { cwd }),
|
|
23
|
+
env: deps.env ?? shellEnv(() => process.env),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function isValidRelativePath(given) {
|
|
27
|
+
return (typeof given === "string" &&
|
|
28
|
+
given.trim() !== "" &&
|
|
29
|
+
!given.includes("\0") &&
|
|
30
|
+
!path.isAbsolute(given));
|
|
31
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { SymlinkPolicy } from "@better-fs-tools/fs";
|
|
2
|
+
import type { Clock, Digest, ReadStateStore, ReadTool, ReadToolDeps, ToolCallContext } from "@better-fs-tools/read";
|
|
3
|
+
import type { ApplyPatchTool, ApplyPatchToolDeps, EditTool, EditToolDeps, FsToolsSharedKey, InvalidateOutcome, LockManager, WriteTool, WriteToolDeps } from "@better-fs-tools/write";
|
|
4
|
+
import type { BashTool, ShellToolDeps } from "@better-fs-tools/shell";
|
|
5
|
+
import type { NodeFileSystem } from "./filesystem.ts";
|
|
6
|
+
/**
|
|
7
|
+
* Options for the bundle's bash tool, all optional. `runner` defaults to
|
|
8
|
+
* nodeCommandRunner({ cwd }), and `env` to shellEnv(() => process.env).
|
|
9
|
+
*/
|
|
10
|
+
export type NodeFsToolsBashOptions<THost = undefined> = Omit<Partial<ShellToolDeps<THost>>, "digest" | "clock">;
|
|
11
|
+
export interface CreateNodeFsToolsOptions<THost = undefined> {
|
|
12
|
+
/** Default process.cwd(). */
|
|
13
|
+
readonly cwd?: string;
|
|
14
|
+
/** Default [cwd]. They do not limit a bash command. */
|
|
15
|
+
readonly allowedRoots?: readonly string[];
|
|
16
|
+
readonly denyRoots?: readonly string[];
|
|
17
|
+
readonly symlinks?: SymlinkPolicy;
|
|
18
|
+
readonly hardLinks?: "refuse" | "in-place";
|
|
19
|
+
/** Mode of a new file, exactly. Default 0o666 less the process umask. */
|
|
20
|
+
readonly newFileMode?: number;
|
|
21
|
+
/** Mode of a directory that createParents makes, exactly. Default 0o777 less the umask. */
|
|
22
|
+
readonly newDirectoryMode?: number;
|
|
23
|
+
/** Default a memory store on the bundle clock. null turns read-before-write off. */
|
|
24
|
+
readonly state?: ReadStateStore | null;
|
|
25
|
+
/** Default nodeDigest(). */
|
|
26
|
+
readonly digest?: Digest;
|
|
27
|
+
/** Default memoryLocks(). */
|
|
28
|
+
readonly locks?: LockManager;
|
|
29
|
+
/** Default () => new Date(). */
|
|
30
|
+
readonly clock?: Clock;
|
|
31
|
+
readonly read?: Omit<Partial<ReadToolDeps<THost>>, FsToolsSharedKey>;
|
|
32
|
+
readonly edit?: Omit<Partial<EditToolDeps<THost>>, FsToolsSharedKey>;
|
|
33
|
+
readonly write?: Omit<Partial<WriteToolDeps<THost>>, FsToolsSharedKey>;
|
|
34
|
+
readonly applyPatch?: Omit<Partial<ApplyPatchToolDeps<THost>>, FsToolsSharedKey>;
|
|
35
|
+
/**
|
|
36
|
+
* `true` or an options object adds a bash tool. Off by default. The runner
|
|
37
|
+
* defaults to nodeCommandRunner({ cwd }), and env to
|
|
38
|
+
* shellEnv(() => process.env). With your own runner, commands still run in
|
|
39
|
+
* an explicit top-level cwd. bash.cwd wins over both.
|
|
40
|
+
*/
|
|
41
|
+
readonly bash?: boolean | NodeFsToolsBashOptions<THost>;
|
|
42
|
+
}
|
|
43
|
+
export interface NodeFsTools<THost = undefined> {
|
|
44
|
+
readonly read: ReadTool<THost>;
|
|
45
|
+
readonly edit: EditTool<THost>;
|
|
46
|
+
readonly write: WriteTool<THost>;
|
|
47
|
+
readonly applyPatch: ApplyPatchTool<THost>;
|
|
48
|
+
/** null unless options.bash is set. Runs in cwd. It does not share the read state: see invalidate. */
|
|
49
|
+
readonly bash: BashTool<THost> | null;
|
|
50
|
+
readonly fs: NodeFileSystem;
|
|
51
|
+
readonly state: ReadStateStore | null;
|
|
52
|
+
readonly digest: Digest;
|
|
53
|
+
readonly locks: LockManager;
|
|
54
|
+
readonly clock: Clock;
|
|
55
|
+
/**
|
|
56
|
+
* Forgets the read record for a path, so the next edit needs a fresh read.
|
|
57
|
+
* With state null it reports recorded: false. `call` is ignored.
|
|
58
|
+
*/
|
|
59
|
+
invalidate(path: string, call?: ToolCallContext<THost>): Promise<InvalidateOutcome>;
|
|
60
|
+
}
|
|
61
|
+
/** The result when options.bash is true or an object: bash is there. */
|
|
62
|
+
export interface NodeFsToolsWithBash<THost = undefined> extends NodeFsTools<THost> {
|
|
63
|
+
readonly bash: BashTool<THost>;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Creates read, edit, write, and apply_patch tools over one local filesystem.
|
|
67
|
+
* They share one read state store, digest, lock manager, and clock. With
|
|
68
|
+
* `bash`, adds a bash tool in the same cwd. The allowed roots do not limit
|
|
69
|
+
* what a bash command touches. To make the next edit after a command need a
|
|
70
|
+
* read, call invalidate(path) from a bash afterRun hook.
|
|
71
|
+
*/
|
|
72
|
+
export declare function createNodeFsTools<THost = undefined>(options: CreateNodeFsToolsOptions<THost> & {
|
|
73
|
+
readonly bash: true | NodeFsToolsBashOptions<THost>;
|
|
74
|
+
}): NodeFsToolsWithBash<THost>;
|
|
75
|
+
export declare function createNodeFsTools<THost = undefined>(options?: CreateNodeFsToolsOptions<THost>): NodeFsTools<THost>;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { createFsTools } from "@better-fs-tools/write";
|
|
3
|
+
import { withNodeShellDefaults } from "./create-node-bash-tool.js";
|
|
4
|
+
import { nodeDigest } from "./digest.js";
|
|
5
|
+
import { nodeFileSystem } from "./filesystem.js";
|
|
6
|
+
const KNOWN_OPTIONS = new Set([
|
|
7
|
+
"cwd",
|
|
8
|
+
"allowedRoots",
|
|
9
|
+
"denyRoots",
|
|
10
|
+
"symlinks",
|
|
11
|
+
"hardLinks",
|
|
12
|
+
"newFileMode",
|
|
13
|
+
"newDirectoryMode",
|
|
14
|
+
"state",
|
|
15
|
+
"digest",
|
|
16
|
+
"locks",
|
|
17
|
+
"clock",
|
|
18
|
+
"read",
|
|
19
|
+
"edit",
|
|
20
|
+
"write",
|
|
21
|
+
"applyPatch",
|
|
22
|
+
"bash",
|
|
23
|
+
]);
|
|
24
|
+
const BUNDLE_SHARED_KEYS_BY_TOOL = {
|
|
25
|
+
read: ["fs", "state", "digest", "clock"],
|
|
26
|
+
edit: ["fs", "state", "digest", "locks", "clock"],
|
|
27
|
+
write: ["fs", "state", "digest", "locks", "clock"],
|
|
28
|
+
applyPatch: ["fs", "state", "digest", "locks", "clock"],
|
|
29
|
+
bash: ["digest", "clock"],
|
|
30
|
+
};
|
|
31
|
+
export function createNodeFsTools(options = {}) {
|
|
32
|
+
checkOptions(options);
|
|
33
|
+
const cwd = path.resolve(options.cwd ?? process.cwd());
|
|
34
|
+
const fs = nodeFileSystem({
|
|
35
|
+
cwd,
|
|
36
|
+
allowedRoots: options.allowedRoots ?? [cwd],
|
|
37
|
+
...pickDefined(options, [
|
|
38
|
+
"denyRoots",
|
|
39
|
+
"symlinks",
|
|
40
|
+
"hardLinks",
|
|
41
|
+
"newFileMode",
|
|
42
|
+
"newDirectoryMode",
|
|
43
|
+
]),
|
|
44
|
+
});
|
|
45
|
+
const bash = options.bash === true ? {} : options.bash;
|
|
46
|
+
const tools = createFsTools({
|
|
47
|
+
fs,
|
|
48
|
+
digest: options.digest ?? nodeDigest(),
|
|
49
|
+
...pickDefined(options, ["state", "locks", "clock", "read", "edit", "write", "applyPatch"]),
|
|
50
|
+
...(bash === undefined || bash === false ? {} : { bash: bashDeps(bash, options.cwd, cwd) }),
|
|
51
|
+
});
|
|
52
|
+
return Object.freeze({
|
|
53
|
+
read: tools.read,
|
|
54
|
+
edit: tools.edit,
|
|
55
|
+
write: tools.write,
|
|
56
|
+
applyPatch: tools.applyPatch,
|
|
57
|
+
bash: tools.bash,
|
|
58
|
+
fs,
|
|
59
|
+
state: tools.state,
|
|
60
|
+
digest: tools.digest,
|
|
61
|
+
locks: tools.locks,
|
|
62
|
+
clock: tools.clock,
|
|
63
|
+
invalidate: (target) => tools.invalidate(target),
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function checkOptions(options) {
|
|
67
|
+
if (options === null || typeof options !== "object" || Array.isArray(options)) {
|
|
68
|
+
throw new TypeError("createNodeFsTools options must be an object");
|
|
69
|
+
}
|
|
70
|
+
for (const key of Object.keys(options)) {
|
|
71
|
+
if (!KNOWN_OPTIONS.has(key))
|
|
72
|
+
throw new TypeError(`Unknown createNodeFsTools option: ${key}`);
|
|
73
|
+
}
|
|
74
|
+
const state = options.state;
|
|
75
|
+
if (state !== undefined && state !== null && !isReadStateStore(state)) {
|
|
76
|
+
throw new TypeError(`createNodeFsTools state must be a read state store or null: a bundle takes one store, not a per-call factory`);
|
|
77
|
+
}
|
|
78
|
+
for (const [tool, keys] of Object.entries(BUNDLE_SHARED_KEYS_BY_TOOL)) {
|
|
79
|
+
const part = options[tool];
|
|
80
|
+
if (part === undefined || (tool === "bash" && typeof part === "boolean"))
|
|
81
|
+
continue;
|
|
82
|
+
if (part === null || typeof part !== "object" || Array.isArray(part)) {
|
|
83
|
+
throw new TypeError(`createNodeFsTools ${tool} options must be an object`);
|
|
84
|
+
}
|
|
85
|
+
for (const key of keys) {
|
|
86
|
+
if (Object.hasOwn(part, key)) {
|
|
87
|
+
throw new TypeError(`createNodeFsTools ${tool} options cannot set ${key}: set it once at the top level`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function pickDefined(options, keys) {
|
|
93
|
+
const picked = {};
|
|
94
|
+
for (const key of keys) {
|
|
95
|
+
if (options[key] !== undefined)
|
|
96
|
+
picked[key] = options[key];
|
|
97
|
+
}
|
|
98
|
+
return picked;
|
|
99
|
+
}
|
|
100
|
+
function bashDeps(bash, explicitCwd, cwd) {
|
|
101
|
+
const deps = withNodeShellDefaults(bash, cwd);
|
|
102
|
+
const customRunnerNeedsExplicitCwd = bash.runner !== undefined && explicitCwd !== undefined && bash.cwd === undefined;
|
|
103
|
+
if (!customRunnerNeedsExplicitCwd)
|
|
104
|
+
return deps;
|
|
105
|
+
return { ...deps, cwd };
|
|
106
|
+
}
|
|
107
|
+
function isReadStateStore(value) {
|
|
108
|
+
if (value === null || typeof value !== "object")
|
|
109
|
+
return false;
|
|
110
|
+
const store = value;
|
|
111
|
+
return ["get", "put", "delete"].every((key) => typeof store[key] === "function");
|
|
112
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ReadTool, ReadToolDeps, StateNeedsDigestOrDefault } from "@better-fs-tools/read";
|
|
2
|
+
/** Options for createNodeReadTool, all optional. A `state` needs a digest that is not null. */
|
|
3
|
+
export type CreateNodeReadToolOptions<THost = undefined> = Partial<ReadToolDeps<THost>> & StateNeedsDigestOrDefault;
|
|
4
|
+
/**
|
|
5
|
+
* Creates a read tool for local files. `fs` defaults to nodeFileSystem rooted
|
|
6
|
+
* at process.cwd(). `digest` defaults to nodeDigest(); pass `digest: null` to
|
|
7
|
+
* turn observations off.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createNodeReadTool<THost = undefined>(deps?: CreateNodeReadToolOptions<THost>): ReadTool<THost>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { createReadTool } from "@better-fs-tools/read";
|
|
2
|
+
import { nodeDigest } from "./digest.js";
|
|
3
|
+
import { nodeFileSystem } from "./filesystem.js";
|
|
4
|
+
/**
|
|
5
|
+
* Creates a read tool for local files. `fs` defaults to nodeFileSystem rooted
|
|
6
|
+
* at process.cwd(). `digest` defaults to nodeDigest(); pass `digest: null` to
|
|
7
|
+
* turn observations off.
|
|
8
|
+
*/
|
|
9
|
+
export function createNodeReadTool(deps = {}) {
|
|
10
|
+
if (deps === null || typeof deps !== "object" || Array.isArray(deps)) {
|
|
11
|
+
throw new TypeError("read tool dependencies must be an object");
|
|
12
|
+
}
|
|
13
|
+
const fs = deps.fs ?? defaultFileSystem();
|
|
14
|
+
// digest: null narrows the options to the branch without a state.
|
|
15
|
+
if (deps.digest === null)
|
|
16
|
+
return createReadTool({ ...deps, fs, digest: null });
|
|
17
|
+
return createReadTool({ ...deps, fs, digest: deps.digest ?? nodeDigest() });
|
|
18
|
+
}
|
|
19
|
+
function defaultFileSystem() {
|
|
20
|
+
const cwd = process.cwd();
|
|
21
|
+
return nodeFileSystem({ cwd, allowedRoots: [cwd] });
|
|
22
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ApplyPatchTool, ApplyPatchToolDeps, EditTool, EditToolDeps, WriteTool, WriteToolDeps } from "@better-fs-tools/write";
|
|
2
|
+
import type { StateNeedsDigestOrDefault } from "@better-fs-tools/read";
|
|
3
|
+
/** Options for createNodeEditTool, all optional. A `state` needs a digest that is not null. */
|
|
4
|
+
export type CreateNodeEditToolOptions<THost = undefined> = Partial<EditToolDeps<THost>> & StateNeedsDigestOrDefault;
|
|
5
|
+
/** As CreateNodeEditToolOptions, for write. */
|
|
6
|
+
export type CreateNodeWriteToolOptions<THost = undefined> = Partial<WriteToolDeps<THost>> & StateNeedsDigestOrDefault;
|
|
7
|
+
/** As CreateNodeEditToolOptions, for apply_patch. */
|
|
8
|
+
export type CreateNodeApplyPatchToolOptions<THost = undefined> = Partial<ApplyPatchToolDeps<THost>> & StateNeedsDigestOrDefault;
|
|
9
|
+
/**
|
|
10
|
+
* Creates an edit tool for local files. `fs` defaults to nodeFileSystem rooted
|
|
11
|
+
* at process.cwd(). `digest` defaults to nodeDigest(); pass `digest: null` to
|
|
12
|
+
* turn it off. Read-before-write is off unless you pass a `state`; use
|
|
13
|
+
* createNodeFsTools() for a store shared with read.
|
|
14
|
+
*/
|
|
15
|
+
export declare function createNodeEditTool<THost = undefined>(deps?: CreateNodeEditToolOptions<THost>): EditTool<THost>;
|
|
16
|
+
/** Creates a write tool for local files, with the same defaults as createNodeEditTool. */
|
|
17
|
+
export declare function createNodeWriteTool<THost = undefined>(deps?: CreateNodeWriteToolOptions<THost>): WriteTool<THost>;
|
|
18
|
+
/** Creates an apply_patch tool for local files, with the same defaults as createNodeEditTool. */
|
|
19
|
+
export declare function createNodeApplyPatchTool<THost = undefined>(deps?: CreateNodeApplyPatchToolOptions<THost>): ApplyPatchTool<THost>;
|