@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.
@@ -0,0 +1,42 @@
1
+ import { createApplyPatchTool, createEditTool, createWriteTool } from "@better-fs-tools/write";
2
+ import { nodeDigest } from "./digest.js";
3
+ import { nodeFileSystem } from "./filesystem.js";
4
+ /**
5
+ * Creates an edit tool for local files. `fs` defaults to nodeFileSystem rooted
6
+ * at process.cwd(). `digest` defaults to nodeDigest(); pass `digest: null` to
7
+ * turn it off. Read-before-write is off unless you pass a `state`; use
8
+ * createNodeFsTools() for a store shared with read.
9
+ */
10
+ export function createNodeEditTool(deps = {}) {
11
+ checkDeps(deps, "edit");
12
+ const fs = deps.fs ?? defaultFileSystem();
13
+ // digest: null narrows the options to the branch without a state.
14
+ if (deps.digest === null)
15
+ return createEditTool({ ...deps, fs, digest: null });
16
+ return createEditTool({ ...deps, fs, digest: deps.digest ?? nodeDigest() });
17
+ }
18
+ /** Creates a write tool for local files, with the same defaults as createNodeEditTool. */
19
+ export function createNodeWriteTool(deps = {}) {
20
+ checkDeps(deps, "write");
21
+ const fs = deps.fs ?? defaultFileSystem();
22
+ if (deps.digest === null)
23
+ return createWriteTool({ ...deps, fs, digest: null });
24
+ return createWriteTool({ ...deps, fs, digest: deps.digest ?? nodeDigest() });
25
+ }
26
+ /** Creates an apply_patch tool for local files, with the same defaults as createNodeEditTool. */
27
+ export function createNodeApplyPatchTool(deps = {}) {
28
+ checkDeps(deps, "apply_patch");
29
+ const fs = deps.fs ?? defaultFileSystem();
30
+ if (deps.digest === null)
31
+ return createApplyPatchTool({ ...deps, fs, digest: null });
32
+ return createApplyPatchTool({ ...deps, fs, digest: deps.digest ?? nodeDigest() });
33
+ }
34
+ function checkDeps(deps, tool) {
35
+ if (deps === null || typeof deps !== "object" || Array.isArray(deps)) {
36
+ throw new TypeError(`${tool} tool dependencies must be an object`);
37
+ }
38
+ }
39
+ function defaultFileSystem() {
40
+ const cwd = process.cwd();
41
+ return nodeFileSystem({ cwd, allowedRoots: [cwd] });
42
+ }
@@ -0,0 +1,3 @@
1
+ import type { Digest } from "@better-fs-tools/read";
2
+ /** A SHA-256 digest using `node:crypto`. The default digest of the Node tools. */
3
+ export declare function nodeDigest(): Digest;
package/dist/digest.js ADDED
@@ -0,0 +1,21 @@
1
+ import { createHash } from "node:crypto";
2
+ /** A SHA-256 digest using `node:crypto`. The default digest of the Node tools. */
3
+ export function nodeDigest() {
4
+ return Object.freeze({
5
+ id: "sha256",
6
+ create() {
7
+ const hash = createHash("sha256");
8
+ return {
9
+ update(bytes) {
10
+ hash.update(bytes);
11
+ },
12
+ digest() {
13
+ return `sha256:${hash.digest("hex")}`;
14
+ },
15
+ };
16
+ },
17
+ hash(value) {
18
+ return `sha256:${createHash("sha256").update(value, "utf8").digest("hex")}`;
19
+ },
20
+ });
21
+ }
@@ -0,0 +1,15 @@
1
+ import type { FileSystemRootSettings, ListOptions, ListOutcome, MutateOptions, MutationOutcome, StageOutcome, SymlinkPolicy, WritableFileSystem, WriteOptions } from "@better-fs-tools/fs";
2
+ import type { NodeFileSystemOptions } from "./policy.ts";
3
+ /** A WritableFileSystem with every optional method present, and its resolved root options. */
4
+ export interface NodeFileSystem extends WritableFileSystem, FileSystemRootSettings<SymlinkPolicy, "required"> {
5
+ list(path: string, options: ListOptions): Promise<ListOutcome>;
6
+ stage(path: string, bytes: Uint8Array, options: WriteOptions): Promise<StageOutcome>;
7
+ remove(path: string, options: MutateOptions): Promise<MutationOutcome>;
8
+ }
9
+ /**
10
+ * A filesystem over local files on POSIX, confined to the allowed roots, with
11
+ * the deny roots and the symlink policy applied to every call. A file swapped
12
+ * after the checks is not read, a FIFO cannot block a read, and a write
13
+ * replaces a file atomically.
14
+ */
15
+ export declare function nodeFileSystem(options: NodeFileSystemOptions): NodeFileSystem;
@@ -0,0 +1,226 @@
1
+ import { constants } from "node:fs";
2
+ import { lstat, open, opendir, realpath } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { posixPaths } from "@better-fs-tools/fs";
5
+ import { checkRequest, checkResolved, errorCode, fail, hasSymlinkComponent, insideRoots, mapError, matchDenyRoot, nodeContext, nodeIdentity, notAFile, SYMLINK_REJECTED, targetPaths as pathsOf, } from "./policy.js";
6
+ import { nodeStat } from "./stat.js";
7
+ import { nodeWrites } from "./write.js";
8
+ const DESCRIPTOR_READ_BYTES = 64 * 1024;
9
+ /**
10
+ * A filesystem over local files on POSIX, confined to the allowed roots, with
11
+ * the deny roots and the symlink policy applied to every call. A file swapped
12
+ * after the checks is not read, a FIFO cannot block a read, and a write
13
+ * replaces a file atomically.
14
+ */
15
+ export function nodeFileSystem(options) {
16
+ if (process.platform === "win32") {
17
+ throw new TypeError("nodeFileSystem supports POSIX platforms only in this release");
18
+ }
19
+ const context = nodeContext(options);
20
+ const { config } = context;
21
+ const writes = nodeWrites(context);
22
+ return Object.freeze({
23
+ id: config.id,
24
+ cwd: config.cwd,
25
+ allowedRoots: Object.freeze([...config.allowedRoots]),
26
+ denyRoots: Object.freeze([...config.denyRoots]),
27
+ symlinks: config.symlinks,
28
+ identity: "required",
29
+ capabilities: Object.freeze({ streaming: true, identity: true }),
30
+ writeCapabilities: Object.freeze({ atomic: true, compareAndSwap: true, preserveMode: true }),
31
+ paths: posixPaths,
32
+ stat: (path, callOptions = {}) => nodeStat(context, path, callOptions),
33
+ write: writes.write,
34
+ stage: writes.stage,
35
+ remove: writes.remove,
36
+ async open(requested, callOptions = {}) {
37
+ const signal = callOptions.signal;
38
+ if (signal?.aborted)
39
+ return fail({ reason: "aborted" });
40
+ const checked = checkRequest(config, requested);
41
+ if ("error" in checked)
42
+ return fail(checked.error);
43
+ const { lexical } = checked;
44
+ let roots;
45
+ try {
46
+ roots = await context.roots();
47
+ }
48
+ catch (error) {
49
+ return fail(mapError(error, "root-resolution"));
50
+ }
51
+ let target;
52
+ try {
53
+ if (config.symlinks === "reject" && (await hasSymlinkComponent(lexical))) {
54
+ return fail({ reason: "denied", detail: SYMLINK_REJECTED });
55
+ }
56
+ target = await realpath(lexical);
57
+ }
58
+ catch (error) {
59
+ return fail(mapError(error, "resolve"));
60
+ }
61
+ const refused = checkResolved(roots, target);
62
+ if (refused !== null)
63
+ return fail(refused);
64
+ // O_NONBLOCK stops a FIFO from blocking before the descriptor type check.
65
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
66
+ const nonBlock = typeof constants.O_NONBLOCK === "number" ? constants.O_NONBLOCK : 0;
67
+ const targetPaths = pathsOf(config.cwd, target);
68
+ let handle;
69
+ try {
70
+ handle = await open(target, constants.O_RDONLY | noFollow | nonBlock);
71
+ }
72
+ catch (error) {
73
+ // Linux refuses open() on a socket with ENXIO, before the descriptor type check.
74
+ if (errorCode(error) === "ENXIO") {
75
+ const stats = await lstat(target, { bigint: true }).catch(() => null);
76
+ if (stats !== null && !stats.isFile())
77
+ return fail(notAFile(stats, targetPaths));
78
+ }
79
+ return fail(mapError(error, "open", targetPaths));
80
+ }
81
+ try {
82
+ const stats = await handle.stat({ bigint: true });
83
+ if (!stats.isFile()) {
84
+ await handle.close();
85
+ return fail(notAFile(stats, targetPaths));
86
+ }
87
+ if (stats.size > BigInt(Number.MAX_SAFE_INTEGER)) {
88
+ await handle.close();
89
+ return fail({
90
+ reason: "denied",
91
+ detail: "the reported file size is outside the safe numeric range",
92
+ });
93
+ }
94
+ return { ok: true, file: nodeOpenFile(handle, targetPaths, stats, signal) };
95
+ }
96
+ catch (error) {
97
+ await handle.close().catch(() => { });
98
+ return fail(mapError(error, "inspect", targetPaths));
99
+ }
100
+ },
101
+ async list(directory, listOptions) {
102
+ if (listOptions.signal?.aborted)
103
+ return fail({ reason: "aborted" });
104
+ const lexical = path.resolve(config.cwd, directory);
105
+ if (!insideRoots(config.allowedRoots, lexical)) {
106
+ return fail({ reason: "outside-allowed-roots" });
107
+ }
108
+ const dangerous = matchDenyRoot(lexical, config.denyRoots);
109
+ if (dangerous !== null)
110
+ return fail({ reason: "dangerous-path", detail: dangerous });
111
+ let roots;
112
+ let target;
113
+ try {
114
+ roots = await context.roots();
115
+ if (config.symlinks === "reject" && (await hasSymlinkComponent(lexical))) {
116
+ return fail({ reason: "denied", detail: "symlinked directory" });
117
+ }
118
+ target = await realpath(lexical);
119
+ }
120
+ catch (error) {
121
+ return fail(mapError(error, "list-resolve"));
122
+ }
123
+ if (!insideRoots(roots.allowed, target))
124
+ return fail({ reason: "outside-allowed-roots" });
125
+ if (matchDenyRoot(target, roots.denied) !== null)
126
+ return fail({ reason: "dangerous-path" });
127
+ const entries = [];
128
+ let truncated = false;
129
+ try {
130
+ const opened = await opendir(target);
131
+ try {
132
+ for await (const entry of opened) {
133
+ if (entries.length >= listOptions.limit) {
134
+ truncated = true;
135
+ break;
136
+ }
137
+ entries.push({
138
+ name: entry.name,
139
+ type: entry.isFile() ? "file" : entry.isDirectory() ? "directory" : "other",
140
+ });
141
+ }
142
+ }
143
+ finally {
144
+ await closeDirectoryIfStillOpen(opened);
145
+ }
146
+ }
147
+ catch (error) {
148
+ return fail(mapError(error, "list"));
149
+ }
150
+ return { ok: true, entries, truncated };
151
+ },
152
+ });
153
+ }
154
+ function nodeOpenFile(handle, target, stats, signal) {
155
+ const identity = nodeIdentity(stats);
156
+ let consumed = false;
157
+ let closed = false;
158
+ return {
159
+ info: {
160
+ resolvedPath: target.resolvedPath,
161
+ displayPath: target.displayPath,
162
+ size: Number(stats.size),
163
+ mtimeMs: Number(stats.mtimeNs) / 1_000_000,
164
+ identity,
165
+ mimeType: null,
166
+ version: identity,
167
+ },
168
+ bytes() {
169
+ if (consumed)
170
+ throw new TypeError("descriptor byte source is single-use");
171
+ consumed = true;
172
+ let stopped = false;
173
+ return {
174
+ [Symbol.asyncIterator]() {
175
+ return {
176
+ async next() {
177
+ if (stopped || closed)
178
+ return { done: true, value: undefined };
179
+ if (signal?.aborted)
180
+ return { done: true, value: undefined };
181
+ // A fresh buffer per chunk: a consumer may keep a chunk after asking for the next.
182
+ const buffer = new Uint8Array(DESCRIPTOR_READ_BYTES);
183
+ const { bytesRead } = await handle.read(buffer, 0, buffer.byteLength, null);
184
+ if (stopped || closed || bytesRead === 0) {
185
+ stopped = true;
186
+ return { done: true, value: undefined };
187
+ }
188
+ return { done: false, value: buffer.subarray(0, bytesRead) };
189
+ },
190
+ async return() {
191
+ stopped = true;
192
+ return { done: true, value: undefined };
193
+ },
194
+ };
195
+ },
196
+ };
197
+ },
198
+ async verify() {
199
+ if (closed)
200
+ return fail({ reason: "io", detail: "the handle is closed" });
201
+ try {
202
+ const current = await handle.stat({ bigint: true });
203
+ return { ok: true, changed: nodeIdentity(current) !== identity };
204
+ }
205
+ catch (error) {
206
+ return fail(mapError(error, "verify"));
207
+ }
208
+ },
209
+ async close() {
210
+ if (closed)
211
+ return;
212
+ closed = true;
213
+ await handle.close().catch(() => { });
214
+ },
215
+ };
216
+ }
217
+ async function closeDirectoryIfStillOpen(directory) {
218
+ try {
219
+ // Bun's Dir.close() resolves to undefined, so this cannot chain.
220
+ await directory.close();
221
+ }
222
+ catch (error) {
223
+ if (errorCode(error) !== "ERR_DIR_CLOSED")
224
+ throw error;
225
+ }
226
+ }
@@ -0,0 +1,13 @@
1
+ export { nodeCommandRunner } from "./command-runner.ts";
2
+ export type { NodeCommandRunnerOptions } from "./command-runner.ts";
3
+ export { createNodeBashTool } from "./create-node-bash-tool.ts";
4
+ export { createNodeFsTools } from "./create-node-fs-tools.ts";
5
+ export type { CreateNodeFsToolsOptions, NodeFsTools, NodeFsToolsBashOptions, NodeFsToolsWithBash, } from "./create-node-fs-tools.ts";
6
+ export { createNodeReadTool } from "./create-node-read-tool.ts";
7
+ export type { CreateNodeReadToolOptions } from "./create-node-read-tool.ts";
8
+ export { createNodeApplyPatchTool, createNodeEditTool, createNodeWriteTool, } from "./create-node-write-tools.ts";
9
+ export type { CreateNodeApplyPatchToolOptions, CreateNodeEditToolOptions, CreateNodeWriteToolOptions, } from "./create-node-write-tools.ts";
10
+ export { nodeDigest } from "./digest.ts";
11
+ export { nodeFileSystem } from "./filesystem.ts";
12
+ export type { NodeFileSystem } from "./filesystem.ts";
13
+ export type { NodeFileSystemOptions } from "./policy.ts";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { nodeCommandRunner } from "./command-runner.js";
2
+ export { createNodeBashTool } from "./create-node-bash-tool.js";
3
+ export { createNodeFsTools } from "./create-node-fs-tools.js";
4
+ export { createNodeReadTool } from "./create-node-read-tool.js";
5
+ export { createNodeApplyPatchTool, createNodeEditTool, createNodeWriteTool, } from "./create-node-write-tools.js";
6
+ export { nodeDigest } from "./digest.js";
7
+ export { nodeFileSystem } from "./filesystem.js";
@@ -0,0 +1,73 @@
1
+ import type { BigIntStats } from "node:fs";
2
+ import type { FileSystemError, FileSystemRootOptions, SymlinkPolicy } from "@better-fs-tools/fs";
3
+ /**
4
+ * Options for nodeFileSystem. `cwd` defaults to process.cwd(), and a relative
5
+ * `cwd` resolves against it. `denyRoots` are added to /dev, /proc, and /sys,
6
+ * and a path under any of them is refused as dangerous-path. `symlinks`
7
+ * defaults to "follow-within-roots". `identity` is always "required". `id`
8
+ * defaults to "node".
9
+ */
10
+ export interface NodeFileSystemOptions extends FileSystemRootOptions<SymlinkPolicy, "required"> {
11
+ /** How to replace a file with more than one hard link. Default "refuse". "in-place" truncates and writes, which is not atomic. */
12
+ readonly hardLinks?: "refuse" | "in-place";
13
+ /**
14
+ * Mode of a new file, exactly: the umask does not apply to a mode you set.
15
+ * Default 0o666 less the process umask (0o644 under the usual umask 0o022).
16
+ */
17
+ readonly newFileMode?: number;
18
+ /**
19
+ * Mode of a directory that createParents makes, exactly. Default 0o777 less
20
+ * the process umask (0o755 under 0o022).
21
+ */
22
+ readonly newDirectoryMode?: number;
23
+ }
24
+ export interface NodeConfig {
25
+ readonly id: string;
26
+ readonly cwd: string;
27
+ readonly allowedRoots: readonly string[];
28
+ readonly denyRoots: readonly string[];
29
+ readonly symlinks: SymlinkPolicy;
30
+ readonly hardLinks: "refuse" | "in-place";
31
+ /** null: the default, which depends on the umask when the file is made. */
32
+ readonly newFileMode: number | null;
33
+ /** null: the default, which depends on the umask when the directory is made. */
34
+ readonly newDirectoryMode: number | null;
35
+ }
36
+ export interface Roots {
37
+ readonly allowed: readonly string[];
38
+ readonly denied: readonly string[];
39
+ }
40
+ export interface NodeContext {
41
+ readonly config: NodeConfig;
42
+ roots(): Promise<Roots>;
43
+ }
44
+ export interface TargetPaths {
45
+ readonly resolvedPath: string;
46
+ readonly displayPath: string;
47
+ }
48
+ export declare function nodeContext(options: NodeFileSystemOptions): NodeContext;
49
+ export declare function checkRequest(config: NodeConfig, requested: string): {
50
+ readonly lexical: string;
51
+ } | {
52
+ readonly error: FileSystemError;
53
+ };
54
+ export declare function checkResolved(roots: Roots, target: string): FileSystemError | null;
55
+ export declare const SYMLINK_REJECTED = "the path contains a symbolic link and policy rejects symlinks";
56
+ export declare function createModes(config: NodeConfig): {
57
+ readonly file: number;
58
+ readonly directory: number;
59
+ };
60
+ export declare function isMode(value: unknown): value is number;
61
+ export declare function fail<TError>(error: TError): {
62
+ readonly ok: false;
63
+ readonly error: TError;
64
+ };
65
+ export declare function displayPathOf(cwd: string, resolvedPath: string): string;
66
+ export declare function targetPaths(cwd: string, resolvedPath: string): TargetPaths;
67
+ export declare function insideRoots(roots: readonly string[], candidate: string): boolean;
68
+ export declare function matchDenyRoot(candidate: string, denyRoots: readonly string[]): string | null;
69
+ export declare function hasSymlinkComponent(candidate: string): Promise<boolean>;
70
+ export declare function nodeIdentity(stats: BigIntStats): string;
71
+ export declare function notAFile(stats: BigIntStats, target: TargetPaths): FileSystemError;
72
+ export declare function mapError(error: unknown, phase: string, target?: TargetPaths): FileSystemError;
73
+ export declare function errorCode(error: unknown): string | null;
package/dist/policy.js ADDED
@@ -0,0 +1,219 @@
1
+ import { lstat, realpath } from "node:fs/promises";
2
+ import path from "node:path";
3
+ const DEFAULT_DENY_ROOTS = Object.freeze(["/dev", "/proc", "/sys"]);
4
+ export function nodeContext(options) {
5
+ const config = resolveOptions(options);
6
+ let rootResolution;
7
+ const roots = async () => {
8
+ const pending = rootResolution ??
9
+ (async () => ({
10
+ allowed: await Promise.all(config.allowedRoots.map((root) => realpath(root))),
11
+ denied: await Promise.all(config.denyRoots.map(async (root) => {
12
+ try {
13
+ return await realpath(root);
14
+ }
15
+ catch (error) {
16
+ if (errorCode(error) === "ENOENT")
17
+ return root;
18
+ throw error;
19
+ }
20
+ })),
21
+ }))();
22
+ rootResolution = pending;
23
+ try {
24
+ return await pending;
25
+ }
26
+ catch (error) {
27
+ rootResolution = undefined;
28
+ throw error;
29
+ }
30
+ };
31
+ return { config, roots };
32
+ }
33
+ export function checkRequest(config, requested) {
34
+ // The raw request is checked too, so /dev/... is refused before the filesystem is touched.
35
+ const rawDangerous = matchDenyRoot(requested, config.denyRoots);
36
+ if (rawDangerous !== null)
37
+ return { error: { reason: "dangerous-path", detail: rawDangerous } };
38
+ const lexical = path.resolve(config.cwd, requested);
39
+ if (!insideRoots(config.allowedRoots, lexical)) {
40
+ return { error: { reason: "outside-allowed-roots" } };
41
+ }
42
+ const lexicalDangerous = matchDenyRoot(lexical, config.denyRoots);
43
+ if (lexicalDangerous !== null) {
44
+ return { error: { reason: "dangerous-path", detail: lexicalDangerous } };
45
+ }
46
+ return { lexical };
47
+ }
48
+ export function checkResolved(roots, target) {
49
+ if (!insideRoots(roots.allowed, target))
50
+ return { reason: "outside-allowed-roots" };
51
+ const dangerous = matchDenyRoot(target, roots.denied);
52
+ return dangerous === null ? null : { reason: "dangerous-path", detail: dangerous };
53
+ }
54
+ export const SYMLINK_REJECTED = "the path contains a symbolic link and policy rejects symlinks";
55
+ function resolveOptions(options) {
56
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
57
+ throw new TypeError("nodeFileSystem options must be an object");
58
+ }
59
+ const cwd = path.resolve(options.cwd ?? process.cwd());
60
+ const roots = options.allowedRoots;
61
+ if (!Array.isArray(roots) ||
62
+ roots.length === 0 ||
63
+ roots.some((root) => typeof root !== "string" || root === "")) {
64
+ throw new TypeError("allowedRoots must contain at least one non-empty path");
65
+ }
66
+ if (options.identity !== undefined && options.identity !== "required") {
67
+ throw new TypeError('identity must be "required": Node always reports device and inode');
68
+ }
69
+ const symlinks = options.symlinks ?? "follow-within-roots";
70
+ if (symlinks !== "follow-within-roots" && symlinks !== "reject") {
71
+ throw new TypeError('symlinks must be "follow-within-roots" or "reject"');
72
+ }
73
+ const hardLinks = options.hardLinks ?? "refuse";
74
+ if (hardLinks !== "refuse" && hardLinks !== "in-place") {
75
+ throw new TypeError('hardLinks must be "refuse" or "in-place"');
76
+ }
77
+ const newFileMode = options.newFileMode ?? null;
78
+ const newDirectoryMode = options.newDirectoryMode ?? null;
79
+ if (newFileMode !== null && !isMode(newFileMode)) {
80
+ throw new TypeError("newFileMode must be an integer from 0 to 0o7777");
81
+ }
82
+ if (newDirectoryMode !== null && !isMode(newDirectoryMode)) {
83
+ throw new TypeError("newDirectoryMode must be an integer from 0 to 0o7777");
84
+ }
85
+ const id = options.id ?? "node";
86
+ if (typeof id !== "string" || id === "")
87
+ throw new TypeError("id must be a non-empty string");
88
+ return {
89
+ id,
90
+ cwd,
91
+ allowedRoots: roots.map((root) => path.resolve(cwd, root)),
92
+ denyRoots: [
93
+ ...DEFAULT_DENY_ROOTS,
94
+ ...(options.denyRoots ?? []).map((root) => path.resolve(cwd, root)),
95
+ ],
96
+ symlinks,
97
+ hardLinks,
98
+ newFileMode,
99
+ newDirectoryMode,
100
+ };
101
+ }
102
+ export function createModes(config) {
103
+ if (config.newFileMode !== null && config.newDirectoryMode !== null) {
104
+ return { file: config.newFileMode, directory: config.newDirectoryMode };
105
+ }
106
+ const umask = process.umask();
107
+ return {
108
+ file: config.newFileMode ?? 0o666 & ~umask,
109
+ directory: config.newDirectoryMode ?? 0o777 & ~umask,
110
+ };
111
+ }
112
+ export function isMode(value) {
113
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 0o7777;
114
+ }
115
+ export function fail(error) {
116
+ return { ok: false, error };
117
+ }
118
+ export function displayPathOf(cwd, resolvedPath) {
119
+ return path.relative(cwd, resolvedPath) || path.basename(resolvedPath);
120
+ }
121
+ export function targetPaths(cwd, resolvedPath) {
122
+ return { resolvedPath, displayPath: displayPathOf(cwd, resolvedPath) };
123
+ }
124
+ function containsPath(root, candidate) {
125
+ const relative = path.relative(root, candidate);
126
+ return (relative === "" ||
127
+ (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative)));
128
+ }
129
+ export function insideRoots(roots, candidate) {
130
+ return roots.some((root) => containsPath(root, candidate));
131
+ }
132
+ export function matchDenyRoot(candidate, denyRoots) {
133
+ if (!candidate.startsWith("/"))
134
+ return null;
135
+ for (const root of denyRoots) {
136
+ const normalized = root.replace(/\/$/u, "") || "/";
137
+ if (candidate === normalized)
138
+ return root;
139
+ if (normalized === "/" ? candidate.startsWith("/") : candidate.startsWith(`${normalized}/`)) {
140
+ return root;
141
+ }
142
+ }
143
+ return null;
144
+ }
145
+ export async function hasSymlinkComponent(candidate) {
146
+ const parsed = path.parse(candidate);
147
+ const relative = path.relative(parsed.root, candidate);
148
+ let current = parsed.root;
149
+ for (const segment of relative.split(path.sep).filter(Boolean)) {
150
+ current = path.join(current, segment);
151
+ let stats;
152
+ try {
153
+ stats = await lstat(current);
154
+ }
155
+ catch (error) {
156
+ if (errorCode(error) === "ENOENT")
157
+ return false;
158
+ throw error;
159
+ }
160
+ if (stats.isSymbolicLink())
161
+ return true;
162
+ }
163
+ return false;
164
+ }
165
+ export function nodeIdentity(stats) {
166
+ return `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
167
+ }
168
+ export function notAFile(stats, target) {
169
+ const kind = stats.isDirectory()
170
+ ? "directory"
171
+ : stats.isFIFO()
172
+ ? "fifo"
173
+ : stats.isSocket()
174
+ ? "socket"
175
+ : stats.isCharacterDevice() || stats.isBlockDevice()
176
+ ? "device"
177
+ : "other";
178
+ const detail = stats.isCharacterDevice()
179
+ ? "character device"
180
+ : stats.isBlockDevice()
181
+ ? "block device"
182
+ : undefined;
183
+ return detail === undefined
184
+ ? { reason: "not-a-file", kind, target }
185
+ : { reason: "not-a-file", kind, target, detail };
186
+ }
187
+ export function mapError(error, phase, target) {
188
+ const code = errorCode(error);
189
+ const cause = { code: code ?? "UNKNOWN", phase };
190
+ switch (code) {
191
+ case "ABORT_ERR":
192
+ return { reason: "aborted", cause };
193
+ case "ENOENT":
194
+ case "ENOTDIR":
195
+ return { reason: "not-found", cause };
196
+ case "EACCES":
197
+ case "EPERM":
198
+ return { reason: "permission-denied", cause };
199
+ case "ELOOP":
200
+ return { reason: "denied", detail: "too many symbolic links", cause };
201
+ case "EISDIR":
202
+ return { reason: "not-a-file", kind: "directory", target: target ?? null, cause };
203
+ case "ENAMETOOLONG":
204
+ return { reason: "denied", detail: "the path is too long", cause };
205
+ default:
206
+ return { reason: "io", cause };
207
+ }
208
+ }
209
+ export function errorCode(error) {
210
+ if (error !== null &&
211
+ typeof error === "object" &&
212
+ "code" in error &&
213
+ typeof error.code === "string") {
214
+ return error.code;
215
+ }
216
+ if (error instanceof Error && error.name === "AbortError")
217
+ return "ABORT_ERR";
218
+ return null;
219
+ }
package/dist/stat.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import type { OpenOptions, StatOutcome } from "@better-fs-tools/fs";
2
+ import type { NodeContext } from "./policy.ts";
3
+ export declare function nodeStat(context: NodeContext, requested: string, options?: OpenOptions): Promise<StatOutcome>;