@kawaz/sockat 0.0.0 → 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/dist/fsx.js ADDED
@@ -0,0 +1,149 @@
1
+ import fs from "node:fs";
2
+ import nodePath from "node:path";
3
+ import { errnoCode } from "./errors.js";
4
+ import { isAbs, joinUnder, splitPath } from "./paths.js";
5
+ export function sameId(a, b) {
6
+ return a.dev === b.dev && a.ino === b.ino;
7
+ }
8
+ function idOf(st) {
9
+ return { dev: st.dev, ino: st.ino };
10
+ }
11
+ /**
12
+ * Runs a file system call, turning an error with an errno into a value.
13
+ * An error without one (a bug, not the file system's answer) is thrown.
14
+ */
15
+ export function attempt(f) {
16
+ try {
17
+ return { ok: true, value: f() };
18
+ }
19
+ catch (e) {
20
+ const code = errnoCode(e);
21
+ if (code === undefined) {
22
+ throw e;
23
+ }
24
+ return { ok: false, code };
25
+ }
26
+ }
27
+ export function lstat(path) {
28
+ return attempt(() => fs.lstatSync(path, { bigint: true }));
29
+ }
30
+ export function fstat(fd) {
31
+ return attempt(() => fs.fstatSync(fd, { bigint: true }));
32
+ }
33
+ /** The (st_dev, st_ino) of what path names (following symlinks), null when it cannot be looked up. */
34
+ export function statId(path) {
35
+ const r = attempt(() => fs.statSync(path, { bigint: true }));
36
+ return r.ok ? idOf(r.value) : null;
37
+ }
38
+ export function lstatId(path) {
39
+ const r = lstat(path);
40
+ return r.ok ? idOf(r.value) : null;
41
+ }
42
+ export function fstatId(fd) {
43
+ const r = fstat(fd);
44
+ return r.ok ? idOf(r.value) : null;
45
+ }
46
+ /** The effective uid (B's name and the checks of B, D and their ancestors). */
47
+ export function euid() {
48
+ if (process.geteuid === undefined) {
49
+ throw new Error("sockat needs a POSIX system (process.geteuid)");
50
+ }
51
+ return process.geteuid();
52
+ }
53
+ /** Whether st is a directory owned by the effective uid. */
54
+ export function isOurDir(st) {
55
+ return st.isDirectory() && st.uid === BigInt(euid());
56
+ }
57
+ /** The permission bits of st (mode & 07777). */
58
+ export function modeBits(st) {
59
+ return Number(st.mode & 4095n);
60
+ }
61
+ /**
62
+ * dir as a real path (symlinks resolved, absolute), by realpath(3): the
63
+ * system looks up every component, ".." included, as the kernel does (a
64
+ * "sym/.." is the parent of the symlink's target, not the directory the
65
+ * symlink is in). The path is never folded as a string (SPEC "長いパスの経路と
66
+ * 試す順番": パスを字句で畳まない).
67
+ */
68
+ export function realDir(dir) {
69
+ return attempt(() => fs.realpathSync.native(dir));
70
+ }
71
+ /**
72
+ * The socket file at path with its directory resolved to a real path, so a
73
+ * later change of the cwd or of a symlink on the way does not retarget it.
74
+ */
75
+ export function realFile(path) {
76
+ const parts = splitPath(path);
77
+ if (parts === null) {
78
+ return { ok: false, code: "EINVAL" };
79
+ }
80
+ const real = realDir(parts.dir);
81
+ return real.ok ? { ok: true, value: joinUnder(real.value, parts.name) } : real;
82
+ }
83
+ /**
84
+ * How many symlinks socketAt follows before it gives up with ELOOP: at least
85
+ * what the kernels follow in a path (40 on Linux, 32 on macOS).
86
+ */
87
+ const maxFollow = 40;
88
+ /**
89
+ * The socket file at file (whose directory is a real path): when its last
90
+ * component is a symlink, followed as bind(2) follows it on the systems
91
+ * where it does (SPEC "remove", "ForBind の SocketFile"), each target taken
92
+ * relative to the directory of its symlink and its directory resolved to a
93
+ * real path. The real path of the socket reached and its (st_dev, st_ino),
94
+ * or the errno: the lstat's (ENOENT, ...), ENOTSOCK when what is reached is
95
+ * not a socket, ELOOP after maxFollow symlinks.
96
+ */
97
+ export function socketAt(file) {
98
+ let current = file;
99
+ for (let i = 0; i <= maxFollow; i++) {
100
+ const st = lstat(current);
101
+ if (!st.ok) {
102
+ return st;
103
+ }
104
+ if (st.value.isSocket()) {
105
+ return { ok: true, value: { file: current, id: idOf(st.value) } };
106
+ }
107
+ if (!st.value.isSymbolicLink()) {
108
+ return { ok: false, code: "ENOTSOCK" };
109
+ }
110
+ const link = current;
111
+ const target = attempt(() => fs.readlinkSync(link));
112
+ if (!target.ok) {
113
+ return target;
114
+ }
115
+ const next = realFile(isAbs(target.value) ? target.value : `${nodePath.dirname(current)}/${target.value}`);
116
+ if (!next.ok) {
117
+ return next;
118
+ }
119
+ current = next.value;
120
+ }
121
+ return { ok: false, code: "ELOOP" };
122
+ }
123
+ /** How B and D are opened: for reading (D takes its lock, sweep lists B), never through a symlink. */
124
+ export const dirOpenFlags = fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW;
125
+ /**
126
+ * Linux's O_PATH (not in fs.constants): opens a directory with search
127
+ * permission alone (the socket's directory for proc-direct, the parent of B).
128
+ */
129
+ export const oPath = 0o10000000;
130
+ /** The path through which the entry name of dir is reached. */
131
+ export function entry(dir, name) {
132
+ return dir.at !== null ? `${dir.at}/${name}` : joinUnder(dir.real, name);
133
+ }
134
+ /**
135
+ * <proc>/self/fd/<fd>, when proc is set and it names the directory held by
136
+ * fd (the same (st_dev, st_ino) as fd's); null otherwise.
137
+ */
138
+ export function procAt(proc, fd, id) {
139
+ if (proc === "") {
140
+ return null;
141
+ }
142
+ const at = `${proc}/self/fd/${fd}`;
143
+ const seen = statId(at);
144
+ return seen !== null && sameId(seen, id) ? at : null;
145
+ }
146
+ /** Closes fd, ignoring an error (an fd of ours closed once). */
147
+ export function closeQuietly(fd) {
148
+ attempt(() => fs.closeSync(fd));
149
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * sockat: bind and connect Unix domain sockets at paths longer than
3
+ * sun_path, with node:net (Node and Bun). A path the standard takes as it is
4
+ * goes to it unchanged; a longer one is spelt shorter through a directory
5
+ * this user's processes share, or relative to the socket's directory, and
6
+ * that spelling goes to the standard.
7
+ *
8
+ * The behaviour is the language-independent specification's:
9
+ * https://github.com/kawaz/sockat/blob/main/docs/SPEC.md
10
+ *
11
+ * @module
12
+ */
13
+ import type net from "node:net";
14
+ import type { Bound, Connected, ForBind, ForConnect, Options } from "./types.ts";
15
+ export type { Bound, Connected, ForBind, ForConnect, Options, Skip, SocketFile, Spelling } from "./types.ts";
16
+ export type { RouteDiagnostics, SystemError } from "./errors.ts";
17
+ /**
18
+ * Binds and listens at path, as `net.createServer().listen(path)` does,
19
+ * and resolves once it is listening. A path the standard takes (at most
20
+ * sun_path less one byte; 108 bytes for Node on Linux) goes to it as it is.
21
+ *
22
+ * The listener's `address()` returns `path`. Closing it unlinks the spelling
23
+ * the kernel keeps: for a long path through a symlink to the socket file
24
+ * (Spelling `Linked` with `removable: false`), that removes the symlink and
25
+ * leaves the socket file.
26
+ */
27
+ export declare function bind(path: string): Promise<net.Server>;
28
+ /**
29
+ * Connects to path, as `net.connect(path)` does, and resolves once it is
30
+ * connected.
31
+ */
32
+ export declare function connect(path: string): Promise<net.Socket>;
33
+ /**
34
+ * bind, with what the spelling is good for, how to remove the socket file
35
+ * (`file.remove()`), and diagnostics. The error carries `route` and
36
+ * `skipped`.
37
+ *
38
+ * Unlike the specification, closing the listener unlinks the spelling (the
39
+ * runtimes give no way to stop it): call `file.remove()` before closing it.
40
+ */
41
+ export declare function bindEx(path: string, options?: Options): Promise<Bound<net.Server>>;
42
+ /** connect, with diagnostics. The error carries `route` and `skipped`. */
43
+ export declare function connectEx(path: string, options?: Options): Promise<Connected<net.Socket>>;
44
+ /**
45
+ * Spells path so that the standard can bind it (`net.Server.listen`,
46
+ * `Bun.listen`, `Bun.serve({ unix })`, ...): path itself where the standard
47
+ * takes it, otherwise a spelling naming the same place for as long as its
48
+ * `spelling` says. Nothing is bound. ENAMETOOLONG where no spelling fits.
49
+ */
50
+ export declare function resolveForBind(path: string, options?: Options): ForBind;
51
+ /**
52
+ * Spells path so that the standard can connect to it (`net.connect`,
53
+ * `fetch(url, { unix })`, ...), as many times as you like until `cleanup()`.
54
+ * `usableCrossUid` is not looked at.
55
+ */
56
+ export declare function resolveForConnect(path: string, options?: Options): ForConnect;
57
+ /**
58
+ * Removes the directories that processes which have ended left in this
59
+ * user's sockat directories of /tmp, $XDG_RUNTIME_DIR and $TMPDIR. Never
60
+ * called for you.
61
+ */
62
+ export declare function sweep(): void;
63
+ /** sweep for the directory given as `Options.base`, which the application that manages it sweeps. */
64
+ export declare function sweepBase(path: string): void;
package/dist/index.js ADDED
@@ -0,0 +1,69 @@
1
+ import { bindExIn, bindIn, connectExIn, connectIn } from "./netapi.js";
2
+ import { resolveForBindIn, resolveForConnectIn } from "./resolve.js";
3
+ import { forNodeNet } from "./route.js";
4
+ import { sweepBaseIn, sweepIn } from "./sweep.js";
5
+ import { defaultWorld } from "./world.js";
6
+ /**
7
+ * Binds and listens at path, as `net.createServer().listen(path)` does,
8
+ * and resolves once it is listening. A path the standard takes (at most
9
+ * sun_path less one byte; 108 bytes for Node on Linux) goes to it as it is.
10
+ *
11
+ * The listener's `address()` returns `path`. Closing it unlinks the spelling
12
+ * the kernel keeps: for a long path through a symlink to the socket file
13
+ * (Spelling `Linked` with `removable: false`), that removes the symlink and
14
+ * leaves the socket file.
15
+ */
16
+ export function bind(path) {
17
+ return bindIn(defaultWorld(), path);
18
+ }
19
+ /**
20
+ * Connects to path, as `net.connect(path)` does, and resolves once it is
21
+ * connected.
22
+ */
23
+ export function connect(path) {
24
+ return connectIn(defaultWorld(), path);
25
+ }
26
+ /**
27
+ * bind, with what the spelling is good for, how to remove the socket file
28
+ * (`file.remove()`), and diagnostics. The error carries `route` and
29
+ * `skipped`.
30
+ *
31
+ * Unlike the specification, closing the listener unlinks the spelling (the
32
+ * runtimes give no way to stop it): call `file.remove()` before closing it.
33
+ */
34
+ export function bindEx(path, options = {}) {
35
+ return bindExIn(defaultWorld(), path, options);
36
+ }
37
+ /** connect, with diagnostics. The error carries `route` and `skipped`. */
38
+ export function connectEx(path, options = {}) {
39
+ return connectExIn(defaultWorld(), path, options);
40
+ }
41
+ /**
42
+ * Spells path so that the standard can bind it (`net.Server.listen`,
43
+ * `Bun.listen`, `Bun.serve({ unix })`, ...): path itself where the standard
44
+ * takes it, otherwise a spelling naming the same place for as long as its
45
+ * `spelling` says. Nothing is bound. ENAMETOOLONG where no spelling fits.
46
+ */
47
+ export function resolveForBind(path, options = {}) {
48
+ return resolveForBindIn(defaultWorld(), path, options, forNodeNet);
49
+ }
50
+ /**
51
+ * Spells path so that the standard can connect to it (`net.connect`,
52
+ * `fetch(url, { unix })`, ...), as many times as you like until `cleanup()`.
53
+ * `usableCrossUid` is not looked at.
54
+ */
55
+ export function resolveForConnect(path, options = {}) {
56
+ return resolveForConnectIn(defaultWorld(), path, options, forNodeNet);
57
+ }
58
+ /**
59
+ * Removes the directories that processes which have ended left in this
60
+ * user's sockat directories of /tmp, $XDG_RUNTIME_DIR and $TMPDIR. Never
61
+ * called for you.
62
+ */
63
+ export function sweep() {
64
+ sweepIn(defaultWorld());
65
+ }
66
+ /** sweep for the directory given as `Options.base`, which the application that manages it sweeps. */
67
+ export function sweepBase(path) {
68
+ sweepBaseIn(defaultWorld(), path);
69
+ }
package/dist/lock.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import type { LockMethod } from "./config.ts";
2
+ /** The outcome of taking a lock on D. */
3
+ export type Locked = {
4
+ readonly ok: true;
5
+ readonly fd: number;
6
+ }
7
+ /** Another process holds the other kind of lock (busy), or no lock can be taken here (unavailable). */
8
+ | {
9
+ readonly ok: false;
10
+ readonly why: "busy" | "unavailable";
11
+ readonly code: string;
12
+ };
13
+ /**
14
+ * Opens the directory at path (not through a symlink) and takes a lock of
15
+ * the kind on it without waiting: the fd holds the lock until it is closed.
16
+ *
17
+ * - bsd: opened O_SHLOCK / O_EXLOCK | O_NONBLOCK (EAGAIN when it is held
18
+ * otherwise)
19
+ * - flock-command: the fd is handed to flock(1) as its fd 3 (`flock -s -n 3`
20
+ * / `-x`). The lock is on the open file description, which the parent's fd
21
+ * keeps after flock(1) has exited (measured on Linux with Node and Bun,
22
+ * glibc and busybox)
23
+ * - none: no lock can be taken
24
+ *
25
+ * An error opening path (ENOENT, ELOOP, ...) comes back as unavailable with
26
+ * its code.
27
+ */
28
+ export declare function openLocked(path: string, method: LockMethod, kind: "shared" | "exclusive"): Locked;
package/dist/lock.js ADDED
@@ -0,0 +1,61 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import { attempt, closeQuietly, dirOpenFlags } from "./fsx.js";
4
+ // The flock(2) of D (DR-0002 "D のロック"), with no native code: a shared
5
+ // lock for as long as the process holds D, an exclusive one for sweep to tell
6
+ // a D whose process has ended.
7
+ /**
8
+ * O_SHLOCK and O_EXLOCK of Apple's systems, FreeBSD, NetBSD and OpenBSD (not
9
+ * in fs.constants). Each system's sys/fcntl.h defines them with the same
10
+ * values: O_SHLOCK 0x0010, O_EXLOCK 0x0020. Opening with one takes the
11
+ * flock(2) lock of that kind, which other processes' flock(2) see.
12
+ */
13
+ const oShlock = 0x10;
14
+ const oExlock = 0x20;
15
+ /**
16
+ * Opens the directory at path (not through a symlink) and takes a lock of
17
+ * the kind on it without waiting: the fd holds the lock until it is closed.
18
+ *
19
+ * - bsd: opened O_SHLOCK / O_EXLOCK | O_NONBLOCK (EAGAIN when it is held
20
+ * otherwise)
21
+ * - flock-command: the fd is handed to flock(1) as its fd 3 (`flock -s -n 3`
22
+ * / `-x`). The lock is on the open file description, which the parent's fd
23
+ * keeps after flock(1) has exited (measured on Linux with Node and Bun,
24
+ * glibc and busybox)
25
+ * - none: no lock can be taken
26
+ *
27
+ * An error opening path (ENOENT, ELOOP, ...) comes back as unavailable with
28
+ * its code.
29
+ */
30
+ export function openLocked(path, method, kind) {
31
+ switch (method.kind) {
32
+ case "none":
33
+ return { ok: false, why: "unavailable", code: "ENOLCK" };
34
+ case "bsd": {
35
+ const flags = dirOpenFlags | (kind === "shared" ? oShlock : oExlock) | fs.constants.O_NONBLOCK;
36
+ const r = attempt(() => fs.openSync(path, flags));
37
+ if (r.ok) {
38
+ return { ok: true, fd: r.value };
39
+ }
40
+ return { ok: false, why: r.code === "EAGAIN" || r.code === "EWOULDBLOCK" ? "busy" : "unavailable", code: r.code };
41
+ }
42
+ case "flock-command": {
43
+ const r = attempt(() => fs.openSync(path, dirOpenFlags));
44
+ if (!r.ok) {
45
+ return { ok: false, why: "unavailable", code: r.code };
46
+ }
47
+ const fd = r.value;
48
+ const run = spawnSync(method.command, [kind === "shared" ? "-s" : "-x", "-n", "3"], {
49
+ stdio: ["ignore", "ignore", "pipe", fd],
50
+ });
51
+ if (run.error === undefined && run.status === 0) {
52
+ return { ok: true, fd };
53
+ }
54
+ closeQuietly(fd);
55
+ if (run.error !== undefined) {
56
+ return { ok: false, why: "unavailable", code: "ENOLCK" };
57
+ }
58
+ return { ok: false, why: run.status === 1 ? "busy" : "unavailable", code: "EAGAIN" };
59
+ }
60
+ }
61
+ }
@@ -0,0 +1,19 @@
1
+ /** The length of a random name. */
2
+ export declare const randomLength = 10;
3
+ /** How many names createAt tries before giving up. */
4
+ export declare const nameAttempts = 16;
5
+ /**
6
+ * randomLength letters and digits from the system's secure generator, each
7
+ * character equally likely (a byte of 248 or more is drawn again, so no
8
+ * character is favoured by 256 not being a multiple of 62).
9
+ */
10
+ export declare function randomName(): string;
11
+ /** Whether name has the form randomName gives: what a D's name looks like. */
12
+ export declare function isRandomName(name: string): boolean;
13
+ /**
14
+ * Calls create with names from next until one is not taken (EEXIST),
15
+ * nameAttempts at most, and returns the name created. mkdir and symlink fail
16
+ * with EEXIST rather than reuse an entry, so what is created is always new.
17
+ * Any other error of create is thrown; running out of names throws EEXIST's.
18
+ */
19
+ export declare function createAt(next: () => string, create: (name: string) => void): string;
package/dist/names.js ADDED
@@ -0,0 +1,55 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { errnoCode } from "./errors.js";
3
+ // Random names: of D, of the default connect's E, and of a B fallen back to
4
+ // (SPEC-routes "D と E").
5
+ /** The length of a random name. */
6
+ export const randomLength = 10;
7
+ /** How many names createAt tries before giving up. */
8
+ export const nameAttempts = 16;
9
+ /** The characters of a random name: letters and digits (62 kinds). */
10
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
11
+ /** The largest multiple of 62 a byte can hold: bytes from it up are drawn again. */
12
+ const unbiasedLimit = 256 - (256 % alphabet.length);
13
+ /**
14
+ * randomLength letters and digits from the system's secure generator, each
15
+ * character equally likely (a byte of 248 or more is drawn again, so no
16
+ * character is favoured by 256 not being a multiple of 62).
17
+ */
18
+ export function randomName() {
19
+ let name = "";
20
+ while (name.length < randomLength) {
21
+ for (const b of randomBytes(randomLength)) {
22
+ if (b < unbiasedLimit && name.length < randomLength) {
23
+ name += alphabet.charAt(b % alphabet.length);
24
+ }
25
+ }
26
+ }
27
+ return name;
28
+ }
29
+ /** Whether name has the form randomName gives: what a D's name looks like. */
30
+ export function isRandomName(name) {
31
+ return name.length === randomLength && [...name].every((c) => alphabet.includes(c));
32
+ }
33
+ /**
34
+ * Calls create with names from next until one is not taken (EEXIST),
35
+ * nameAttempts at most, and returns the name created. mkdir and symlink fail
36
+ * with EEXIST rather than reuse an entry, so what is created is always new.
37
+ * Any other error of create is thrown; running out of names throws EEXIST's.
38
+ */
39
+ export function createAt(next, create) {
40
+ let last;
41
+ for (let i = 0; i < nameAttempts; i++) {
42
+ const name = next();
43
+ try {
44
+ create(name);
45
+ return name;
46
+ }
47
+ catch (e) {
48
+ if (errnoCode(e) !== "EEXIST") {
49
+ throw e;
50
+ }
51
+ last = e;
52
+ }
53
+ }
54
+ throw last;
55
+ }
@@ -0,0 +1,12 @@
1
+ import net from "node:net";
2
+ import { type Attempted } from "./drive.ts";
3
+ import type { Bound, Connected, Options } from "./types.ts";
4
+ import type { World } from "./world.ts";
5
+ /** Listens on spelling with a new net.Server, once it is listening or has failed. */
6
+ export declare function listenAt(spelling: string): Promise<Attempted<net.Server>>;
7
+ /** Connects to spelling with a new net.Socket (as a path, never a port), once it is connected or has failed. */
8
+ export declare function connectAt(spelling: string): Promise<Attempted<net.Socket>>;
9
+ export declare function bindIn(w: World, path: string): Promise<net.Server>;
10
+ export declare function connectIn(w: World, path: string): Promise<net.Socket>;
11
+ export declare function bindExIn(w: World, path: string, options: Options, at?: (spelling: string) => Promise<Attempted<net.Server>>): Promise<Bound<net.Server>>;
12
+ export declare function connectExIn(w: World, path: string, options: Options, at?: (spelling: string) => Promise<Attempted<net.Socket>>): Promise<Connected<net.Socket>>;
package/dist/netapi.js ADDED
@@ -0,0 +1,80 @@
1
+ import net from "node:net";
2
+ import { bindSteps } from "./bind.js";
3
+ import { connectSteps } from "./connect.js";
4
+ import { beforeBind, boundOf, diagnosed, driveAsync } from "./drive.js";
5
+ import { Trace } from "./errors.js";
6
+ import { forNodeNet } from "./route.js";
7
+ // The node:net side of the public API, on a given world (the tests hand
8
+ // their own to force each route). Every spelling node:net is handed went
9
+ // through forNodeNet, so none is read as a TCP port.
10
+ /** Listens on spelling with a new net.Server, once it is listening or has failed. */
11
+ export function listenAt(spelling) {
12
+ return new Promise((resolve) => {
13
+ const server = net.createServer();
14
+ const onError = (error) => resolve({ ok: false, error });
15
+ server.once("error", onError);
16
+ server.listen(spelling, () => {
17
+ server.off("error", onError);
18
+ resolve({ ok: true, socket: server, close: () => server.close() });
19
+ });
20
+ });
21
+ }
22
+ /** Connects to spelling with a new net.Socket (as a path, never a port), once it is connected or has failed. */
23
+ export function connectAt(spelling) {
24
+ return new Promise((resolve) => {
25
+ const socket = net.connect({ path: spelling });
26
+ const onError = (error) => resolve({ ok: false, error });
27
+ socket.once("error", onError);
28
+ socket.once("connect", () => {
29
+ socket.off("error", onError);
30
+ resolve({ ok: true, socket, close: () => socket.destroy() });
31
+ });
32
+ });
33
+ }
34
+ /**
35
+ * The listener's address() returns what the standard's returns, with the
36
+ * caller's path in place of the spelling the kernel keeps (DR-0002) when
37
+ * they differ: the path while it listens; once closed, whatever the
38
+ * standard gives then (Node keeps the name it listened on, Bun's node:net
39
+ * gives null), never the spelling.
40
+ */
41
+ function showPath(server, path, spelt) {
42
+ if (spelt !== path) {
43
+ const standard = server.address.bind(server);
44
+ server.address = () => {
45
+ const a = standard();
46
+ return a === spelt ? path : a;
47
+ };
48
+ }
49
+ }
50
+ export async function bindIn(w, path) {
51
+ const { result, socket } = await driveAsync(bindSteps(w, path, {}, new Trace(), "listen", forNodeNet), listenAt);
52
+ showPath(socket, path, result.spelt);
53
+ return socket;
54
+ }
55
+ export async function connectIn(w, path) {
56
+ const { socket } = await driveAsync(connectSteps(w, path, {}, new Trace(), "connect", forNodeNet), connectAt);
57
+ return socket;
58
+ }
59
+ export async function bindExIn(w, path, options, at = listenAt) {
60
+ const trace = new Trace();
61
+ try {
62
+ const before = beforeBind(path);
63
+ const { result, socket } = await driveAsync(bindSteps(w, path, options, trace, "listen", forNodeNet), at);
64
+ showPath(socket, path, result.spelt);
65
+ return boundOf(path, before, result, socket, () => socket.close(), trace);
66
+ }
67
+ catch (e) {
68
+ throw diagnosed(e, trace);
69
+ }
70
+ }
71
+ export async function connectExIn(w, path, options, at = connectAt) {
72
+ const trace = new Trace();
73
+ try {
74
+ const { result, socket } = await driveAsync(connectSteps(w, path, options, trace, "connect", forNodeNet), at);
75
+ return { socket, route: result.route, skipped: [...trace.skipped] };
76
+ }
77
+ catch (e) {
78
+ throw diagnosed(e, trace);
79
+ }
80
+ }
@@ -0,0 +1,46 @@
1
+ /** The byte length of a path as the kernel sees it (UTF-8). */
2
+ export declare function byteLength(path: string): number;
3
+ export declare function isAbs(path: string): boolean;
4
+ /**
5
+ * Splits a socket path into the directory that holds the socket and the
6
+ * socket's file name, by what follows the last '/'. A path that does not end
7
+ * with a name ("dir/", "dir/.", "dir/..", "..") gives null: the kernel would
8
+ * resolve it as a directory, not as a socket file.
9
+ *
10
+ * | path | directory | file name |
11
+ * |-------------|-----------|-----------|
12
+ * | /d/e/s.sock | /d/e | s.sock |
13
+ * | /s.sock | / | s.sock |
14
+ * | s.sock | . | s.sock |
15
+ * | d//s.sock | d/ | s.sock |
16
+ */
17
+ export declare function splitPath(path: string): {
18
+ dir: string;
19
+ name: string;
20
+ } | null;
21
+ /**
22
+ * Splits a path into its components the way the kernel walks it: empty
23
+ * segments and "." are dropped, ".." is kept as it is (it is not interpreted
24
+ * lexically, which would be wrong across symlinks). An absolute path starts
25
+ * with the component "/".
26
+ */
27
+ export declare function components(path: string): string[];
28
+ /** Whether a and b are the same spelling component by component. */
29
+ export declare function sameComponents(a: string, b: string): boolean;
30
+ /**
31
+ * The part of target below the directory prefix, when target starts with
32
+ * prefix component by component ("/a/b" is a prefix of "/a/b/c" but not of
33
+ * "/a/bc"). null when either is not absolute or prefix is not a proper prefix.
34
+ */
35
+ export declare function below(target: string, prefix: string): string | null;
36
+ /**
37
+ * The absolute path target spelt relative to the absolute directory cwd:
38
+ * climb with ".." out of the part of cwd that target does not share, then
39
+ * descend along the rest of target. Only meaningful when both are real paths
40
+ * (each ".." then climbs out of a real directory, as the kernel does); the
41
+ * caller confirms that the result names the same directory. null when either
42
+ * is not absolute, or target is cwd itself or one of its ancestors.
43
+ */
44
+ export declare function relativeTo(target: string, cwd: string): string | null;
45
+ /** The entry name of the directory dir. */
46
+ export declare function joinUnder(dir: string, name: string): string;