@thedriveai/device-helper 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -35,7 +35,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
35
35
  var require_XMLHttpRequest = __commonJS({
36
36
  "node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js"(exports2, module2) {
37
37
  "use strict";
38
- var fs17 = require("fs");
38
+ var fs16 = require("fs");
39
39
  var Url = require("url");
40
40
  var spawn = require("child_process").spawn;
41
41
  module2.exports = XMLHttpRequest3;
@@ -193,7 +193,7 @@ var require_XMLHttpRequest = __commonJS({
193
193
  throw new Error("XMLHttpRequest: Only GET method is supported");
194
194
  }
195
195
  if (settings.async) {
196
- fs17.readFile(unescape(url2.pathname), function(error, data2) {
196
+ fs16.readFile(unescape(url2.pathname), function(error, data2) {
197
197
  if (error) {
198
198
  self.handleError(error, error.errno || -1);
199
199
  } else {
@@ -205,7 +205,7 @@ var require_XMLHttpRequest = __commonJS({
205
205
  });
206
206
  } else {
207
207
  try {
208
- this.response = fs17.readFileSync(unescape(url2.pathname));
208
+ this.response = fs16.readFileSync(unescape(url2.pathname));
209
209
  this.responseText = this.response.toString("utf8");
210
210
  this.status = 200;
211
211
  setState(self.DONE);
@@ -331,15 +331,15 @@ var require_XMLHttpRequest = __commonJS({
331
331
  } else {
332
332
  var contentFile = ".node-xmlhttprequest-content-" + process.pid;
333
333
  var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
334
- fs17.writeFileSync(syncFile, "", "utf8");
334
+ fs16.writeFileSync(syncFile, "", "utf8");
335
335
  var execString = "var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http" + (ssl ? "s" : "") + ".request;var options = " + JSON.stringify(options) + ";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('" + contentFile + "', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('" + syncFile + "');});response.on('error', function(error) {fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('" + syncFile + "');});}).on('error', function(error) {fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('" + syncFile + "');});" + (data ? "req.write('" + JSON.stringify(data).slice(1, -1).replace(/'/g, "\\'") + "');" : "") + "req.end();";
336
336
  var syncProc = spawn(process.argv[0], ["-e", execString]);
337
337
  var statusText;
338
- while (fs17.existsSync(syncFile)) {
338
+ while (fs16.existsSync(syncFile)) {
339
339
  }
340
- self.responseText = fs17.readFileSync(contentFile, "utf8");
340
+ self.responseText = fs16.readFileSync(contentFile, "utf8");
341
341
  syncProc.stdin.end();
342
- fs17.unlinkSync(contentFile);
342
+ fs16.unlinkSync(contentFile);
343
343
  if (self.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)) {
344
344
  var errorObj = JSON.parse(self.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/, ""));
345
345
  self.handleError(errorObj, 503);
@@ -4844,7 +4844,7 @@ __export(cli_exports, {
4844
4844
  isTrashMount: () => isTrashMount
4845
4845
  });
4846
4846
  module.exports = __toCommonJS(cli_exports);
4847
- var import_fs16 = __toESM(require("fs"));
4847
+ var import_fs15 = __toESM(require("fs"));
4848
4848
  var import_path15 = __toESM(require("path"));
4849
4849
 
4850
4850
  // src/config.ts
@@ -4856,11 +4856,12 @@ var import_crypto = require("crypto");
4856
4856
  // src/nasFolders.ts
4857
4857
  var import_fs = __toESM(require("fs"));
4858
4858
  var import_path = __toESM(require("path"));
4859
+
4860
+ // src/nasNames.ts
4859
4861
  var NAS_RECYCLE_BINS = [
4860
4862
  { vendor: "QNAP", name: "@Recycle" },
4861
4863
  { vendor: "Synology", name: "#recycle" }
4862
4864
  ];
4863
- var FALLBACK_BIN = NAS_RECYCLE_BINS.find((b) => b.vendor === "Synology");
4864
4865
  var NAS_SNAPSHOT_FOLDERS = ["#snapshot", "@Recently-Snapshot"];
4865
4866
  var HOUSEKEEPING = new Set([...NAS_RECYCLE_BINS.map((b) => b.name), ...NAS_SNAPSHOT_FOLDERS].map((n) => n.toLowerCase()));
4866
4867
  function isNasHousekeepingName(name) {
@@ -4869,6 +4870,9 @@ function isNasHousekeepingName(name) {
4869
4870
  function isNasRecycleBinName(name) {
4870
4871
  return NAS_RECYCLE_BINS.some((b) => b.name.toLowerCase() === name.toLowerCase());
4871
4872
  }
4873
+
4874
+ // src/nasFolders.ts
4875
+ var FALLBACK_BIN = NAS_RECYCLE_BINS.find((b) => b.vendor === "Synology");
4872
4876
  function shareRecycleBin(rootPath, itemAbs) {
4873
4877
  let root = import_path.default.resolve(rootPath);
4874
4878
  try {
@@ -4941,7 +4945,7 @@ function newRootId(existing) {
4941
4945
  }
4942
4946
 
4943
4947
  // src/index.ts
4944
- var import_fs15 = __toESM(require("fs"));
4948
+ var import_fs14 = __toESM(require("fs"));
4945
4949
  var import_path14 = __toESM(require("path"));
4946
4950
 
4947
4951
  // node_modules/engine.io-client/build/esm-debug/transports/polling-xhr.node.js
@@ -8463,6 +8467,15 @@ var import_path5 = __toESM(require("path"));
8463
8467
  // src/fsitems.ts
8464
8468
  var import_fs3 = __toESM(require("fs"));
8465
8469
  var import_path3 = __toESM(require("path"));
8470
+
8471
+ // src/ignoredNames.ts
8472
+ 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"]);
8473
+ function isIgnoredFileName(name, backslashSeparates = true) {
8474
+ if (backslashSeparates && name.includes("\\")) return true;
8475
+ return name.startsWith(".") || IGNORED_NAMES.has(name) || isNasHousekeepingName(name) || name.startsWith("~$") || name.endsWith(".crdownload") || name.endsWith(".part") || name.endsWith(".tmp");
8476
+ }
8477
+
8478
+ // src/fsitems.ts
8466
8479
  var PathError = class extends Error {
8467
8480
  constructor(code, message) {
8468
8481
  super(message);
@@ -8470,12 +8483,10 @@ var PathError = class extends Error {
8470
8483
  this.name = "PathError";
8471
8484
  }
8472
8485
  };
8473
- 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"]);
8474
8486
  var TRASH_MARKER = ".thedrive-trash";
8475
8487
  var DEPENDENCY_MARKERS = ["pyvenv.cfg", TRASH_MARKER];
8476
8488
  function isIgnoredName(name) {
8477
- if (process.platform !== "win32" && name.includes("\\")) return true;
8478
- return name.startsWith(".") || IGNORED_NAMES.has(name) || isNasHousekeepingName(name) || name.startsWith("~$") || name.endsWith(".crdownload") || name.endsWith(".part") || name.endsWith(".tmp");
8489
+ return isIgnoredFileName(name, process.platform !== "win32");
8479
8490
  }
8480
8491
  function isDependencyFolder(abs) {
8481
8492
  for (const marker of DEPENDENCY_MARKERS) if (import_fs3.default.existsSync(import_path3.default.join(abs, marker))) return true;
@@ -9841,7 +9852,7 @@ async function trashItem(root, abs, devicePath) {
9841
9852
  }
9842
9853
  if (root.trash !== "os" || process.env.TDAI_DOCKER === "1") throw new Error("this folder has no trash");
9843
9854
  if (process.platform === "darwin") {
9844
- await runFile("osascript", ["-e", "on run argv", "-e", 'tell application "Finder" to delete POSIX file (item 1 of argv)', "-e", "end run", abs]);
9855
+ await runFile("osascript", ["-e", "on run argv", "-e", "set trashedItem to (POSIX file (item 1 of argv)) as alias", "-e", 'tell application "Finder" to delete trashedItem', "-e", "end run", abs]);
9845
9856
  return;
9846
9857
  }
9847
9858
  if (process.platform === "linux") {
@@ -9874,7 +9885,7 @@ async function markDownloaded(abs, platform = process.platform) {
9874
9885
  }
9875
9886
  }
9876
9887
 
9877
- // src/ops.ts
9888
+ // src/opError.ts
9878
9889
  var OpError = class extends Error {
9879
9890
  constructor(code, message) {
9880
9891
  super(message);
@@ -9882,6 +9893,16 @@ var OpError = class extends Error {
9882
9893
  this.name = "OpError";
9883
9894
  }
9884
9895
  };
9896
+ var CODES = /* @__PURE__ */ new Set(["NOT_FOUND", "EXISTS", "PERMISSION_DENIED", "READ_ONLY", "NO_TRASH", "TOO_LARGE", "BAD_PATH", "UNSUPPORTED", "UNAVAILABLE", "ONLINE_ONLY", "INTERNAL"]);
9897
+ function asOpError(error) {
9898
+ if (error instanceof OpError) return error;
9899
+ const code = error?.code;
9900
+ const message = error?.message;
9901
+ const text = typeof message === "string" && message ? message : String(error);
9902
+ return new OpError(typeof code === "string" && CODES.has(code) ? code : "INTERNAL", text);
9903
+ }
9904
+
9905
+ // src/ops.ts
9885
9906
  function toOpError(error) {
9886
9907
  if (error instanceof OpError) return error;
9887
9908
  if (error instanceof PathError) return new OpError(error.code, error.message);
@@ -10396,7 +10417,8 @@ var RootOps = class {
10396
10417
  if (!stat || !stat.isFile()) throw new OpError("NOT_FOUND", `no such file: ${resolved.device}`);
10397
10418
  if (!params.allowFetch && placeholdersFor(import_fs11.default.realpathSync(this.rootPath)).has(resolved.abs)) throw new OpError("ONLINE_ONLY", `${deviceBasename(resolved.device)} is online-only (its bytes are in the cloud, not on this computer); reading it would download it`);
10398
10419
  if (typeof params.maxBytes === "number" && params.maxBytes > 0 && stat.size > params.maxBytes) throw new OpError("TOO_LARGE", `${deviceBasename(resolved.device)} is ${stat.size} bytes; the limit for this read is ${params.maxBytes}`);
10399
- return { abs: resolved.abs, size: stat.size, name: deviceBasename(resolved.device) };
10420
+ const abs = resolved.abs;
10421
+ return { abs, size: stat.size, name: deviceBasename(resolved.device), label: abs, chunks: (chunkBytes) => import_fs11.default.createReadStream(abs, { highWaterMark: chunkBytes }) };
10400
10422
  }
10401
10423
  /**
10402
10424
  * The watcher's report of a path that may have changed: stat it and journal the difference, if there is one.
@@ -10792,8 +10814,17 @@ var RootWatcher = class {
10792
10814
  };
10793
10815
 
10794
10816
  // src/client.ts
10795
- var import_fs13 = __toESM(require("fs"));
10796
10817
  var import_crypto4 = require("crypto");
10818
+
10819
+ // src/clientCore.ts
10820
+ function looseStreamId() {
10821
+ const hex = (n) => Array.from({ length: n }, () => Math.floor(Math.random() * 16).toString(16)).join("");
10822
+ return `${hex(8)}-${hex(4)}-4${hex(3)}-a${hex(3)}-${hex(12)}`;
10823
+ }
10824
+ function background(timer) {
10825
+ timer.unref?.();
10826
+ return timer;
10827
+ }
10797
10828
  var WRITES = /* @__PURE__ */ new Set(["mkdir", "move", "copy", "trash", "write", "write_open", "write_close"]);
10798
10829
  var REPLY_MEMORY_MS = 5 * 6e4;
10799
10830
  var REPLY_MEMORY_MAX = 2e3;
@@ -10842,7 +10873,7 @@ var RecentReplies = class {
10842
10873
  return this.byId.size;
10843
10874
  }
10844
10875
  };
10845
- var DeviceClient = class {
10876
+ var CoreDeviceClient = class {
10846
10877
  constructor(deps) {
10847
10878
  this.deps = deps;
10848
10879
  }
@@ -10874,8 +10905,7 @@ var DeviceClient = class {
10874
10905
  } catch {
10875
10906
  }
10876
10907
  }, this.deps.changeDebounceMs ?? 1500);
10877
- timer.unref?.();
10878
- this.pendingNudges.set(rootId, timer);
10908
+ this.pendingNudges.set(rootId, background(timer));
10879
10909
  }
10880
10910
  start() {
10881
10911
  const { socket } = this.deps;
@@ -10897,10 +10927,9 @@ var DeviceClient = class {
10897
10927
  if (reason === "io server disconnect" && socket.connect) {
10898
10928
  const base = this.deps.reconnectAfterMs ?? 5e3;
10899
10929
  const wait = Math.min(base * 2 ** Math.min(this.refusals, 10), Math.max(base, 10 * 6e4));
10900
- const timer = setTimeout(() => {
10930
+ background(setTimeout(() => {
10901
10931
  if (!socket.connected) socket.connect?.();
10902
- }, wait);
10903
- timer.unref?.();
10932
+ }, wait));
10904
10933
  }
10905
10934
  });
10906
10935
  socket.on("connect_error", (error) => this.deps.log(`cannot connect: ${error.message}`));
@@ -10940,6 +10969,7 @@ var DeviceClient = class {
10940
10969
  this.deps.log(`stopped sharing ${refused.length} folder(s) that were removed while this device was away`);
10941
10970
  this.deps.retireRequested?.(refused);
10942
10971
  }
10972
+ if (reply?.ok) this.superseded = false;
10943
10973
  if (reply?.ok) {
10944
10974
  this.refusals = 0;
10945
10975
  this.deps.log(`connected as ${this.deps.device.name}: ${hello.roots.length} folder(s) shared`);
@@ -11001,30 +11031,34 @@ var DeviceClient = class {
11001
11031
  case "media":
11002
11032
  return { ok: true, result: await ops.media(params) };
11003
11033
  case "read": {
11004
- const opened = ops.openRead(params);
11034
+ const opened = await ops.openRead(params);
11005
11035
  const named = typeof params.stream === "string" && /^[0-9a-f-]{36}$/i.test(params.stream) ? params.stream : null;
11006
- const stream = named ?? (0, import_crypto4.randomUUID)();
11036
+ const stream = named ?? (this.deps.newStreamId ?? looseStreamId)();
11007
11037
  this.open.add(stream);
11008
- setImmediate(() => {
11009
- void this.pump(stream, opened.abs);
11010
- });
11038
+ setTimeout(() => {
11039
+ void this.pump(stream, opened);
11040
+ }, 0);
11011
11041
  return { ok: true, result: { stream, size: opened.size, mimeType: "application/octet-stream" } };
11012
11042
  }
11013
11043
  default:
11014
11044
  return { ok: false, error: { code: "UNSUPPORTED", message: `unknown method ${String(request.method)}` } };
11015
11045
  }
11016
11046
  } catch (error) {
11017
- const e = toOpError(error);
11047
+ const e = (this.deps.toError ?? asOpError)(error);
11018
11048
  return { ok: false, error: { code: e.code, message: e.message } };
11019
11049
  }
11020
11050
  }
11021
- async pump(stream, abs) {
11051
+ /**
11052
+ * The bytes of one read, a chunk at a time, each sent only once the server acknowledged the one before. One chunk
11053
+ * is held back so the last can say it is the last (an empty file sends one empty, last chunk). Leaving the loop
11054
+ * early (an abort, a dead line) ends the iteration, which is what releases the file.
11055
+ */
11056
+ async pump(stream, opened) {
11022
11057
  const size = this.deps.chunkBytes ?? STREAM_CHUNK_BYTES;
11023
11058
  let seq = 0;
11024
- const file = import_fs13.default.createReadStream(abs, { highWaterMark: size });
11025
11059
  try {
11026
11060
  let last = null;
11027
- for await (const part of file) {
11061
+ for await (const part of opened.chunks(size)) {
11028
11062
  if (this.aborted.has(stream)) break;
11029
11063
  if (last) {
11030
11064
  if (!await this.send({ stream, seq, data: last, last: false })) {
@@ -11035,11 +11069,10 @@ var DeviceClient = class {
11035
11069
  }
11036
11070
  last = part;
11037
11071
  }
11038
- if (!this.aborted.has(stream)) await this.send({ stream, seq, data: last ?? Buffer.alloc(0), last: true });
11072
+ if (!this.aborted.has(stream)) await this.send({ stream, seq, data: last ?? new Uint8Array(0), last: true });
11039
11073
  } catch (error) {
11040
- this.deps.log(`read of ${abs} failed: ${error.message}`);
11074
+ this.deps.log(`read of ${opened.label} failed: ${error.message}`);
11041
11075
  } finally {
11042
- file.destroy();
11043
11076
  this.open.delete(stream);
11044
11077
  this.aborted.delete(stream);
11045
11078
  }
@@ -11053,20 +11086,27 @@ var DeviceClient = class {
11053
11086
  }
11054
11087
  };
11055
11088
 
11089
+ // src/client.ts
11090
+ var DeviceClient = class extends CoreDeviceClient {
11091
+ constructor(deps) {
11092
+ super({ toError: toOpError, newStreamId: import_crypto4.randomUUID, ...deps });
11093
+ }
11094
+ };
11095
+
11056
11096
  // src/identity.ts
11057
- var import_fs14 = __toESM(require("fs"));
11097
+ var import_fs13 = __toESM(require("fs"));
11058
11098
  var import_path13 = __toESM(require("path"));
11059
11099
  function identityOf(rootPath) {
11060
11100
  let stat;
11061
11101
  try {
11062
- stat = import_fs14.default.statSync(rootPath);
11102
+ stat = import_fs13.default.statSync(rootPath);
11063
11103
  } catch {
11064
11104
  return null;
11065
11105
  }
11066
11106
  if (!stat.isDirectory()) return null;
11067
11107
  let parent = null;
11068
11108
  try {
11069
- parent = import_fs14.default.statSync(import_path13.default.dirname(import_path13.default.resolve(rootPath)));
11109
+ parent = import_fs13.default.statSync(import_path13.default.dirname(import_path13.default.resolve(rootPath)));
11070
11110
  } catch {
11071
11111
  }
11072
11112
  const mount = !parent || parent.dev !== stat.dev || parent.ino === stat.ino;
@@ -11087,7 +11127,7 @@ var RootIdentityStore = class {
11087
11127
  load() {
11088
11128
  if (this.recorded !== void 0) return this.recorded;
11089
11129
  try {
11090
- const parsed = JSON.parse(import_fs14.default.readFileSync(this.file, "utf8"));
11130
+ const parsed = JSON.parse(import_fs13.default.readFileSync(this.file, "utf8"));
11091
11131
  this.recorded = typeof parsed.dev === "number" && typeof parsed.ino === "number" ? { dev: parsed.dev, ino: parsed.ino, mount: parsed.mount === true } : null;
11092
11132
  } catch {
11093
11133
  this.recorded = null;
@@ -11097,9 +11137,9 @@ var RootIdentityStore = class {
11097
11137
  save(identity) {
11098
11138
  this.recorded = identity;
11099
11139
  try {
11100
- import_fs14.default.mkdirSync(import_path13.default.dirname(this.file), { recursive: true });
11101
- import_fs14.default.writeFileSync(`${this.file}.tmp`, JSON.stringify(identity));
11102
- import_fs14.default.renameSync(`${this.file}.tmp`, this.file);
11140
+ import_fs13.default.mkdirSync(import_path13.default.dirname(this.file), { recursive: true });
11141
+ import_fs13.default.writeFileSync(`${this.file}.tmp`, JSON.stringify(identity));
11142
+ import_fs13.default.renameSync(`${this.file}.tmp`, this.file);
11103
11143
  } catch {
11104
11144
  }
11105
11145
  }
@@ -11136,7 +11176,7 @@ var RootIdentityStore = class {
11136
11176
  forget() {
11137
11177
  this.recorded = void 0;
11138
11178
  try {
11139
- import_fs14.default.unlinkSync(this.file);
11179
+ import_fs13.default.unlinkSync(this.file);
11140
11180
  } catch {
11141
11181
  }
11142
11182
  }
@@ -11147,7 +11187,7 @@ function looksLikeSharedFolder(rootPath, knownTopLevelNames) {
11147
11187
  if (knownTopLevelNames.length < ADOPT_MIN_KNOWN) return false;
11148
11188
  let present;
11149
11189
  try {
11150
- present = new Set(import_fs14.default.readdirSync(rootPath));
11190
+ present = new Set(import_fs13.default.readdirSync(rootPath));
11151
11191
  } catch {
11152
11192
  return false;
11153
11193
  }
@@ -11156,7 +11196,7 @@ function looksLikeSharedFolder(rootPath, knownTopLevelNames) {
11156
11196
  }
11157
11197
 
11158
11198
  // src/index.ts
11159
- var HELPER_VERSION = "0.1.4";
11199
+ var HELPER_VERSION = "0.2.0";
11160
11200
  var WATCHER_RETRY_MS = 5 * 6e4;
11161
11201
  var WATCHLESS_RESCAN_MINUTES = 30;
11162
11202
  var LOCK_FILE = "helper.lock";
@@ -11167,7 +11207,7 @@ function isMountDerivedRoot(root, env = process.env) {
11167
11207
  }
11168
11208
  function probeRoot(rootPath, identity, options = {}) {
11169
11209
  try {
11170
- if (!import_fs15.default.statSync(rootPath).isDirectory()) return "missing";
11210
+ if (!import_fs14.default.statSync(rootPath).isDirectory()) return "missing";
11171
11211
  } catch {
11172
11212
  return "missing";
11173
11213
  }
@@ -11181,8 +11221,8 @@ function probeRoot(rootPath, identity, options = {}) {
11181
11221
  }
11182
11222
  }
11183
11223
  try {
11184
- import_fs15.default.closeSync(import_fs15.default.openSync(rootPath, "r"));
11185
- import_fs15.default.readdirSync(rootPath);
11224
+ import_fs14.default.closeSync(import_fs14.default.openSync(rootPath, "r"));
11225
+ import_fs14.default.readdirSync(rootPath);
11186
11226
  return "ok";
11187
11227
  } catch (error) {
11188
11228
  const code = error.code;
@@ -11304,28 +11344,28 @@ function logRescanDoubts(config, result, log) {
11304
11344
  }
11305
11345
  var heldLocks = /* @__PURE__ */ new Set();
11306
11346
  function acquireLock(home = deviceHome()) {
11307
- import_fs15.default.mkdirSync(home, { recursive: true });
11347
+ import_fs14.default.mkdirSync(home, { recursive: true });
11308
11348
  const file = import_path14.default.join(home, LOCK_FILE);
11309
11349
  if (heldLocks.has(file)) throw new Error("another tdai-device is already running for this config (this process); stop it first");
11310
11350
  for (let attempt = 0; attempt < 2; attempt += 1) {
11311
11351
  try {
11312
- const fd = import_fs15.default.openSync(file, "wx");
11313
- import_fs15.default.writeSync(fd, String(process.pid));
11314
- import_fs15.default.closeSync(fd);
11352
+ const fd = import_fs14.default.openSync(file, "wx");
11353
+ import_fs14.default.writeSync(fd, String(process.pid));
11354
+ import_fs14.default.closeSync(fd);
11315
11355
  heldLocks.add(file);
11316
11356
  return () => {
11317
11357
  heldLocks.delete(file);
11318
11358
  try {
11319
- if (import_fs15.default.readFileSync(file, "utf8").trim() === String(process.pid)) import_fs15.default.unlinkSync(file);
11359
+ if (import_fs14.default.readFileSync(file, "utf8").trim() === String(process.pid)) import_fs14.default.unlinkSync(file);
11320
11360
  } catch {
11321
11361
  }
11322
11362
  };
11323
11363
  } catch (error) {
11324
11364
  if (error.code !== "EEXIST") throw error;
11325
- const pid = Number(import_fs15.default.readFileSync(file, "utf8").trim());
11365
+ const pid = Number(import_fs14.default.readFileSync(file, "utf8").trim());
11326
11366
  if (Number.isFinite(pid) && pid !== process.pid && pidAlive2(pid)) throw new Error(`another tdai-device is already running for this config (pid ${pid}); stop it first, or pair this copy on its own with a different TDAI_DEVICE_HOME`);
11327
11367
  try {
11328
- import_fs15.default.unlinkSync(file);
11368
+ import_fs14.default.unlinkSync(file);
11329
11369
  } catch {
11330
11370
  }
11331
11371
  }
@@ -11433,7 +11473,7 @@ async function run(options = {}) {
11433
11473
  const heartbeatTimer = process.env.TDAI_DOCKER === "1" ? setInterval(() => {
11434
11474
  if (socket.connected) {
11435
11475
  try {
11436
- import_fs15.default.writeFileSync(heartbeatFile, (/* @__PURE__ */ new Date()).toISOString());
11476
+ import_fs14.default.writeFileSync(heartbeatFile, (/* @__PURE__ */ new Date()).toISOString());
11437
11477
  } catch {
11438
11478
  }
11439
11479
  }
@@ -11492,7 +11532,7 @@ async function pair(code, args) {
11492
11532
  function rootAdd(target, args) {
11493
11533
  const config = loadConfig();
11494
11534
  const abs = import_path15.default.resolve(target);
11495
- if (!import_fs16.default.existsSync(abs) || !import_fs16.default.statSync(abs).isDirectory()) throw new Error(`${abs} is not a folder`);
11535
+ if (!import_fs15.default.existsSync(abs) || !import_fs15.default.statSync(abs).isDirectory()) throw new Error(`${abs} is not a folder`);
11496
11536
  if (config.roots.some((r) => import_path15.default.resolve(r.path) === abs)) throw new Error(`${abs} is already shared`);
11497
11537
  const trash = flag(args, "--trash") ?? (flag(args, "--trash-dir") ? "dir" : "os");
11498
11538
  if (!["os", "dir", "share", "none"].includes(trash)) throw new Error("--trash must be os, dir, share or none");
@@ -11518,8 +11558,8 @@ function rootRemove(id) {
11518
11558
  function rootAcceptRemovals(id) {
11519
11559
  const root = loadConfig().roots.find((r) => r.id === id || r.path === import_path15.default.resolve(id));
11520
11560
  if (!root) throw new Error(`no shared folder ${id}`);
11521
- import_fs16.default.mkdirSync(stateDir(root.id), { recursive: true });
11522
- import_fs16.default.writeFileSync(acceptRemovalsFile(stateDir(root.id)), (/* @__PURE__ */ new Date()).toISOString());
11561
+ import_fs15.default.mkdirSync(stateDir(root.id), { recursive: true });
11562
+ import_fs15.default.writeFileSync(acceptRemovalsFile(stateDir(root.id)), (/* @__PURE__ */ new Date()).toISOString());
11523
11563
  console.log(`The next rescan of "${root.label}" reports those removals.`);
11524
11564
  }
11525
11565
  function rootReadopt(id) {
@@ -11560,8 +11600,8 @@ async function dockerBootstrap() {
11560
11600
  const config = loadConfig();
11561
11601
  if (!config.token && process.env.TDAI_PAIR_CODE) await pair(process.env.TDAI_PAIR_CODE, process.env.TDAI_SERVER ? ["--server", process.env.TDAI_SERVER] : []);
11562
11602
  const fresh = loadConfig();
11563
- if (import_fs16.default.existsSync("/data")) {
11564
- for (const entry of import_fs16.default.readdirSync("/data", { withFileTypes: true })) {
11603
+ if (import_fs15.default.existsSync("/data")) {
11604
+ for (const entry of import_fs15.default.readdirSync("/data", { withFileTypes: true })) {
11565
11605
  if (!entry.isDirectory()) continue;
11566
11606
  const abs = import_path15.default.join("/data", entry.name);
11567
11607
  if (isTrashMount(abs, process.env)) {