@domicile-desktop/system-apps 0.0.0-placeholder → 1.0.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/src/curl.ts ADDED
@@ -0,0 +1,54 @@
1
+ // Fetching a web page with `curl`. A shell page cannot: other sites do not
2
+ // allow its origin to read their answers.
3
+
4
+ import { None, Some } from "@cprussin/option-result";
5
+ import type { AppsDesktop } from "./apps-desktop";
6
+
7
+ import type { Fetch, Page } from "./favicon";
8
+
9
+ /** Seconds a site may take. Lookups run one at a time. */
10
+ const PATIENCE = "10";
11
+
12
+ /** A browser's user agent, since some sites serve other clients a different page. */
13
+ const USER_AGENT =
14
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36";
15
+
16
+ /**
17
+ * Fetches with the `curl` on the desktop's `PATH`, following redirects. Sends
18
+ * no cookies. A site that does not answer, or answers with an error, is
19
+ * nothing.
20
+ */
21
+ export const curlFetch =
22
+ (domicile: AppsDesktop): Fetch =>
23
+ async (url) =>
24
+ (
25
+ await domicile.processes.spawn([
26
+ "curl",
27
+ "--silent",
28
+ "--fail",
29
+ "--location",
30
+ "--max-time",
31
+ PATIENCE,
32
+ "--user-agent",
33
+ USER_AGENT,
34
+ // After the body, on stderr: where it landed, then its type.
35
+ "--write-out",
36
+ "%{stderr}%{url_effective}\n%{content_type}",
37
+ url,
38
+ ])
39
+ ).andThenAsync(async (curl) => {
40
+ const [body, written, exited] = await Promise.all([
41
+ new Response(curl.stdout).arrayBuffer(),
42
+ new Response(curl.stderr).text(),
43
+ curl.exited,
44
+ ]);
45
+ return exited.map(({ code }) => {
46
+ const [landed = url, contentType = ""] = written.split("\n");
47
+ const page: Page = {
48
+ body: new Uint8Array(body),
49
+ contentType: contentType === "" ? undefined : contentType,
50
+ url: landed,
51
+ };
52
+ return code === 0 ? Some(page) : None<Page>();
53
+ });
54
+ });
@@ -0,0 +1,29 @@
1
+ // The XDG data directories, where desktop entries and icons are installed. See
2
+ // https://specifications.freedesktop.org/basedir-spec/latest/.
3
+
4
+ import type { Result } from "@cprussin/option-result";
5
+ import type { SystemError } from "@domicile-desktop/sdk/system";
6
+ import type { AppsDesktop } from "./apps-desktop";
7
+
8
+ import { desktopEnvironment, setVariable } from "./environment";
9
+
10
+ /** The spec's default for an unset or empty `XDG_DATA_DIRS`. */
11
+ const DEFAULT_DATA_DIRS = "/usr/local/share:/usr/share";
12
+
13
+ /**
14
+ * The desktop's data directories, highest priority first: `XDG_DATA_HOME`,
15
+ * then each of `XDG_DATA_DIRS`.
16
+ *
17
+ * Read from the environment processes start in, which a page cannot see. An
18
+ * unset data home is `.local/share`, relative to the home as every system
19
+ * call's path is.
20
+ */
21
+ export const dataDirs = async (
22
+ domicile: AppsDesktop,
23
+ ): Promise<Result<string[], SystemError>> =>
24
+ (await desktopEnvironment(domicile)).map((variables) => [
25
+ setVariable(variables, "XDG_DATA_HOME") ?? ".local/share",
26
+ ...(setVariable(variables, "XDG_DATA_DIRS") ?? DEFAULT_DATA_DIRS).split(
27
+ ":",
28
+ ),
29
+ ]);
@@ -0,0 +1,12 @@
1
+ // Bytes as a `data:` URL, so a page can draw a file it cannot fetch.
2
+
3
+ /** Bytes passed to `String.fromCharCode` at once, under its argument limit. */
4
+ const CHUNK = 0x80_00;
5
+
6
+ export const dataUrl = (mime: string, bytes: Uint8Array): string => {
7
+ const chunks: string[] = [];
8
+ for (let at = 0; at < bytes.length; at += CHUNK) {
9
+ chunks.push(String.fromCharCode(...bytes.subarray(at, at + CHUNK)));
10
+ }
11
+ return `data:${mime};base64,${btoa(chunks.join(""))}`;
12
+ };
@@ -0,0 +1,110 @@
1
+ // Applications named and drawn by their desktop entries, for a shell to show
2
+ // who asks for something.
3
+
4
+ import type { Option } from "@cprussin/option-result";
5
+ import { None, Ok, Result } from "@cprussin/option-result";
6
+ import { readIconTheme } from "@domicile-desktop/sdk/icon-theme";
7
+ import type { SystemError } from "@domicile-desktop/sdk/system";
8
+ import type { IconLookup } from "./app-icons";
9
+ import { appIcons } from "./app-icons";
10
+ import { appIdName } from "./app-id-name";
11
+ import type { AppsDesktop } from "./apps-desktop";
12
+ import { dataDirs } from "./data-dirs";
13
+ import type { DesktopEntry } from "./desktop-entry";
14
+ import { installedApps } from "./installed";
15
+
16
+ /** An application, as its desktop entry describes it. */
17
+ export type DescribedApp = {
18
+ /** Its desktop file ID without `.desktop`, as portals and windows name it. */
19
+ id: string;
20
+ /** Its entry's `Name`, or `id` made readable when it has no entry. */
21
+ name: string;
22
+ /** A `data:` URL, or `undefined` for none. */
23
+ icon: string | undefined;
24
+ };
25
+
26
+ /**
27
+ * Each of `ids`, in order, described by its installed desktop entry, with its
28
+ * icon from the config's icon theme. See {@link entryFor} for how an id finds
29
+ * its entry.
30
+ */
31
+ export const describeApps = async (
32
+ domicile: AppsDesktop,
33
+ ids: readonly string[],
34
+ ): Promise<Result<DescribedApp[], SystemError>> => {
35
+ const [dirs, theme] = await Promise.all([
36
+ dataDirs(domicile),
37
+ readIconTheme(domicile),
38
+ ]);
39
+ return dirs.andThenAsync((found) =>
40
+ theme.andThenAsync((named) =>
41
+ describedIn(
42
+ domicile,
43
+ found,
44
+ appIcons(domicile, found, ["apps"], {
45
+ theme: named.match({ None: () => undefined, Some: (name) => name }),
46
+ }),
47
+ ids,
48
+ ),
49
+ ),
50
+ );
51
+ };
52
+
53
+ /** Each of `ids` described by its entry under `dirs`, drawn by `icons`. */
54
+ const describedIn = async (
55
+ domicile: AppsDesktop,
56
+ dirs: readonly string[],
57
+ icons: IconLookup,
58
+ ids: readonly string[],
59
+ ): Promise<Result<DescribedApp[], SystemError>> =>
60
+ (await installedApps(domicile, dirs)).andThenAsync(async (installed) => {
61
+ return Result.collect(
62
+ await Promise.all(
63
+ ids.map((id) => described(icons, id, entryFor(installed, id))),
64
+ ),
65
+ );
66
+ });
67
+
68
+ /**
69
+ * The entry whose desktop file ID is `id`. Failing that, the first whose ID,
70
+ * `StartupWMClass` or `Name` is `id` or its last reverse-DNS part, ignoring
71
+ * case: a portal can name an application by an id its entry does not use,
72
+ * as `com.chromium.Chromium` for `chromium-browser.desktop`.
73
+ */
74
+ const entryFor = (
75
+ installed: readonly DesktopEntry[],
76
+ id: string,
77
+ ): DesktopEntry | undefined => {
78
+ const wanted = new Set([
79
+ id.toLowerCase(),
80
+ (id.split(".").at(-1) ?? id).toLowerCase(),
81
+ ]);
82
+ return (
83
+ installed.find((entry) => desktopIdOf(entry) === id) ??
84
+ installed.find((entry) =>
85
+ [desktopIdOf(entry), entry.windowClass ?? "", entry.name].some((name) =>
86
+ wanted.has(name.toLowerCase()),
87
+ ),
88
+ )
89
+ );
90
+ };
91
+
92
+ const desktopIdOf = (entry: DesktopEntry): string =>
93
+ entry.id.replace(/\.desktop$/, "");
94
+
95
+ /** App `id`, named and drawn by its `entry` when it has one. */
96
+ const described = async (
97
+ icons: IconLookup,
98
+ id: string,
99
+ entry: DesktopEntry | undefined,
100
+ ): Promise<Result<DescribedApp, SystemError>> =>
101
+ entry === undefined
102
+ ? Ok({ icon: undefined, id, name: appIdName(id) })
103
+ : (entry.icon === undefined
104
+ ? Ok<Option<string>, SystemError>(None())
105
+ : await icons(entry.icon)
106
+ ).map((icon) => ({
107
+ icon: icon.match({ None: () => undefined, Some: (url) => url }),
108
+ id,
109
+ name: entry.name,
110
+ }));
@@ -0,0 +1,98 @@
1
+ // A desktop entry file read into a launchable application. See
2
+ // https://specifications.freedesktop.org/desktop-entry-spec/latest/.
3
+
4
+ import type { Option } from "@cprussin/option-result";
5
+ import { None } from "@cprussin/option-result";
6
+
7
+ import { unescaped } from "./escapes";
8
+ import { commandOf } from "./exec";
9
+
10
+ /** The only group keys are read from. */
11
+ const GROUP = "[Desktop Entry]";
12
+
13
+ /** An application a desktop entry offers. */
14
+ export type DesktopEntry = {
15
+ /** The desktop file ID: its path under `applications/`, `/` read as `-`. */
16
+ id: string;
17
+ name: string;
18
+ /** Empty for an entry with no `Comment`. */
19
+ comment: string;
20
+ /** The argv it runs. */
21
+ command: readonly string[];
22
+ /** `Exec` as written, for `commandOf` to open a file with. */
23
+ exec: string;
24
+ /** `MimeType`: the content types it opens. */
25
+ mimeTypes: readonly string[];
26
+ /** `Name`, `GenericName` and `Keywords`, in lower case, for `findApps`. */
27
+ words: string;
28
+ /** `Icon`: a theme name or an absolute path. See `./app-icons`. */
29
+ icon: string | undefined;
30
+ /** `X-Domicile-Preview`, in the same form as `icon`. */
31
+ preview: string | undefined;
32
+ /** `StartupWMClass`: the app id of the window it opens, if not its own id. */
33
+ windowClass: string | undefined;
34
+ };
35
+
36
+ /**
37
+ * Entry `text` as `id`, or nothing if a launcher should not offer it.
38
+ *
39
+ * Reads only unlocalized keys in `[Desktop Entry]`. Rejects non-applications,
40
+ * `Hidden` entries, entries without a `Name` or a readable `Exec`, and
41
+ * `Terminal` entries, since no terminal is configured. Rejects `NoDisplay`
42
+ * entries too, unless `shown` is false: such an entry still opens files.
43
+ */
44
+ export const parseDesktopEntry = (
45
+ id: string,
46
+ text: string,
47
+ shown = true,
48
+ ): Option<DesktopEntry> => {
49
+ const keys = keysOf(text);
50
+ const flag = (key: string) => keys.get(key) === "true";
51
+ const name = keys.get("Name");
52
+ const exec = keys.get("Exec");
53
+ return keys.get("Type") !== "Application" ||
54
+ flag("Hidden") ||
55
+ (shown && flag("NoDisplay")) ||
56
+ flag("Terminal") ||
57
+ name === undefined ||
58
+ exec === undefined
59
+ ? None()
60
+ : commandOf(exec).map((command) => ({
61
+ command,
62
+ comment: unescaped(keys.get("Comment") ?? ""),
63
+ exec,
64
+ icon: optional(keys.get("Icon")),
65
+ id,
66
+ mimeTypes: (keys.get("MimeType") ?? "")
67
+ .split(";")
68
+ .filter((type) => type !== ""),
69
+ name: unescaped(name),
70
+ preview: optional(keys.get("X-Domicile-Preview")),
71
+ windowClass: optional(keys.get("StartupWMClass")),
72
+ words: [name, keys.get("GenericName") ?? "", keys.get("Keywords") ?? ""]
73
+ .map(unescaped)
74
+ .join("\n")
75
+ .toLowerCase(),
76
+ }));
77
+ };
78
+
79
+ /** The `[Desktop Entry]` group's keys; the first of a repeated key wins. */
80
+ const keysOf = (text: string): ReadonlyMap<string, string> => {
81
+ const keys = new Map<string, string>();
82
+ let group = "";
83
+ for (const line of text.split("\n").map((each) => each.trim())) {
84
+ if (line.startsWith("[")) {
85
+ group = line;
86
+ } else if (group === GROUP && !line.startsWith("#")) {
87
+ const equals = line.indexOf("=");
88
+ const key = line.slice(0, equals).trim();
89
+ if (equals !== -1 && !keys.has(key)) {
90
+ keys.set(key, line.slice(equals + 1).trim());
91
+ }
92
+ }
93
+ }
94
+ return keys;
95
+ };
96
+
97
+ const optional = (value: string | undefined): string | undefined =>
98
+ value === undefined ? undefined : unescaped(value);
@@ -0,0 +1,38 @@
1
+ // The desktop's environment, which a page cannot see.
2
+
3
+ import type { Result } from "@cprussin/option-result";
4
+ import type { SystemError } from "@domicile-desktop/sdk/system";
5
+ import type { AppsDesktop } from "./apps-desktop";
6
+
7
+ /** The variables the shell's processes start with, read with `env -0`. */
8
+ export const desktopEnvironment = async (
9
+ domicile: AppsDesktop,
10
+ ): Promise<Result<ReadonlyMap<string, string>, SystemError>> =>
11
+ (await domicile.processes.run(["env", "-0"])).map((ran) => {
12
+ if (ran.code === 0) {
13
+ return environmentOf(ran.stdout);
14
+ } else {
15
+ throw new Error(`env failed: ${ran.stderr}`);
16
+ }
17
+ });
18
+
19
+ /** Variable `name`, or `undefined` when unset or, per the XDG specs, empty. */
20
+ export const setVariable = (
21
+ variables: ReadonlyMap<string, string>,
22
+ name: string,
23
+ ): string | undefined => {
24
+ const value = variables.get(name);
25
+ return value === "" ? undefined : value;
26
+ };
27
+
28
+ /** `env -0`'s output: `NAME=value`, each ended by a NUL. */
29
+ const environmentOf = (output: string): ReadonlyMap<string, string> =>
30
+ new Map(
31
+ output
32
+ .split("\0")
33
+ .filter((variable) => variable.includes("="))
34
+ .map((variable) => {
35
+ const equals = variable.indexOf("=");
36
+ return [variable.slice(0, equals), variable.slice(equals + 1)];
37
+ }),
38
+ );
package/src/escapes.ts ADDED
@@ -0,0 +1,16 @@
1
+ // The desktop entry spec's string escapes.
2
+
3
+ const ESCAPES: Readonly<Record<string, string>> = {
4
+ "\\": "\\",
5
+ n: "\n",
6
+ r: "\r",
7
+ s: " ",
8
+ t: "\t",
9
+ };
10
+
11
+ /** `value` with `\s`, `\n`, `\t`, `\r` and `\\` resolved; any other `\` kept. */
12
+ export const unescaped = (value: string): string =>
13
+ value.replaceAll(
14
+ /\\(.?)/gs,
15
+ (sequence, next: string) => ESCAPES[next] ?? sequence,
16
+ );
package/src/exec.ts ADDED
@@ -0,0 +1,60 @@
1
+ // An `Exec` value read into argv, per the desktop entry spec.
2
+
3
+ import type { Option } from "@cprussin/option-result";
4
+ import { None, Some } from "@cprussin/option-result";
5
+
6
+ import { unescaped } from "./escapes";
7
+
8
+ /** The field codes for files and URLs. A local file may stand for a URL. */
9
+ const FILE_CODES = new Set(["f", "F", "u", "U"]);
10
+
11
+ /**
12
+ * `exec` as argv opening `file`, or nothing if it is malformed or empty.
13
+ *
14
+ * Unescapes strings, then quoting, in the spec's order. Puts `file` in place
15
+ * of each file or URL field code, or after the last argument when there is
16
+ * none. Drops every other field code, along with any argument that was only a
17
+ * field code.
18
+ */
19
+ export const commandOf = (exec: string, file?: string): Option<string[]> => {
20
+ const words: string[] = [];
21
+ let placed = false;
22
+ let word = "";
23
+ let quoted = false;
24
+ // Whether the previous character was a `\` inside quotes, or a `%`.
25
+ let escaping = false;
26
+ let fieldCode = false;
27
+ for (const char of unescaped(exec)) {
28
+ if (escaping) {
29
+ word += char;
30
+ escaping = false;
31
+ } else if (fieldCode) {
32
+ word += expanded(char, file);
33
+ placed ||= file !== undefined && FILE_CODES.has(char);
34
+ fieldCode = false;
35
+ } else if (char === '"') {
36
+ quoted = !quoted;
37
+ } else if (char === "\\" && quoted) {
38
+ escaping = true;
39
+ } else if (char === "%") {
40
+ fieldCode = true;
41
+ } else if (char === " " && !quoted) {
42
+ words.push(...(word === "" ? [] : [word]));
43
+ word = "";
44
+ } else {
45
+ word += char;
46
+ }
47
+ }
48
+ words.push(...(word === "" ? [] : [word]));
49
+ words.push(...(file === undefined || placed ? [] : [file]));
50
+ return quoted || words.length === 0 ? None() : Some(words);
51
+ };
52
+
53
+ /** What field code `code` stands for when opening `file`. */
54
+ const expanded = (code: string, file: string | undefined): string => {
55
+ if (file !== undefined && FILE_CODES.has(code)) {
56
+ return file;
57
+ } else {
58
+ return code === "%" ? "%" : "";
59
+ }
60
+ };
@@ -0,0 +1,209 @@
1
+ // A desktop's files, processes and D-Bus over an in-memory tree, for a
2
+ // shell's tests.
3
+
4
+ import type { Result } from "@cprussin/option-result";
5
+ import { Err, Ok } from "@cprussin/option-result";
6
+ import type { AppDomicile } from "@domicile-desktop/sdk/desktop/app-desktop";
7
+ import type {
8
+ DbusBody,
9
+ DirEntry,
10
+ Ran,
11
+ Stat,
12
+ Subprocess,
13
+ SystemError,
14
+ } from "@domicile-desktop/sdk/system";
15
+ import { FileType, SystemErrorKind } from "@domicile-desktop/sdk/system";
16
+
17
+ /**
18
+ * A file's contents, a symlink to another path in the tree, or a path every
19
+ * call on fails.
20
+ */
21
+ export type Node =
22
+ | string
23
+ | Uint8Array
24
+ | { linksTo: string }
25
+ | { fails: SystemErrorKind };
26
+
27
+ /** What a spawned argv writes and how it ends. */
28
+ export type Spawned = {
29
+ stdout: Uint8Array | string;
30
+ stderr: string;
31
+ code: number;
32
+ };
33
+
34
+ export type FakeDesktop = AppDomicile & {
35
+ /** Every path read, listed or statted, in order. */
36
+ touched: string[];
37
+ };
38
+
39
+ type Tree = Readonly<Record<string, Node>>;
40
+
41
+ /** The Settings portal interface `readIconTheme` reads. */
42
+ const SETTINGS = "org.freedesktop.impl.portal.Settings";
43
+
44
+ /**
45
+ * A desktop whose files are `tree`, keyed by path, with the directories
46
+ * between them implied. `spawned` answers `spawn` and `run`. Its Settings
47
+ * portal serves `iconTheme`, or no icon theme when `undefined`.
48
+ */
49
+ export const fakeDesktop = (
50
+ tree: Tree,
51
+ spawned: (argv: readonly string[]) => Spawned = unexpected,
52
+ iconTheme: string | undefined = undefined,
53
+ ): FakeDesktop => {
54
+ const touched: string[] = [];
55
+ const at = (path: string): Result<Found, SystemError> => {
56
+ touched.push(path);
57
+ return found(tree, path);
58
+ };
59
+ const readFile = (path: string): Result<Uint8Array, SystemError> =>
60
+ at(path).andThen((node) =>
61
+ typeof node === "string" || node instanceof Uint8Array
62
+ ? Ok(bytesOf(node))
63
+ : Err({ kind: SystemErrorKind.IsADirectory, message: path }),
64
+ );
65
+ return {
66
+ dbus: {
67
+ call: (call) =>
68
+ call.interface === SETTINGS && call.member === "ReadAll"
69
+ ? Promise.resolve(Ok(settings(iconTheme)))
70
+ : unexpected(),
71
+ match: unexpected,
72
+ },
73
+ files: {
74
+ createDir: unexpected,
75
+ read: (path) => Promise.resolve(readFile(path)),
76
+ readDir: (path) =>
77
+ Promise.resolve(
78
+ at(path).andThen((node) =>
79
+ typeof node === "string" || node instanceof Uint8Array
80
+ ? Err({ kind: SystemErrorKind.NotADirectory, message: path })
81
+ : Ok(listing(tree, node.directory)),
82
+ ),
83
+ ),
84
+ readText: (path) =>
85
+ Promise.resolve(
86
+ readFile(path).map((bytes) => new TextDecoder().decode(bytes)),
87
+ ),
88
+ stat: (path) =>
89
+ Promise.resolve(
90
+ at(path).map(
91
+ (node): Stat =>
92
+ typeof node === "string" || node instanceof Uint8Array
93
+ ? {
94
+ fileType: FileType.File,
95
+ modifiedMs: undefined,
96
+ realPath: path,
97
+ size: bytesOf(node).byteLength,
98
+ }
99
+ : {
100
+ fileType: FileType.Directory,
101
+ modifiedMs: undefined,
102
+ realPath: path,
103
+ size: 0,
104
+ },
105
+ ),
106
+ ),
107
+ watch: unexpected,
108
+ write: unexpected,
109
+ },
110
+ processes: {
111
+ run: (argv) => {
112
+ const { code, stderr, stdout } = spawned(argv);
113
+ const ran: Ran = {
114
+ code,
115
+ signal: undefined,
116
+ stderr,
117
+ stdout: new TextDecoder().decode(bytesOf(stdout)),
118
+ };
119
+ return Promise.resolve(Ok(ran));
120
+ },
121
+ spawn: (argv) => Promise.resolve(Ok(subprocess(spawned(argv)))),
122
+ },
123
+ touched,
124
+ };
125
+ };
126
+
127
+ /** `ReadAll`'s answer for `org.gnome.desktop.interface`. */
128
+ const settings = (iconTheme: string | undefined): DbusBody => ({
129
+ body: [
130
+ iconTheme === undefined
131
+ ? {}
132
+ : {
133
+ "org.gnome.desktop.interface": {
134
+ "icon-theme": { signature: "s", value: iconTheme },
135
+ },
136
+ },
137
+ ],
138
+ signature: "a{sa{sv}}",
139
+ });
140
+
141
+ /** A file's contents, or the directory a path resolved to. */
142
+ type Found = string | Uint8Array | { directory: string };
143
+
144
+ /** What is at `path`, following symlinks. */
145
+ const found = (tree: Tree, path: string): Result<Found, SystemError> => {
146
+ const node = tree[path];
147
+ const linkedParent = Object.entries(tree)
148
+ .flatMap(([link, each]) =>
149
+ typeof each === "object" && "linksTo" in each
150
+ ? [{ link, to: each.linksTo }]
151
+ : [],
152
+ )
153
+ .find(({ link }) => path.startsWith(`${link}/`));
154
+ if (linkedParent !== undefined) {
155
+ const { link, to } = linkedParent;
156
+ return found(tree, `${to}${path.slice(link.length)}`);
157
+ } else if (node === undefined) {
158
+ return Object.keys(tree).some((each) => each.startsWith(`${path}/`))
159
+ ? Ok({ directory: path })
160
+ : Err({ kind: SystemErrorKind.NotFound, message: path });
161
+ } else if (typeof node === "string" || node instanceof Uint8Array) {
162
+ return Ok(node);
163
+ } else {
164
+ return "linksTo" in node
165
+ ? found(tree, node.linksTo)
166
+ : Err({ kind: node.fails, message: path });
167
+ }
168
+ };
169
+
170
+ const listing = (tree: Tree, path: string): DirEntry[] => {
171
+ const names = new Map<string, FileType>();
172
+ for (const [each, node] of Object.entries(tree)) {
173
+ if (each.startsWith(`${path}/`)) {
174
+ const [name = "", ...below] = each.slice(path.length + 1).split("/");
175
+ names.set(name, below.length > 0 ? FileType.Directory : ownType(node));
176
+ }
177
+ }
178
+ return [...names].map(([name, fileType]) => ({ fileType, name }));
179
+ };
180
+
181
+ /** A node's type without following it. */
182
+ const ownType = (node: Node): FileType =>
183
+ typeof node === "object" && "linksTo" in node
184
+ ? FileType.Symlink
185
+ : FileType.File;
186
+
187
+ const subprocess = ({ code, stderr, stdout }: Spawned): Subprocess => ({
188
+ closeStdin: unexpected,
189
+ exited: Promise.resolve(Ok({ code, signal: undefined })),
190
+ kill: unexpected,
191
+ stderr: streamOf(bytesOf(stderr)),
192
+ stdout: streamOf(bytesOf(stdout)),
193
+ write: unexpected,
194
+ });
195
+
196
+ const bytesOf = (data: string | Uint8Array): Uint8Array =>
197
+ typeof data === "string" ? new TextEncoder().encode(data) : data;
198
+
199
+ const streamOf = (bytes: Uint8Array): ReadableStream<Uint8Array> =>
200
+ new ReadableStream({
201
+ start: (controller) => {
202
+ controller.enqueue(bytes);
203
+ controller.close();
204
+ },
205
+ });
206
+
207
+ const unexpected = (): never => {
208
+ throw new Error("the code under test made a call this fake does not take");
209
+ };