@yaks/file 0.0.0-stage → 0.2.36

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.
Files changed (54) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +121 -2
  3. package/_dist/blobs.d.ts +16 -0
  4. package/_dist/blobs.d.ts.map +1 -0
  5. package/_dist/io.d.ts +148 -0
  6. package/_dist/io.d.ts.map +1 -0
  7. package/_dist/local.d.ts +18 -0
  8. package/_dist/local.d.ts.map +1 -0
  9. package/_dist/mod.d.ts +27 -0
  10. package/_dist/mod.d.ts.map +1 -0
  11. package/_dist/occupancy.d.ts +207 -0
  12. package/_dist/occupancy.d.ts.map +1 -0
  13. package/_dist/service.d.ts +31 -0
  14. package/_dist/service.d.ts.map +1 -0
  15. package/_dist/views.d.ts +24 -0
  16. package/_dist/views.d.ts.map +1 -0
  17. package/_dist/vocab.d.ts +9 -0
  18. package/_dist/vocab.d.ts.map +1 -0
  19. package/blobs.js +47 -0
  20. package/blobs.js.map +1 -0
  21. package/blobs.ts +52 -0
  22. package/deno.json +1 -0
  23. package/io.js +361 -0
  24. package/io.js.map +1 -0
  25. package/io.ts +528 -0
  26. package/local.js +105 -0
  27. package/local.js.map +1 -0
  28. package/local.ts +91 -0
  29. package/measure.js +88 -0
  30. package/measure.js.map +1 -0
  31. package/measure.ts +109 -0
  32. package/mod.js +86 -0
  33. package/mod.js.map +1 -0
  34. package/mod.ts +84 -0
  35. package/occupancy.js +256 -0
  36. package/occupancy.js.map +1 -0
  37. package/occupancy.ts +341 -0
  38. package/package.json +54 -4
  39. package/page.js +296 -0
  40. package/page.js.map +1 -0
  41. package/page.ts +444 -0
  42. package/service.js +116 -0
  43. package/service.js.map +1 -0
  44. package/service.ts +155 -0
  45. package/upkeep.js +52 -0
  46. package/upkeep.js.map +1 -0
  47. package/upkeep.ts +78 -0
  48. package/views.js +27 -0
  49. package/views.js.map +1 -0
  50. package/views.ts +25 -0
  51. package/vocab.js +19 -0
  52. package/vocab.js.map +1 -0
  53. package/vocab.json +163 -0
  54. package/vocab.ts +20 -0
package/local.ts ADDED
@@ -0,0 +1,91 @@
1
+ // This computer, and the files on its disks: the effects at the package's edge.
2
+ // The computer is the machine addressed `local://`, written once; a directory
3
+ // is never a computer's identity, and nothing remote calls this. Its volumes
4
+ // are rows: a path sits on the one with the longest mount that contains it,
5
+ // and the root volume (`/`) is written the first time a path needs it.
6
+ //
7
+ // Both are read once per graph. A volume written later is seen by a process
8
+ // that starts after it, and moving files already placed onto it is a
9
+ // migration.
10
+
11
+ import type { Bundle, Comp, Eid, Graph } from '@yaks/graph'
12
+ import { mint } from '@yaks/graph'
13
+ import { line } from '@yaks/query'
14
+ import { joined, onVolume, placed, volumeOf } from './mod.js'
15
+
16
+ let found = async (g: Graph): Promise<Eid> => {
17
+ let held = await g.read('.machine.address=local://')
18
+ if (held.length > 1) throw Error('Multiple computers claim local://')
19
+ if (held[0]) return held[0].entity.eid
20
+ let eid = mint()
21
+ await g.apply([{ entity: { eid }, machine: { address: 'local://' } }])
22
+ return eid
23
+ }
24
+
25
+ let mounted = async (g: Graph): Promise<Map<string, Eid>> => {
26
+ let machine = await here(g)
27
+ let rows = await g.read(line`.volume.machine=${machine}`)
28
+ let mounts = new Map(
29
+ rows.map((b) => [String((b.volume as Comp).mount), b.entity.eid]),
30
+ )
31
+ if (!mounts.has('/')) {
32
+ let eid = volumeOf(machine, '/')
33
+ await g.apply([{ entity: { eid }, volume: { machine, mount: '/' } }])
34
+ mounts.set('/', eid)
35
+ }
36
+ return mounts
37
+ }
38
+
39
+ let perGraph = <T>(f: (g: Graph) => Promise<T>) => {
40
+ let held = new WeakMap<Graph, Promise<T>>()
41
+ return (g: Graph): Promise<T> => {
42
+ let p = held.get(g)
43
+ if (p) return p
44
+ p = f(g)
45
+ held.set(g, p)
46
+ p.catch(() => held.delete(g))
47
+ return p
48
+ }
49
+ }
50
+
51
+ /** This computer: the machine addressed `local://`, written the first time
52
+ * a graph is asked for it. */
53
+ export let here: (g: Graph) => Promise<Eid> = perGraph(found)
54
+
55
+ let volumes = perGraph(mounted)
56
+
57
+ /**
58
+ * An absolute path on this computer, as the file it is: the bundle that makes
59
+ * it one, on the volume that holds it. Writing it again writes the same
60
+ * entity.
61
+ *
62
+ * ```ts
63
+ * import { onDisk } from '@yaks/file/local'
64
+ *
65
+ * // let [file] = await onDisk(graph, '/home/me/.claude/projects/x.jsonl')
66
+ * // file.file -> { path: 'home/me/.claude/projects/x.jsonl', root: <volume> }
67
+ * ```
68
+ */
69
+ export let onDisk = async (g: Graph, absolute: string): Promise<Bundle[]> => {
70
+ let mounts = await volumes(g)
71
+ let at = placed([...mounts.keys()], absolute)
72
+ if (!at) throw Error(`No volume of this computer holds ${absolute}`)
73
+ return onVolume(mounts.get(at.mount)!, at.path)
74
+ }
75
+
76
+ /** Where a file is on this computer's disks: its absolute path, or nothing
77
+ * for a file in a repository or on another machine. */
78
+ export let absolute = async (
79
+ g: Graph,
80
+ file: Bundle,
81
+ ): Promise<string | undefined> => {
82
+ let { root, path } = (file.file ?? {}) as Comp
83
+ if (root == null || path == null) return undefined
84
+ let [volume] = await g.get([String(root)], ['volume'])
85
+ let { machine, mount } = (volume?.volume ?? {}) as Comp
86
+ if (machine == null || mount == null) return undefined
87
+ let [computer] = await g.get([String(machine)], ['machine'])
88
+ return (computer?.machine as Comp | undefined)?.address == 'local://'
89
+ ? joined(String(mount), String(path))
90
+ : undefined
91
+ }
package/measure.js ADDED
@@ -0,0 +1,88 @@
1
+ /** Filesystem measurements through the host's file API, without commands. */ import * as disk from "./io.js";
2
+ import { sleep, system } from "@yaks/fp";
3
+ // A path can disappear while measuring; protected directories remain uncounted.
4
+ let readable = (error)=>{
5
+ if (!disk.isNotFound(error) && !disk.isPermissionDenied(error)) throw error;
6
+ };
7
+ /** Allocated bytes, counting hard links once and stopping at other devices.
8
+ * Symlinks are measured themselves; their targets are never followed.
9
+ * `breathe` is awaited before each directory is read, so a caller can pace a
10
+ * walk that lstats every file on the disk ({@link paced}). */ export let walk = async (mount, least, signal, fs = disk, breathe = ()=>Promise.resolve())=>{
11
+ let root = await fs.lstat(mount);
12
+ let seen = new Set();
13
+ let paths = {};
14
+ let visit = async (absolute, path)=>{
15
+ if (signal?.aborted) return 0;
16
+ let stat = await fs.lstat(absolute).catch(readable);
17
+ if (!stat || stat.dev != root.dev || seen.has(stat.ino)) return 0;
18
+ seen.add(stat.ino);
19
+ let bytes = stat.blocks == null ? stat.size : stat.blocks * 512;
20
+ if (stat.isDirectory) {
21
+ await breathe();
22
+ try {
23
+ for await (let entry of fs.readDir(absolute)){
24
+ if (signal?.aborted) break;
25
+ bytes += await visit(disk.join(absolute, entry.name), path ? path + '/' + entry.name : entry.name);
26
+ }
27
+ } catch (error) {
28
+ readable(error);
29
+ }
30
+ }
31
+ if (path && bytes >= least) {
32
+ paths[path + (stat.isDirectory ? '/' : '')] = bytes;
33
+ }
34
+ return bytes;
35
+ };
36
+ let counted = await visit(mount, '');
37
+ return signal?.aborted ? undefined : {
38
+ counted,
39
+ paths
40
+ };
41
+ };
42
+ /** A pace for {@link walk}: after each `burst` ms of walking, a pause long
43
+ * enough that the walk keeps to `share` of the time, so a walk of a whole disk
44
+ * leaves the CPUs to everything else on the computer.
45
+ *
46
+ * ```ts
47
+ * import { clock, equal } from '@yaks/testing'
48
+ * let time = clock()
49
+ * let breathe = paced(0.25, 50, time)
50
+ * await breathe()
51
+ * equal(time.pending(), 0)
52
+ * await time.advance(60)
53
+ * let paused = breathe()
54
+ * equal(time.pending(), 1)
55
+ * await time.advance(180)
56
+ * await paused
57
+ * equal([time.now(), time.pending()], [240, 0])
58
+ * ```
59
+ */ export let paced = (share = 0.25, burst = 50, clock = system)=>{
60
+ let since = clock.now();
61
+ return async ()=>{
62
+ let ran = clock.now() - since;
63
+ if (ran < burst) return;
64
+ await sleep(ran * (1 / share - 1), undefined, clock);
65
+ since = clock.now();
66
+ };
67
+ };
68
+ /** The filesystems holding `places`, each once, at its mount: the highest
69
+ * directory above a place that is still on the place's device. */ export let disksAt = async (places, fs = disk)=>{
70
+ let found = new Map();
71
+ for (let place of places){
72
+ let mount = await fs.realPath(place);
73
+ let { dev } = await fs.lstat(mount);
74
+ if (found.has(dev)) continue;
75
+ for(let up = disk.dirname(mount); up != mount; up = disk.dirname(up)){
76
+ if ((await fs.lstat(up)).dev != dev) break;
77
+ mount = up;
78
+ }
79
+ found.set(dev, {
80
+ mount,
81
+ ...await fs.space(mount)
82
+ });
83
+ }
84
+ return [
85
+ ...found.values()
86
+ ].toSorted((a, b)=>a.mount.localeCompare(b.mount));
87
+ };
88
+ //# sourceMappingURL=measure.js.map
package/measure.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"measure.js","sources":["./measure.ts"],"names":[],"mappings":"AAAA,2EAA2E,GAC3E,YAAY,oBAAmB;AAE/B,SAAqB,KAAK,EAAE,MAAM,wBAA6B;AAO/D,gFAAgF;AAChF,IAAI,WAAW,CAAC;EACd,IAAI,CAAC,KAAK,UAAU,CAAC,UAAU,CAAC,KAAK,kBAAkB,CAAC,QAAQ,MAAM;AACxE;AAEA;;;4DAG4D,GAC5D,OAAO,IAAI,OAAO,OAChB,OACA,OACA,QACA,KAAiB,IAAI,EACrB,UAA+B,IAAM,QAAQ,OAAO,EAAE;EAEtD,IAAI,OAAO,MAAM,GAAG,KAAK,CAAC;EAC1B,IAAI,OAAO,IAAI;EACf,IAAI,QAAgC,CAAC;EACrC,IAAI,QAAQ,OAAO,UAAkB;IACnC,IAAI,QAAQ,SAAS,OAAO;IAC5B,IAAI,OAAO,MAAM,GAAG,KAAK,CAAC,UAAU,KAAK,CAAC;IAC1C,IAAI,CAAC,QAAQ,KAAK,GAAG,IAAI,KAAK,GAAG,IAAI,KAAK,GAAG,CAAC,KAAK,GAAG,GAAG,OAAO;IAChE,KAAK,GAAG,CAAC,KAAK,GAAG;IACjB,IAAI,QAAQ,KAAK,MAAM,IAAI,OAAO,KAAK,IAAI,GAAG,KAAK,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AAC,GAAG,EAAE,GAAG,IAAI,KAAK;MACrC,QAAQ;IACV;IACA,MAAM,GAAG,CAAC,KAAK;MAAE;MAAO,GAAG,MAAM,GAAG,KAAK,CAAC,MAAM;IAAC;EACnD;EACA,OAAO;OAAI,MAAM,MAAM;GAAG,CAAC,QAAQ,CAAC,CAAC,GAAG,IAAM,EAAE,KAAK,CAAC,aAAa,CAAC,EAAE,KAAK;AAC7E,EAAC"}
package/measure.ts ADDED
@@ -0,0 +1,109 @@
1
+ /** Filesystem measurements through the host's file API, without commands. */
2
+ import * as disk from './io.js'
3
+ import type { Disk, Walk } from './occupancy.ts'
4
+ import { type Clock, sleep, system } from '@yaks/fp'
5
+
6
+ export type Filesystem = Pick<
7
+ typeof disk,
8
+ 'lstat' | 'readDir' | 'realPath' | 'space'
9
+ >
10
+
11
+ // A path can disappear while measuring; protected directories remain uncounted.
12
+ let readable = (error: unknown): undefined => {
13
+ if (!disk.isNotFound(error) && !disk.isPermissionDenied(error)) throw error
14
+ }
15
+
16
+ /** Allocated bytes, counting hard links once and stopping at other devices.
17
+ * Symlinks are measured themselves; their targets are never followed.
18
+ * `breathe` is awaited before each directory is read, so a caller can pace a
19
+ * walk that lstats every file on the disk ({@link paced}). */
20
+ export let walk = async (
21
+ mount: string,
22
+ least: number,
23
+ signal?: AbortSignal,
24
+ fs: Filesystem = disk,
25
+ breathe: () => Promise<void> = () => Promise.resolve(),
26
+ ): Promise<Walk | undefined> => {
27
+ let root = await fs.lstat(mount)
28
+ let seen = new Set<number>()
29
+ let paths: Record<string, number> = {}
30
+ let visit = async (absolute: string, path: string): Promise<number> => {
31
+ if (signal?.aborted) return 0
32
+ let stat = await fs.lstat(absolute).catch(readable)
33
+ if (!stat || stat.dev != root.dev || seen.has(stat.ino)) return 0
34
+ seen.add(stat.ino)
35
+ let bytes = stat.blocks == null ? stat.size : stat.blocks * 512
36
+ if (stat.isDirectory) {
37
+ await breathe()
38
+ try {
39
+ for await (let entry of fs.readDir(absolute)) {
40
+ if (signal?.aborted) break
41
+ bytes += await visit(
42
+ disk.join(absolute, entry.name),
43
+ path ? path + '/' + entry.name : entry.name,
44
+ )
45
+ }
46
+ } catch (error) {
47
+ readable(error)
48
+ }
49
+ }
50
+ if (path && bytes >= least) {
51
+ paths[path + (stat.isDirectory ? '/' : '')] = bytes
52
+ }
53
+ return bytes
54
+ }
55
+ let counted = await visit(mount, '')
56
+ return signal?.aborted ? undefined : { counted, paths }
57
+ }
58
+
59
+ /** A pace for {@link walk}: after each `burst` ms of walking, a pause long
60
+ * enough that the walk keeps to `share` of the time, so a walk of a whole disk
61
+ * leaves the CPUs to everything else on the computer.
62
+ *
63
+ * ```ts
64
+ * import { clock, equal } from '@yaks/testing'
65
+ * let time = clock()
66
+ * let breathe = paced(0.25, 50, time)
67
+ * await breathe()
68
+ * equal(time.pending(), 0)
69
+ * await time.advance(60)
70
+ * let paused = breathe()
71
+ * equal(time.pending(), 1)
72
+ * await time.advance(180)
73
+ * await paused
74
+ * equal([time.now(), time.pending()], [240, 0])
75
+ * ```
76
+ */
77
+ export let paced = (
78
+ share = 0.25,
79
+ burst = 50,
80
+ clock: Clock = system,
81
+ ): () => Promise<void> => {
82
+ let since = clock.now()
83
+ return async () => {
84
+ let ran = clock.now() - since
85
+ if (ran < burst) return
86
+ await sleep(ran * (1 / share - 1), undefined, clock)
87
+ since = clock.now()
88
+ }
89
+ }
90
+
91
+ /** The filesystems holding `places`, each once, at its mount: the highest
92
+ * directory above a place that is still on the place's device. */
93
+ export let disksAt = async (
94
+ places: string[],
95
+ fs: Filesystem = disk,
96
+ ): Promise<Disk[]> => {
97
+ let found = new Map<number, Disk>()
98
+ for (let place of places) {
99
+ let mount = await fs.realPath(place)
100
+ let { dev } = await fs.lstat(mount)
101
+ if (found.has(dev)) continue
102
+ for (let up = disk.dirname(mount); up != mount; up = disk.dirname(up)) {
103
+ if ((await fs.lstat(up)).dev != dev) break
104
+ mount = up
105
+ }
106
+ found.set(dev, { mount, ...await fs.space(mount) })
107
+ }
108
+ return [...found.values()].toSorted((a, b) => a.mount.localeCompare(b.mount))
109
+ }
package/mod.js ADDED
@@ -0,0 +1,86 @@
1
+ // Files as entities. A file is a path read in a root: a repository, whose files
2
+ // are abstract (a path in its tree, at any commit, on no disk), or a volume, a
3
+ // filesystem a machine mounts, whose files are bytes on a disk. A place in a
4
+ // file is `lines{file, start, end}` on whatever entity sits there.
5
+ //
6
+ // Everything here is pure: the eids the words derive, where a machine's path
7
+ // sits among its mounts, and bytes as a reader takes them in. Reading this
8
+ // computer is ./local.ts; what fills a volume is ./occupancy.ts.
9
+ import { identityEid } from "@yaks/graph/identity";
10
+ let UNITS = [
11
+ [
12
+ 1e12,
13
+ 'TB'
14
+ ],
15
+ [
16
+ 1e9,
17
+ 'GB'
18
+ ],
19
+ [
20
+ 1e6,
21
+ 'MB'
22
+ ],
23
+ [
24
+ 1e3,
25
+ 'kB'
26
+ ]
27
+ ];
28
+ /**
29
+ * Bytes as a reader takes them in, to three figures.
30
+ *
31
+ * ```ts
32
+ * import { size } from '@yaks/file'
33
+ * import { equal } from '@yaks/testing'
34
+ *
35
+ * equal([size(147), size(41_300_000), size(14_341_947_392), size(-2_000)], ['147 B', '41.3 MB', '14.3 GB', '−2 kB'])
36
+ * ```
37
+ */ export let size = (n = 0)=>{
38
+ let a = Math.abs(n);
39
+ let [d, unit] = UNITS.find(([d])=>a >= d) ?? [
40
+ 1,
41
+ 'B'
42
+ ];
43
+ let figure = Number((a / d).toPrecision(3)).toString();
44
+ return `${n < 0 ? '−' : ''}${d == 1 ? Math.round(a) : figure} ${unit}`;
45
+ };
46
+ /// fileOf('r', 'a/b.ts') == fileOf('r', 'a/b.ts') -> true
47
+ /// fileOf('r', 'a/b.ts') == fileOf('s', 'a/b.ts') -> false
48
+ /** The entity a path in a root is: the eid `file{path, root}` derives. */ export let fileOf = (root, path)=>identityEid('file', [
49
+ path,
50
+ root
51
+ ]);
52
+ /// volumeOf('m', '/') == volumeOf('m', '/') -> true
53
+ /** The entity a machine's mount is: the eid `volume{machine, mount}`
54
+ * derives. */ export let volumeOf = (machine, mount)=>identityEid('volume', [
55
+ machine,
56
+ mount
57
+ ]);
58
+ /// placed(['/', '/mnt/data'], '/mnt/data/x.txt') -> { mount: '/mnt/data', path: 'x.txt' }
59
+ /// placed(['/'], '/home/yaks/a.jsonl') -> { mount: '/', path: 'home/yaks/a.jsonl' }
60
+ /// placed(['/mnt/data'], '/mnt/database/x') -> undefined
61
+ /** Where an absolute path sits among a machine's mounts: on the longest
62
+ * mount that contains it, at the path from there. Nothing when no mount
63
+ * contains it. */ export let placed = (mounts, absolute)=>{
64
+ let within = (m)=>absolute == m || absolute.startsWith(m.endsWith('/') ? m : m + '/');
65
+ let [mount] = mounts.filter(within).sort((a, b)=>b.length - a.length);
66
+ return mount == null ? undefined : {
67
+ mount,
68
+ path: absolute.slice(mount.length).replace(/^\/+/, '')
69
+ };
70
+ };
71
+ /// joined('/', 'home/yaks/a.jsonl') -> '/home/yaks/a.jsonl'
72
+ /// joined('/mnt/data', 'x.txt') -> '/mnt/data/x.txt'
73
+ /** The absolute path a file on a volume has on the machine that mounts it. */ export let joined = (mount, path)=>mount.replace(/\/+$/, '') + '/' + path;
74
+ /// onVolume('v', 'a.txt')[0].file -> { path: 'a.txt', root: 'v' }
75
+ /** The bundle that makes a path on a volume a file. */ export let onVolume = (volume, path)=>[
76
+ {
77
+ entity: {
78
+ eid: fileOf(volume, path)
79
+ },
80
+ file: {
81
+ path,
82
+ root: volume
83
+ }
84
+ }
85
+ ];
86
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,+EAA+E;AAC/E,6EAA6E;AAC7E,mEAAmE;AACnE,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,iEAAiE;AAGjE,SAAS,WAAW,oCAAyC;AAQ7D,IAAI,QAA4B;EAC9B;I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AAM,OAAO,CAAC,QAAQ,MAAM,MAAM,KAAI;AAExC,kEAAkE;AAClE,qDAAqD,GACrD,OAAO,IAAI,WAAW,CAAC,QAAa,OAA2B;IAAC;MAC9D,QAAQ;QAAE,KAAK,OAAO,QAAQ;MAAM;MACpC,MAAM;QAAE;QAAM,MAAM;MAAO;IAC7B;GAAE,CAAA"}
package/mod.ts ADDED
@@ -0,0 +1,84 @@
1
+ // Files as entities. A file is a path read in a root: a repository, whose files
2
+ // are abstract (a path in its tree, at any commit, on no disk), or a volume, a
3
+ // filesystem a machine mounts, whose files are bytes on a disk. A place in a
4
+ // file is `lines{file, start, end}` on whatever entity sits there.
5
+ //
6
+ // Everything here is pure: the eids the words derive, where a machine's path
7
+ // sits among its mounts, and bytes as a reader takes them in. Reading this
8
+ // computer is ./local.ts; what fills a volume is ./occupancy.ts.
9
+
10
+ import type { Bundle, Eid } from 'jsr:@yaks/graph@0.2.36'
11
+ import { identityEid } from '@yaks/graph/identity'
12
+
13
+ /** Read at most `limit` trailing bytes of a regular file as UTF-8. */
14
+ export type TextTail = (
15
+ path: string | URL,
16
+ limit: number,
17
+ ) => { text: string; truncated: boolean } | undefined
18
+
19
+ let UNITS: [number, string][] = [
20
+ [1e12, 'TB'],
21
+ [1e9, 'GB'],
22
+ [1e6, 'MB'],
23
+ [1e3, 'kB'],
24
+ ]
25
+
26
+ /**
27
+ * Bytes as a reader takes them in, to three figures.
28
+ *
29
+ * ```ts
30
+ * import { size } from '@yaks/file'
31
+ * import { equal } from '@yaks/testing'
32
+ *
33
+ * equal([size(147), size(41_300_000), size(14_341_947_392), size(-2_000)], ['147 B', '41.3 MB', '14.3 GB', '−2 kB'])
34
+ * ```
35
+ */
36
+ export let size = (n = 0): string => {
37
+ let a = Math.abs(n)
38
+ let [d, unit] = UNITS.find(([d]) => a >= d) ?? [1, 'B']
39
+ let figure = Number((a / d).toPrecision(3)).toString()
40
+ return `${n < 0 ? '−' : ''}${d == 1 ? Math.round(a) : figure} ${unit}`
41
+ }
42
+
43
+ /// fileOf('r', 'a/b.ts') == fileOf('r', 'a/b.ts') -> true
44
+ /// fileOf('r', 'a/b.ts') == fileOf('s', 'a/b.ts') -> false
45
+ /** The entity a path in a root is: the eid `file{path, root}` derives. */
46
+ export let fileOf = (root: Eid, path: string): Eid =>
47
+ identityEid('file', [path, root])
48
+
49
+ /// volumeOf('m', '/') == volumeOf('m', '/') -> true
50
+ /** The entity a machine's mount is: the eid `volume{machine, mount}`
51
+ * derives. */
52
+ export let volumeOf = (machine: Eid, mount: string): Eid =>
53
+ identityEid('volume', [machine, mount])
54
+
55
+ /// placed(['/', '/mnt/data'], '/mnt/data/x.txt') -> { mount: '/mnt/data', path: 'x.txt' }
56
+ /// placed(['/'], '/home/yaks/a.jsonl') -> { mount: '/', path: 'home/yaks/a.jsonl' }
57
+ /// placed(['/mnt/data'], '/mnt/database/x') -> undefined
58
+ /** Where an absolute path sits among a machine's mounts: on the longest
59
+ * mount that contains it, at the path from there. Nothing when no mount
60
+ * contains it. */
61
+ export let placed = (
62
+ mounts: string[],
63
+ absolute: string,
64
+ ): { mount: string; path: string } | undefined => {
65
+ let within = (m: string) =>
66
+ absolute == m || absolute.startsWith(m.endsWith('/') ? m : m + '/')
67
+ let [mount] = mounts.filter(within).sort((a, b) => b.length - a.length)
68
+ return mount == null
69
+ ? undefined
70
+ : { mount, path: absolute.slice(mount.length).replace(/^\/+/, '') }
71
+ }
72
+
73
+ /// joined('/', 'home/yaks/a.jsonl') -> '/home/yaks/a.jsonl'
74
+ /// joined('/mnt/data', 'x.txt') -> '/mnt/data/x.txt'
75
+ /** The absolute path a file on a volume has on the machine that mounts it. */
76
+ export let joined = (mount: string, path: string): string =>
77
+ mount.replace(/\/+$/, '') + '/' + path
78
+
79
+ /// onVolume('v', 'a.txt')[0].file -> { path: 'a.txt', root: 'v' }
80
+ /** The bundle that makes a path on a volume a file. */
81
+ export let onVolume = (volume: Eid, path: string): Bundle[] => [{
82
+ entity: { eid: fileOf(volume, path) },
83
+ file: { path, root: volume },
84
+ }]