@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/io.ts ADDED
@@ -0,0 +1,528 @@
1
+ /** The host filesystem, shared by packages without exposing its runtime. */
2
+ import * as fs from 'node:fs'
3
+ import * as fsp from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ export { homedir } from 'node:os'
6
+ import { join, sep } from 'node:path'
7
+ import process from 'node:process'
8
+ import type { TextTail } from './mod.ts'
9
+ export {
10
+ basename,
11
+ dirname,
12
+ extname,
13
+ isAbsolute,
14
+ join,
15
+ relative,
16
+ resolve,
17
+ } from 'node:path'
18
+ export { fileURLToPath, pathToFileURL } from 'node:url'
19
+
20
+ export type Path = string | URL
21
+ export type MkdirOptions = { recursive?: boolean; mode?: number }
22
+ export type WriteFileOptions = {
23
+ append?: boolean
24
+ create?: boolean
25
+ createNew?: boolean
26
+ mode?: number
27
+ signal?: AbortSignal
28
+ }
29
+ export type OpenOptions = {
30
+ read?: boolean
31
+ write?: boolean
32
+ append?: boolean
33
+ truncate?: boolean
34
+ create?: boolean
35
+ createNew?: boolean
36
+ mode?: number
37
+ }
38
+ export type DirEntry = {
39
+ name: string
40
+ isFile: boolean
41
+ isDirectory: boolean
42
+ isSymlink: boolean
43
+ }
44
+ export type FileInfo =
45
+ & Pick<
46
+ fs.Stats,
47
+ | 'dev'
48
+ | 'ino'
49
+ | 'mode'
50
+ | 'nlink'
51
+ | 'uid'
52
+ | 'gid'
53
+ | 'rdev'
54
+ | 'size'
55
+ | 'blksize'
56
+ | 'blocks'
57
+ | 'atime'
58
+ | 'mtime'
59
+ | 'ctime'
60
+ | 'birthtime'
61
+ >
62
+ & {
63
+ isFile: boolean
64
+ isDirectory: boolean
65
+ isSymlink: boolean
66
+ }
67
+
68
+ type Failure = {
69
+ new (message?: string): Error
70
+ [Symbol.hasInstance]: (error: unknown) => boolean
71
+ }
72
+ let fault = (name: string, codes: string[]): Failure =>
73
+ class extends Error {
74
+ constructor(message?: string) {
75
+ super(message)
76
+ this.name = name
77
+ }
78
+ static override [Symbol.hasInstance](error: unknown): boolean {
79
+ let e = error as { code?: string; name?: string } | undefined
80
+ return !!e && (codes.includes(e.code ?? '') || e.name == name)
81
+ }
82
+ }
83
+ export let errors: Record<
84
+ 'NotFound' | 'NotADirectory' | 'AlreadyExists' | 'PermissionDenied',
85
+ Failure
86
+ > = {
87
+ NotFound: fault('NotFound', ['ENOENT', 'ESRCH']),
88
+ NotADirectory: fault('NotADirectory', ['ENOTDIR']),
89
+ AlreadyExists: fault('AlreadyExists', ['EEXIST']),
90
+ PermissionDenied: fault('PermissionDenied', ['EACCES', 'EPERM']),
91
+ }
92
+ export let isNotADirectory = (error: unknown): boolean =>
93
+ error instanceof errors.NotADirectory
94
+ export let isNotFound = (error: unknown): boolean =>
95
+ error instanceof errors.NotFound
96
+ export let isAlreadyExists = (error: unknown): boolean =>
97
+ error instanceof errors.AlreadyExists
98
+ export let isPermissionDenied = (error: unknown): boolean =>
99
+ error instanceof errors.PermissionDenied
100
+
101
+ let readers = new Set<(path: Path) => void>()
102
+ /** Observe filesystem inputs read by this process; returns an unsubscribe. */
103
+ export let watchReads = (read: (path: Path) => void): () => void => {
104
+ readers.add(read)
105
+ return () => {
106
+ readers.delete(read)
107
+ }
108
+ }
109
+ let reading = <T extends Path>(path: T): T => {
110
+ for (let read of readers) read(path)
111
+ return path
112
+ }
113
+ let info = (s: fs.Stats): FileInfo => ({
114
+ ...s,
115
+ atime: s.atime,
116
+ mtime: s.mtime,
117
+ ctime: s.ctime,
118
+ birthtime: s.birthtime,
119
+ isFile: s.isFile(),
120
+ isDirectory: s.isDirectory(),
121
+ isSymlink: s.isSymbolicLink(),
122
+ })
123
+ let entry = (e: fs.Dirent): DirEntry => ({
124
+ name: e.name,
125
+ isFile: e.isFile(),
126
+ isDirectory: e.isDirectory(),
127
+ isSymlink: e.isSymbolicLink(),
128
+ })
129
+ let flags = (o: OpenOptions = {}): number =>
130
+ (o.read && (o.write || o.append)
131
+ ? fs.constants.O_RDWR
132
+ : o.write || o.append
133
+ ? fs.constants.O_WRONLY
134
+ : fs.constants.O_RDONLY) |
135
+ (o.create || o.createNew ? fs.constants.O_CREAT : 0) |
136
+ (o.createNew ? fs.constants.O_EXCL : 0) |
137
+ (o.truncate ? fs.constants.O_TRUNC : 0) |
138
+ (o.append ? fs.constants.O_APPEND : 0)
139
+ let writing = (o: WriteFileOptions = {}): OpenOptions => ({
140
+ ...o,
141
+ write: true,
142
+ create: o.create !== false,
143
+ truncate: !o.append,
144
+ })
145
+
146
+ export let readTextFile = (path: Path): Promise<string> =>
147
+ fsp.readFile(reading(path), 'utf8')
148
+ export let readTextFileSync = (path: Path): string =>
149
+ fs.readFileSync(reading(path), 'utf8')
150
+
151
+ /** A bounded, best-effort tail. Skip special files that could block or stream. */
152
+ export let tailTextSync: TextTail = (path, limit) => {
153
+ let file: FsFile | undefined
154
+ try {
155
+ if (!statSync(path).isFile) return
156
+ file = openSync(path, { read: true })
157
+ let size = file.statSync().size
158
+ let start = Math.max(0, size - limit)
159
+ file.seekSync(start, SeekMode.Start)
160
+ let bytes = new Uint8Array(size - start)
161
+ let read = 0
162
+ while (read < bytes.length) {
163
+ let n = file.readSync(bytes.subarray(read))
164
+ if (n == null) break
165
+ read += n
166
+ }
167
+ return {
168
+ text: new TextDecoder().decode(bytes.subarray(0, read)),
169
+ truncated: start > 0,
170
+ }
171
+ } catch {
172
+ return
173
+ } finally {
174
+ file?.close()
175
+ }
176
+ }
177
+
178
+ export let readFile = async (path: Path): Promise<Uint8Array> =>
179
+ new Uint8Array(await fsp.readFile(reading(path)))
180
+ export let readFileSync = (path: Path): Uint8Array =>
181
+ new Uint8Array(fs.readFileSync(reading(path)))
182
+ export let writeTextFile = async (
183
+ path: Path,
184
+ data: string,
185
+ o: WriteFileOptions = {},
186
+ ): Promise<void> => {
187
+ await fsp.writeFile(path, data, {
188
+ flag: flags(writing(o)),
189
+ mode: o.mode,
190
+ signal: o.signal,
191
+ })
192
+ }
193
+ export let writeTextFileSync = (
194
+ path: Path,
195
+ data: string,
196
+ o: WriteFileOptions = {},
197
+ ): void => {
198
+ let fd = fs.openSync(path, flags(writing(o)), o.mode)
199
+ try {
200
+ fs.writeFileSync(fd, data)
201
+ } finally {
202
+ fs.closeSync(fd)
203
+ }
204
+ }
205
+ export let writeFile = async (
206
+ path: Path,
207
+ data: Uint8Array,
208
+ o: WriteFileOptions = {},
209
+ ): Promise<void> => {
210
+ await fsp.writeFile(path, data, {
211
+ flag: flags(writing(o)),
212
+ mode: o.mode,
213
+ signal: o.signal,
214
+ })
215
+ }
216
+ export let writeFileSync = (
217
+ path: Path,
218
+ data: Uint8Array,
219
+ o: WriteFileOptions = {},
220
+ ): void => {
221
+ let fd = fs.openSync(path, flags(writing(o)), o.mode)
222
+ try {
223
+ fs.writeFileSync(fd, data)
224
+ } finally {
225
+ fs.closeSync(fd)
226
+ }
227
+ }
228
+ export let mkdir = async (path: Path, o: MkdirOptions = {}): Promise<void> => {
229
+ await fsp.mkdir(path, o)
230
+ }
231
+ export let mkdirSync = (path: Path, o: MkdirOptions = {}): void => {
232
+ fs.mkdirSync(path, o)
233
+ }
234
+ /** What `remove` takes: `recursive` removes a directory with its contents,
235
+ * and `force` lets a path that is already gone count as removed. */
236
+ export type RemoveOptions = { recursive?: boolean; force?: boolean }
237
+ let gone = (o: RemoveOptions) => (error: unknown) => {
238
+ if (!(o.force && isNotFound(error))) throw error
239
+ }
240
+ export let remove = async (
241
+ path: Path,
242
+ o: RemoveOptions = {},
243
+ ): Promise<void> => {
244
+ try {
245
+ if (o.recursive) await fsp.rm(path, { recursive: true })
246
+ else if ((await fsp.lstat(path)).isDirectory()) await fsp.rmdir(path)
247
+ else await fsp.unlink(path)
248
+ } catch (error) {
249
+ gone(o)(error)
250
+ }
251
+ }
252
+ export let removeSync = (path: Path, o: RemoveOptions = {}): void => {
253
+ try {
254
+ if (o.recursive) fs.rmSync(path, { recursive: true })
255
+ else if (fs.lstatSync(path).isDirectory()) fs.rmdirSync(path)
256
+ else fs.unlinkSync(path)
257
+ } catch (error) {
258
+ gone(o)(error)
259
+ }
260
+ }
261
+ export let stat = async (path: Path): Promise<FileInfo> =>
262
+ info(await fsp.stat(reading(path)))
263
+ export let statSync = (path: Path): FileInfo => info(fs.statSync(reading(path)))
264
+ export let lstat = async (path: Path): Promise<FileInfo> =>
265
+ info(await fsp.lstat(reading(path)))
266
+ export let lstatSync = (path: Path): FileInfo =>
267
+ info(fs.lstatSync(reading(path)))
268
+ export let readDir = async function* (path: Path): AsyncGenerator<DirEntry> {
269
+ for (let e of await fsp.readdir(reading(path), { withFileTypes: true })) {
270
+ yield entry(e)
271
+ }
272
+ }
273
+ export let readDirSync = (path: Path): Iterable<DirEntry> =>
274
+ fs.readdirSync(reading(path), { withFileTypes: true }).map(entry)
275
+ /** The bytes of the filesystem holding a path: its size, those in use, and
276
+ * those free to a writer without privilege. */
277
+ export type Space = { size: number; used: number; free: number }
278
+ export let space = async (path: Path): Promise<Space> => {
279
+ let { bsize, blocks, bfree, bavail } = await fsp.statfs(reading(path))
280
+ return {
281
+ size: blocks * bsize,
282
+ used: (blocks - bfree) * bsize,
283
+ free: bavail * bsize,
284
+ }
285
+ }
286
+ export let realPath = (path: Path): Promise<string> =>
287
+ fsp.realpath(reading(path))
288
+ export let realPathSync = (path: Path): string => fs.realpathSync(reading(path))
289
+ export let readLink = (path: Path): Promise<string> =>
290
+ fsp.readlink(reading(path))
291
+ export let readLinkSync = (path: Path): string => fs.readlinkSync(reading(path))
292
+ export let rename: typeof fsp.rename = fsp.rename
293
+ export let renameSync: typeof fs.renameSync = fs.renameSync
294
+ export let copyFile = (from: Path, to: Path): Promise<void> =>
295
+ fsp.copyFile(reading(from), to)
296
+ export let copyFileSync = (from: Path, to: Path): void =>
297
+ fs.copyFileSync(reading(from), to)
298
+ export let chmod: typeof fsp.chmod = fsp.chmod
299
+ export let chmodSync: typeof fs.chmodSync = fs.chmodSync
300
+ export let utime: typeof fsp.utimes = fsp.utimes
301
+ export let utimeSync: typeof fs.utimesSync = fs.utimesSync
302
+ export let link: typeof fsp.link = fsp.link
303
+ export let linkSync: typeof fs.linkSync = fs.linkSync
304
+ export let symlink = (
305
+ target: Path,
306
+ path: Path,
307
+ options: { type?: 'file' | 'dir' | 'junction' } = {},
308
+ ): Promise<void> => fsp.symlink(target, path, options.type)
309
+ export let symlinkSync = (
310
+ target: Path,
311
+ path: Path,
312
+ options: { type?: 'file' | 'dir' | 'junction' } = {},
313
+ ): void => fs.symlinkSync(target, path, options.type)
314
+ export let makeTempDir = (
315
+ o: { dir?: string; prefix?: string; suffix?: string } = {},
316
+ ): Promise<string> =>
317
+ fsp.mkdtemp(join(o.dir ?? tmpdir(), o.prefix ?? '') + (o.prefix ? '' : sep))
318
+ .then(async (path) => {
319
+ if (!o.suffix) return path
320
+ await fsp.rename(path, path + o.suffix)
321
+ return path + o.suffix
322
+ })
323
+ export let makeTempDirSync = (
324
+ o: { dir?: string; prefix?: string; suffix?: string } = {},
325
+ ): string => {
326
+ let path = fs.mkdtempSync(
327
+ join(o.dir ?? tmpdir(), o.prefix ?? '') + (o.prefix ? '' : sep),
328
+ )
329
+ if (!o.suffix) return path
330
+ fs.renameSync(path, path + o.suffix)
331
+ return path + o.suffix
332
+ }
333
+
334
+ export let makeTempFile = async (
335
+ o: { dir?: string; prefix?: string; suffix?: string } = {},
336
+ ): Promise<string> => {
337
+ let path = join(
338
+ o.dir ?? tmpdir(),
339
+ (o.prefix ?? '') + crypto.randomUUID() + (o.suffix ?? ''),
340
+ )
341
+ await fsp.writeFile(path, '', { flag: 'wx', mode: 0o600 })
342
+ return path
343
+ }
344
+ export let makeTempFileSync = (
345
+ o: { dir?: string; prefix?: string; suffix?: string } = {},
346
+ ): string => {
347
+ let path = join(
348
+ o.dir ?? tmpdir(),
349
+ (o.prefix ?? '') + crypto.randomUUID() + (o.suffix ?? ''),
350
+ )
351
+ fs.writeFileSync(path, '', { flag: 'wx', mode: 0o600 })
352
+ return path
353
+ }
354
+
355
+ export let SeekMode: {
356
+ readonly Start: 0
357
+ readonly Current: 1
358
+ readonly End: 2
359
+ } = { Start: 0, Current: 1, End: 2 }
360
+ let call = <T>(
361
+ fn: (done: (error: NodeJS.ErrnoException | null, result: T) => void) => void,
362
+ ): Promise<T> =>
363
+ new Promise((resolve, reject) =>
364
+ fn((error, result) => error ? reject(error) : resolve(result))
365
+ )
366
+
367
+ /** An open file. Closing releases its descriptor and any lock it holds. */
368
+ export type FsFile = {
369
+ readonly fd: number
370
+ read: (buffer: Uint8Array) => Promise<number | null>
371
+ readSync: (buffer: Uint8Array) => number | null
372
+ write: (buffer: Uint8Array) => Promise<number>
373
+ writeSync: (buffer: Uint8Array) => number
374
+ seek: (offset: number, mode: number) => Promise<number>
375
+ seekSync: (offset: number, mode: number) => number
376
+ stat: () => Promise<FileInfo>
377
+ statSync: () => FileInfo
378
+ truncate: (size?: number) => Promise<void>
379
+ truncateSync: (size?: number) => void
380
+ sync: () => Promise<void>
381
+ syncSync: () => void
382
+ lock: (exclusive?: boolean) => Promise<void>
383
+ tryLock: (exclusive?: boolean) => Promise<boolean>
384
+ tryLockSync: (exclusive?: boolean) => boolean
385
+ unlock: () => Promise<void>
386
+ close: () => void
387
+ [Symbol.dispose]: () => void
388
+ }
389
+
390
+ // Contenders have unique names, so recovery removes only a dead descriptor's
391
+ // claim, never a subsequent holder. The directory stays across acquisitions.
392
+ let locking = (fd: number) => {
393
+ let { dev, ino } = fs.fstatSync(fd)
394
+ let at = join(
395
+ tmpdir(),
396
+ `yaks-file-locks-${process.getuid?.() ?? 'user'}`,
397
+ `${dev}.${ino}`,
398
+ )
399
+ let key = `${process.pid}.${crypto.randomUUID()}`
400
+ let token = ''
401
+ let own = ''
402
+ let exclusiveHeld = false
403
+ let held = false
404
+ let unlock = () => {
405
+ if (!held) return
406
+ fs.unlinkSync(own)
407
+ held = false
408
+ }
409
+ let tryLock = (exclusive = false) => {
410
+ if (held && exclusiveHeld == exclusive) return true
411
+ unlock()
412
+ token = `${key}.${exclusive ? 'write' : 'read'}`
413
+ own = join(at, token)
414
+ exclusiveHeld = exclusive
415
+ fs.mkdirSync(at, { recursive: true, mode: 0o700 })
416
+ fs.closeSync(fs.openSync(own, 'wx', 0o600))
417
+ try {
418
+ for (let name of fs.readdirSync(at)) {
419
+ if (name == token) continue
420
+ let pid = Number(name.split('.')[0])
421
+ if (!pid) throw new Error(`invalid file lock: ${join(at, name)}`)
422
+ try {
423
+ process.kill(pid, 0)
424
+ if (exclusive || name.endsWith('.write')) return false
425
+ continue
426
+ } catch (e) {
427
+ if (!isNotFound(e)) throw e
428
+ }
429
+ try {
430
+ fs.unlinkSync(join(at, name))
431
+ } catch (e) {
432
+ if (!isNotFound(e)) throw e
433
+ }
434
+ }
435
+ return held = true
436
+ } finally {
437
+ if (!held) fs.unlinkSync(own)
438
+ }
439
+ }
440
+ return { tryLock, unlock }
441
+ }
442
+
443
+ let opened = (fd: number): FsFile => {
444
+ let position = 0
445
+ let closed = false
446
+ let locks: ReturnType<typeof locking> | undefined
447
+ let tryLock = (exclusive = false) => {
448
+ if (closed) throw new Error('file is closed')
449
+ return (locks ??= locking(fd)).tryLock(exclusive)
450
+ }
451
+ let seek = (offset: number, mode: number) => {
452
+ position = offset +
453
+ (mode == SeekMode.Current
454
+ ? position
455
+ : mode == SeekMode.End
456
+ ? fs.fstatSync(fd).size
457
+ : 0)
458
+ if (position < 0) throw new RangeError('negative seek position')
459
+ return position
460
+ }
461
+ let close = () => {
462
+ if (closed) return
463
+ try {
464
+ locks?.unlock()
465
+ } finally {
466
+ fs.closeSync(fd)
467
+ closed = true
468
+ }
469
+ }
470
+ return {
471
+ fd,
472
+ read: async (buffer) => {
473
+ let n = await call<number>((done) =>
474
+ fs.read(fd, buffer, 0, buffer.length, position, done)
475
+ )
476
+ position += n
477
+ return n || (buffer.length ? null : 0)
478
+ },
479
+ readSync: (buffer) => {
480
+ let n = fs.readSync(fd, buffer, 0, buffer.length, position)
481
+ position += n
482
+ return n || (buffer.length ? null : 0)
483
+ },
484
+ write: async (buffer) => {
485
+ let n = await call<number>((done) =>
486
+ fs.write(fd, buffer, 0, buffer.length, position, done)
487
+ )
488
+ position += n
489
+ return n
490
+ },
491
+ writeSync: (buffer) => {
492
+ let n = fs.writeSync(fd, buffer, 0, buffer.length, position)
493
+ position += n
494
+ return n
495
+ },
496
+ seek: (offset, mode) => Promise.resolve(seek(offset, mode)),
497
+ seekSync: seek,
498
+ stat: async () => info(await call<fs.Stats>((done) => fs.fstat(fd, done))),
499
+ statSync: () => info(fs.fstatSync(fd)),
500
+ truncate: (size = 0) => call<void>((done) => fs.ftruncate(fd, size, done)),
501
+ truncateSync: (size = 0) => fs.ftruncateSync(fd, size),
502
+ sync: () => call<void>((done) => fs.fsync(fd, done)),
503
+ syncSync: () => fs.fsyncSync(fd),
504
+ lock: async (exclusive = false) => {
505
+ while (!tryLock(exclusive)) {
506
+ await new Promise((resolve) =>
507
+ setTimeout(resolve, 5 + Math.random() * 10)
508
+ )
509
+ }
510
+ },
511
+ tryLock: (exclusive) => Promise.resolve(tryLock(exclusive)),
512
+ tryLockSync: tryLock,
513
+ unlock: () => {
514
+ locks?.unlock()
515
+ return Promise.resolve()
516
+ },
517
+ close,
518
+ [Symbol.dispose]: close,
519
+ }
520
+ }
521
+ export let open = async (path: Path, o: OpenOptions = {}): Promise<FsFile> =>
522
+ opened(
523
+ await call<number>((done) =>
524
+ fs.open(reading(path), flags(o), o.mode, done)
525
+ ),
526
+ )
527
+ export let openSync = (path: Path, o: OpenOptions = {}): FsFile =>
528
+ opened(fs.openSync(reading(path), flags(o), o.mode))
package/local.js ADDED
@@ -0,0 +1,105 @@
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
+ import { mint } from "@yaks/graph";
11
+ import { line } from "@yaks/query";
12
+ import { joined, onVolume, placed, volumeOf } from "./mod.js";
13
+ let found = async (g)=>{
14
+ let held = await g.read('.machine.address=local://');
15
+ if (held.length > 1) throw Error('Multiple computers claim local://');
16
+ if (held[0]) return held[0].entity.eid;
17
+ let eid = mint();
18
+ await g.apply([
19
+ {
20
+ entity: {
21
+ eid
22
+ },
23
+ machine: {
24
+ address: 'local://'
25
+ }
26
+ }
27
+ ]);
28
+ return eid;
29
+ };
30
+ let mounted = async (g)=>{
31
+ let machine = await here(g);
32
+ let rows = await g.read(line`.volume.machine=${machine}`);
33
+ let mounts = new Map(rows.map((b)=>[
34
+ String(b.volume.mount),
35
+ b.entity.eid
36
+ ]));
37
+ if (!mounts.has('/')) {
38
+ let eid = volumeOf(machine, '/');
39
+ await g.apply([
40
+ {
41
+ entity: {
42
+ eid
43
+ },
44
+ volume: {
45
+ machine,
46
+ mount: '/'
47
+ }
48
+ }
49
+ ]);
50
+ mounts.set('/', eid);
51
+ }
52
+ return mounts;
53
+ };
54
+ let perGraph = (f)=>{
55
+ let held = new WeakMap();
56
+ return (g)=>{
57
+ let p = held.get(g);
58
+ if (p) return p;
59
+ p = f(g);
60
+ held.set(g, p);
61
+ p.catch(()=>held.delete(g));
62
+ return p;
63
+ };
64
+ };
65
+ /** This computer: the machine addressed `local://`, written the first time
66
+ * a graph is asked for it. */ export let here = perGraph(found);
67
+ let volumes = perGraph(mounted);
68
+ /**
69
+ * An absolute path on this computer, as the file it is: the bundle that makes
70
+ * it one, on the volume that holds it. Writing it again writes the same
71
+ * entity.
72
+ *
73
+ * ```ts
74
+ * import { onDisk } from '@yaks/file/local'
75
+ *
76
+ * // let [file] = await onDisk(graph, '/home/me/.claude/projects/x.jsonl')
77
+ * // file.file -> { path: 'home/me/.claude/projects/x.jsonl', root: <volume> }
78
+ * ```
79
+ */ export let onDisk = async (g, absolute)=>{
80
+ let mounts = await volumes(g);
81
+ let at = placed([
82
+ ...mounts.keys()
83
+ ], absolute);
84
+ if (!at) throw Error(`No volume of this computer holds ${absolute}`);
85
+ return onVolume(mounts.get(at.mount), at.path);
86
+ };
87
+ /** Where a file is on this computer's disks: its absolute path, or nothing
88
+ * for a file in a repository or on another machine. */ export let absolute = async (g, file)=>{
89
+ let { root, path } = file.file ?? {};
90
+ if (root == null || path == null) return undefined;
91
+ let [volume] = await g.get([
92
+ String(root)
93
+ ], [
94
+ 'volume'
95
+ ]);
96
+ let { machine, mount } = volume?.volume ?? {};
97
+ if (machine == null || mount == null) return undefined;
98
+ let [computer] = await g.get([
99
+ String(machine)
100
+ ], [
101
+ 'machine'
102
+ ]);
103
+ return computer?.machine?.address == 'local://' ? joined(String(mount), String(path)) : undefined;
104
+ };
105
+ //# sourceMappingURL=local.js.map
package/local.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local.js","sources":["./local.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,8EAA8E;AAC9E,6EAA6E;AAC7E,4EAA4E;AAC5E,uEAAuE;AACvE,EAAE;AACF,4EAA4E;AAC5E,qEAAqE;AACrE,aAAa;AAGb,SAAS,IAAI,2BAAgC;AAC7C,SAAS,IAAI,2BAAgC;AAC7C,SAAS,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,mBAAkB;AAE7D,IAAI,QAAQ,OAAO;EACjB,IAAI,OAAO,MAAM,EAAE,IAAI,CAAC;EACxB,IAAI,KAAK,MAAM,GAAG,GAAG,MAAM,MAAM;EACjC,IAAI,IAAI,CAAC,EAAE,EAAE,OAAO,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,GAAG;EACtC,IAAI,MAAM;EACV,MAAM,EAAE,KAAK,CAAC;IAAC;MAAE,QAAQ;QAAE;MAAI;MAAG,SAAS;QAAE,SAAS;MAAW;IAAE;GAAE;EACrE,OAAO;AACT;AAEA,IAAI,UAAU,OAAO;EACnB,IAAI,UAAU,MAAM,KAAK;EACzB,IAAI,OAAO,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,QAAQ,CAAC;EACxD,IAAI,SAAS,IAAI,IACf,KAAK,GAAG,CAAC,CAAC,IAAM;MAAC,OAAO,AAAC,EAAE,MAAM,CAAU,KAAK;MAAG,EAAE,MAAM,CAAC,GAAG;KAAC;EAElE,IAAI,CAAC,OAAO,GAAG,CAAC,MAAM;IACpB,IAAI,MAAM,SAAS,SAAS;IAC5B,MAAM,EAAE,KAAK,CAAC;MAAC;QAAE,QAAQ;UAAE;QAAI;QAAG,QAAQ;UAAE;UAAS,OAAO;QAAI;MAAE;KAAE;IACpE,OAAO,GAAG,CAAC,KAAK;EAClB;EACA,OAAO;AACT;AAEA,IAAI,WAAW,CAAI;EACjB,IAAI,OAAO,IAAI;EACf,OAAO,CAAC;IACN,IAAI,IAAI,KAAK,GAAG,CAAC;IACjB,IAAI,GAAG,OAAO;IACd,IAAI,EAAE;IACN,KAAK,GAAG,CAAC,GAAG;IACZ,EAAE,KAAK,CAAC,IAAM,KAAK,MAAM,CAAC;IAC1B,OAAO;EACT;AACF;AAEA;4BAC4B,GAC5B,OAAO,IAAI,OAAmC,SAAS,OAAM;AAE7D,IAAI,UAAU,SAAS;AAEvB;;;;;;;;;;;CAWC,GACD,OAAO,IAAI,SAAS,OAAO,GAAU;EACnC,IAAI,SAAS,MAAM,QAAQ;EAC3B,IAAI,KAAK,OAAO;OAAI,OAAO,IAAI;GAAG,EAAE;EACpC,IAAI,CAAC,IAAI,MAAM,MAAM,CAAC,iCAAiC,EAAE,UAAU;EACnE,OAAO,SAAS,OAAO,GAAG,CAAC,GAAG,KAAK,GAAI,GAAG,IAAI;AAChD,EAAC;AAED;qDACqD,GACrD,OAAO,IAAI,WAAW,OACpB,GACA;EAEA,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,GAAI,KAAK,IAAI,IAAI,CAAC;EACpC,IAAI,QAAQ,QAAQ,QAAQ,MAAM,OAAO;EACzC,IAAI,CAAC,OAAO,GAAG,MAAM,EAAE,GAAG,CAAC;IAAC,OAAO;GAAM,EAAE;IAAC;GAAS;EACrD,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,GAAI,QAAQ,UAAU,CAAC;EAC7C,IAAI,WAAW,QAAQ,SAAS,MAAM,OAAO;EAC7C,IAAI,CAAC,SAAS,GAAG,MAAM,EAAE,GAAG,CAAC;IAAC,OAAO;GAAS,EAAE;IAAC;GAAU;EAC3D,OAAO,AAAC,UAAU,SAA8B,WAAW,aACvD,OAAO,OAAO,QAAQ,OAAO,SAC7B;AACN,EAAC"}