@thedriveai/device-helper 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.d.ts ADDED
@@ -0,0 +1,741 @@
1
+ interface CatalogItem {
2
+ externalId: string;
3
+ /** The platform's id of the parent; null when the platform reports none (shared with me). */
4
+ parentExternalId: string | null;
5
+ name: string;
6
+ kind: "file" | "folder";
7
+ mimeType: string;
8
+ size: number | null;
9
+ mtime: string | null;
10
+ ctime: string | null;
11
+ /** Algo-prefixed (contentIdentity.contentHashKey); null when the provider reports none. */
12
+ contentHash: string | null;
13
+ ownerEmail: string | null;
14
+ webUrl: string | null;
15
+ trashed: boolean;
16
+ /** Trashed by itself rather than by a folder above it; absent = same as `trashed`. */
17
+ explicitlyTrashed?: boolean;
18
+ /**
19
+ * The bytes are not where the item is (a cloud placeholder on a device: iCloud, Dropbox, OneDrive online-only).
20
+ * Reading it downloads it; the index, the hash backfill and every background read leave it alone
21
+ * (docs/agent/DEVICE_MOUNTS.md §11). Absent = present.
22
+ */
23
+ onlineOnly?: boolean;
24
+ /**
25
+ * An image's embedded facts as the PLATFORM reports them (Google Drive's imageMediaMetadata). Present = the
26
+ * platform answered for this file (every field may still be null: a photo without EXIF); absent = not asked,
27
+ * so the catalog keeps what it had.
28
+ */
29
+ media?: CatalogMedia;
30
+ }
31
+ interface CatalogMedia {
32
+ takenAt: string | null;
33
+ gpsLat: number | null;
34
+ gpsLng: number | null;
35
+ cameraMake: string | null;
36
+ cameraModel: string | null;
37
+ width: number | null;
38
+ height: number | null;
39
+ }
40
+ interface CatalogChange {
41
+ externalId: string;
42
+ /**
43
+ * The item stood at this address before (a device's journal pairs a rename or a move into ONE entry). The
44
+ * catalogue rewrites the node's address instead of deleting one row and inserting another, so the node keeps its
45
+ * id, its text, and every dataset and grant that names it. Absent on every platform with minted ids.
46
+ */
47
+ movedFrom?: string;
48
+ /** No longer listed by the platform: deleted, trashed on a platform that does not list its trash, or out of view. */
49
+ removed: boolean;
50
+ /**
51
+ * The platform cannot say whether a removal is permanent or a trip to its recycle bin (Graph's `deleted`
52
+ * facet is the same for both): the item MAY come back. The catalog keeps a tombstone instead of dropping the
53
+ * row, so a restore finds the same node id — the one the journal, grants and datasets hold. A removal
54
+ * without it (Google's `removed`: gone for good, since Drive lists its trash) drops the row.
55
+ */
56
+ recoverable?: boolean;
57
+ /**
58
+ * The platform SAW this path appear (a device's journal knows a new file from a rewritten one; a cloud feed
59
+ * does not say). A workflow trigger takes it as the verdict; absent, created-vs-updated is decided from the
60
+ * file's creation time against the watch's currency, as for every cloud platform.
61
+ */
62
+ created?: boolean;
63
+ item: CatalogItem | null;
64
+ }
65
+ /**
66
+ * 2 (2026-10-12): a move or rename is ONE journal entry naming where the item was (CatalogChange.movedFrom); a
67
+ * version-1 helper sends a removal and an upsert, which the server still takes. Photo facts may be `'unknown'`.
68
+ */
69
+ export declare const DEVICE_PROTOCOL_VERSION = 2;
70
+ /** The socket.io namespace devices connect to. */
71
+ export declare const DEVICE_NAMESPACE = "/devices";
72
+ /** One chunk of a streamed read, as the helper sends it. */
73
+ export declare const STREAM_CHUNK_BYTES: number;
74
+ /**
75
+ * What the helper runs on. `ios` and `android` are the mobile app sharing a picked folder (DEVICE_MOUNTS.md §28): the
76
+ * same protocol, answered only while the app is open.
77
+ */
78
+ export type DevicePlatform = "darwin" | "linux" | "win32" | "docker" | "ios" | "android";
79
+ /** A phone: present only while its app is open, so "offline" is its ordinary state and not a fault. */
80
+ export declare function isPhonePlatform(platform: string | null | undefined): boolean;
81
+ /**
82
+ * Where a delete goes on a root whose host has no trash an app may use (a phone): a folder of this name at the top
83
+ * of the shared folder, which the helper never lists. One name for both ends, so the person is told the folder the
84
+ * helper really uses.
85
+ */
86
+ export declare const DEVICE_TRASH_FOLDER = "Deleted by The Drive AI";
87
+ /** A folder the helper shares, as it announces it. The id is minted by the helper and survives a path change. */
88
+ export interface DeviceRoot {
89
+ id: string;
90
+ label: string;
91
+ /** Whether a delete here goes to a trash the person can recover from (Finder, the Recycle Bin, a --trash-dir). */
92
+ trash: boolean;
93
+ /**
94
+ * `folder`: that trash is DEVICE_TRASH_FOLDER inside the shared folder itself (a phone), so the person is told to
95
+ * look there rather than in an OS trash. Absent = the host's own trash.
96
+ */
97
+ trashIn?: "folder";
98
+ /** The helper refuses every write to this root. */
99
+ readOnly: boolean;
100
+ /**
101
+ * What the index may read of it (DEVICE_MOUNTS.md §10): `names` = nothing, the agent organises by name, date and
102
+ * photo facts; `documents` = their text, as for any drive. Absent = leave the source's current choice alone.
103
+ */
104
+ content?: "names" | "documents";
105
+ /**
106
+ * Share with the whole workspace (a NAS): honoured when the root is first catalogued and the pairing person is an
107
+ * admin; a choice made later in Settings is never overridden by a hello. Absent = personal.
108
+ */
109
+ shared?: boolean;
110
+ /**
111
+ * Whether the root can be read right now (DEVICE_MOUNTS.md §11): `denied` = the OS has not allowed the helper to
112
+ * read it (macOS privacy); `missing` = the path is not there (a disk unplugged, a volume asleep). Absent = ok.
113
+ * The source is paused with the reason while the state lasts; nothing is ever catalogued as empty.
114
+ */
115
+ state?: "ok" | "denied" | "missing";
116
+ /** The cloud drive this folder is the local copy of (Dropbox, OneDrive, Google Drive, iCloud, Box), when it is one. */
117
+ syncOf?: "dropbox" | "onedrive" | "google_drive" | "icloud" | "box";
118
+ }
119
+ export interface DeviceHello {
120
+ protocol: number;
121
+ /**
122
+ * `push` (a phone only): the install's Expo push token. With it the server can wake THIS phone when work needs
123
+ * its folders and the app is not open (DEVICE_MOUNTS.md §29). Honoured only while its owner has the same token
124
+ * registered for the assistant's pushes; never shown to anyone.
125
+ */
126
+ device: {
127
+ id: string;
128
+ name: string;
129
+ platform: DevicePlatform;
130
+ helperVersion: string;
131
+ push?: string;
132
+ };
133
+ roots: DeviceRoot[];
134
+ /**
135
+ * Roots the person STOPPED SHARING (DEVICE_MOUNTS.md §17): the server retires their sources outright, where a
136
+ * root merely absent from `roots` is only paused (a reconfiguration, a released transient). The helper repeats
137
+ * them until a hello carrying them is acknowledged.
138
+ */
139
+ retired?: string[];
140
+ }
141
+ export interface DeviceHelloAck {
142
+ ok: boolean;
143
+ /** The connection id the device is known by, for its logs. */
144
+ connectionId?: string;
145
+ /**
146
+ * Roots the server will not take back (DEVICE_MOUNTS.md §17): they were retired (stopped from Settings while the
147
+ * device was away, or retired before and announced again). A root id is minted once per share and never reused, so a
148
+ * retired id is dead; the helper stops sharing these.
149
+ */
150
+ retire?: string[];
151
+ error?: string;
152
+ }
153
+ type RpcErrorCode = "NOT_FOUND" | "EXISTS" | "PERMISSION_DENIED" | "READ_ONLY" | "NO_TRASH" | "TOO_LARGE" | "BAD_PATH" | "UNSUPPORTED" | "RESET"
154
+ /** The root cannot be read right now (missing, denied): the server treats it as an offline device. */
155
+ | "UNAVAILABLE"
156
+ /** The file's bytes are not on the disk (a cloud placeholder) and the read did not allow fetching them. */
157
+ | "ONLINE_ONLY" | "INTERNAL";
158
+ interface RpcError {
159
+ code: RpcErrorCode;
160
+ message: string;
161
+ }
162
+ export type RpcResult<T> = {
163
+ ok: true;
164
+ result: T;
165
+ } | {
166
+ ok: false;
167
+ error: RpcError;
168
+ };
169
+ export interface RpcRequest<M extends RpcMethod = RpcMethod> {
170
+ id: string;
171
+ method: M;
172
+ params: RpcParams[M];
173
+ }
174
+ /** A file or folder as the helper describes it: the catalog's item shape, path-addressed. */
175
+ export type DeviceItem = CatalogItem;
176
+ interface DeviceChanged {
177
+ root: string;
178
+ cursor: string;
179
+ }
180
+ interface RpcParams {
181
+ enumerate: {
182
+ root: string;
183
+ cursor: string | null;
184
+ limit: number;
185
+ };
186
+ changes: {
187
+ root: string;
188
+ cursor: string;
189
+ limit: number;
190
+ };
191
+ stat: {
192
+ root: string;
193
+ path: string;
194
+ };
195
+ list: {
196
+ root: string;
197
+ path: string;
198
+ cursor: string | null;
199
+ limit: number;
200
+ };
201
+ /** `allowFetch`: an online-only placeholder may be downloaded by the OS to answer (a person's own read of that file). */
202
+ /** `stream`: the id the server is already listening on for this read's chunks (older helpers pick their own and answer it). */
203
+ read: {
204
+ root: string;
205
+ path: string;
206
+ maxBytes?: number;
207
+ allowFetch?: boolean;
208
+ stream?: string;
209
+ };
210
+ write: {
211
+ root: string;
212
+ path: string;
213
+ data: Buffer;
214
+ mode: "create" | "replace";
215
+ };
216
+ /**
217
+ * A streamed write, the mirror of `read` (DEVICE_MOUNTS.md §4): the server opens it naming the stream it will
218
+ * send on, sends `write_chunk`s each acknowledged by the helper, then closes it; the file appears at `path` only
219
+ * at the close (written beside, renamed over). `size` is what the server expects to send when it knows.
220
+ */
221
+ write_open: {
222
+ root: string;
223
+ path: string;
224
+ mode: "create" | "replace";
225
+ size: number | null;
226
+ stream: string;
227
+ };
228
+ /** `bytes`: what the server sent; the helper refuses a close that does not match what it wrote. */
229
+ write_close: {
230
+ root: string;
231
+ path: string;
232
+ stream: string;
233
+ bytes?: number;
234
+ };
235
+ mkdir: {
236
+ root: string;
237
+ path: string;
238
+ };
239
+ /** `to` is the full new path: a rename changes the last segment, a move the folder, one call does either. */
240
+ move: {
241
+ root: string;
242
+ from: string;
243
+ to: string;
244
+ };
245
+ copy: {
246
+ root: string;
247
+ from: string;
248
+ to: string;
249
+ };
250
+ trash: {
251
+ root: string;
252
+ path: string;
253
+ };
254
+ /** SHA-256 of each file's bytes, computed on the device (a file over `maxBytes` is skipped). */
255
+ hash: {
256
+ root: string;
257
+ paths: string[];
258
+ maxBytes?: number;
259
+ };
260
+ /** Photo facts (EXIF: when, where, camera, pixels) read on the device for these files; nothing but the facts travels. */
261
+ media: {
262
+ root: string;
263
+ paths: string[];
264
+ };
265
+ }
266
+ interface RpcResults {
267
+ /** `unreadable`: folders on this page whose contents could not be read (unknown, not empty). */
268
+ enumerate: {
269
+ items: DeviceItem[];
270
+ cursor: string | null;
271
+ done: boolean;
272
+ unreadable?: string[];
273
+ };
274
+ changes: {
275
+ changes: CatalogChange[];
276
+ cursor: string;
277
+ done: boolean;
278
+ resetRequired?: boolean;
279
+ };
280
+ stat: DeviceItem | null;
281
+ list: {
282
+ items: DeviceItem[];
283
+ cursor: string | null;
284
+ };
285
+ /** The stream the chunks will arrive on, and what they are. */
286
+ read: {
287
+ stream: string;
288
+ size: number | null;
289
+ mimeType: string;
290
+ };
291
+ write: DeviceItem;
292
+ write_open: {
293
+ stream: string;
294
+ };
295
+ write_close: DeviceItem;
296
+ mkdir: DeviceItem;
297
+ move: DeviceItem;
298
+ copy: DeviceItem;
299
+ trash: {
300
+ ok: true;
301
+ };
302
+ /** path → hex SHA-256; null when the file is gone, unreadable or over the limit. */
303
+ hash: {
304
+ hashes: Record<string, string | null>;
305
+ };
306
+ /**
307
+ * path → facts; null when the device has none for it (not a photo, no EXIF, a format it cannot read): an answer, so
308
+ * it is never asked again; `'unknown'` when the device could not find out this time (its tool failed, the file was
309
+ * gone): no answer, the server records nothing and asks again later.
310
+ */
311
+ media: {
312
+ media: Record<string, CatalogMedia | null | "unknown">;
313
+ };
314
+ }
315
+ type RpcMethod = keyof RpcParams;
316
+ interface StreamChunk {
317
+ stream: string;
318
+ seq: number;
319
+ data: Buffer;
320
+ last: boolean;
321
+ }
322
+ interface StreamAbort {
323
+ stream: string;
324
+ reason: string;
325
+ }
326
+ /** Path helpers shared by both ends: a device path is '' or '/a/b', never trailing-slashed. */
327
+ export declare function normalizeDevicePath(input: string): string;
328
+ export declare function deviceDirname(path: string): string;
329
+ export declare function deviceBasename(path: string): string;
330
+ export declare function deviceJoin(folder: string, name: string): string;
331
+ /** A path is well-formed when it has no `.`/`..` segments and no empty segment: the helper refuses anything else. */
332
+ export declare function isSafeDevicePath(path: string): boolean;
333
+ type OpErrorCode = Exclude<RpcErrorCode, "RESET">;
334
+ export declare class OpError extends Error {
335
+ readonly code: OpErrorCode;
336
+ constructor(code: OpErrorCode, message: string);
337
+ }
338
+ /**
339
+ * Anything thrown, as an OpError. An error that already names one of the protocol's codes keeps it (a host's own
340
+ * error class, an OpError from another copy of this module in a bundle); everything else is INTERNAL. A host whose
341
+ * errors carry their own vocabulary (Node's errno) maps them before this is reached.
342
+ */
343
+ export declare function asOpError(error: unknown): OpError;
344
+ /** An opened read: how big the file is when known, and its bytes in pieces no larger than asked. */
345
+ export interface ReadOpened {
346
+ size: number | null;
347
+ /** What to call the file in a log line. */
348
+ label: string;
349
+ /** The bytes, in order. Iterated once; stopping early (the server aborted, the line dropped) releases the file. */
350
+ chunks(chunkBytes: number): AsyncIterable<Uint8Array>;
351
+ }
352
+ export interface RootPort {
353
+ /** The change feed's last durable position, as the nudge to the server carries it. */
354
+ readonly position: string;
355
+ stat(params: RpcParams["stat"]): Promise<RpcResults["stat"]>;
356
+ list(params: RpcParams["list"]): Promise<RpcResults["list"]>;
357
+ enumerate(params: RpcParams["enumerate"]): Promise<RpcResults["enumerate"]>;
358
+ changes(params: RpcParams["changes"]): Promise<RpcResults["changes"]>;
359
+ mkdir(params: RpcParams["mkdir"]): Promise<RpcResults["mkdir"]>;
360
+ move(params: RpcParams["move"]): Promise<RpcResults["move"]>;
361
+ copy(params: RpcParams["copy"]): Promise<RpcResults["copy"]>;
362
+ trash(params: RpcParams["trash"]): Promise<RpcResults["trash"]>;
363
+ write(params: RpcParams["write"]): Promise<RpcResults["write"]>;
364
+ openWrite(params: RpcParams["write_open"]): Promise<RpcResults["write_open"]>;
365
+ /** One chunk, in order; true once it is kept (the server's permission to send the next). */
366
+ appendWrite(chunk: {
367
+ stream: string;
368
+ seq: number;
369
+ data: Uint8Array | ArrayBuffer;
370
+ }): Promise<boolean>;
371
+ closeWrite(params: RpcParams["write_close"]): Promise<RpcResults["write_close"]>;
372
+ /** The server gave up, or the line went: what was written so far is dropped, the destination untouched. */
373
+ abortWrite(stream: string): Promise<void>;
374
+ hash(params: RpcParams["hash"]): Promise<RpcResults["hash"]>;
375
+ media(params: RpcParams["media"]): Promise<RpcResults["media"]>;
376
+ openRead(params: RpcParams["read"]): ReadOpened | Promise<ReadOpened>;
377
+ }
378
+ export interface ClientSocketLike {
379
+ on(event: "connect", handler: () => void): void;
380
+ on(event: "disconnect", handler: (reason: string) => void): void;
381
+ on(event: "connect_error", handler: (error: Error) => void): void;
382
+ on(event: "rpc", handler: (request: RpcRequest, ack: (reply: RpcResult<unknown>) => void) => void): void;
383
+ on(event: "stream_abort", handler: (abort: StreamAbort) => void): void;
384
+ on(event: "write_chunk", handler: (chunk: StreamChunk, ack: (ok: boolean) => void) => void): void;
385
+ on(event: "superseded", handler: (notice: {
386
+ reason: string;
387
+ }) => void): void;
388
+ emit(event: "hello", hello: DeviceHello, ack: (reply: DeviceHelloAck) => void): void;
389
+ emit(event: "changed", notice: DeviceChanged): void;
390
+ timeout(ms: number): {
391
+ emitWithAck(event: "chunk", chunk: StreamChunk): Promise<boolean>;
392
+ };
393
+ connected: boolean;
394
+ /** socket.io's connect(): used to come back after the server hung up, which socket.io does not retry on its own. */
395
+ connect?(): unknown;
396
+ }
397
+ export interface DeviceClientDeps {
398
+ socket: ClientSocketLike;
399
+ device: DeviceHello["device"];
400
+ roots: () => Array<{
401
+ announce: DeviceRoot;
402
+ ops: RootPort;
403
+ }>;
404
+ /** Roots the person stopped sharing, until the server has heard it (§17). */
405
+ retired?: () => string[];
406
+ /** The server acknowledged a hello that carried these: forget them. */
407
+ retiredAcked?: (ids: string[]) => void;
408
+ /** The server will not take these roots back (retired while this device was away): stop sharing them here. */
409
+ retireRequested?: (ids: string[]) => void;
410
+ log: (line: string) => void;
411
+ chunkBytes?: number;
412
+ /** How long to wait before dialling again after the server hung up. */
413
+ reconnectAfterMs?: number;
414
+ /** How long a burst of changes on one root is let settle before the server is nudged. */
415
+ changeDebounceMs?: number;
416
+ /** Anything a root threw, as the protocol's error. A host with its own error vocabulary (Node's errno) maps it here. */
417
+ toError?: (error: unknown) => OpError;
418
+ /** A stream id for a read an older server did not name (a uuid). Today's server always names its own. */
419
+ newStreamId?: () => string;
420
+ }
421
+ /** How long, and how many, answers to writes are remembered: well past the server's retries of one call. */
422
+ export declare const REPLY_MEMORY_MS: number;
423
+ /** How long one chunk may wait for the server's ack: a slow reader holds it back on purpose. */
424
+ export declare const CHUNK_ACK_WAIT_MS: number;
425
+ /**
426
+ * Answers by request id, in flight or finished, for a few minutes after they SETTLE; the oldest settled go first. An
427
+ * answer still running is never forgotten: the server asks again under the same id for as long as the op takes (a
428
+ * folder copy of gigabytes), and a forgotten in-flight entry would start the op a second time beside the first.
429
+ */
430
+ export declare class RecentReplies<T> {
431
+ private readonly ttlMs;
432
+ private readonly max;
433
+ private readonly now;
434
+ private readonly byId;
435
+ constructor(ttlMs?: number, max?: number, now?: () => number);
436
+ once(id: string, run: () => Promise<T>): Promise<T>;
437
+ private evict;
438
+ /** Test seam. */
439
+ get size(): number;
440
+ }
441
+ declare class CoreDeviceClient {
442
+ private readonly deps;
443
+ private readonly replies;
444
+ private readonly aborted;
445
+ private readonly open;
446
+ /** Write streams the server has open, by stream, with the root they write into. */
447
+ private readonly writing;
448
+ private readonly pendingNudges;
449
+ /** Another copy of this device connected with the same token: this one stays down rather than fight it. */
450
+ private superseded;
451
+ /** Hellos the server refused in a row (an unsupported protocol, a token of another device): each wait doubles. */
452
+ private refusals;
453
+ constructor(deps: DeviceClientDeps);
454
+ /**
455
+ * A root's journal moved: nudge the server once the burst settles (a save writes a file three times; a
456
+ * download lands a thousand). The nudge carries only the position; the server reads from its own cursor, so
457
+ * one lost while offline costs nothing: the server's catch-up and the next nudge both read the same feed.
458
+ */
459
+ notifyChanged(rootId: string): void;
460
+ start(): void;
461
+ announce(): void;
462
+ private rootOps;
463
+ /**
464
+ * One RPC. A write the server sends again under the same request id (its ack timed out; the first may have
465
+ * finished, or still be running) gets the first one's answer, never a second run on a half-finished op.
466
+ */
467
+ handle(request: RpcRequest): Promise<RpcResult<unknown>>;
468
+ private dispatch;
469
+ /**
470
+ * The bytes of one read, a chunk at a time, each sent only once the server acknowledged the one before. One chunk
471
+ * is held back so the last can say it is the last (an empty file sends one empty, last chunk). Leaving the loop
472
+ * early (an abort, a dead line) ends the iteration, which is what releases the file.
473
+ */
474
+ private pump;
475
+ private send;
476
+ }
477
+ export interface FolderEntry {
478
+ name: string;
479
+ kind: "file" | "folder";
480
+ /** Bytes; null for a folder or when the store does not say. */
481
+ size: number | null;
482
+ /** Milliseconds since the epoch; null when the store does not say. */
483
+ modifiedMs: number | null;
484
+ /** Android's document tree has no creation time; iOS does. */
485
+ createdMs?: number | null;
486
+ }
487
+ /**
488
+ * How a port fails. Carried as `code` on whatever is thrown (an error from a native module keeps its code and loses
489
+ * its class), so PortableRoot reads the code, never `instanceof`.
490
+ *
491
+ * - NOT_FOUND the item is not there
492
+ * - EXISTS something already stands at the destination
493
+ * - DENIED the OS no longer lets the app into the folder (the grant was revoked, a bookmark went stale)
494
+ * - UNAVAILABLE the folder cannot be reached now (an SD card out, a cloud provider offline)
495
+ * - UNSUPPORTED the store cannot do this at all (a provider without move)
496
+ * - IO anything else the store reported
497
+ */
498
+ export type FolderPortErrorCode = "NOT_FOUND" | "EXISTS" | "DENIED" | "UNAVAILABLE" | "UNSUPPORTED" | "IO";
499
+ export declare class FolderPortError extends Error {
500
+ readonly code: FolderPortErrorCode;
501
+ constructor(code: FolderPortErrorCode, message: string);
502
+ }
503
+ /** The port's code on anything thrown; IO when it names none. */
504
+ export declare function folderPortCode(error: unknown): FolderPortErrorCode;
505
+ export interface FolderPort {
506
+ /**
507
+ * Every child of a folder, in ONE call, in any order. Whole or not at all: a listing that broke off half-way
508
+ * throws, because half a folder read as the folder would report the other half deleted. NOT_FOUND when the folder
509
+ * is not there.
510
+ */
511
+ list(path: string): Promise<FolderEntry[]>;
512
+ /** One item as it is now; null when nothing stands there. */
513
+ stat(path: string): Promise<FolderEntry | null>;
514
+ /** Create one folder; its parent exists. EXISTS when something stands there. */
515
+ mkdir(path: string): Promise<void>;
516
+ /**
517
+ * Rename or move, one call: the item lands exactly at `to`, or the call throws and the item is where it was. A
518
+ * store that would rather pick another name (Android's renames to "name (1)") puts the item back and throws
519
+ * EXISTS. A change of case only is a rename of the same item, never a collision with itself.
520
+ */
521
+ move(from: string, to: string): Promise<void>;
522
+ /** Copy one FILE to a path where nothing stands. A folder is copied by PortableRoot, item by item. */
523
+ copyFile(from: string, to: string): Promise<void>;
524
+ /** Up to `length` bytes from `offset`; fewer (or none) at the end of the file. */
525
+ read(path: string, offset: number, length: number): Promise<Uint8Array>;
526
+ /**
527
+ * The read of this file is over, finished or abandoned. A port that keeps the file open between chunks lets go of
528
+ * it here: kept, an abandoned read would serve the OLD file's bytes to the next read after the file was replaced.
529
+ */
530
+ readEnd?(path: string): Promise<void>;
531
+ /**
532
+ * Start a file that will stand at `path` once committed. The bytes go beside it under a name the walk ignores
533
+ * (a leading dot, a `.part` ending), so a reader never sees half a file and a crash leaves only that.
534
+ */
535
+ writeBegin(path: string): Promise<string>;
536
+ writeAppend(handle: string, data: Uint8Array): Promise<void>;
537
+ /** Land the file. `replace`: a file already at the path is replaced; otherwise one that appeared meanwhile is EXISTS. */
538
+ writeCommit(handle: string, replace: boolean): Promise<void>;
539
+ /** Drop what was written; never throws for a handle already gone. */
540
+ writeAbort(handle: string): Promise<void>;
541
+ /** Lower-case hex SHA-256 of a file's bytes, computed where the bytes are. Absent: the root answers "no hash". */
542
+ sha256?(path: string): Promise<string>;
543
+ /** A photo's embedded facts (EXIF); null when it has none. Absent: the root answers "none" for every file. */
544
+ media?(path: string): Promise<CatalogMedia | null>;
545
+ }
546
+ /**
547
+ * Where a root keeps what it knows between runs: its change journal and its snapshot of the tree. Two named texts in
548
+ * the app's own storage, never in the shared folder.
549
+ */
550
+ export interface StatePort {
551
+ /** The whole text; null when it was never written. */
552
+ read(name: PortableStateName): Promise<string | null>;
553
+ /** Replace the whole text, all or nothing (written beside, moved over). */
554
+ write(name: PortableStateName, text: string): Promise<void>;
555
+ /** Add to the end; resolved once it would survive the app being killed. */
556
+ append(name: PortableStateName, text: string): Promise<void>;
557
+ }
558
+ export type PortableStateName = "journal" | "snapshot";
559
+ export type PortableRootState = "ok" | "denied" | "missing";
560
+ export interface PortableRootConfig {
561
+ /** Minted once per share and never reused (the server retires an id for good). */
562
+ id: string;
563
+ label: string;
564
+ readOnly?: boolean;
565
+ /** What the index may read (DEVICE_MOUNTS.md §10). A phone defaults to names: bytes cost the person's data plan. */
566
+ content?: "names" | "documents";
567
+ /** False: deletes are refused (the agent moves instead). Default: deletes go to DEVICE_TRASH_FOLDER in this folder. */
568
+ trash?: boolean;
569
+ }
570
+ export interface PortableRootDeps {
571
+ config: PortableRootConfig;
572
+ port: FolderPort;
573
+ state: StatePort;
574
+ log?: (line: string) => void;
575
+ now?: () => number;
576
+ /** The journal moved: the host nudges the server (DeviceClient.notifyChanged). */
577
+ onChanged?: () => void;
578
+ /** The folder became readable, or stopped being: the host announces again. */
579
+ onStateChange?: (state: PortableRootState) => void;
580
+ /** How old the last look may be before the server's `changes` poll starts another. */
581
+ staleAfterMs?: number;
582
+ /** Folders listed at once during a walk. A listing is a round trip to another process (or thread); a tree of ten thousand folders walked one at a time is ten thousand of them in a row. */
583
+ walkConcurrency?: number;
584
+ journalKeep?: number;
585
+ }
586
+ export interface PortableRescanResult {
587
+ seen: number;
588
+ added: number;
589
+ changed: number;
590
+ removed: number;
591
+ /** Folders that could not be read: what was known under them is kept. */
592
+ unreadable: string[];
593
+ /** More changes than the journal replays: a new epoch, the server re-enumerates. */
594
+ reset?: {
595
+ changes: number;
596
+ };
597
+ }
598
+ /** The largest write taken in one message (ops.ts's bound). */
599
+ export declare const PORTABLE_MAX_WRITE_BYTES: number;
600
+ export declare class PortableRoot implements RootPort {
601
+ private readonly deps;
602
+ private readonly journal;
603
+ private readonly snapshot;
604
+ private rootState;
605
+ /** The first walk finished: the snapshot is the tree. */
606
+ private walked;
607
+ private opened;
608
+ private scanning;
609
+ private lastLookAt;
610
+ /** When the last walk BEGAN: what it saw is at least this old. */
611
+ private lookBeganAt;
612
+ private stopped;
613
+ /** Writes and rescans, one at a time. */
614
+ private turn;
615
+ private readonly writes;
616
+ private readonly closed;
617
+ constructor(deps: PortableRootDeps);
618
+ /** There is a catalogue to answer from: this run walked the folder, or the last run's snapshot was loaded. */
619
+ private get known();
620
+ private get port();
621
+ private get config();
622
+ private now;
623
+ private log;
624
+ get id(): string;
625
+ get state(): PortableRootState;
626
+ get reason(): string | null;
627
+ get position(): string;
628
+ /** Items the catalogue of this folder holds. */
629
+ get count(): number;
630
+ get rescanning(): boolean;
631
+ get hasTrash(): boolean;
632
+ /** The root as the hello announces it. */
633
+ announce(): DeviceRoot;
634
+ /**
635
+ * Load what was known, look at the folder, walk it. A folder that cannot be read comes up paused with its state
636
+ * (announced, so the server pauses the source with the reason); `reprobe` finishes the job once it can be.
637
+ * Nothing is ever walked as empty.
638
+ */
639
+ open(): Promise<void>;
640
+ /**
641
+ * The stored snapshot may be behind the journal (the app was killed after an op, before a save): what the journal
642
+ * recorded since is applied, so the next walk does not find those changes a second time.
643
+ */
644
+ private replayJournal;
645
+ private probe;
646
+ private setState;
647
+ /** Ask the OS again (the app came back, the folder was chosen again). True when the state changed. */
648
+ reprobe(): Promise<boolean>;
649
+ /** Everything recorded is durable and the snapshot stored: called when the app leaves the foreground. */
650
+ flush(): Promise<void>;
651
+ /**
652
+ * The folder is no longer served (stopped sharing, signed out). A walk in progress ends at its next folder and
653
+ * whatever holds the queue finishes first, so nothing touches the port or the state store after this resolves:
654
+ * the host is about to give the grant back and may delete the state.
655
+ */
656
+ stop(): Promise<void>;
657
+ private isShared;
658
+ /** A path as the server named it, checked: well-formed and inside what this root shares. */
659
+ private resolve;
660
+ private available;
661
+ private writable;
662
+ /**
663
+ * What the port threw, as the protocol's error. A denial or an unreachable store is asked of the ROOT before it
664
+ * is believed of the item: the grant gone or the card out pauses the whole folder (announced), one locked file
665
+ * does not.
666
+ */
667
+ private fail;
668
+ private call;
669
+ private exclusive;
670
+ private withHash;
671
+ private item;
672
+ private statSnap;
673
+ private record;
674
+ private forget;
675
+ /** A write answers once what it journaled is durable; the snapshot follows every so often. */
676
+ private landed;
677
+ /** One walk at a time: a rescan asked for while one runs gets that one's answer. */
678
+ rescan(): Promise<PortableRescanResult>;
679
+ /**
680
+ * The whole tree, as the port lists it now. A folder that cannot be read is named, never taken as empty. Several
681
+ * folders are listed at once (walkConcurrency): the order they answer in does not matter, because what is built is
682
+ * a map of paths, and the walk's ORDER is a property of the paths themselves (compareWalkOrder), not of the visit.
683
+ */
684
+ private walk;
685
+ private walkAndDiff;
686
+ /** The first walk is what `enumerate` and the feed stand on: wait for it rather than answer from nothing. */
687
+ private ready;
688
+ /**
689
+ * Make sure the folder has been looked at recently: a look that BEGAN within the last `maxAgeMs` is enough,
690
+ * otherwise another is made. 0 means "look now": a walk already under way began before this was asked and may
691
+ * have passed the folder that just changed, so it is waited for and then followed by a fresh one.
692
+ */
693
+ refresh(maxAgeMs: number): Promise<void>;
694
+ stat(params: RpcParams["stat"]): Promise<RpcResults["stat"]>;
695
+ /** One folder's children as they are NOW (the executor's namesake check), in the walk's order, a page at a time. */
696
+ list(params: RpcParams["list"]): Promise<RpcResults["list"]>;
697
+ /** A page of the whole tree, out of the snapshot, in the walk's order. The cursor is the last item sent. */
698
+ enumerate(params: RpcParams["enumerate"]): Promise<RpcResults["enumerate"]>;
699
+ /**
700
+ * The feed since a cursor. Answered from the journal at once; when the last look at the folder is stale, another
701
+ * is started behind the answer, and what it finds nudges the server to ask again.
702
+ */
703
+ changes(params: RpcParams["changes"]): Promise<RpcResults["changes"]>;
704
+ openRead(params: RpcParams["read"]): Promise<ReadOpened>;
705
+ mkdir(params: RpcParams["mkdir"]): Promise<RpcResults["mkdir"]>;
706
+ /** `to` is the full destination path: one call renames or moves. Descendants are reported, each naming where it was. */
707
+ move(params: RpcParams["move"]): Promise<RpcResults["move"]>;
708
+ private copyTree;
709
+ /** What stands under a path now, the path included, as snapshot entries (after a copy: its result). */
710
+ private look;
711
+ copy(params: RpcParams["copy"]): Promise<RpcResults["copy"]>;
712
+ /**
713
+ * A delete: the item goes into this folder's own trash folder, where the person finds it. Never removed for good.
714
+ * A name already in the trash gets the time added, so yesterday's deleted "scan.pdf" is not written over.
715
+ */
716
+ trash(params: RpcParams["trash"]): Promise<RpcResults["trash"]>;
717
+ private checkDestination;
718
+ write(params: RpcParams["write"]): Promise<RpcResults["write"]>;
719
+ openWrite(params: RpcParams["write_open"]): Promise<RpcResults["write_open"]>;
720
+ appendWrite(chunk: {
721
+ stream: string;
722
+ seq: number;
723
+ data: Uint8Array | ArrayBuffer;
724
+ }): Promise<boolean>;
725
+ closeWrite(params: RpcParams["write_close"]): Promise<RpcResults["write_close"]>;
726
+ abortWrite(stream: string): Promise<void>;
727
+ hash(params: RpcParams["hash"]): Promise<RpcResults["hash"]>;
728
+ media(params: RpcParams["media"]): Promise<RpcResults["media"]>;
729
+ }
730
+ /**
731
+ * `backslashSeparates`: a backslash is legal in a POSIX file name and is the path separator in a device path
732
+ * (normalizeDevicePath): such a name has no address the server could send back, so it is not shared rather than
733
+ * re-addressed to a path that does not exist. On Windows a name cannot hold one.
734
+ */
735
+ export declare function isIgnoredFileName(name: string, backslashSeparates?: boolean): boolean;
736
+
737
+ export {
738
+ CoreDeviceClient as DeviceClient,
739
+ };
740
+
741
+ export {};