@domicile-desktop/system-apps 0.0.0-alpha-44f63a072a84 → 0.0.0-alpha-9a2cb3bbe5b4

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/README.md CHANGED
@@ -33,7 +33,7 @@ const editors = findApps(apps, "edit", 50);
33
33
  | `./mime-apps` | A content type's default applications from every `mimeapps.list`, the desktop's own (`domicile-mimeapps.list`) first. |
34
34
  | `./openers` | The applications that open a file, its default first, and the argv each opens it with. The type comes from shared-mime-info's `mime/globs2`, by name. |
35
35
  | `./omit` | Desktop file IDs left out, as globs. |
36
- | `./app-icons` | Icon names resolved in `hicolor` (`apps`, or the contexts given) and `pixmaps` to `data:` URLs (PNG, SVG, 128 KiB at most). |
36
+ | `./app-icons` | Icon names resolved to `data:` URLs (PNG, SVG, 128 KiB at most) by the icon theme spec: a theme, its `Inherits`, `hicolor`, then `pixmaps`, at the size asked for, in `apps` or the contexts given. `themedIcons` falls back to `<name>-symbolic` and says which icons are symbolic. Pass the theme `readIconTheme` reads. |
37
37
  | `./favicon`, `./curl`, `./favicons` | A bookmark's icon: picked from the page, fetched with `curl`, kept and retried. |
38
38
  | `./fake-system` | A `System` over an in-memory tree, for tests. |
39
39
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "dependencies": {
3
3
  "@cprussin/option-result": "^2.0.1",
4
- "@domicile-desktop/sdk": "0.0.0-alpha-44f63a072a84",
4
+ "@domicile-desktop/sdk": "0.0.0-alpha-9a2cb3bbe5b4",
5
5
  "zod": "^4.5.4"
6
6
  },
7
7
  "description": "Installed applications and bookmarks for a Domicile shell's launcher, read through @domicile-desktop/sdk/system.",
@@ -48,5 +48,5 @@
48
48
  "test:unit": "bun test"
49
49
  },
50
50
  "type": "module",
51
- "version": "0.0.0-alpha-44f63a072a84"
51
+ "version": "0.0.0-alpha-9a2cb3bbe5b4"
52
52
  }
package/src/app-icons.ts CHANGED
@@ -1,34 +1,29 @@
1
- // Desktop-entry icon names resolved to `data:` URLs, for `Icon` and
2
- // `X-Domicile-Preview`.
1
+ // Icon names resolved to `data:` URLs, for a desktop entry's `Icon` and
2
+ // `X-Domicile-Preview` and a tray menu's `icon-name`.
3
3
  //
4
- // Follows the icon theme spec: `icons/hicolor/<size>/<context>/<name>.<ext>`
5
- // under each data directory, then `pixmaps/<name>.<ext>`. Only `hicolor` is
6
- // searched: every application installs into it and every theme inherits it.
4
+ // Follows the icon theme spec: the theme, its `Inherits` and then `hicolor`,
5
+ // each under every data directory's `icons`, then `pixmaps`. A theme's
6
+ // `index.theme` says which directory suits a size. `hicolor` without one is
7
+ // read as `<size>/<context>`, the layout applications install into.
7
8
 
8
9
  import type { Option, Result } from "@cprussin/option-result";
9
10
  import { None, Ok, Some } from "@cprussin/option-result";
10
11
  import type { System, SystemError } from "@domicile-desktop/sdk/system";
11
12
 
12
13
  import { dataUrl } from "./data-url";
14
+ import type { ThemeDirectory } from "./icon-theme-index";
15
+ import {
16
+ DirectoryType,
17
+ parseIndexTheme,
18
+ sizeDistance,
19
+ } from "./icon-theme-index";
13
20
  import { allOk, orAbsent } from "./results";
14
21
 
15
- /**
16
- * Icon sizes to try, most preferred first. The first few are large enough for
17
- * a preview and small enough to draw in every row.
18
- */
19
- const SIZES = [
20
- "48x48",
21
- "64x64",
22
- "32x32",
23
- "96x96",
24
- "128x128",
25
- "scalable",
26
- "256x256",
27
- "24x24",
28
- "22x22",
29
- "16x16",
30
- "512x512",
31
- ];
22
+ /** The theme every theme inherits from last. */
23
+ const HICOLOR = "hicolor";
24
+
25
+ /** The suffix of an icon drawn in one color, to be tinted. */
26
+ const SYMBOLIC = "-symbolic";
32
27
 
33
28
  /** Extensions a page can draw, preferred first, and their MIME types. */
34
29
  const KINDS: Readonly<Record<string, string>> = {
@@ -44,35 +39,66 @@ export type IconLookup = (
44
39
  name: string,
45
40
  ) => Promise<Result<Option<string>, SystemError>>;
46
41
 
47
- /** A directory icons may be in, and the file names it holds. */
48
- type Listed = { dir: string; names: ReadonlySet<string> };
42
+ /** An icon found by {@link themedIcons}. */
43
+ export type ThemedIcon = {
44
+ url: string;
45
+ /**
46
+ * Drawn in one color, to be tinted to the text around it, such as a CSS
47
+ * mask over `currentColor`.
48
+ */
49
+ symbolic: boolean;
50
+ };
51
+
52
+ export type ThemedIconLookup = (
53
+ name: string,
54
+ ) => Promise<Result<Option<ThemedIcon>, SystemError>>;
55
+
56
+ export type IconOptions = {
57
+ /** The icon theme searched before `hicolor`, such as `readIconTheme` reads. */
58
+ theme?: string | undefined;
59
+ /** The size drawn at, in CSS pixels. 48, a launcher row's, by default. */
60
+ size?: number;
61
+ };
62
+
63
+ /** {@link themedIcons}' URLs alone, for pictures that keep their own colors. */
64
+ export const appIcons = (
65
+ system: System,
66
+ dataDirs: readonly string[],
67
+ contexts: readonly string[] = ["apps"],
68
+ options: IconOptions = {},
69
+ ): IconLookup => {
70
+ const lookup = themedIcons(system, dataDirs, contexts, options);
71
+ return async (name) =>
72
+ (await lookup(name)).map((icon) => icon.map(({ url }) => url));
73
+ };
49
74
 
50
75
  /**
51
- * Icons under `dataDirs`, highest priority first, in `contexts` (theme
52
- * subdirectories such as `apps` or `status`) in order. An absolute name is
53
- * read as a file, as the spec allows.
76
+ * Icons under `dataDirs`, highest priority first, in `contexts` (`apps`,
77
+ * `actions`, `status` and so on). A name with no icon falls back to its
78
+ * `-symbolic` one. An absolute name is read as a file, as the spec allows.
54
79
  *
55
- * Lists the theme's directories once, on the first lookup, and each name
56
- * once. Make a new lookup to see newly installed icons.
80
+ * Reads the themes on the first lookup, and each name once. Make a new
81
+ * lookup to see newly installed icons.
57
82
  */
58
- export const appIcons = (
83
+ export const themedIcons = (
59
84
  system: System,
60
85
  dataDirs: readonly string[],
61
86
  contexts: readonly string[] = ["apps"],
62
- ): IconLookup => {
63
- let listed: Promise<Result<Listed[], SystemError>> | undefined;
87
+ { size = 48, theme }: IconOptions = {},
88
+ ): ThemedIconLookup => {
89
+ let listed: Promise<Result<Listed[][], SystemError>> | undefined;
64
90
  const looked = new Map<
65
91
  string,
66
- Promise<Result<Option<string>, SystemError>>
92
+ Promise<Result<Option<ThemedIcon>, SystemError>>
67
93
  >();
68
94
  return (name) => {
69
95
  const known = looked.get(name);
70
96
  if (known === undefined) {
71
- listed ??= listings(system, dataDirs, contexts);
97
+ listed ??= listings(system, dataDirs, contexts, theme);
72
98
  const lookup = name.startsWith("/")
73
99
  ? read(system, name)
74
- : listed.then((dirs) =>
75
- dirs.andThenAsync((each) => firstUsable(system, each, name)),
100
+ : listed.then((themes) =>
101
+ themes.andThenAsync((each) => orSymbolic(system, each, size, name)),
76
102
  );
77
103
  looked.set(name, lookup);
78
104
  return lookup;
@@ -82,84 +108,297 @@ export const appIcons = (
82
108
  };
83
109
  };
84
110
 
85
- /** Every directory an icon may be in, in the order to search them. */
111
+ /** A directory icons may be in, the file names it holds, and its sizes. */
112
+ type Listed = {
113
+ dir: string;
114
+ names: ReadonlySet<string>;
115
+ /** Absent for `pixmaps`, which suits every size. */
116
+ directory: ThemeDirectory | undefined;
117
+ };
118
+
119
+ /** A theme's name and the directories it lists. */
120
+ type Theme = { name: string; directories: readonly ThemeDirectory[] };
121
+
122
+ /**
123
+ * Every directory an icon may be in: one list per theme, in the order to
124
+ * search them, then `pixmaps`.
125
+ */
86
126
  const listings = async (
87
127
  system: System,
88
128
  dataDirs: readonly string[],
89
129
  contexts: readonly string[],
90
- ): Promise<Result<Listed[], SystemError>> => {
91
- const themed = allOk(
92
- await Promise.all(dataDirs.map((dir) => themeDirs(system, dir, contexts))),
93
- ).map((dirs) => dirs.flat());
94
- const pixmaps = dataDirs.map((dir) => `${dir}/pixmaps`);
95
- return themed.andThenAsync(async (dirs) =>
130
+ theme: string | undefined,
131
+ ): Promise<Result<Listed[][], SystemError>> => {
132
+ const themes = await chain(system, dataDirs, contexts, theme);
133
+ return themes.andThenAsync(async (each) =>
96
134
  allOk(
97
- await Promise.all(
98
- [...dirs, ...pixmaps].map(async (dir) =>
99
- orAbsent(await system.readDir(dir), []).map(
100
- (entries): Listed => ({
101
- dir,
102
- names: new Set(entries.map((entry) => entry.name)),
103
- }),
104
- ),
105
- ),
106
- ),
135
+ await Promise.all([
136
+ ...each.map((one) => themeListing(system, dataDirs, one)),
137
+ pixmaps(system, dataDirs),
138
+ ]),
107
139
  ),
108
140
  );
109
141
  };
110
142
 
111
- /** `hicolor`'s `contexts` directories under `dataDir`, by preferred size. */
112
- const themeDirs = async (
143
+ /**
144
+ * `theme` and the themes it inherits, depth first and each once, then
145
+ * `hicolor`. A theme installed nowhere is skipped.
146
+ */
147
+ const chain = async (
113
148
  system: System,
114
- dataDir: string,
149
+ dataDirs: readonly string[],
115
150
  contexts: readonly string[],
116
- ): Promise<Result<string[], SystemError>> => {
117
- const theme = `${dataDir}/icons/hicolor`;
118
- return orAbsent(await system.readDir(theme), []).map((entries) => {
119
- const sizes = new Set(entries.map((entry) => entry.name));
120
- return contexts.flatMap((context) =>
121
- SIZES.filter((size) => sizes.has(size)).map(
122
- (size) => `${theme}/${size}/${context}`,
151
+ theme: string | undefined,
152
+ ): Promise<Result<Theme[], SystemError>> => {
153
+ const seen = new Set<string>();
154
+ const visit = async (name: string): Promise<Result<Theme[], SystemError>> => {
155
+ if (seen.has(name)) {
156
+ return Ok([]);
157
+ } else {
158
+ seen.add(name);
159
+ const loaded = await loadTheme(system, dataDirs, contexts, name);
160
+ return loaded.andThenAsync((found) =>
161
+ found.match({
162
+ None: () => Promise.resolve(Ok<Theme[], SystemError>([])),
163
+ Some: async ({ directories, inherits }) =>
164
+ // One parent at a time, so `seen` holds the earlier ones'.
165
+ (
166
+ await inherits.reduce(
167
+ async (earlier, parent) =>
168
+ (
169
+ await earlier
170
+ ).andThenAsync(async (themes) =>
171
+ (await visit(parent)).map((more) => [...themes, ...more]),
172
+ ),
173
+ Promise.resolve(Ok<Theme[], SystemError>([])),
174
+ )
175
+ ).map((parents) => [{ directories, name }, ...parents]),
176
+ }),
177
+ );
178
+ }
179
+ };
180
+ const themed = await visit(theme ?? HICOLOR);
181
+ return themed.andThenAsync(async (themes) =>
182
+ (await visit(HICOLOR)).map((hicolor) => [...themes, ...hicolor]),
183
+ );
184
+ };
185
+
186
+ /**
187
+ * Theme `name`'s parents and the directories in `contexts`, from the first
188
+ * `index.theme` found, or nothing if it is not installed.
189
+ */
190
+ const loadTheme = async (
191
+ system: System,
192
+ dataDirs: readonly string[],
193
+ contexts: readonly string[],
194
+ name: string,
195
+ ): Promise<
196
+ Result<
197
+ Option<{ inherits: readonly string[]; directories: ThemeDirectory[] }>,
198
+ SystemError
199
+ >
200
+ > => {
201
+ for (const dir of dataDirs) {
202
+ const text = orAbsent(
203
+ (await system.readTextFile(`${dir}/icons/${name}/index.theme`)).map(
204
+ (read): Option<string> => Some(read),
123
205
  ),
206
+ None(),
207
+ );
208
+ if (text.mapOr(true, (found) => found.isSome())) {
209
+ return text.map((found) =>
210
+ found.map((read) => {
211
+ const { directories, inherits } = parseIndexTheme(read);
212
+ return {
213
+ directories: directories.filter(
214
+ ({ context }) =>
215
+ context === undefined || contexts.includes(context),
216
+ ),
217
+ inherits,
218
+ };
219
+ }),
220
+ );
221
+ }
222
+ }
223
+ return name === HICOLOR
224
+ ? (await laidOut(system, dataDirs, contexts)).map((directories) =>
225
+ Some({ directories, inherits: [] }),
226
+ )
227
+ : Ok(None());
228
+ };
229
+
230
+ /** `hicolor`'s `<size>/<context>` directories, read from its layout. */
231
+ const laidOut = async (
232
+ system: System,
233
+ dataDirs: readonly string[],
234
+ contexts: readonly string[],
235
+ ): Promise<Result<ThemeDirectory[], SystemError>> =>
236
+ allOk(
237
+ await Promise.all(
238
+ dataDirs.map(async (dir) =>
239
+ orAbsent(await system.readDir(`${dir}/icons/${HICOLOR}`), []).map(
240
+ (entries) => entries.map((entry) => entry.name),
241
+ ),
242
+ ),
243
+ ),
244
+ ).map((listed) => {
245
+ const sizes = [...new Set(listed.flat())].flatMap(sized);
246
+ return contexts.flatMap((context) =>
247
+ sizes.map((directory) => ({
248
+ ...directory,
249
+ context,
250
+ path: `${directory.path}/${context}`,
251
+ })),
124
252
  );
125
253
  });
254
+
255
+ /** A `hicolor` size directory such as `48x48` or `scalable`. */
256
+ const sized = (name: string): Omit<ThemeDirectory, "context">[] => {
257
+ const pixels = /^(\d+)x\1$/.exec(name)?.[1];
258
+ if (name === "scalable") {
259
+ return [
260
+ {
261
+ maxSize: 512,
262
+ minSize: 1,
263
+ path: name,
264
+ size: 128,
265
+ threshold: 2,
266
+ type: DirectoryType.Scalable,
267
+ },
268
+ ];
269
+ } else {
270
+ return pixels === undefined
271
+ ? []
272
+ : [
273
+ {
274
+ maxSize: Number(pixels),
275
+ minSize: Number(pixels),
276
+ path: name,
277
+ size: Number(pixels),
278
+ threshold: 2,
279
+ type: DirectoryType.Threshold,
280
+ },
281
+ ];
282
+ }
126
283
  };
127
284
 
128
- /** The first of `name`'s files in `dirs` that can be drawn. */
129
- const firstUsable = async (
285
+ /** `theme`'s directories that exist, each directory under every data directory. */
286
+ const themeListing = async (
130
287
  system: System,
131
- dirs: readonly Listed[],
132
- name: string,
133
- ): Promise<Result<Option<string>, SystemError>> => {
134
- const candidates = dirs.flatMap(({ dir, names }) =>
135
- Object.keys(KINDS)
136
- .map((kind) => `${name}.${kind}`)
137
- .filter((file) => names.has(file))
138
- .map((file) => `${dir}/${file}`),
288
+ dataDirs: readonly string[],
289
+ { directories, name }: Theme,
290
+ ): Promise<Result<Listed[], SystemError>> => {
291
+ const roots = allOk(
292
+ await Promise.all(
293
+ dataDirs.map(async (dir) => {
294
+ const root = `${dir}/icons/${name}`;
295
+ return orAbsent(await system.readDir(root), []).map((entries) => ({
296
+ root,
297
+ tops: new Set(entries.map((entry) => entry.name)),
298
+ }));
299
+ }),
300
+ ),
301
+ );
302
+ return roots.andThenAsync(async (present) =>
303
+ allOk(
304
+ await Promise.all(
305
+ directories.flatMap((directory) =>
306
+ present
307
+ .filter(({ tops }) => tops.has(directory.path.split("/")[0] ?? ""))
308
+ .map(({ root }) =>
309
+ listing(system, `${root}/${directory.path}`, directory),
310
+ ),
311
+ ),
312
+ ),
313
+ ),
139
314
  );
140
- for (const path of candidates) {
141
- const icon = await read(system, path);
142
- if (icon.mapOr(true, (found) => found.isSome())) {
143
- return icon;
315
+ };
316
+
317
+ const pixmaps = async (
318
+ system: System,
319
+ dataDirs: readonly string[],
320
+ ): Promise<Result<Listed[], SystemError>> =>
321
+ allOk(
322
+ await Promise.all(
323
+ dataDirs.map((dir) => listing(system, `${dir}/pixmaps`, undefined)),
324
+ ),
325
+ );
326
+
327
+ const listing = async (
328
+ system: System,
329
+ dir: string,
330
+ directory: ThemeDirectory | undefined,
331
+ ): Promise<Result<Listed, SystemError>> =>
332
+ orAbsent(await system.readDir(dir), []).map((entries) => ({
333
+ dir,
334
+ directory,
335
+ names: new Set(entries.map((entry) => entry.name)),
336
+ }));
337
+
338
+ /** `name`'s icon, else its `-symbolic` one's. */
339
+ const orSymbolic = async (
340
+ system: System,
341
+ themes: readonly Listed[][],
342
+ size: number,
343
+ name: string,
344
+ ): Promise<Result<Option<ThemedIcon>, SystemError>> => {
345
+ const plain = await named(system, themes, size, name);
346
+ return plain.mapOr(true, (found) => found.isSome()) || name.endsWith(SYMBOLIC)
347
+ ? plain
348
+ : named(system, themes, size, `${name}${SYMBOLIC}`);
349
+ };
350
+
351
+ /**
352
+ * `name`'s best icon: in the first theme that has one, the file whose
353
+ * directory suits `size` best, earliest listed among equals.
354
+ */
355
+ const named = async (
356
+ system: System,
357
+ themes: readonly Listed[][],
358
+ size: number,
359
+ name: string,
360
+ ): Promise<Result<Option<ThemedIcon>, SystemError>> => {
361
+ for (const dirs of themes) {
362
+ const candidates = dirs
363
+ .flatMap(({ dir, directory, names }) =>
364
+ Object.keys(KINDS)
365
+ .map((kind) => `${name}.${kind}`)
366
+ .filter((file) => names.has(file))
367
+ .map((file) => ({
368
+ distance:
369
+ directory === undefined ? 0 : sizeDistance(directory, size),
370
+ path: `${dir}/${file}`,
371
+ })),
372
+ )
373
+ .toSorted((a, b) => a.distance - b.distance);
374
+ for (const { path } of candidates) {
375
+ const icon = await read(system, path);
376
+ if (icon.mapOr(true, (found) => found.isSome())) {
377
+ return icon;
378
+ }
144
379
  }
145
380
  }
146
381
  return Ok(None());
147
382
  };
148
383
 
149
- /** The file at `path` as a `data:` URL, or nothing if it cannot be drawn. */
384
+ /** The file at `path` as an icon, or nothing if it cannot be drawn. */
150
385
  const read = async (
151
386
  system: System,
152
387
  path: string,
153
- ): Promise<Result<Option<string>, SystemError>> => {
154
- const mime = KINDS[path.slice(path.lastIndexOf(".") + 1)];
388
+ ): Promise<Result<Option<ThemedIcon>, SystemError>> => {
389
+ const dot = path.lastIndexOf(".");
390
+ const mime = KINDS[path.slice(dot + 1)];
155
391
  return mime === undefined
156
392
  ? Ok(None())
157
393
  : orAbsent(
158
394
  await (await system.stat(path)).andThenAsync(async ({ size }) =>
159
395
  size > LARGEST
160
- ? Ok(None<string>())
396
+ ? Ok(None<ThemedIcon>())
161
397
  : (await system.readFile(path)).map((bytes) =>
162
- Some(dataUrl(mime, bytes)),
398
+ Some({
399
+ symbolic: path.slice(0, dot).endsWith(SYMBOLIC),
400
+ url: dataUrl(mime, bytes),
401
+ }),
163
402
  ),
164
403
  ),
165
404
  None(),
@@ -0,0 +1,148 @@
1
+ // An icon theme's `index.theme`: its parents and the directories it holds
2
+ // icons in. See
3
+ // https://specifications.freedesktop.org/icon-theme-spec/latest/.
4
+
5
+ /** How a directory's icons scale. */
6
+ export enum DirectoryType {
7
+ Fixed,
8
+ Scalable,
9
+ Threshold,
10
+ }
11
+
12
+ /** A theme directory and the icon sizes it suits. */
13
+ export type ThemeDirectory = {
14
+ /** Relative to the theme, such as `16x16/actions`. */
15
+ path: string;
16
+ /** As `contexts` name it: `apps`, `actions`, `status` and so on. */
17
+ context: string | undefined;
18
+ type: DirectoryType;
19
+ size: number;
20
+ minSize: number;
21
+ maxSize: number;
22
+ threshold: number;
23
+ };
24
+
25
+ export type IndexTheme = {
26
+ /** `Inherits`, in order. */
27
+ inherits: readonly string[];
28
+ /** `Directories`, in order. */
29
+ directories: readonly ThemeDirectory[];
30
+ };
31
+
32
+ /** The spec's contexts, by the directory names themes install them under. */
33
+ const CONTEXTS: Readonly<Record<string, string>> = {
34
+ Actions: "actions",
35
+ Animations: "animations",
36
+ Applications: "apps",
37
+ Categories: "categories",
38
+ Devices: "devices",
39
+ Emblems: "emblems",
40
+ Emotes: "emotes",
41
+ International: "intl",
42
+ MimeTypes: "mimetypes",
43
+ Places: "places",
44
+ Status: "status",
45
+ };
46
+
47
+ /** `text` read as an `index.theme`. A directory with no `Size` is skipped. */
48
+ export const parseIndexTheme = (text: string): IndexTheme => {
49
+ const groups = groupsOf(text);
50
+ const theme = groups.get("Icon Theme") ?? new Map<string, string>();
51
+ return {
52
+ directories: listOf(theme.get("Directories")).flatMap((path) => {
53
+ const keys = groups.get(path) ?? new Map<string, string>();
54
+ const size = numberOf(keys.get("Size"));
55
+ const context = keys.get("Context");
56
+ return size === undefined
57
+ ? []
58
+ : [
59
+ {
60
+ context:
61
+ context === undefined
62
+ ? undefined
63
+ : (CONTEXTS[context] ?? context.toLowerCase()),
64
+ maxSize: numberOf(keys.get("MaxSize")) ?? size,
65
+ minSize: numberOf(keys.get("MinSize")) ?? size,
66
+ path,
67
+ size,
68
+ threshold: numberOf(keys.get("Threshold")) ?? 2,
69
+ type: typeOf(keys.get("Type")),
70
+ },
71
+ ];
72
+ }),
73
+ inherits: listOf(theme.get("Inherits")),
74
+ };
75
+ };
76
+
77
+ /**
78
+ * How far `directory`'s icons are from `size` pixels: 0 where they suit it.
79
+ * The spec's `DirectorySizeDistance`, at scale 1.
80
+ */
81
+ export const sizeDistance = (
82
+ { maxSize, minSize, size: own, threshold, type }: ThemeDirectory,
83
+ size: number,
84
+ ): number => {
85
+ switch (type) {
86
+ case DirectoryType.Fixed: {
87
+ return Math.abs(own - size);
88
+ }
89
+ case DirectoryType.Scalable: {
90
+ return Math.max(minSize - size, size - maxSize, 0);
91
+ }
92
+ case DirectoryType.Threshold: {
93
+ if (size < own - threshold) {
94
+ return minSize - size;
95
+ } else {
96
+ return size > own + threshold ? size - maxSize : 0;
97
+ }
98
+ }
99
+ }
100
+ };
101
+
102
+ /** Each group's keys; the first of a repeated key wins. */
103
+ const groupsOf = (
104
+ text: string,
105
+ ): ReadonlyMap<string, ReadonlyMap<string, string>> => {
106
+ const groups = new Map<string, Map<string, string>>();
107
+ let group = new Map<string, string>();
108
+ for (const line of text.split("\n").map((each) => each.trim())) {
109
+ if (line.startsWith("[") && line.endsWith("]")) {
110
+ const name = line.slice(1, -1);
111
+ group = groups.get(name) ?? new Map<string, string>();
112
+ groups.set(name, group);
113
+ } else {
114
+ const at = line.indexOf("=");
115
+ const key = line.slice(0, at).trim();
116
+ if (at > 0 && !group.has(key)) {
117
+ group.set(key, line.slice(at + 1).trim());
118
+ }
119
+ }
120
+ }
121
+ return groups;
122
+ };
123
+
124
+ const listOf = (value: string | undefined): string[] =>
125
+ (value ?? "")
126
+ .split(",")
127
+ .map((each) => each.trim())
128
+ .filter((each) => each !== "");
129
+
130
+ const numberOf = (value: string | undefined): number | undefined => {
131
+ const read = Number.parseInt(value ?? "", 10);
132
+ return Number.isNaN(read) ? undefined : read;
133
+ };
134
+
135
+ /** `Type`, which is `Threshold` when absent or unknown. */
136
+ const typeOf = (value: string | undefined): DirectoryType => {
137
+ switch (value) {
138
+ case "Fixed": {
139
+ return DirectoryType.Fixed;
140
+ }
141
+ case "Scalable": {
142
+ return DirectoryType.Scalable;
143
+ }
144
+ default: {
145
+ return DirectoryType.Threshold;
146
+ }
147
+ }
148
+ };