@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/LICENSE +21 -0
- package/README.md +97 -2
- package/dist/cli.js +11703 -0
- package/dist/core.d.ts +741 -0
- package/dist/core.js +1591 -0
- package/dist/lib.d.ts +865 -0
- package/dist/lib.js +3076 -0
- package/package.json +65 -4
package/dist/core.js
ADDED
|
@@ -0,0 +1,1591 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
21
|
+
|
|
22
|
+
// src/core.ts
|
|
23
|
+
var core_exports = {};
|
|
24
|
+
__export(core_exports, {
|
|
25
|
+
CHUNK_ACK_WAIT_MS: () => CHUNK_ACK_WAIT_MS,
|
|
26
|
+
DEVICE_NAMESPACE: () => DEVICE_NAMESPACE,
|
|
27
|
+
DEVICE_PROTOCOL_VERSION: () => DEVICE_PROTOCOL_VERSION,
|
|
28
|
+
DEVICE_TRASH_FOLDER: () => DEVICE_TRASH_FOLDER,
|
|
29
|
+
DeviceClient: () => CoreDeviceClient,
|
|
30
|
+
FolderPortError: () => FolderPortError,
|
|
31
|
+
OpError: () => OpError,
|
|
32
|
+
PORTABLE_MAX_WRITE_BYTES: () => PORTABLE_MAX_WRITE_BYTES,
|
|
33
|
+
PortableRoot: () => PortableRoot,
|
|
34
|
+
REPLY_MEMORY_MS: () => REPLY_MEMORY_MS,
|
|
35
|
+
RecentReplies: () => RecentReplies,
|
|
36
|
+
STREAM_CHUNK_BYTES: () => STREAM_CHUNK_BYTES,
|
|
37
|
+
asOpError: () => asOpError,
|
|
38
|
+
deviceBasename: () => deviceBasename,
|
|
39
|
+
deviceDirname: () => deviceDirname,
|
|
40
|
+
deviceJoin: () => deviceJoin,
|
|
41
|
+
folderPortCode: () => folderPortCode,
|
|
42
|
+
isIgnoredFileName: () => isIgnoredFileName,
|
|
43
|
+
isPhonePlatform: () => isPhonePlatform,
|
|
44
|
+
isSafeDevicePath: () => isSafeDevicePath,
|
|
45
|
+
normalizeDevicePath: () => normalizeDevicePath
|
|
46
|
+
});
|
|
47
|
+
module.exports = __toCommonJS(core_exports);
|
|
48
|
+
|
|
49
|
+
// protocol.ts (shared with the server)
|
|
50
|
+
var DEVICE_PROTOCOL_VERSION = 2;
|
|
51
|
+
var DEVICE_NAMESPACE = "/devices";
|
|
52
|
+
var STREAM_CHUNK_BYTES = 256 * 1024;
|
|
53
|
+
function isPhonePlatform(platform) {
|
|
54
|
+
return platform === "ios" || platform === "android";
|
|
55
|
+
}
|
|
56
|
+
var DEVICE_TRASH_FOLDER = "Deleted by The Drive AI";
|
|
57
|
+
var DEVICE_FOLDER_MIME = "application/vnd.thedrive.folder";
|
|
58
|
+
function normalizeDevicePath(input) {
|
|
59
|
+
const slashed = input.replace(/\\/g, "/").replace(/\/+/g, "/");
|
|
60
|
+
const trimmed = slashed.replace(/\/+$/, "");
|
|
61
|
+
if (!trimmed || trimmed === "/") return "";
|
|
62
|
+
return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
|
63
|
+
}
|
|
64
|
+
function deviceDirname(path) {
|
|
65
|
+
const p = normalizeDevicePath(path);
|
|
66
|
+
const at = p.lastIndexOf("/");
|
|
67
|
+
return at <= 0 ? "" : p.slice(0, at);
|
|
68
|
+
}
|
|
69
|
+
function deviceBasename(path) {
|
|
70
|
+
const p = normalizeDevicePath(path);
|
|
71
|
+
return p.slice(p.lastIndexOf("/") + 1);
|
|
72
|
+
}
|
|
73
|
+
function deviceJoin(folder, name) {
|
|
74
|
+
return normalizeDevicePath(`${normalizeDevicePath(folder)}/${name}`);
|
|
75
|
+
}
|
|
76
|
+
function isSafeDevicePath(path) {
|
|
77
|
+
if (path === "") return true;
|
|
78
|
+
if (!path.startsWith("/")) return false;
|
|
79
|
+
return path.slice(1).split("/").every((segment) => segment !== "" && segment !== "." && segment !== ".." && !segment.includes("\0"));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// src/opError.ts
|
|
83
|
+
var OpError = class extends Error {
|
|
84
|
+
constructor(code, message) {
|
|
85
|
+
super(message);
|
|
86
|
+
this.code = code;
|
|
87
|
+
this.name = "OpError";
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
var CODES = /* @__PURE__ */ new Set(["NOT_FOUND", "EXISTS", "PERMISSION_DENIED", "READ_ONLY", "NO_TRASH", "TOO_LARGE", "BAD_PATH", "UNSUPPORTED", "UNAVAILABLE", "ONLINE_ONLY", "INTERNAL"]);
|
|
91
|
+
function asOpError(error) {
|
|
92
|
+
if (error instanceof OpError) return error;
|
|
93
|
+
const code = error?.code;
|
|
94
|
+
const message = error?.message;
|
|
95
|
+
const text = typeof message === "string" && message ? message : String(error);
|
|
96
|
+
return new OpError(typeof code === "string" && CODES.has(code) ? code : "INTERNAL", text);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/clientCore.ts
|
|
100
|
+
function looseStreamId() {
|
|
101
|
+
const hex = (n) => Array.from({ length: n }, () => Math.floor(Math.random() * 16).toString(16)).join("");
|
|
102
|
+
return `${hex(8)}-${hex(4)}-4${hex(3)}-a${hex(3)}-${hex(12)}`;
|
|
103
|
+
}
|
|
104
|
+
function background(timer) {
|
|
105
|
+
timer.unref?.();
|
|
106
|
+
return timer;
|
|
107
|
+
}
|
|
108
|
+
var WRITES = /* @__PURE__ */ new Set(["mkdir", "move", "copy", "trash", "write", "write_open", "write_close"]);
|
|
109
|
+
var REPLY_MEMORY_MS = 5 * 6e4;
|
|
110
|
+
var REPLY_MEMORY_MAX = 2e3;
|
|
111
|
+
var CHUNK_ACK_WAIT_MS = 15 * 6e4;
|
|
112
|
+
var RecentReplies = class {
|
|
113
|
+
constructor(ttlMs = REPLY_MEMORY_MS, max = REPLY_MEMORY_MAX, now = Date.now) {
|
|
114
|
+
this.ttlMs = ttlMs;
|
|
115
|
+
this.max = max;
|
|
116
|
+
this.now = now;
|
|
117
|
+
__publicField(this, "byId", /* @__PURE__ */ new Map());
|
|
118
|
+
}
|
|
119
|
+
once(id, run) {
|
|
120
|
+
const at = this.now();
|
|
121
|
+
this.evict(at);
|
|
122
|
+
const known = this.byId.get(id);
|
|
123
|
+
if (known) return known.reply;
|
|
124
|
+
const entry = { at, settled: false, reply: run() };
|
|
125
|
+
entry.reply.then(() => {
|
|
126
|
+
entry.at = this.now();
|
|
127
|
+
entry.settled = true;
|
|
128
|
+
}, () => {
|
|
129
|
+
entry.at = this.now();
|
|
130
|
+
entry.settled = true;
|
|
131
|
+
});
|
|
132
|
+
this.byId.set(id, entry);
|
|
133
|
+
return entry.reply;
|
|
134
|
+
}
|
|
135
|
+
evict(at) {
|
|
136
|
+
let oldest = null;
|
|
137
|
+
let oldestAt = Infinity;
|
|
138
|
+
for (const [key, entry] of this.byId) {
|
|
139
|
+
if (!entry.settled) continue;
|
|
140
|
+
if (at - entry.at >= this.ttlMs) {
|
|
141
|
+
this.byId.delete(key);
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (entry.at < oldestAt) {
|
|
145
|
+
oldestAt = entry.at;
|
|
146
|
+
oldest = key;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (this.byId.size >= this.max && oldest) this.byId.delete(oldest);
|
|
150
|
+
}
|
|
151
|
+
/** Test seam. */
|
|
152
|
+
get size() {
|
|
153
|
+
return this.byId.size;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
var CoreDeviceClient = class {
|
|
157
|
+
constructor(deps) {
|
|
158
|
+
this.deps = deps;
|
|
159
|
+
__publicField(this, "replies", new RecentReplies());
|
|
160
|
+
__publicField(this, "aborted", /* @__PURE__ */ new Set());
|
|
161
|
+
__publicField(this, "open", /* @__PURE__ */ new Set());
|
|
162
|
+
/** Write streams the server has open, by stream, with the root they write into. */
|
|
163
|
+
__publicField(this, "writing", /* @__PURE__ */ new Map());
|
|
164
|
+
__publicField(this, "pendingNudges", /* @__PURE__ */ new Map());
|
|
165
|
+
/** Another copy of this device connected with the same token: this one stays down rather than fight it. */
|
|
166
|
+
__publicField(this, "superseded", false);
|
|
167
|
+
/** Hellos the server refused in a row (an unsupported protocol, a token of another device): each wait doubles. */
|
|
168
|
+
__publicField(this, "refusals", 0);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* A root's journal moved: nudge the server once the burst settles (a save writes a file three times; a
|
|
172
|
+
* download lands a thousand). The nudge carries only the position; the server reads from its own cursor, so
|
|
173
|
+
* one lost while offline costs nothing: the server's catch-up and the next nudge both read the same feed.
|
|
174
|
+
*/
|
|
175
|
+
notifyChanged(rootId) {
|
|
176
|
+
const pending = this.pendingNudges.get(rootId);
|
|
177
|
+
if (pending) clearTimeout(pending);
|
|
178
|
+
const timer = setTimeout(() => {
|
|
179
|
+
this.pendingNudges.delete(rootId);
|
|
180
|
+
if (!this.deps.socket.connected) return;
|
|
181
|
+
const root = this.deps.roots().find((r) => r.announce.id === rootId);
|
|
182
|
+
if (!root) return;
|
|
183
|
+
try {
|
|
184
|
+
this.deps.socket.emit("changed", { root: rootId, cursor: root.ops.position });
|
|
185
|
+
} catch {
|
|
186
|
+
}
|
|
187
|
+
}, this.deps.changeDebounceMs ?? 1500);
|
|
188
|
+
this.pendingNudges.set(rootId, background(timer));
|
|
189
|
+
}
|
|
190
|
+
start() {
|
|
191
|
+
const { socket } = this.deps;
|
|
192
|
+
socket.on("connect", () => {
|
|
193
|
+
this.announce();
|
|
194
|
+
for (const root of this.deps.roots()) this.notifyChanged(root.announce.id);
|
|
195
|
+
});
|
|
196
|
+
socket.on("disconnect", (reason) => {
|
|
197
|
+
this.deps.log(`disconnected (${reason}); reconnecting`);
|
|
198
|
+
for (const s of this.open) this.aborted.add(s);
|
|
199
|
+
for (const [s, ops] of this.writing) {
|
|
200
|
+
void ops.abortWrite(s);
|
|
201
|
+
}
|
|
202
|
+
this.writing.clear();
|
|
203
|
+
if (this.superseded) {
|
|
204
|
+
this.deps.log("another copy of this device connected with the same token; this one stopped. Pair this copy on its own (tdai-device pair) to run both.");
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (reason === "io server disconnect" && socket.connect) {
|
|
208
|
+
const base = this.deps.reconnectAfterMs ?? 5e3;
|
|
209
|
+
const wait = Math.min(base * 2 ** Math.min(this.refusals, 10), Math.max(base, 10 * 6e4));
|
|
210
|
+
background(setTimeout(() => {
|
|
211
|
+
if (!socket.connected) socket.connect?.();
|
|
212
|
+
}, wait));
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
socket.on("connect_error", (error) => this.deps.log(`cannot connect: ${error.message}`));
|
|
216
|
+
socket.on("rpc", (request, ack) => {
|
|
217
|
+
void this.handle(request).then(ack);
|
|
218
|
+
});
|
|
219
|
+
socket.on("stream_abort", (abort) => {
|
|
220
|
+
if (this.open.has(abort.stream)) this.aborted.add(abort.stream);
|
|
221
|
+
const writing = this.writing.get(abort.stream);
|
|
222
|
+
if (writing) {
|
|
223
|
+
this.writing.delete(abort.stream);
|
|
224
|
+
void writing.abortWrite(abort.stream);
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
socket.on("write_chunk", (chunk, ack) => {
|
|
228
|
+
const ops = chunk && typeof chunk === "object" ? this.writing.get(chunk.stream) : void 0;
|
|
229
|
+
if (!ops) {
|
|
230
|
+
ack(false);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
ops.appendWrite(chunk).then(ack, () => {
|
|
234
|
+
this.writing.delete(chunk.stream);
|
|
235
|
+
ack(false);
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
socket.on("superseded", () => {
|
|
239
|
+
this.superseded = true;
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
announce() {
|
|
243
|
+
const retired = this.deps.retired?.() ?? [];
|
|
244
|
+
const hello = { protocol: DEVICE_PROTOCOL_VERSION, device: this.deps.device, roots: this.deps.roots().map((r) => r.announce), ...retired.length ? { retired } : {} };
|
|
245
|
+
this.deps.socket.emit("hello", hello, (reply) => {
|
|
246
|
+
if (reply?.ok && retired.length) this.deps.retiredAcked?.(retired);
|
|
247
|
+
const refused = Array.isArray(reply?.retire) ? reply.retire.filter((id) => typeof id === "string") : [];
|
|
248
|
+
if (reply?.ok && refused.length) {
|
|
249
|
+
this.deps.log(`stopped sharing ${refused.length} folder(s) that were removed while this device was away`);
|
|
250
|
+
this.deps.retireRequested?.(refused);
|
|
251
|
+
}
|
|
252
|
+
if (reply?.ok) this.superseded = false;
|
|
253
|
+
if (reply?.ok) {
|
|
254
|
+
this.refusals = 0;
|
|
255
|
+
this.deps.log(`connected as ${this.deps.device.name}: ${hello.roots.length} folder(s) shared`);
|
|
256
|
+
} else {
|
|
257
|
+
this.refusals += 1;
|
|
258
|
+
this.deps.log(`the server refused this device: ${reply?.error ?? "no reason given"}`);
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
rootOps(rootId) {
|
|
263
|
+
const found = this.deps.roots().find((r) => r.announce.id === rootId);
|
|
264
|
+
if (!found) throw new OpError("NOT_FOUND", `no shared folder ${rootId}`);
|
|
265
|
+
return found.ops;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* One RPC. A write the server sends again under the same request id (its ack timed out; the first may have
|
|
269
|
+
* finished, or still be running) gets the first one's answer, never a second run on a half-finished op.
|
|
270
|
+
*/
|
|
271
|
+
handle(request) {
|
|
272
|
+
if (!request || typeof request !== "object" || !WRITES.has(request.method) || typeof request.id !== "string" || !request.id) return this.dispatch(request);
|
|
273
|
+
return this.replies.once(request.id, () => this.dispatch(request));
|
|
274
|
+
}
|
|
275
|
+
async dispatch(request) {
|
|
276
|
+
try {
|
|
277
|
+
if (!request || typeof request !== "object" || typeof request.method !== "string") return { ok: false, error: { code: "UNSUPPORTED", message: "malformed request" } };
|
|
278
|
+
const params = request.params ?? {};
|
|
279
|
+
const ops = this.rootOps(String(params.root ?? ""));
|
|
280
|
+
switch (request.method) {
|
|
281
|
+
case "stat":
|
|
282
|
+
return { ok: true, result: await ops.stat(params) };
|
|
283
|
+
case "list":
|
|
284
|
+
return { ok: true, result: await ops.list(params) };
|
|
285
|
+
case "enumerate":
|
|
286
|
+
return { ok: true, result: await ops.enumerate(params) };
|
|
287
|
+
case "changes":
|
|
288
|
+
return { ok: true, result: await ops.changes(params) };
|
|
289
|
+
case "mkdir":
|
|
290
|
+
return { ok: true, result: await ops.mkdir(params) };
|
|
291
|
+
case "move":
|
|
292
|
+
return { ok: true, result: await ops.move(params) };
|
|
293
|
+
case "copy":
|
|
294
|
+
return { ok: true, result: await ops.copy(params) };
|
|
295
|
+
case "trash":
|
|
296
|
+
return { ok: true, result: await ops.trash(params) };
|
|
297
|
+
case "write":
|
|
298
|
+
return { ok: true, result: await ops.write(params) };
|
|
299
|
+
case "write_open": {
|
|
300
|
+
const opened = await ops.openWrite(params);
|
|
301
|
+
this.writing.set(opened.stream, ops);
|
|
302
|
+
return { ok: true, result: opened };
|
|
303
|
+
}
|
|
304
|
+
case "write_close": {
|
|
305
|
+
const stream = String(params.stream ?? "");
|
|
306
|
+
this.writing.delete(stream);
|
|
307
|
+
return { ok: true, result: await ops.closeWrite(params) };
|
|
308
|
+
}
|
|
309
|
+
case "hash":
|
|
310
|
+
return { ok: true, result: await ops.hash(params) };
|
|
311
|
+
case "media":
|
|
312
|
+
return { ok: true, result: await ops.media(params) };
|
|
313
|
+
case "read": {
|
|
314
|
+
const opened = await ops.openRead(params);
|
|
315
|
+
const named = typeof params.stream === "string" && /^[0-9a-f-]{36}$/i.test(params.stream) ? params.stream : null;
|
|
316
|
+
const stream = named ?? (this.deps.newStreamId ?? looseStreamId)();
|
|
317
|
+
this.open.add(stream);
|
|
318
|
+
setTimeout(() => {
|
|
319
|
+
void this.pump(stream, opened);
|
|
320
|
+
}, 0);
|
|
321
|
+
return { ok: true, result: { stream, size: opened.size, mimeType: "application/octet-stream" } };
|
|
322
|
+
}
|
|
323
|
+
default:
|
|
324
|
+
return { ok: false, error: { code: "UNSUPPORTED", message: `unknown method ${String(request.method)}` } };
|
|
325
|
+
}
|
|
326
|
+
} catch (error) {
|
|
327
|
+
const e = (this.deps.toError ?? asOpError)(error);
|
|
328
|
+
return { ok: false, error: { code: e.code, message: e.message } };
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* The bytes of one read, a chunk at a time, each sent only once the server acknowledged the one before. One chunk
|
|
333
|
+
* is held back so the last can say it is the last (an empty file sends one empty, last chunk). Leaving the loop
|
|
334
|
+
* early (an abort, a dead line) ends the iteration, which is what releases the file.
|
|
335
|
+
*/
|
|
336
|
+
async pump(stream, opened) {
|
|
337
|
+
const size = this.deps.chunkBytes ?? STREAM_CHUNK_BYTES;
|
|
338
|
+
let seq = 0;
|
|
339
|
+
try {
|
|
340
|
+
let last = null;
|
|
341
|
+
for await (const part of opened.chunks(size)) {
|
|
342
|
+
if (this.aborted.has(stream)) break;
|
|
343
|
+
if (last) {
|
|
344
|
+
if (!await this.send({ stream, seq, data: last, last: false })) {
|
|
345
|
+
this.aborted.add(stream);
|
|
346
|
+
break;
|
|
347
|
+
}
|
|
348
|
+
seq += 1;
|
|
349
|
+
}
|
|
350
|
+
last = part;
|
|
351
|
+
}
|
|
352
|
+
if (!this.aborted.has(stream)) await this.send({ stream, seq, data: last ?? new Uint8Array(0), last: true });
|
|
353
|
+
} catch (error) {
|
|
354
|
+
this.deps.log(`read of ${opened.label} failed: ${error.message}`);
|
|
355
|
+
} finally {
|
|
356
|
+
this.open.delete(stream);
|
|
357
|
+
this.aborted.delete(stream);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
async send(chunk) {
|
|
361
|
+
try {
|
|
362
|
+
return await this.deps.socket.timeout(CHUNK_ACK_WAIT_MS).emitWithAck("chunk", chunk) === true;
|
|
363
|
+
} catch {
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
// src/nasNames.ts
|
|
370
|
+
var NAS_RECYCLE_BINS = [
|
|
371
|
+
{ vendor: "QNAP", name: "@Recycle" },
|
|
372
|
+
{ vendor: "Synology", name: "#recycle" }
|
|
373
|
+
];
|
|
374
|
+
var NAS_SNAPSHOT_FOLDERS = ["#snapshot", "@Recently-Snapshot"];
|
|
375
|
+
var HOUSEKEEPING = new Set([...NAS_RECYCLE_BINS.map((b) => b.name), ...NAS_SNAPSHOT_FOLDERS].map((n) => n.toLowerCase()));
|
|
376
|
+
function isNasHousekeepingName(name) {
|
|
377
|
+
return HOUSEKEEPING.has(name.toLowerCase());
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// src/ignoredNames.ts
|
|
381
|
+
var IGNORED_NAMES = /* @__PURE__ */ new Set([".DS_Store", "Thumbs.db", "desktop.ini", "@eaDir", "$RECYCLE.BIN", "System Volume Information", ".Trashes", ".Trash", ".Spotlight-V100", ".fseventsd", ".TemporaryItems", "lost+found", "node_modules", ".git", "__pycache__", "site-packages", "bower_components"]);
|
|
382
|
+
function isIgnoredFileName(name, backslashSeparates = true) {
|
|
383
|
+
if (backslashSeparates && name.includes("\\")) return true;
|
|
384
|
+
return name.startsWith(".") || IGNORED_NAMES.has(name) || isNasHousekeepingName(name) || name.startsWith("~$") || name.endsWith(".crdownload") || name.endsWith(".part") || name.endsWith(".tmp");
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// src/portable/folderPort.ts
|
|
388
|
+
var FolderPortError = class extends Error {
|
|
389
|
+
constructor(code, message) {
|
|
390
|
+
super(message);
|
|
391
|
+
this.code = code;
|
|
392
|
+
this.name = "FolderPortError";
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
var PORT_CODES = /* @__PURE__ */ new Set(["NOT_FOUND", "EXISTS", "DENIED", "UNAVAILABLE", "UNSUPPORTED", "IO"]);
|
|
396
|
+
function folderPortCode(error) {
|
|
397
|
+
const code = error?.code;
|
|
398
|
+
return typeof code === "string" && PORT_CODES.has(code) ? code : "IO";
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// src/portable/portableFeed.ts
|
|
402
|
+
var PORTABLE_PAGE_MAX_BYTES = 256 * 1024;
|
|
403
|
+
var PORTABLE_JOURNAL_KEEP = 2e4;
|
|
404
|
+
function utf8Length(text) {
|
|
405
|
+
let bytes = 0;
|
|
406
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
407
|
+
const c = text.charCodeAt(i);
|
|
408
|
+
if (c < 128) bytes += 1;
|
|
409
|
+
else if (c < 2048) bytes += 2;
|
|
410
|
+
else if (c >= 55296 && c <= 56319) {
|
|
411
|
+
bytes += 4;
|
|
412
|
+
i += 1;
|
|
413
|
+
} else bytes += 3;
|
|
414
|
+
}
|
|
415
|
+
return bytes;
|
|
416
|
+
}
|
|
417
|
+
function portableWireBytes(value) {
|
|
418
|
+
return utf8Length(JSON.stringify(value)) + 1;
|
|
419
|
+
}
|
|
420
|
+
function sameSnap(a, b) {
|
|
421
|
+
return a.k === b.k && (a.k === "folder" || a.s === b.s && a.m === b.m);
|
|
422
|
+
}
|
|
423
|
+
function itemOfSnap(path, snap, nameOverride) {
|
|
424
|
+
return {
|
|
425
|
+
externalId: path,
|
|
426
|
+
parentExternalId: path === "" ? null : deviceDirname(path),
|
|
427
|
+
name: nameOverride ?? deviceBasename(path),
|
|
428
|
+
kind: snap.k,
|
|
429
|
+
// The server derives a file's type from its name; the helper ships no mime table.
|
|
430
|
+
mimeType: snap.k === "folder" ? DEVICE_FOLDER_MIME : "application/octet-stream",
|
|
431
|
+
size: snap.k === "file" ? snap.s : null,
|
|
432
|
+
mtime: snap.m,
|
|
433
|
+
ctime: snap.c ?? null,
|
|
434
|
+
contentHash: snap.k === "file" && snap.h ? `sha256:${snap.h}` : null,
|
|
435
|
+
ownerEmail: null,
|
|
436
|
+
webUrl: null,
|
|
437
|
+
trashed: false
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
function newEpoch() {
|
|
441
|
+
return `${Date.now().toString(36)}${Math.floor(Math.random() * 1048575).toString(36)}`.slice(-10).padStart(10, "0");
|
|
442
|
+
}
|
|
443
|
+
var PortableJournal = class {
|
|
444
|
+
constructor(state, keep = PORTABLE_JOURNAL_KEEP) {
|
|
445
|
+
this.state = state;
|
|
446
|
+
this.keep = keep;
|
|
447
|
+
__publicField(this, "epoch", "");
|
|
448
|
+
/** The last seq handed to an entry, durable or not. */
|
|
449
|
+
__publicField(this, "seq", 0);
|
|
450
|
+
/** The last seq the host has kept: everything served stops here. */
|
|
451
|
+
__publicField(this, "durable", 0);
|
|
452
|
+
__publicField(this, "entries", []);
|
|
453
|
+
__publicField(this, "unwritten", []);
|
|
454
|
+
/** The next write replaces the text with the kept tail (compaction) instead of appending. */
|
|
455
|
+
__publicField(this, "rewrite", false);
|
|
456
|
+
__publicField(this, "writing", null);
|
|
457
|
+
/** Told after entries are durable (the host nudges the server). */
|
|
458
|
+
__publicField(this, "onRecord", null);
|
|
459
|
+
/** This load found no journal and started one: no cursor of it has ever been handed out. */
|
|
460
|
+
__publicField(this, "created", false);
|
|
461
|
+
}
|
|
462
|
+
/** Replay the stored journal; a missing or unreadable one starts a new epoch. */
|
|
463
|
+
async load() {
|
|
464
|
+
this.entries = [];
|
|
465
|
+
this.seq = 0;
|
|
466
|
+
this.epoch = "";
|
|
467
|
+
this.unwritten = [];
|
|
468
|
+
this.created = false;
|
|
469
|
+
const raw = await this.state.read("journal");
|
|
470
|
+
let torn = false;
|
|
471
|
+
if (raw) {
|
|
472
|
+
torn = !raw.endsWith("\n");
|
|
473
|
+
for (const line of raw.split("\n")) {
|
|
474
|
+
if (!line) continue;
|
|
475
|
+
let parsed;
|
|
476
|
+
try {
|
|
477
|
+
parsed = JSON.parse(line);
|
|
478
|
+
} catch {
|
|
479
|
+
torn = true;
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
if (typeof parsed.epoch === "string") {
|
|
483
|
+
this.epoch = parsed.epoch;
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
if (typeof parsed.seq !== "number" || typeof parsed.path !== "string") continue;
|
|
487
|
+
this.entries.push({ seq: parsed.seq, path: parsed.path, removed: !!parsed.removed, item: parsed.item ?? null, ...parsed.created ? { created: true } : {}, ...typeof parsed.movedFrom === "string" ? { movedFrom: parsed.movedFrom } : {}, ...parsed.recoverable === false ? { recoverable: false } : {} });
|
|
488
|
+
this.seq = Math.max(this.seq, parsed.seq);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
if (!this.epoch) {
|
|
492
|
+
this.epoch = newEpoch();
|
|
493
|
+
this.entries = [];
|
|
494
|
+
this.seq = 0;
|
|
495
|
+
this.created = true;
|
|
496
|
+
await this.state.write("journal", `${JSON.stringify({ epoch: this.epoch })}
|
|
497
|
+
`);
|
|
498
|
+
} else if (torn || this.entries.length > this.keep) {
|
|
499
|
+
if (this.entries.length > this.keep) this.entries.splice(0, this.entries.length - this.keep);
|
|
500
|
+
await this.state.write("journal", this.body());
|
|
501
|
+
}
|
|
502
|
+
this.durable = this.seq;
|
|
503
|
+
}
|
|
504
|
+
body() {
|
|
505
|
+
return [JSON.stringify({ epoch: this.epoch }), ...this.entries.map((e) => JSON.stringify(e))].join("\n") + "\n";
|
|
506
|
+
}
|
|
507
|
+
/** The last durable position: what the server may hold as a cursor. */
|
|
508
|
+
get position() {
|
|
509
|
+
return `${this.epoch}:${this.durable}`;
|
|
510
|
+
}
|
|
511
|
+
get keepCount() {
|
|
512
|
+
return this.keep;
|
|
513
|
+
}
|
|
514
|
+
/** The journal was started by this load (no server holds a cursor of it). */
|
|
515
|
+
get fresh() {
|
|
516
|
+
return this.created;
|
|
517
|
+
}
|
|
518
|
+
/** Entries after a position of THIS epoch, oldest first; null when the journal no longer reaches back that far. */
|
|
519
|
+
after(position) {
|
|
520
|
+
const at = position.indexOf(":");
|
|
521
|
+
if (at <= 0 || position.slice(0, at) !== this.epoch) return null;
|
|
522
|
+
const seq = Number(position.slice(at + 1));
|
|
523
|
+
if (!Number.isInteger(seq) || seq < 0 || seq > this.seq) return null;
|
|
524
|
+
if (this.entries.length && seq < this.entries[0].seq - 1) return null;
|
|
525
|
+
return this.entries.filter((e) => e.seq > seq);
|
|
526
|
+
}
|
|
527
|
+
/** Start a new epoch: every cursor the server holds answers `resetRequired`, and it re-enumerates. */
|
|
528
|
+
async reset() {
|
|
529
|
+
await this.flush();
|
|
530
|
+
this.epoch = newEpoch();
|
|
531
|
+
this.entries = [];
|
|
532
|
+
this.seq = 0;
|
|
533
|
+
this.durable = 0;
|
|
534
|
+
this.unwritten = [];
|
|
535
|
+
this.rewrite = false;
|
|
536
|
+
await this.state.write("journal", `${JSON.stringify({ epoch: this.epoch })}
|
|
537
|
+
`);
|
|
538
|
+
try {
|
|
539
|
+
this.onRecord?.();
|
|
540
|
+
} catch {
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
record(entry) {
|
|
544
|
+
this.seq += 1;
|
|
545
|
+
const kept = { seq: this.seq, ...entry };
|
|
546
|
+
this.entries.push(kept);
|
|
547
|
+
this.unwritten.push(JSON.stringify(kept));
|
|
548
|
+
if (this.entries.length > this.keep * 2) {
|
|
549
|
+
this.entries.splice(0, this.entries.length - this.keep);
|
|
550
|
+
this.rewrite = true;
|
|
551
|
+
}
|
|
552
|
+
this.writing ?? (this.writing = this.drain());
|
|
553
|
+
}
|
|
554
|
+
/** `created`: the path was not known before. `movedFrom`: the item stood there; ONE entry, so the server keeps the node. */
|
|
555
|
+
upsert(item, created = false, movedFrom) {
|
|
556
|
+
this.record({ path: item.externalId, removed: false, item, ...created ? { created: true } : {}, ...movedFrom ? { movedFrom } : {} });
|
|
557
|
+
}
|
|
558
|
+
/** `recoverable: false`: the path left the share by policy, not for the trash; the server drops its row. */
|
|
559
|
+
remove(path, options = {}) {
|
|
560
|
+
this.record({ path, removed: true, item: null, ...options.recoverable === false ? { recoverable: false } : {} });
|
|
561
|
+
}
|
|
562
|
+
async drain() {
|
|
563
|
+
try {
|
|
564
|
+
await null;
|
|
565
|
+
while (this.unwritten.length || this.rewrite) {
|
|
566
|
+
const upTo = this.seq;
|
|
567
|
+
const lines = this.unwritten.splice(0);
|
|
568
|
+
try {
|
|
569
|
+
if (this.rewrite) {
|
|
570
|
+
this.rewrite = false;
|
|
571
|
+
await this.state.write("journal", this.body());
|
|
572
|
+
} else await this.state.append("journal", `${lines.join("\n")}
|
|
573
|
+
`);
|
|
574
|
+
} catch {
|
|
575
|
+
this.unwritten.unshift(...lines);
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
this.durable = upTo;
|
|
579
|
+
try {
|
|
580
|
+
this.onRecord?.();
|
|
581
|
+
} catch {
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
} finally {
|
|
585
|
+
this.writing = null;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
/** Changes after `cursor`, bounded by count and bytes; '' asks for the current position only. */
|
|
589
|
+
since(cursor, limit, maxBytes = PORTABLE_PAGE_MAX_BYTES) {
|
|
590
|
+
if (cursor === "") return { changes: [], cursor: this.position, done: true };
|
|
591
|
+
const at = cursor.indexOf(":");
|
|
592
|
+
const epoch = at > 0 ? cursor.slice(0, at) : "";
|
|
593
|
+
const seq = Number(cursor.slice(at + 1));
|
|
594
|
+
const reset = { changes: [], cursor: this.position, done: true, resetRequired: true };
|
|
595
|
+
if (epoch !== this.epoch || !Number.isInteger(seq) || seq < 0 || seq > this.durable) return reset;
|
|
596
|
+
if (this.entries.length && seq < this.entries[0].seq - 1) return reset;
|
|
597
|
+
const changes = [];
|
|
598
|
+
let last = seq;
|
|
599
|
+
let bytes = 0;
|
|
600
|
+
for (const entry of this.entries) {
|
|
601
|
+
if (entry.seq <= seq) continue;
|
|
602
|
+
if (entry.seq > this.durable) break;
|
|
603
|
+
const change = entry.removed ? { externalId: entry.path, removed: true, recoverable: entry.recoverable !== false, item: null } : { externalId: entry.path, removed: false, item: entry.item, ...entry.created ? { created: true } : {}, ...entry.movedFrom ? { movedFrom: entry.movedFrom } : {} };
|
|
604
|
+
const size = portableWireBytes(change);
|
|
605
|
+
if (changes.length && (changes.length >= Math.max(1, limit) || bytes + size > maxBytes)) break;
|
|
606
|
+
changes.push(change);
|
|
607
|
+
bytes += size;
|
|
608
|
+
last = entry.seq;
|
|
609
|
+
}
|
|
610
|
+
return { changes, cursor: `${this.epoch}:${last}`, done: last >= this.durable };
|
|
611
|
+
}
|
|
612
|
+
/** Wait until everything recorded so far is durable (an op before it answers, a rescan before its snapshot). */
|
|
613
|
+
async flush() {
|
|
614
|
+
while (this.writing) await this.writing;
|
|
615
|
+
if (this.unwritten.length || this.rewrite) {
|
|
616
|
+
this.writing ?? (this.writing = this.drain());
|
|
617
|
+
await this.writing;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
/** Whether everything recorded is durable (a store that refused leaves this false). */
|
|
621
|
+
get settled() {
|
|
622
|
+
return this.durable === this.seq;
|
|
623
|
+
}
|
|
624
|
+
/** Test seam. */
|
|
625
|
+
get size() {
|
|
626
|
+
return this.entries.length;
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
function compareWalkOrder(a, aKind, b, bKind) {
|
|
630
|
+
if (a === b) return 0;
|
|
631
|
+
const as = a.split("/");
|
|
632
|
+
const bs = b.split("/");
|
|
633
|
+
const shared = Math.min(as.length, bs.length);
|
|
634
|
+
for (let i = 1; i < shared; i += 1) {
|
|
635
|
+
if (as[i] === bs[i]) continue;
|
|
636
|
+
const ak = i === as.length - 1 ? aKind : "folder";
|
|
637
|
+
const bk = i === bs.length - 1 ? bKind : "folder";
|
|
638
|
+
if (ak !== bk) return ak === "folder" ? -1 : 1;
|
|
639
|
+
return as[i] < bs[i] ? -1 : 1;
|
|
640
|
+
}
|
|
641
|
+
return as.length - bs.length;
|
|
642
|
+
}
|
|
643
|
+
var PortableSnapshot = class {
|
|
644
|
+
constructor(state) {
|
|
645
|
+
this.state = state;
|
|
646
|
+
__publicField(this, "entries", /* @__PURE__ */ new Map());
|
|
647
|
+
__publicField(this, "loaded", false);
|
|
648
|
+
/** The journal position the stored snapshot includes. */
|
|
649
|
+
__publicField(this, "storedAt", "");
|
|
650
|
+
/** The walk order of the paths, built when asked and dropped at the next change. */
|
|
651
|
+
__publicField(this, "order", null);
|
|
652
|
+
__publicField(this, "dirtyHashes", false);
|
|
653
|
+
__publicField(this, "saving", Promise.resolve());
|
|
654
|
+
}
|
|
655
|
+
/** Whether a snapshot was stored: without one the first walk only records (the server enumerates). */
|
|
656
|
+
async load() {
|
|
657
|
+
this.entries = /* @__PURE__ */ new Map();
|
|
658
|
+
this.order = null;
|
|
659
|
+
this.storedAt = "";
|
|
660
|
+
const raw = await this.state.read("snapshot");
|
|
661
|
+
this.loaded = false;
|
|
662
|
+
if (!raw) return false;
|
|
663
|
+
let complete = false;
|
|
664
|
+
for (const line of raw.split("\n")) {
|
|
665
|
+
if (!line) continue;
|
|
666
|
+
try {
|
|
667
|
+
const parsed = JSON.parse(line);
|
|
668
|
+
if (typeof parsed.at === "string") {
|
|
669
|
+
this.storedAt = parsed.at;
|
|
670
|
+
continue;
|
|
671
|
+
}
|
|
672
|
+
if (parsed.end === true) {
|
|
673
|
+
complete = true;
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
if (typeof parsed.p === "string" && (parsed.k === "file" || parsed.k === "folder")) this.entries.set(parsed.p, { k: parsed.k, s: parsed.s ?? null, m: parsed.m ?? null, ...parsed.c ? { c: parsed.c } : {}, ...typeof parsed.h === "string" ? { h: parsed.h } : {} });
|
|
677
|
+
} catch {
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (!complete) {
|
|
681
|
+
this.entries = /* @__PURE__ */ new Map();
|
|
682
|
+
this.storedAt = "";
|
|
683
|
+
return false;
|
|
684
|
+
}
|
|
685
|
+
this.loaded = true;
|
|
686
|
+
return true;
|
|
687
|
+
}
|
|
688
|
+
/** A snapshot is STORED (loaded at start, or saved since): what a restart would find. */
|
|
689
|
+
get exists() {
|
|
690
|
+
return this.loaded;
|
|
691
|
+
}
|
|
692
|
+
get count() {
|
|
693
|
+
return this.entries.size;
|
|
694
|
+
}
|
|
695
|
+
get at() {
|
|
696
|
+
return this.storedAt;
|
|
697
|
+
}
|
|
698
|
+
has(path) {
|
|
699
|
+
return this.entries.has(path);
|
|
700
|
+
}
|
|
701
|
+
get(path) {
|
|
702
|
+
return this.entries.get(path);
|
|
703
|
+
}
|
|
704
|
+
paths() {
|
|
705
|
+
return this.entries.keys();
|
|
706
|
+
}
|
|
707
|
+
set(path, snap) {
|
|
708
|
+
const before = this.entries.get(path);
|
|
709
|
+
const keep = before?.h && before.k === "file" && snap.k === "file" && before.s === snap.s && before.m === snap.m && !snap.h ? { h: before.h } : {};
|
|
710
|
+
if (!before || before.k !== snap.k) this.order = null;
|
|
711
|
+
this.entries.set(path, { ...snap, ...keep });
|
|
712
|
+
}
|
|
713
|
+
/** Forget one path, nothing under it. */
|
|
714
|
+
deleteOne(path) {
|
|
715
|
+
if (this.entries.delete(path)) this.order = null;
|
|
716
|
+
}
|
|
717
|
+
/** A path and everything under it, deepest first. */
|
|
718
|
+
under(path) {
|
|
719
|
+
const prefix = `${path}/`;
|
|
720
|
+
const found = [];
|
|
721
|
+
for (const key of this.entries.keys()) if (key.startsWith(prefix)) found.push(key);
|
|
722
|
+
return found.sort((a, b) => b.length - a.length);
|
|
723
|
+
}
|
|
724
|
+
/** Replace the whole tree (a rescan). */
|
|
725
|
+
replace(entries) {
|
|
726
|
+
this.entries = entries;
|
|
727
|
+
this.order = null;
|
|
728
|
+
}
|
|
729
|
+
hashOf(path, size, mtime) {
|
|
730
|
+
const e = this.entries.get(path);
|
|
731
|
+
return e && e.h && e.s === size && e.m === mtime ? e.h : void 0;
|
|
732
|
+
}
|
|
733
|
+
setHash(path, size, mtime, hash) {
|
|
734
|
+
const e = this.entries.get(path);
|
|
735
|
+
if (e && e.k === "file" && e.s === size && e.m === mtime) {
|
|
736
|
+
e.h = hash;
|
|
737
|
+
this.dirtyHashes = true;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
get hasUnsavedHashes() {
|
|
741
|
+
return this.dirtyHashes;
|
|
742
|
+
}
|
|
743
|
+
/** The paths in the walk's order. */
|
|
744
|
+
walkOrder() {
|
|
745
|
+
if (!this.order) {
|
|
746
|
+
const kind = (p) => this.entries.get(p).k;
|
|
747
|
+
this.order = [...this.entries.keys()].sort((a, b) => compareWalkOrder(a, kind(a), b, kind(b)));
|
|
748
|
+
}
|
|
749
|
+
return this.order;
|
|
750
|
+
}
|
|
751
|
+
/** Store the tree, marked with the journal position it includes. One writer at a time. */
|
|
752
|
+
save(at) {
|
|
753
|
+
const run = this.saving.then(async () => {
|
|
754
|
+
const lines = [JSON.stringify({ at })];
|
|
755
|
+
for (const [p, snap] of this.entries) lines.push(JSON.stringify({ p, ...snap }));
|
|
756
|
+
lines.push(JSON.stringify({ end: true }));
|
|
757
|
+
await this.state.write("snapshot", `${lines.join("\n")}
|
|
758
|
+
`);
|
|
759
|
+
this.storedAt = at;
|
|
760
|
+
this.loaded = true;
|
|
761
|
+
this.dirtyHashes = false;
|
|
762
|
+
});
|
|
763
|
+
this.saving = run.catch(() => void 0);
|
|
764
|
+
return run;
|
|
765
|
+
}
|
|
766
|
+
};
|
|
767
|
+
|
|
768
|
+
// src/portable/portableRoot.ts
|
|
769
|
+
var PORTABLE_MAX_WRITE_BYTES = 64 * 1024 * 1024;
|
|
770
|
+
var PORTABLE_HASH_BATCH = 200;
|
|
771
|
+
var PORTABLE_SAVE_EVERY = 500;
|
|
772
|
+
var CLOSED_MEMORY_MS = 5 * 6e4;
|
|
773
|
+
var CLOSED_MEMORY_MAX = 500;
|
|
774
|
+
var PORTABLE_WALK_CONCURRENCY = 6;
|
|
775
|
+
var MAX_DEPTH = 64;
|
|
776
|
+
function stateReason(state, label) {
|
|
777
|
+
if (state === "denied") return `this phone no longer allows The Drive AI into "${label}"; choose the folder again in the app`;
|
|
778
|
+
if (state === "missing") return `"${label}" is not there right now (a memory card removed, a cloud folder offline, or the folder was deleted)`;
|
|
779
|
+
return null;
|
|
780
|
+
}
|
|
781
|
+
function snapOf(entry) {
|
|
782
|
+
const iso = (ms) => typeof ms === "number" && Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : null;
|
|
783
|
+
const created = iso(entry.createdMs);
|
|
784
|
+
return { k: entry.kind, s: entry.kind === "file" ? entry.size : null, m: iso(entry.modifiedMs), ...created ? { c: created } : {} };
|
|
785
|
+
}
|
|
786
|
+
function bytesOf(data) {
|
|
787
|
+
if (data instanceof Uint8Array) return data;
|
|
788
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
789
|
+
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
790
|
+
throw new OpError("INTERNAL", "the write carried no bytes");
|
|
791
|
+
}
|
|
792
|
+
var PortableRoot = class {
|
|
793
|
+
constructor(deps) {
|
|
794
|
+
this.deps = deps;
|
|
795
|
+
__publicField(this, "journal");
|
|
796
|
+
__publicField(this, "snapshot");
|
|
797
|
+
__publicField(this, "rootState", "missing");
|
|
798
|
+
/** The first walk finished: the snapshot is the tree. */
|
|
799
|
+
__publicField(this, "walked", false);
|
|
800
|
+
__publicField(this, "opened", null);
|
|
801
|
+
__publicField(this, "scanning", null);
|
|
802
|
+
__publicField(this, "lastLookAt", 0);
|
|
803
|
+
/** When the last walk BEGAN: what it saw is at least this old. */
|
|
804
|
+
__publicField(this, "lookBeganAt", 0);
|
|
805
|
+
__publicField(this, "stopped", false);
|
|
806
|
+
/** Writes and rescans, one at a time. */
|
|
807
|
+
__publicField(this, "turn", Promise.resolve());
|
|
808
|
+
__publicField(this, "writes", /* @__PURE__ */ new Map());
|
|
809
|
+
__publicField(this, "closed", /* @__PURE__ */ new Map());
|
|
810
|
+
this.journal = new PortableJournal(deps.state, deps.journalKeep);
|
|
811
|
+
this.snapshot = new PortableSnapshot(deps.state);
|
|
812
|
+
this.journal.onRecord = () => {
|
|
813
|
+
try {
|
|
814
|
+
deps.onChanged?.();
|
|
815
|
+
} catch {
|
|
816
|
+
}
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
/** There is a catalogue to answer from: this run walked the folder, or the last run's snapshot was loaded. */
|
|
820
|
+
get known() {
|
|
821
|
+
return this.walked || this.snapshot.exists;
|
|
822
|
+
}
|
|
823
|
+
get port() {
|
|
824
|
+
return this.deps.port;
|
|
825
|
+
}
|
|
826
|
+
get config() {
|
|
827
|
+
return this.deps.config;
|
|
828
|
+
}
|
|
829
|
+
now() {
|
|
830
|
+
return (this.deps.now ?? Date.now)();
|
|
831
|
+
}
|
|
832
|
+
log(line) {
|
|
833
|
+
this.deps.log?.(`${this.config.label}: ${line}`);
|
|
834
|
+
}
|
|
835
|
+
get id() {
|
|
836
|
+
return this.config.id;
|
|
837
|
+
}
|
|
838
|
+
get state() {
|
|
839
|
+
return this.rootState;
|
|
840
|
+
}
|
|
841
|
+
get reason() {
|
|
842
|
+
return stateReason(this.rootState, this.config.label);
|
|
843
|
+
}
|
|
844
|
+
get position() {
|
|
845
|
+
return this.journal.position;
|
|
846
|
+
}
|
|
847
|
+
/** Items the catalogue of this folder holds. */
|
|
848
|
+
get count() {
|
|
849
|
+
return this.snapshot.count;
|
|
850
|
+
}
|
|
851
|
+
get rescanning() {
|
|
852
|
+
return !!this.scanning;
|
|
853
|
+
}
|
|
854
|
+
get hasTrash() {
|
|
855
|
+
return this.config.trash !== false && !this.config.readOnly;
|
|
856
|
+
}
|
|
857
|
+
/** The root as the hello announces it. */
|
|
858
|
+
announce() {
|
|
859
|
+
return {
|
|
860
|
+
id: this.config.id,
|
|
861
|
+
label: this.config.label,
|
|
862
|
+
trash: this.hasTrash,
|
|
863
|
+
readOnly: this.config.readOnly === true,
|
|
864
|
+
content: this.config.content ?? "names",
|
|
865
|
+
...this.hasTrash ? { trashIn: "folder" } : {},
|
|
866
|
+
...this.rootState !== "ok" ? { state: this.rootState } : {}
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
// ── Coming up ────────────────────────────────────────────────────────
|
|
870
|
+
/**
|
|
871
|
+
* Load what was known, look at the folder, walk it. A folder that cannot be read comes up paused with its state
|
|
872
|
+
* (announced, so the server pauses the source with the reason); `reprobe` finishes the job once it can be.
|
|
873
|
+
* Nothing is ever walked as empty.
|
|
874
|
+
*/
|
|
875
|
+
open() {
|
|
876
|
+
this.opened ?? (this.opened = (async () => {
|
|
877
|
+
await this.journal.load();
|
|
878
|
+
const had = await this.snapshot.load();
|
|
879
|
+
if (had) this.replayJournal();
|
|
880
|
+
else if (!this.journal.fresh) await this.journal.reset();
|
|
881
|
+
this.rootState = await this.probe();
|
|
882
|
+
if (this.rootState !== "ok") {
|
|
883
|
+
this.log(this.reason ?? "not available");
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
const look = this.rescan().catch((error) => this.log(`could not be read: ${error.message}`));
|
|
887
|
+
if (!this.known) await look;
|
|
888
|
+
})().catch((error) => {
|
|
889
|
+
this.opened = null;
|
|
890
|
+
throw error;
|
|
891
|
+
}));
|
|
892
|
+
return this.opened;
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* The stored snapshot may be behind the journal (the app was killed after an op, before a save): what the journal
|
|
896
|
+
* recorded since is applied, so the next walk does not find those changes a second time.
|
|
897
|
+
*/
|
|
898
|
+
replayJournal() {
|
|
899
|
+
const later = this.journal.after(this.snapshot.at);
|
|
900
|
+
if (!later) return;
|
|
901
|
+
for (const entry of later) {
|
|
902
|
+
if (entry.removed) {
|
|
903
|
+
for (const p of this.snapshot.under(entry.path)) this.snapshot.deleteOne(p);
|
|
904
|
+
this.snapshot.deleteOne(entry.path);
|
|
905
|
+
continue;
|
|
906
|
+
}
|
|
907
|
+
if (entry.movedFrom) this.snapshot.deleteOne(entry.movedFrom);
|
|
908
|
+
if (entry.item) this.snapshot.set(entry.path, { k: entry.item.kind, s: entry.item.size, m: entry.item.mtime, ...entry.item.ctime ? { c: entry.item.ctime } : {} });
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
async probe() {
|
|
912
|
+
try {
|
|
913
|
+
const root = await this.port.stat("");
|
|
914
|
+
return root && root.kind === "folder" ? "ok" : "missing";
|
|
915
|
+
} catch (error) {
|
|
916
|
+
return folderPortCode(error) === "DENIED" ? "denied" : "missing";
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
setState(next) {
|
|
920
|
+
if (next === this.rootState) return false;
|
|
921
|
+
this.rootState = next;
|
|
922
|
+
try {
|
|
923
|
+
this.deps.onStateChange?.(next);
|
|
924
|
+
} catch {
|
|
925
|
+
}
|
|
926
|
+
return true;
|
|
927
|
+
}
|
|
928
|
+
/** Ask the OS again (the app came back, the folder was chosen again). True when the state changed. */
|
|
929
|
+
async reprobe() {
|
|
930
|
+
await this.open();
|
|
931
|
+
const next = await this.probe();
|
|
932
|
+
const changed = this.setState(next);
|
|
933
|
+
if (next === "ok" && (changed || !this.walked)) await this.rescan().catch((error) => this.log(`could not be read: ${error.message}`));
|
|
934
|
+
return changed;
|
|
935
|
+
}
|
|
936
|
+
/** Everything recorded is durable and the snapshot stored: called when the app leaves the foreground. */
|
|
937
|
+
async flush() {
|
|
938
|
+
await this.journal.flush();
|
|
939
|
+
if (this.known && this.journal.settled && (this.snapshot.at !== this.journal.position || this.snapshot.hasUnsavedHashes)) await this.snapshot.save(this.journal.position).catch(() => void 0);
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* The folder is no longer served (stopped sharing, signed out). A walk in progress ends at its next folder and
|
|
943
|
+
* whatever holds the queue finishes first, so nothing touches the port or the state store after this resolves:
|
|
944
|
+
* the host is about to give the grant back and may delete the state.
|
|
945
|
+
*/
|
|
946
|
+
async stop() {
|
|
947
|
+
this.stopped = true;
|
|
948
|
+
for (const stream of [...this.writes.keys()]) await this.abortWrite(stream);
|
|
949
|
+
await this.turn.catch(() => void 0);
|
|
950
|
+
await this.flush();
|
|
951
|
+
}
|
|
952
|
+
// ── Paths ────────────────────────────────────────────────────────────
|
|
953
|
+
isShared(path) {
|
|
954
|
+
if (path === "") return true;
|
|
955
|
+
const segments = path.slice(1).split("/");
|
|
956
|
+
if (segments.some((s) => isIgnoredFileName(s))) return false;
|
|
957
|
+
return !(this.config.trash !== false && segments[0] === DEVICE_TRASH_FOLDER);
|
|
958
|
+
}
|
|
959
|
+
/** A path as the server named it, checked: well-formed and inside what this root shares. */
|
|
960
|
+
resolve(raw) {
|
|
961
|
+
const path = normalizeDevicePath(String(raw ?? ""));
|
|
962
|
+
if (!isSafeDevicePath(path)) throw new OpError("BAD_PATH", `not a valid path: ${raw}`);
|
|
963
|
+
if (!this.isShared(path)) throw new OpError("BAD_PATH", `${path} is a hidden, system or trash path and is not shared`);
|
|
964
|
+
return path;
|
|
965
|
+
}
|
|
966
|
+
available() {
|
|
967
|
+
if (this.stopped) throw new OpError("UNAVAILABLE", `${this.config.label} is no longer shared`);
|
|
968
|
+
if (this.rootState !== "ok") throw new OpError("UNAVAILABLE", this.reason ?? "the folder is not available");
|
|
969
|
+
}
|
|
970
|
+
writable() {
|
|
971
|
+
if (this.config.readOnly) throw new OpError("READ_ONLY", `${this.config.label} is shared read-only`);
|
|
972
|
+
}
|
|
973
|
+
/**
|
|
974
|
+
* What the port threw, as the protocol's error. A denial or an unreachable store is asked of the ROOT before it
|
|
975
|
+
* is believed of the item: the grant gone or the card out pauses the whole folder (announced), one locked file
|
|
976
|
+
* does not.
|
|
977
|
+
*/
|
|
978
|
+
async fail(error, what) {
|
|
979
|
+
if (error instanceof OpError) return error;
|
|
980
|
+
const code = folderPortCode(error);
|
|
981
|
+
const message = error?.message || what;
|
|
982
|
+
if (code === "DENIED" || code === "UNAVAILABLE") {
|
|
983
|
+
const state = await this.probe();
|
|
984
|
+
if (state !== "ok") {
|
|
985
|
+
this.setState(state);
|
|
986
|
+
return new OpError("UNAVAILABLE", stateReason(state, this.config.label));
|
|
987
|
+
}
|
|
988
|
+
return new OpError(code === "DENIED" ? "PERMISSION_DENIED" : "INTERNAL", message);
|
|
989
|
+
}
|
|
990
|
+
if (code === "NOT_FOUND") return new OpError("NOT_FOUND", message);
|
|
991
|
+
if (code === "EXISTS") return new OpError("EXISTS", message);
|
|
992
|
+
if (code === "UNSUPPORTED") return new OpError("UNSUPPORTED", message);
|
|
993
|
+
return asOpError(error);
|
|
994
|
+
}
|
|
995
|
+
async call(what, run) {
|
|
996
|
+
try {
|
|
997
|
+
return await run();
|
|
998
|
+
} catch (error) {
|
|
999
|
+
throw await this.fail(error, what);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
exclusive(run) {
|
|
1003
|
+
const next = this.turn.then(run, run);
|
|
1004
|
+
this.turn = next.catch(() => void 0);
|
|
1005
|
+
return next;
|
|
1006
|
+
}
|
|
1007
|
+
withHash(path, snap) {
|
|
1008
|
+
const h = snap.k === "file" ? this.snapshot.hashOf(path, snap.s, snap.m) : void 0;
|
|
1009
|
+
return h ? { ...snap, h } : snap;
|
|
1010
|
+
}
|
|
1011
|
+
item(path, snap) {
|
|
1012
|
+
return itemOfSnap(path, this.withHash(path, snap), path === "" ? this.config.label : void 0);
|
|
1013
|
+
}
|
|
1014
|
+
async statSnap(path) {
|
|
1015
|
+
const entry = await this.call(`stat ${path || "/"}`, () => this.port.stat(path));
|
|
1016
|
+
return entry ? snapOf(entry) : null;
|
|
1017
|
+
}
|
|
1018
|
+
// ── The journal, in step with the snapshot ───────────────────────────
|
|
1019
|
+
record(path, snap, options = {}) {
|
|
1020
|
+
const movedFrom = options.movedFrom && options.movedFrom !== path ? options.movedFrom : void 0;
|
|
1021
|
+
const created = movedFrom ? deviceDirname(movedFrom) !== deviceDirname(path) : !this.snapshot.has(path);
|
|
1022
|
+
const before = movedFrom ? this.snapshot.get(movedFrom) : void 0;
|
|
1023
|
+
const kept = before?.h && before.k === "file" && snap.k === "file" && before.s === snap.s && before.m === snap.m ? { ...snap, h: before.h } : snap;
|
|
1024
|
+
if (movedFrom) this.snapshot.deleteOne(movedFrom);
|
|
1025
|
+
this.snapshot.set(path, kept);
|
|
1026
|
+
const item = this.item(path, kept);
|
|
1027
|
+
this.journal.upsert(item, created, movedFrom);
|
|
1028
|
+
return item;
|
|
1029
|
+
}
|
|
1030
|
+
forget(path) {
|
|
1031
|
+
for (const child of this.snapshot.under(path)) {
|
|
1032
|
+
this.journal.remove(child);
|
|
1033
|
+
this.snapshot.deleteOne(child);
|
|
1034
|
+
}
|
|
1035
|
+
this.journal.remove(path);
|
|
1036
|
+
this.snapshot.deleteOne(path);
|
|
1037
|
+
}
|
|
1038
|
+
/** A write answers once what it journaled is durable; the snapshot follows every so often. */
|
|
1039
|
+
async landed(result) {
|
|
1040
|
+
await this.journal.flush();
|
|
1041
|
+
if (!this.journal.settled) throw new OpError("INTERNAL", "the change was made but could not be recorded on this phone (its storage refused the write)");
|
|
1042
|
+
const behind = Number(this.journal.position.split(":")[1]) - Number(this.snapshot.at.split(":")[1] ?? 0);
|
|
1043
|
+
if (this.known && (this.snapshot.at.split(":")[0] !== this.journal.position.split(":")[0] || behind >= PORTABLE_SAVE_EVERY)) await this.snapshot.save(this.journal.position).catch(() => void 0);
|
|
1044
|
+
return result;
|
|
1045
|
+
}
|
|
1046
|
+
// ── Rescan ───────────────────────────────────────────────────────────
|
|
1047
|
+
/** One walk at a time: a rescan asked for while one runs gets that one's answer. */
|
|
1048
|
+
rescan() {
|
|
1049
|
+
this.scanning ?? (this.scanning = this.exclusive(() => this.walkAndDiff()).finally(() => {
|
|
1050
|
+
this.scanning = null;
|
|
1051
|
+
}));
|
|
1052
|
+
return this.scanning;
|
|
1053
|
+
}
|
|
1054
|
+
/**
|
|
1055
|
+
* The whole tree, as the port lists it now. A folder that cannot be read is named, never taken as empty. Several
|
|
1056
|
+
* folders are listed at once (walkConcurrency): the order they answer in does not matter, because what is built is
|
|
1057
|
+
* a map of paths, and the walk's ORDER is a property of the paths themselves (compareWalkOrder), not of the visit.
|
|
1058
|
+
*/
|
|
1059
|
+
async walk() {
|
|
1060
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1061
|
+
const unreadable = [];
|
|
1062
|
+
const pending = [{ path: "", depth: 0 }];
|
|
1063
|
+
const limit = Math.max(1, this.deps.walkConcurrency ?? PORTABLE_WALK_CONCURRENCY);
|
|
1064
|
+
let active = 0;
|
|
1065
|
+
let failure = null;
|
|
1066
|
+
const visit = async ({ path, depth }) => {
|
|
1067
|
+
let entries;
|
|
1068
|
+
try {
|
|
1069
|
+
entries = await this.port.list(path);
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
if (path === "") {
|
|
1072
|
+
failure = error;
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
if (folderPortCode(error) === "NOT_FOUND") {
|
|
1076
|
+
seen.delete(path);
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
unreadable.push(path);
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
for (const entry of entries) {
|
|
1083
|
+
if (typeof entry?.name !== "string" || !entry.name || entry.name.includes("/")) continue;
|
|
1084
|
+
const child = `${path}/${entry.name}`;
|
|
1085
|
+
if (deviceJoin(path, entry.name) !== child || !isSafeDevicePath(child) || !this.isShared(child)) continue;
|
|
1086
|
+
if (entry.kind !== "file" && entry.kind !== "folder") continue;
|
|
1087
|
+
seen.set(child, snapOf(entry));
|
|
1088
|
+
if (entry.kind === "folder" && depth + 1 < MAX_DEPTH) pending.push({ path: child, depth: depth + 1 });
|
|
1089
|
+
}
|
|
1090
|
+
};
|
|
1091
|
+
await new Promise((resolve) => {
|
|
1092
|
+
const pump = () => {
|
|
1093
|
+
const ended = failure !== null || this.stopped;
|
|
1094
|
+
while (!ended && active < limit && pending.length) {
|
|
1095
|
+
active += 1;
|
|
1096
|
+
void visit(pending.pop()).catch((error) => {
|
|
1097
|
+
failure ?? (failure = error);
|
|
1098
|
+
}).then(() => {
|
|
1099
|
+
active -= 1;
|
|
1100
|
+
pump();
|
|
1101
|
+
});
|
|
1102
|
+
}
|
|
1103
|
+
if (!active && (ended || !pending.length)) resolve();
|
|
1104
|
+
};
|
|
1105
|
+
pump();
|
|
1106
|
+
});
|
|
1107
|
+
if (this.stopped) throw new OpError("UNAVAILABLE", `${this.config.label} is no longer shared`);
|
|
1108
|
+
if (failure !== null) throw failure;
|
|
1109
|
+
return { seen, unreadable };
|
|
1110
|
+
}
|
|
1111
|
+
async walkAndDiff() {
|
|
1112
|
+
if (this.rootState !== "ok") throw new OpError("UNAVAILABLE", this.reason ?? "the folder is not available");
|
|
1113
|
+
const started = this.now();
|
|
1114
|
+
this.lookBeganAt = started;
|
|
1115
|
+
let walked;
|
|
1116
|
+
try {
|
|
1117
|
+
walked = await this.walk();
|
|
1118
|
+
} catch (error) {
|
|
1119
|
+
throw await this.fail(error, "the folder could not be listed");
|
|
1120
|
+
}
|
|
1121
|
+
if (this.stopped) throw new OpError("UNAVAILABLE", `${this.config.label} is no longer shared`);
|
|
1122
|
+
const { seen, unreadable } = walked;
|
|
1123
|
+
const report = this.walked || this.snapshot.exists;
|
|
1124
|
+
const under = (p) => unreadable.some((u) => p === u || p.startsWith(`${u}/`));
|
|
1125
|
+
if (unreadable.length) {
|
|
1126
|
+
for (const p of this.snapshot.paths()) if (!seen.has(p) && under(p)) seen.set(p, this.snapshot.get(p));
|
|
1127
|
+
}
|
|
1128
|
+
const upserts = [];
|
|
1129
|
+
const gone = [];
|
|
1130
|
+
if (report) {
|
|
1131
|
+
for (const [p, snap] of seen) {
|
|
1132
|
+
const before = this.snapshot.get(p);
|
|
1133
|
+
if (!before) upserts.push({ path: p, snap, created: true });
|
|
1134
|
+
else if (!sameSnap(before, snap)) upserts.push({ path: p, snap, created: false });
|
|
1135
|
+
}
|
|
1136
|
+
for (const p of this.snapshot.paths()) if (!seen.has(p)) gone.push(p);
|
|
1137
|
+
}
|
|
1138
|
+
const movedFrom = /* @__PURE__ */ new Map();
|
|
1139
|
+
if (gone.length && upserts.length) {
|
|
1140
|
+
const byShape = /* @__PURE__ */ new Map();
|
|
1141
|
+
for (const p of gone) {
|
|
1142
|
+
const e = this.snapshot.get(p);
|
|
1143
|
+
if (e?.k === "file" && e.m) {
|
|
1144
|
+
const key = `${e.s}|${e.m}`;
|
|
1145
|
+
byShape.set(key, [...byShape.get(key) ?? [], p]);
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
1149
|
+
for (const u of upserts) {
|
|
1150
|
+
if (!u.created || u.snap.k !== "file" || !u.snap.m) continue;
|
|
1151
|
+
const candidates = byShape.get(`${u.snap.s}|${u.snap.m}`) ?? [];
|
|
1152
|
+
if (candidates.length === 1 && !claimed.has(candidates[0])) {
|
|
1153
|
+
movedFrom.set(u.path, candidates[0]);
|
|
1154
|
+
claimed.add(candidates[0]);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
let added = 0;
|
|
1159
|
+
let changed = 0;
|
|
1160
|
+
let removed = 0;
|
|
1161
|
+
let reset;
|
|
1162
|
+
if (report && upserts.length + gone.length > this.journal.keepCount) {
|
|
1163
|
+
reset = { changes: upserts.length + gone.length };
|
|
1164
|
+
await this.journal.reset();
|
|
1165
|
+
}
|
|
1166
|
+
for (const [p, snap] of seen) {
|
|
1167
|
+
const h = snap.k === "file" ? this.snapshot.hashOf(p, snap.s, snap.m) : void 0;
|
|
1168
|
+
if (h) seen.set(p, { ...snap, h });
|
|
1169
|
+
}
|
|
1170
|
+
if (report && !reset) {
|
|
1171
|
+
for (const u of upserts) {
|
|
1172
|
+
const from = movedFrom.get(u.path);
|
|
1173
|
+
const before = from ? this.snapshot.get(from) : void 0;
|
|
1174
|
+
const snap = before?.h ? { ...u.snap, h: before.h } : u.snap;
|
|
1175
|
+
if (from) {
|
|
1176
|
+
seen.set(u.path, snap);
|
|
1177
|
+
changed += 1;
|
|
1178
|
+
this.journal.upsert(itemOfSnap(u.path, snap), deviceDirname(from) !== deviceDirname(u.path), from);
|
|
1179
|
+
continue;
|
|
1180
|
+
}
|
|
1181
|
+
if (u.created) added += 1;
|
|
1182
|
+
else changed += 1;
|
|
1183
|
+
this.journal.upsert(itemOfSnap(u.path, snap), u.created);
|
|
1184
|
+
}
|
|
1185
|
+
const paired = new Set(movedFrom.values());
|
|
1186
|
+
for (const p of gone.filter((g) => !paired.has(g)).sort((a, b) => b.length - a.length)) {
|
|
1187
|
+
removed += 1;
|
|
1188
|
+
this.journal.remove(p);
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
await this.journal.flush();
|
|
1192
|
+
const unchanged = this.snapshot.exists && !added && !changed && !removed && !reset && this.snapshot.at === this.journal.position && !this.snapshot.hasUnsavedHashes;
|
|
1193
|
+
this.snapshot.replace(seen);
|
|
1194
|
+
this.walked = true;
|
|
1195
|
+
this.lastLookAt = this.now();
|
|
1196
|
+
if (!unchanged && this.journal.settled) await this.snapshot.save(this.journal.position).catch((error) => this.log(`the catalogue could not be saved on this phone: ${error.message}`));
|
|
1197
|
+
const result = { seen: seen.size, added, changed, removed, unreadable, ...reset ? { reset } : {} };
|
|
1198
|
+
this.log(`${seen.size} items${report ? ` (+${added} ~${changed} -${removed})` : ""} in ${Math.max(0, Math.round((this.now() - started) / 100) / 10)} s${unreadable.length ? `; ${unreadable.length} folder(s) could not be read and keep what was known` : ""}${reset ? `; ${reset.changes} changes, too many to replay: the server lists the folder again` : ""}`);
|
|
1199
|
+
return result;
|
|
1200
|
+
}
|
|
1201
|
+
/** The first walk is what `enumerate` and the feed stand on: wait for it rather than answer from nothing. */
|
|
1202
|
+
async ready() {
|
|
1203
|
+
await this.open();
|
|
1204
|
+
this.available();
|
|
1205
|
+
if (!this.known) await this.rescan();
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* Make sure the folder has been looked at recently: a look that BEGAN within the last `maxAgeMs` is enough,
|
|
1209
|
+
* otherwise another is made. 0 means "look now": a walk already under way began before this was asked and may
|
|
1210
|
+
* have passed the folder that just changed, so it is waited for and then followed by a fresh one.
|
|
1211
|
+
*/
|
|
1212
|
+
async refresh(maxAgeMs) {
|
|
1213
|
+
await this.open();
|
|
1214
|
+
if (this.rootState !== "ok" || this.stopped) return;
|
|
1215
|
+
const since = this.now() - maxAgeMs;
|
|
1216
|
+
if (this.scanning) await this.scanning.catch(() => void 0);
|
|
1217
|
+
if (this.stopped || this.rootState !== "ok") return;
|
|
1218
|
+
if (maxAgeMs <= 0 || this.lookBeganAt < since) await this.rescan();
|
|
1219
|
+
}
|
|
1220
|
+
// ── Reads ────────────────────────────────────────────────────────────
|
|
1221
|
+
async stat(params) {
|
|
1222
|
+
await this.open();
|
|
1223
|
+
this.available();
|
|
1224
|
+
let path;
|
|
1225
|
+
try {
|
|
1226
|
+
path = this.resolve(params.path);
|
|
1227
|
+
} catch {
|
|
1228
|
+
return null;
|
|
1229
|
+
}
|
|
1230
|
+
const snap = await this.statSnap(path);
|
|
1231
|
+
return snap ? this.item(path, snap) : null;
|
|
1232
|
+
}
|
|
1233
|
+
/** One folder's children as they are NOW (the executor's namesake check), in the walk's order, a page at a time. */
|
|
1234
|
+
async list(params) {
|
|
1235
|
+
await this.open();
|
|
1236
|
+
this.available();
|
|
1237
|
+
const path = this.resolve(params.path);
|
|
1238
|
+
const limit = Math.max(1, Math.min(params.limit || 200, 5e3));
|
|
1239
|
+
let after = null;
|
|
1240
|
+
if (params.cursor) {
|
|
1241
|
+
try {
|
|
1242
|
+
const parsed = JSON.parse(params.cursor);
|
|
1243
|
+
if (parsed.after && typeof parsed.after.name === "string") after = { kind: parsed.after.kind === "folder" ? "folder" : "file", name: parsed.after.name };
|
|
1244
|
+
} catch {
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
const entries = await this.call(`list ${path || "/"}`, () => this.port.list(path));
|
|
1248
|
+
const order = (a, b) => a.kind !== b.kind ? a.kind === "folder" ? -1 : 1 : a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
|
|
1249
|
+
const children = entries.filter((e) => typeof e?.name === "string" && !!e.name && !e.name.includes("/") && this.isShared(`${path}/${e.name}`)).sort(order).filter((e) => !after || order(e, after) > 0);
|
|
1250
|
+
const items = [];
|
|
1251
|
+
let bytes = 0;
|
|
1252
|
+
for (const entry of children) {
|
|
1253
|
+
const item = this.item(`${path}/${entry.name}`, snapOf(entry));
|
|
1254
|
+
const size = portableWireBytes(item);
|
|
1255
|
+
if (items.length && (items.length >= limit || bytes + size > PORTABLE_PAGE_MAX_BYTES)) {
|
|
1256
|
+
const last = items[items.length - 1];
|
|
1257
|
+
return { items, cursor: JSON.stringify({ after: { kind: last.kind, name: last.name } }) };
|
|
1258
|
+
}
|
|
1259
|
+
items.push(item);
|
|
1260
|
+
bytes += size;
|
|
1261
|
+
}
|
|
1262
|
+
return { items, cursor: null };
|
|
1263
|
+
}
|
|
1264
|
+
/** A page of the whole tree, out of the snapshot, in the walk's order. The cursor is the last item sent. */
|
|
1265
|
+
async enumerate(params) {
|
|
1266
|
+
await this.ready();
|
|
1267
|
+
const limit = Math.max(1, Math.min(params.limit || 2e3, 1e4));
|
|
1268
|
+
const order = this.snapshot.walkOrder();
|
|
1269
|
+
let from = 0;
|
|
1270
|
+
if (params.cursor) {
|
|
1271
|
+
let at = null;
|
|
1272
|
+
try {
|
|
1273
|
+
at = JSON.parse(params.cursor);
|
|
1274
|
+
} catch {
|
|
1275
|
+
at = null;
|
|
1276
|
+
}
|
|
1277
|
+
if (at && typeof at.at === "string" && at.at.startsWith("/")) {
|
|
1278
|
+
const kind = at.folder ? "folder" : "file";
|
|
1279
|
+
let lo = 0;
|
|
1280
|
+
let hi = order.length;
|
|
1281
|
+
while (lo < hi) {
|
|
1282
|
+
const mid = lo + hi >> 1;
|
|
1283
|
+
if (compareWalkOrder(order[mid], this.snapshot.get(order[mid]).k, at.at, kind) <= 0) lo = mid + 1;
|
|
1284
|
+
else hi = mid;
|
|
1285
|
+
}
|
|
1286
|
+
from = lo;
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
const items = [];
|
|
1290
|
+
let bytes = 0;
|
|
1291
|
+
let i = from;
|
|
1292
|
+
for (; i < order.length; i += 1) {
|
|
1293
|
+
const item = this.item(order[i], this.snapshot.get(order[i]));
|
|
1294
|
+
const size = portableWireBytes(item);
|
|
1295
|
+
if (items.length && (items.length >= limit || bytes + size > PORTABLE_PAGE_MAX_BYTES)) break;
|
|
1296
|
+
items.push(item);
|
|
1297
|
+
bytes += size;
|
|
1298
|
+
}
|
|
1299
|
+
const more = i < order.length;
|
|
1300
|
+
const last = items[items.length - 1];
|
|
1301
|
+
return { items, cursor: more && last ? JSON.stringify({ at: last.externalId, folder: last.kind === "folder" }) : null, done: !more };
|
|
1302
|
+
}
|
|
1303
|
+
/**
|
|
1304
|
+
* The feed since a cursor. Answered from the journal at once; when the last look at the folder is stale, another
|
|
1305
|
+
* is started behind the answer, and what it finds nudges the server to ask again.
|
|
1306
|
+
*/
|
|
1307
|
+
async changes(params) {
|
|
1308
|
+
await this.ready();
|
|
1309
|
+
if (this.now() - this.lastLookAt > (this.deps.staleAfterMs ?? 6e4)) void this.rescan().catch(() => void 0);
|
|
1310
|
+
return this.journal.since(params.cursor, Math.max(1, Math.min(params.limit || 2e3, 1e4)));
|
|
1311
|
+
}
|
|
1312
|
+
async openRead(params) {
|
|
1313
|
+
await this.open();
|
|
1314
|
+
this.available();
|
|
1315
|
+
const path = this.resolve(params.path);
|
|
1316
|
+
const snap = await this.statSnap(path);
|
|
1317
|
+
if (!snap || snap.k !== "file") throw new OpError("NOT_FOUND", `no such file: ${path}`);
|
|
1318
|
+
const size = snap.s;
|
|
1319
|
+
if (typeof params.maxBytes === "number" && params.maxBytes > 0 && size !== null && size > params.maxBytes) throw new OpError("TOO_LARGE", `${deviceBasename(path)} is ${size} bytes; the limit for this read is ${params.maxBytes}`);
|
|
1320
|
+
const port = this.port;
|
|
1321
|
+
const maxBytes = typeof params.maxBytes === "number" && params.maxBytes > 0 ? params.maxBytes : null;
|
|
1322
|
+
return {
|
|
1323
|
+
size,
|
|
1324
|
+
label: path,
|
|
1325
|
+
chunks: async function* (chunkBytes) {
|
|
1326
|
+
let offset = 0;
|
|
1327
|
+
try {
|
|
1328
|
+
for (; ; ) {
|
|
1329
|
+
const part = await port.read(path, offset, chunkBytes);
|
|
1330
|
+
if (!part || part.length === 0) return;
|
|
1331
|
+
offset += part.length;
|
|
1332
|
+
if (maxBytes !== null && offset > maxBytes) throw new OpError("TOO_LARGE", `${deviceBasename(path)} is larger than the ${maxBytes} bytes this read allows`);
|
|
1333
|
+
yield part;
|
|
1334
|
+
if (part.length < chunkBytes || size !== null && offset >= size) return;
|
|
1335
|
+
}
|
|
1336
|
+
} finally {
|
|
1337
|
+
await port.readEnd?.(path).catch(() => void 0);
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
// ── Writes ───────────────────────────────────────────────────────────
|
|
1343
|
+
async mkdir(params) {
|
|
1344
|
+
await this.ready();
|
|
1345
|
+
this.writable();
|
|
1346
|
+
const path = this.resolve(params.path);
|
|
1347
|
+
if (path === "") throw new OpError("EXISTS", "the root exists");
|
|
1348
|
+
return this.exclusive(async () => {
|
|
1349
|
+
if (await this.statSnap(path)) throw new OpError("EXISTS", `${path} exists`);
|
|
1350
|
+
await this.call(`mkdir ${path}`, () => this.port.mkdir(path));
|
|
1351
|
+
const snap = await this.statSnap(path);
|
|
1352
|
+
if (!snap) throw new OpError("INTERNAL", `${path} was not created`);
|
|
1353
|
+
return this.landed(this.record(path, snap));
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
/** `to` is the full destination path: one call renames or moves. Descendants are reported, each naming where it was. */
|
|
1357
|
+
async move(params) {
|
|
1358
|
+
await this.ready();
|
|
1359
|
+
this.writable();
|
|
1360
|
+
const from = this.resolve(params.from);
|
|
1361
|
+
const to = this.resolve(params.to);
|
|
1362
|
+
if (from === "" || to === "") throw new OpError("BAD_PATH", "the root cannot be moved");
|
|
1363
|
+
if (to.startsWith(`${from}/`)) throw new OpError("BAD_PATH", "a folder cannot be moved into itself");
|
|
1364
|
+
return this.exclusive(async () => {
|
|
1365
|
+
const source = await this.statSnap(from);
|
|
1366
|
+
if (!source) throw new OpError("NOT_FOUND", `no such item: ${from}`);
|
|
1367
|
+
if (to === from) return this.item(from, source);
|
|
1368
|
+
const caseOnly = to.toLowerCase() === from.toLowerCase();
|
|
1369
|
+
if (!caseOnly && await this.statSnap(to)) throw new OpError("EXISTS", `${to} exists`);
|
|
1370
|
+
await this.call(`move ${from}`, () => this.port.move(from, to));
|
|
1371
|
+
const landed = await this.statSnap(to);
|
|
1372
|
+
if (!landed) throw new OpError("INTERNAL", `${from} was moved but is not at ${to}`);
|
|
1373
|
+
const children = source.k === "folder" ? this.snapshot.under(from).reverse() : [];
|
|
1374
|
+
const moved = children.map((p) => ({ from: p, to: `${to}${p.slice(from.length)}`, snap: this.snapshot.get(p) }));
|
|
1375
|
+
const item = this.record(to, landed, { movedFrom: from });
|
|
1376
|
+
for (const child of moved) this.record(child.to, child.snap, { movedFrom: child.from });
|
|
1377
|
+
return this.landed(item);
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
async copyTree(from, to, depth) {
|
|
1381
|
+
const source = await this.statSnap(from);
|
|
1382
|
+
if (!source) throw new OpError("NOT_FOUND", `no such item: ${from}`);
|
|
1383
|
+
if (source.k === "file") {
|
|
1384
|
+
await this.call(`copy ${from}`, () => this.port.copyFile(from, to));
|
|
1385
|
+
return;
|
|
1386
|
+
}
|
|
1387
|
+
if (depth >= MAX_DEPTH) throw new OpError("UNSUPPORTED", `${from} is nested too deeply to copy`);
|
|
1388
|
+
await this.call(`mkdir ${to}`, () => this.port.mkdir(to));
|
|
1389
|
+
for (const entry of await this.call(`list ${from}`, () => this.port.list(from))) {
|
|
1390
|
+
if (!this.isShared(`${from}/${entry.name}`)) continue;
|
|
1391
|
+
await this.copyTree(`${from}/${entry.name}`, `${to}/${entry.name}`, depth + 1);
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
/** What stands under a path now, the path included, as snapshot entries (after a copy: its result). */
|
|
1395
|
+
async look(path, into, depth = 0) {
|
|
1396
|
+
const snap = await this.statSnap(path);
|
|
1397
|
+
if (!snap) return;
|
|
1398
|
+
into.set(path, snap);
|
|
1399
|
+
if (snap.k !== "folder" || depth >= MAX_DEPTH) return;
|
|
1400
|
+
for (const entry of await this.call(`list ${path}`, () => this.port.list(path))) {
|
|
1401
|
+
const child = `${path}/${entry.name}`;
|
|
1402
|
+
if (!this.isShared(child)) continue;
|
|
1403
|
+
if (entry.kind === "folder") await this.look(child, into, depth + 1);
|
|
1404
|
+
else into.set(child, snapOf(entry));
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
async copy(params) {
|
|
1408
|
+
await this.ready();
|
|
1409
|
+
this.writable();
|
|
1410
|
+
const from = this.resolve(params.from);
|
|
1411
|
+
const to = this.resolve(params.to);
|
|
1412
|
+
if (from === "" || to === "") throw new OpError("BAD_PATH", "the root cannot be copied");
|
|
1413
|
+
if (to === from || to.startsWith(`${from}/`)) throw new OpError("BAD_PATH", "a folder cannot be copied into itself");
|
|
1414
|
+
return this.exclusive(async () => {
|
|
1415
|
+
if (await this.statSnap(to)) throw new OpError("EXISTS", `${to} exists`);
|
|
1416
|
+
await this.copyTree(from, to, 0);
|
|
1417
|
+
const made = /* @__PURE__ */ new Map();
|
|
1418
|
+
await this.look(to, made);
|
|
1419
|
+
const top = made.get(to);
|
|
1420
|
+
if (!top) throw new OpError("INTERNAL", `${from} was copied but is not at ${to}`);
|
|
1421
|
+
let item = null;
|
|
1422
|
+
for (const p of [...made.keys()].sort((a, b) => a.length - b.length)) {
|
|
1423
|
+
const recorded = this.record(p, made.get(p));
|
|
1424
|
+
if (p === to) item = recorded;
|
|
1425
|
+
}
|
|
1426
|
+
return this.landed(item);
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
/**
|
|
1430
|
+
* A delete: the item goes into this folder's own trash folder, where the person finds it. Never removed for good.
|
|
1431
|
+
* A name already in the trash gets the time added, so yesterday's deleted "scan.pdf" is not written over.
|
|
1432
|
+
*/
|
|
1433
|
+
async trash(params) {
|
|
1434
|
+
await this.ready();
|
|
1435
|
+
this.writable();
|
|
1436
|
+
if (!this.hasTrash) throw new OpError("NO_TRASH", `${this.config.label} has no trash; move the item instead`);
|
|
1437
|
+
const path = this.resolve(params.path);
|
|
1438
|
+
if (path === "") throw new OpError("BAD_PATH", "the root cannot be trashed");
|
|
1439
|
+
return this.exclusive(async () => {
|
|
1440
|
+
if (!await this.statSnap(path)) throw new OpError("NOT_FOUND", `no such item: ${path}`);
|
|
1441
|
+
const bin = `/${DEVICE_TRASH_FOLDER}`;
|
|
1442
|
+
if (!await this.statSnap(bin)) await this.call("create the trash folder", () => this.port.mkdir(bin));
|
|
1443
|
+
const name = deviceBasename(path);
|
|
1444
|
+
let target = `${bin}/${name}`;
|
|
1445
|
+
if (await this.statSnap(target)) {
|
|
1446
|
+
const dot = name.lastIndexOf(".");
|
|
1447
|
+
const stamp = new Date(this.now()).toISOString().replace(/[:.]/g, "-");
|
|
1448
|
+
target = dot > 0 ? `${bin}/${name.slice(0, dot)} (${stamp})${name.slice(dot)}` : `${bin}/${name} (${stamp})`;
|
|
1449
|
+
}
|
|
1450
|
+
await this.call(`trash ${path}`, () => this.port.move(path, target));
|
|
1451
|
+
this.forget(path);
|
|
1452
|
+
return this.landed({ ok: true });
|
|
1453
|
+
});
|
|
1454
|
+
}
|
|
1455
|
+
async checkDestination(path, mode) {
|
|
1456
|
+
if (path === "") throw new OpError("BAD_PATH", "the root is a folder");
|
|
1457
|
+
const existing = await this.statSnap(path);
|
|
1458
|
+
if (mode === "create" && existing) throw new OpError("EXISTS", `${path} exists`);
|
|
1459
|
+
if (mode === "replace" && !existing) throw new OpError("NOT_FOUND", `no such file: ${path}`);
|
|
1460
|
+
if (existing?.k === "folder") throw new OpError("EXISTS", `${path} is a folder`);
|
|
1461
|
+
}
|
|
1462
|
+
async write(params) {
|
|
1463
|
+
await this.ready();
|
|
1464
|
+
this.writable();
|
|
1465
|
+
const data = bytesOf(params.data);
|
|
1466
|
+
if (data.length > PORTABLE_MAX_WRITE_BYTES) throw new OpError("TOO_LARGE", `${data.length} bytes is more than this phone accepts in one write (${PORTABLE_MAX_WRITE_BYTES})`);
|
|
1467
|
+
const path = this.resolve(params.path);
|
|
1468
|
+
return this.exclusive(async () => {
|
|
1469
|
+
await this.checkDestination(path, params.mode);
|
|
1470
|
+
const handle = await this.call(`write ${path}`, () => this.port.writeBegin(path));
|
|
1471
|
+
try {
|
|
1472
|
+
await this.port.writeAppend(handle, data);
|
|
1473
|
+
await this.port.writeCommit(handle, params.mode === "replace");
|
|
1474
|
+
} catch (error) {
|
|
1475
|
+
await this.port.writeAbort(handle).catch(() => void 0);
|
|
1476
|
+
throw await this.fail(error, `write ${path}`);
|
|
1477
|
+
}
|
|
1478
|
+
const snap = await this.statSnap(path);
|
|
1479
|
+
if (!snap) throw new OpError("INTERNAL", `${path} was written but is not there`);
|
|
1480
|
+
return this.landed(this.record(path, snap));
|
|
1481
|
+
});
|
|
1482
|
+
}
|
|
1483
|
+
async openWrite(params) {
|
|
1484
|
+
await this.ready();
|
|
1485
|
+
this.writable();
|
|
1486
|
+
if (typeof params.stream !== "string" || !params.stream) throw new OpError("BAD_PATH", "a write stream needs a name");
|
|
1487
|
+
if (this.writes.has(params.stream)) return { stream: params.stream };
|
|
1488
|
+
const path = this.resolve(params.path);
|
|
1489
|
+
await this.checkDestination(path, params.mode);
|
|
1490
|
+
const handle = await this.call(`write ${path}`, () => this.port.writeBegin(path));
|
|
1491
|
+
const expected = typeof params.size === "number" && Number.isFinite(params.size) && params.size >= 0 ? params.size : null;
|
|
1492
|
+
this.writes.set(params.stream, { path, handle, mode: params.mode, expected, seq: 0, bytes: 0 });
|
|
1493
|
+
return { stream: params.stream };
|
|
1494
|
+
}
|
|
1495
|
+
async appendWrite(chunk) {
|
|
1496
|
+
const open = this.writes.get(chunk.stream);
|
|
1497
|
+
if (!open) return false;
|
|
1498
|
+
if (chunk.seq !== open.seq) {
|
|
1499
|
+
await this.abortWrite(chunk.stream);
|
|
1500
|
+
return false;
|
|
1501
|
+
}
|
|
1502
|
+
const data = bytesOf(chunk.data);
|
|
1503
|
+
try {
|
|
1504
|
+
await this.port.writeAppend(open.handle, data);
|
|
1505
|
+
} catch (error) {
|
|
1506
|
+
await this.abortWrite(chunk.stream);
|
|
1507
|
+
throw await this.fail(error, `write ${open.path}`);
|
|
1508
|
+
}
|
|
1509
|
+
open.seq += 1;
|
|
1510
|
+
open.bytes += data.length;
|
|
1511
|
+
return true;
|
|
1512
|
+
}
|
|
1513
|
+
async closeWrite(params) {
|
|
1514
|
+
const open = this.writes.get(params.stream);
|
|
1515
|
+
if (!open) {
|
|
1516
|
+
const done = this.closed.get(params.stream);
|
|
1517
|
+
if (done && this.now() - done.at < CLOSED_MEMORY_MS) return done.item;
|
|
1518
|
+
throw new OpError("NOT_FOUND", `no write stream ${params.stream}`);
|
|
1519
|
+
}
|
|
1520
|
+
if (normalizeDevicePath(params.path) !== open.path) {
|
|
1521
|
+
await this.abortWrite(params.stream);
|
|
1522
|
+
throw new OpError("BAD_PATH", "the close names another path than the open");
|
|
1523
|
+
}
|
|
1524
|
+
this.writes.delete(params.stream);
|
|
1525
|
+
return this.exclusive(async () => {
|
|
1526
|
+
try {
|
|
1527
|
+
if (open.expected !== null && open.bytes !== open.expected) throw new OpError("INTERNAL", `the write ended at ${open.bytes} bytes, not the ${open.expected} announced`);
|
|
1528
|
+
if (typeof params.bytes === "number" && params.bytes !== open.bytes) throw new OpError("INTERNAL", `the server sent ${params.bytes} bytes, this phone took ${open.bytes}`);
|
|
1529
|
+
await this.port.writeCommit(open.handle, open.mode === "replace");
|
|
1530
|
+
} catch (error) {
|
|
1531
|
+
await this.port.writeAbort(open.handle).catch(() => void 0);
|
|
1532
|
+
throw await this.fail(error, `write ${open.path}`);
|
|
1533
|
+
}
|
|
1534
|
+
const snap = await this.statSnap(open.path);
|
|
1535
|
+
if (!snap) throw new OpError("INTERNAL", `${open.path} was written but is not there`);
|
|
1536
|
+
const item = await this.landed(this.record(open.path, snap));
|
|
1537
|
+
this.closed.set(params.stream, { at: this.now(), item });
|
|
1538
|
+
for (const [stream, entry] of this.closed) {
|
|
1539
|
+
if (this.now() - entry.at >= CLOSED_MEMORY_MS || this.closed.size > CLOSED_MEMORY_MAX) this.closed.delete(stream);
|
|
1540
|
+
else break;
|
|
1541
|
+
}
|
|
1542
|
+
return item;
|
|
1543
|
+
});
|
|
1544
|
+
}
|
|
1545
|
+
async abortWrite(stream) {
|
|
1546
|
+
const open = this.writes.get(stream);
|
|
1547
|
+
if (!open) return;
|
|
1548
|
+
this.writes.delete(stream);
|
|
1549
|
+
await this.port.writeAbort(open.handle).catch(() => void 0);
|
|
1550
|
+
}
|
|
1551
|
+
// ── Facts computed where the bytes are ───────────────────────────────
|
|
1552
|
+
async hash(params) {
|
|
1553
|
+
await this.ready();
|
|
1554
|
+
const hashes = {};
|
|
1555
|
+
for (const raw of (params.paths ?? []).slice(0, PORTABLE_HASH_BATCH)) {
|
|
1556
|
+
hashes[raw] = null;
|
|
1557
|
+
if (!this.port.sha256) continue;
|
|
1558
|
+
try {
|
|
1559
|
+
const path = this.resolve(raw);
|
|
1560
|
+
const snap = await this.statSnap(path);
|
|
1561
|
+
if (!snap || snap.k !== "file" || typeof params.maxBytes === "number" && snap.s !== null && snap.s > params.maxBytes) continue;
|
|
1562
|
+
const cached = this.snapshot.hashOf(path, snap.s, snap.m);
|
|
1563
|
+
if (cached) {
|
|
1564
|
+
hashes[raw] = `sha256:${cached}`;
|
|
1565
|
+
continue;
|
|
1566
|
+
}
|
|
1567
|
+
const digest = (await this.port.sha256(path)).toLowerCase();
|
|
1568
|
+
if (!/^[0-9a-f]{64}$/.test(digest)) continue;
|
|
1569
|
+
this.snapshot.setHash(path, snap.s, snap.m, digest);
|
|
1570
|
+
hashes[raw] = `sha256:${digest}`;
|
|
1571
|
+
} catch {
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
return { hashes };
|
|
1575
|
+
}
|
|
1576
|
+
async media(params) {
|
|
1577
|
+
await this.ready();
|
|
1578
|
+
const media = {};
|
|
1579
|
+
for (const raw of (params.paths ?? []).slice(0, PORTABLE_HASH_BATCH)) {
|
|
1580
|
+
media[raw] = null;
|
|
1581
|
+
if (!this.port.media) continue;
|
|
1582
|
+
try {
|
|
1583
|
+
const path = this.resolve(raw);
|
|
1584
|
+
media[raw] = await this.port.media(path);
|
|
1585
|
+
} catch (error) {
|
|
1586
|
+
media[raw] = folderPortCode(error) === "NOT_FOUND" ? null : "unknown";
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
return { media };
|
|
1590
|
+
}
|
|
1591
|
+
};
|