cursedbelt-server 4.50.0 → 4.52.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.
@@ -19,7 +19,8 @@
19
19
  * 1. **A file is deleted only after the destination CONFIRMS it.** The dropzone is the one
20
20
  * place the owner's copy may be the only copy: they dragged it in expecting it to be taken.
21
21
  * A sweep that deletes on "the upload didn't throw" turns any catalog failure into data
22
- * loss. The handler returns `stored`/`duplicate` and only then does the original go.
22
+ * loss. The handler returns `stored`/`duplicate` and only then does the original go. A file
23
+ * reached through a LINK is never deleted at all: it is the owner's copy where it lives.
23
24
  *
24
25
  * 2. **A file must measure the same size twice before it is touched.** Dropping a 4 GB video
25
26
  * into a folder is not atomic. Without this the sweep ingests a truncated file, reports
@@ -33,8 +34,9 @@
33
34
  */
34
35
 
35
36
  import type { Dirent } from "node:fs";
36
- import { readdir, rm, rmdir, stat } from "node:fs/promises";
37
+ import { lstat, readdir, realpath, rm, rmdir, stat } from "node:fs/promises";
37
38
  import { join, relative } from "node:path";
39
+ import { type LinkSource, linkSource, linkTarget, namedIn } from "./links.js";
38
40
  import type { IngestReporter, ReportFile, ReportResult } from "./report.js";
39
41
 
40
42
  /** A file the sweep found, with everything a handler needs to decide about it. */
@@ -49,12 +51,26 @@ export interface DroppedFile {
49
51
  ext: string;
50
52
  size: number;
51
53
  mtimeMs: number;
54
+ /**
55
+ * The inode and the change time, from the same `stat` as `size` — what tells a file that was
56
+ * REPLACED from one that kept its name and size (collections' linked ledger keys on it, forge
57
+ * task 3585). Optional only so a handler's test can build a `DroppedFile` without them; the walk
58
+ * always sets both.
59
+ */
60
+ ino?: number;
61
+ ctimeMs?: number;
52
62
  /** Every other FILE name in the same directory — see {@link ScanOptions.captureSiblings}. */
53
63
  siblings: string[];
64
+ /**
65
+ * Reached through a symlink (`followLinks`): the owner's own copy, where it lives. A sweep
66
+ * never deletes one, whatever the handler answers — see rule 1. `realPath` is what an app keys
67
+ * it on, so renaming the link neither re-reads the drive nor files anything twice.
68
+ */
69
+ linked?: { realPath: string };
54
70
  }
55
71
 
56
72
  export type DropOutcome =
57
- /** Filed successfully. The original is deleted. */
73
+ /** Filed successfully. The original is deleted — unless it is `linked`, which stays where it is. */
58
74
  | { kind: "stored"; detail?: string }
59
75
  /** Already present at the destination. The original is deleted — that is the point. */
60
76
  | { kind: "duplicate"; detail?: string }
@@ -76,7 +92,11 @@ export interface SweepReport {
76
92
  unstable: string[];
77
93
  bytesRemoved: number;
78
94
  emptyDirsRemoved: number;
79
- /** Anything left in the root when the sweep finished. Empty is the goal. */
95
+ /** Linked files dealt with and LEFT IN PLACE — the owner's copy on their own drive (`followLinks`). */
96
+ leftInPlace: number;
97
+ /** Links whose target is not there this sweep — a drive unplugged, or a folder gone (`followLinks`). */
98
+ unreachable: UnreachableLink[];
99
+ /** Anything left in the root when the sweep finished, links not followed. Empty is the goal. */
80
100
  remaining: number;
81
101
  }
82
102
 
@@ -97,6 +117,23 @@ export interface ScanOptions {
97
117
  captureSiblings?: boolean;
98
118
  /** Directory names to skip entirely at any depth (another app's queue, our own state). */
99
119
  skipDirs?: string[];
120
+ /**
121
+ * Directory names skipped only directly under the root, compared as APFS does (case-insensitive)
122
+ * — an app's quarantine or `done/`, a name that is the owner's own inside a linked folder.
123
+ */
124
+ skipTopDirs?: readonly string[];
125
+ /**
126
+ * Skip every directory whose name starts with a dot, at any depth — another tool's state, never
127
+ * content. Matters most with {@link followLinks}: a link to a whole drive would otherwise walk its
128
+ * `.Spotlight-V100`, `.fseventsd` and `.Trashes`. Off by default, so no consumer changes
129
+ * behavior unasked.
130
+ */
131
+ skipHiddenDirs?: boolean;
132
+ /**
133
+ * Walk THROUGH symlinks: a linked folder is ingested in place (`links.ts`). Off by default, so
134
+ * no consumer changes behavior unasked. See {@link walkDropzone}.
135
+ */
136
+ followLinks?: boolean;
100
137
  /** Stop after this many files. Absent means everything. */
101
138
  limit?: number;
102
139
  }
@@ -128,6 +165,26 @@ const extOf = (name: string): string => {
128
165
  return dot > 0 ? name.slice(dot).toLowerCase() : "";
129
166
  };
130
167
 
168
+ /** A symlink the walk met whose target is not there this pass. */
169
+ export interface UnreachableLink {
170
+ /** The link, relative to the dropzone root. */
171
+ relativePath: string;
172
+ /** The link, absolute. */
173
+ path: string;
174
+ /**
175
+ * The link is in the dropzone's OWN tree (the owner put it there), not one met inside a linked
176
+ * folder on the owner's drive. Only an app's own link is ever its to act on.
177
+ */
178
+ inDropzone: boolean;
179
+ source: Exclude<LinkSource, { state: "ok" }>;
180
+ }
181
+
182
+ /** One walk: the files, and — with `followLinks` — the links that could not be followed. */
183
+ export interface DropzoneScan {
184
+ files: DroppedFile[];
185
+ unreachable: UnreachableLink[];
186
+ }
187
+
131
188
  /**
132
189
  * Every candidate file under `root`, deepest-last, with each one's sibling listing.
133
190
  *
@@ -136,11 +193,57 @@ const extOf = (name: string): string => {
136
193
  * {@link isJunkName} is exported so a handler can classify without re-deriving the list.
137
194
  */
138
195
  export async function scanDropzone(root: string, opts: ScanOptions = {}): Promise<DroppedFile[]> {
196
+ return (await walkDropzone(root, opts)).files;
197
+ }
198
+
199
+ /**
200
+ * {@link scanDropzone}, with the links it could not follow.
201
+ *
202
+ * Without `followLinks` a symlink is skipped, as it always was. With it, a link to a directory is
203
+ * walked — once per REAL path, so a loop, or two links to one folder, or a link back into the
204
+ * dropzone, is not walked twice — and a link to a file is one file; everything reached through a
205
+ * link carries `linked`. A link whose target is missing is returned under `unreachable`, told
206
+ * apart by {@link linkSource}: `unmounted` (wait) or `deleted` (say so). A dangling link INSIDE a
207
+ * linked folder is the owner's drive's business; it is returned too, with `inDropzone: false`.
208
+ */
209
+ export async function walkDropzone(root: string, opts: ScanOptions = {}): Promise<DropzoneScan> {
139
210
  const skip = new Set(opts.skipDirs ?? []);
140
211
  const out: DroppedFile[] = [];
212
+ const unreachable: UnreachableLink[] = [];
213
+ const walked = new Set<string>();
214
+ const full = (n: number): boolean => opts.limit !== undefined && n >= opts.limit;
215
+
216
+ const push = async (path: string, name: string, siblings: string[], linked: boolean): Promise<void> => {
217
+ try {
218
+ const info = await stat(path);
219
+ out.push({
220
+ path,
221
+ relativePath: relative(root, path),
222
+ name,
223
+ ext: extOf(name),
224
+ size: info.size,
225
+ mtimeMs: info.mtimeMs,
226
+ ino: info.ino,
227
+ ctimeMs: info.ctimeMs,
228
+ siblings,
229
+ ...(linked ? { linked: { realPath: await realpath(path) } } : {}),
230
+ });
231
+ } catch {
232
+ /* gone between readdir and stat */
233
+ }
234
+ };
235
+
236
+ /** `false` when this directory's real path was already walked — the one way a link loops. */
237
+ const firstVisit = async (dir: string): Promise<boolean> => {
238
+ if (!opts.followLinks) return true;
239
+ const real = await realpath(dir).catch(() => null);
240
+ if (!real || walked.has(real)) return false;
241
+ walked.add(real);
242
+ return true;
243
+ };
141
244
 
142
- const walk = async (dir: string): Promise<void> => {
143
- if (opts.limit !== undefined && out.length >= opts.limit) return;
245
+ const walk = async (dir: string, linked: boolean): Promise<void> => {
246
+ if (full(out.length)) return;
144
247
  let entries: Dirent[];
145
248
  try {
146
249
  entries = await readdir(dir, { withFileTypes: true });
@@ -152,33 +255,39 @@ export async function scanDropzone(root: string, opts: ScanOptions = {}): Promis
152
255
  : [];
153
256
 
154
257
  for (const entry of entries) {
155
- if (opts.limit !== undefined && out.length >= opts.limit) return;
156
- const full = join(dir, entry.name);
157
- if (entry.isDirectory()) {
258
+ if (full(out.length)) return;
259
+ const path = join(dir, entry.name);
260
+ let isDir = entry.isDirectory();
261
+ let isFile = entry.isFile();
262
+ let viaLink = linked;
263
+ if (entry.isSymbolicLink()) {
264
+ if (!opts.followLinks) continue;
265
+ const target = await stat(path).catch(() => null);
266
+ if (!target) {
267
+ const source = linkSource((await linkTarget(path)) ?? path);
268
+ if (source.state !== "ok")
269
+ unreachable.push({ relativePath: relative(root, path), path, inDropzone: !linked, source });
270
+ continue;
271
+ }
272
+ isDir = target.isDirectory();
273
+ isFile = target.isFile();
274
+ viaLink = true;
275
+ }
276
+ if (isDir) {
158
277
  if (skip.has(entry.name)) continue;
159
- await walk(full);
278
+ if (opts.skipHiddenDirs && entry.name.startsWith(".")) continue;
279
+ if (dir === root && namedIn(opts.skipTopDirs, entry.name)) continue;
280
+ if (!(await firstVisit(path))) continue;
281
+ await walk(path, viaLink);
160
282
  continue;
161
283
  }
162
- if (!entry.isFile()) continue;
163
- try {
164
- const info = await stat(full);
165
- out.push({
166
- path: full,
167
- relativePath: relative(root, full),
168
- name: entry.name,
169
- ext: extOf(entry.name),
170
- size: info.size,
171
- mtimeMs: info.mtimeMs,
172
- siblings,
173
- });
174
- } catch {
175
- /* gone between readdir and stat */
176
- }
284
+ if (isFile) await push(path, entry.name, siblings, viaLink);
177
285
  }
178
286
  };
179
287
 
180
- await walk(root);
181
- return out;
288
+ if (opts.followLinks) await firstVisit(root);
289
+ await walk(root, false);
290
+ return { files: out, unreachable };
182
291
  }
183
292
 
184
293
  /**
@@ -221,6 +330,11 @@ export async function isStable(file: DroppedFile, stabilityMs = 750): Promise<bo
221
330
  * recursive delete here would take a file the sweep deliberately chose not to ingest — a held
222
331
  * duplicate, a failure left in place for the owner to look at — which is precisely the set of
223
332
  * files that must survive.
333
+ *
334
+ * 🔴 `lstat`, never `stat`: a symlink is a linked source, and following it would `rmdir` every
335
+ * empty folder on the owner's own drive (collections met exactly this, 2026-10-21). The one thing
336
+ * removed first is Finder's bookkeeping (`.DS_Store`, `._*`): Finder writes one into every folder
337
+ * the owner LOOKS at, and without this a tree they watched go in stays behind as empty shells.
224
338
  */
225
339
  export async function pruneEmptyDirs(root: string, dir = root): Promise<number> {
226
340
  let removed = 0;
@@ -233,13 +347,16 @@ export async function pruneEmptyDirs(root: string, dir = root): Promise<number>
233
347
  for (const name of entries) {
234
348
  const full = join(dir, name);
235
349
  try {
236
- if ((await stat(full)).isDirectory()) removed += await pruneEmptyDirs(root, full);
350
+ if ((await lstat(full)).isDirectory()) removed += await pruneEmptyDirs(root, full);
237
351
  } catch {
238
352
  /* gone */
239
353
  }
240
354
  }
241
355
  if (dir === root) return removed;
242
356
  try {
357
+ const left = await readdir(dir);
358
+ if (left.length > 0 && left.every(isFinderBookkeeping))
359
+ for (const name of left) await rm(join(dir, name)).catch(() => undefined);
243
360
  await rmdir(dir);
244
361
  return removed + 1;
245
362
  } catch {
@@ -247,6 +364,8 @@ export async function pruneEmptyDirs(root: string, dir = root): Promise<number>
247
364
  }
248
365
  }
249
366
 
367
+ const isFinderBookkeeping = (name: string): boolean => name === ".DS_Store" || name.startsWith("._");
368
+
250
369
  /**
251
370
  * What the app supplies: what to do with one file. `uploading(key)` names the binary-server key its
252
371
  * bytes stage under, once the handler knows it — station's Uploads page shows that transfer's own
@@ -325,11 +444,14 @@ async function sweep(
325
444
  unstable: [],
326
445
  bytesRemoved: 0,
327
446
  emptyDirsRemoved: 0,
447
+ leftInPlace: 0,
448
+ unreachable: [],
328
449
  remaining: 0,
329
450
  };
330
451
 
331
452
  reporter?.walking();
332
- const files = await scanDropzone(root, opts);
453
+ const { files, unreachable } = await walkDropzone(root, opts);
454
+ report.unreachable = unreachable;
333
455
  reporter?.found(files.map(as));
334
456
  for (const [index, file] of files.entries()) {
335
457
  report.scanned++;
@@ -366,6 +488,12 @@ async function sweep(
366
488
  else if (outcome.kind === "duplicate") report.duplicate++;
367
489
  else report.discarded++;
368
490
  if (opts.dryRun) break;
491
+ // Rule 1, for a link: the destination confirming it is not permission to delete the
492
+ // owner's copy on their own drive. Stored, and left where it lives.
493
+ if (file.linked) {
494
+ report.leftInPlace++;
495
+ break;
496
+ }
369
497
  try {
370
498
  await rm(file.path);
371
499
  report.bytesRemoved += file.size;
@@ -391,7 +519,7 @@ async function sweep(
391
519
  }
392
520
 
393
521
  if (!opts.dryRun) report.emptyDirsRemoved = await pruneEmptyDirs(root);
394
- report.remaining = (await scanDropzone(root, { skipDirs: opts.skipDirs })).length;
522
+ report.remaining = (await scanDropzone(root, { skipDirs: opts.skipDirs, skipTopDirs: opts.skipTopDirs })).length;
395
523
  return report;
396
524
  }
397
525
 
@@ -399,6 +527,8 @@ async function sweep(
399
527
  export const describeSweep = (report: SweepReport): string =>
400
528
  `${report.stored} added, ${report.duplicate} already had, ${report.discarded} discarded, ` +
401
529
  `${report.held} held, ${report.failed.length} failed, ${report.unstable.length} still copying` +
530
+ (report.leftInPlace > 0 ? ` · ${report.leftInPlace} linked file(s) left in place` : "") +
531
+ (report.unreachable.length > 0 ? ` · ${report.unreachable.length} link(s) not reachable` : "") +
402
532
  (report.bytesRemoved > 0
403
533
  ? ` · ${(report.bytesRemoved / 1024 ** 3).toFixed(2)} GB freed from the queue`
404
534
  : "") +