pinggy 0.6.10 → 0.6.11

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/index.cjs CHANGED
@@ -3130,11 +3130,11 @@ var init_ipcClient = __esm({
3130
3130
  call(key, body, timeoutMs) {
3131
3131
  const spaceIdx = key.indexOf(" ");
3132
3132
  const method = key.slice(0, spaceIdx);
3133
- const path20 = key.slice(spaceIdx + 1);
3133
+ const path23 = key.slice(spaceIdx + 1);
3134
3134
  const payload = method === "GET" ? void 0 : JSON.stringify(body ?? {});
3135
- return this.request(method, path20, payload, timeoutMs);
3135
+ return this.request(method, path23, payload, timeoutMs);
3136
3136
  }
3137
- request(method, path20, body, timeoutMs) {
3137
+ request(method, path23, body, timeoutMs) {
3138
3138
  return new Promise((resolve, reject) => {
3139
3139
  const headers = {
3140
3140
  "X-Pinggy-Origin": this.origin
@@ -3147,7 +3147,7 @@ var init_ipcClient = __esm({
3147
3147
  {
3148
3148
  hostname: "127.0.0.1",
3149
3149
  port: this.port,
3150
- path: path20,
3150
+ path: path23,
3151
3151
  method,
3152
3152
  headers,
3153
3153
  timeout: timeoutMs ?? REQUEST_TIMEOUT_MS,
@@ -3498,7 +3498,7 @@ var init_installKind = __esm({
3498
3498
  }
3499
3499
  });
3500
3500
 
3501
- // src/daemon/lifecycle/serviceInstaller.ts
3501
+ // src/daemon/lifecycle/servicePaths.ts
3502
3502
  function installerBinaryPath(platform3, home, env) {
3503
3503
  if (platform3 === "win32") {
3504
3504
  const localAppData = env.LOCALAPPDATA || import_node_path4.default.win32.join(home, "AppData", "Local");
@@ -3506,6 +3506,29 @@ function installerBinaryPath(platform3, home, env) {
3506
3506
  }
3507
3507
  return import_node_path4.default.posix.join(home, ".pinggy", "bin", "pinggy");
3508
3508
  }
3509
+ function systemdServicePath(home) {
3510
+ return import_node_path4.default.posix.join(home, ".config", "systemd", "user", `${SYSTEMD_SERVICE_NAME}.service`);
3511
+ }
3512
+ function launchdPlistPath(home) {
3513
+ return import_node_path4.default.posix.join(home, "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
3514
+ }
3515
+ function autostartFilePath(platform3, home) {
3516
+ if (platform3 === "linux") return systemdServicePath(home);
3517
+ if (platform3 === "darwin") return launchdPlistPath(home);
3518
+ return null;
3519
+ }
3520
+ var import_node_path4, SERVICE_LABEL, SYSTEMD_SERVICE_NAME;
3521
+ var init_servicePaths = __esm({
3522
+ "src/daemon/lifecycle/servicePaths.ts"() {
3523
+ "use strict";
3524
+ init_cjs_shims();
3525
+ import_node_path4 = __toESM(require("path"), 1);
3526
+ SERVICE_LABEL = "io.pinggy.agent";
3527
+ SYSTEMD_SERVICE_NAME = "pinggy";
3528
+ }
3529
+ });
3530
+
3531
+ // src/daemon/lifecycle/serviceInstaller.ts
3509
3532
  function realPath(p) {
3510
3533
  try {
3511
3534
  return import_node_fs5.default.realpathSync(p);
@@ -3577,8 +3600,7 @@ function toolError(err) {
3577
3600
  return stderr ? stderr.replace(/^ERROR:\s*/i, "") : errorMessage(err);
3578
3601
  }
3579
3602
  function getSystemdServicePath() {
3580
- const dir = import_node_path4.default.join(import_node_os2.default.homedir(), ".config", "systemd", "user");
3581
- return import_node_path4.default.join(dir, `${SYSTEMD_SERVICE_NAME}.service`);
3603
+ return systemdServicePath(import_node_os2.default.homedir());
3582
3604
  }
3583
3605
  function generateSystemdUnit(program) {
3584
3606
  const execStart = `${program} --_daemon-child`;
@@ -3599,7 +3621,7 @@ WantedBy=default.target
3599
3621
  }
3600
3622
  function installSystemd(program) {
3601
3623
  const servicePath = getSystemdServicePath();
3602
- const dir = import_node_path4.default.dirname(servicePath);
3624
+ const dir = import_node_path5.default.dirname(servicePath);
3603
3625
  import_node_fs5.default.mkdirSync(dir, { recursive: true });
3604
3626
  import_node_fs5.default.writeFileSync(servicePath, generateSystemdUnit(program), "utf-8");
3605
3627
  (0, import_node_child_process.execSync)("systemctl --user daemon-reload", QUIET);
@@ -3647,7 +3669,7 @@ function uninstallSystemd() {
3647
3669
  }
3648
3670
  }
3649
3671
  function getLaunchdPlistPath() {
3650
- return import_node_path4.default.join(import_node_os2.default.homedir(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
3672
+ return launchdPlistPath(import_node_os2.default.homedir());
3651
3673
  }
3652
3674
  function generateLaunchdPlist(program) {
3653
3675
  const allArgs = [program, "--_daemon-child"];
@@ -3673,7 +3695,7 @@ ${programArgs}
3673
3695
  }
3674
3696
  function installLaunchd(program) {
3675
3697
  const plistPath = getLaunchdPlistPath();
3676
- const dir = import_node_path4.default.dirname(plistPath);
3698
+ const dir = import_node_path5.default.dirname(plistPath);
3677
3699
  import_node_fs5.default.mkdirSync(dir, { recursive: true });
3678
3700
  import_node_fs5.default.writeFileSync(plistPath, generateLaunchdPlist(program), "utf-8");
3679
3701
  const uid = process.getuid?.() ?? 501;
@@ -3760,7 +3782,7 @@ function generateTaskXml(program, userId) {
3760
3782
  }
3761
3783
  function createWindowsTask(program) {
3762
3784
  const xml = generateTaskXml(program, getWindowsUserId());
3763
- const tmpPath = import_node_path4.default.join(import_node_os2.default.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
3785
+ const tmpPath = import_node_path5.default.join(import_node_os2.default.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
3764
3786
  import_node_fs5.default.writeFileSync(tmpPath, "\uFEFF" + xml, "utf16le");
3765
3787
  try {
3766
3788
  (0, import_node_child_process.execFileSync)("schtasks", ["/Create", "/TN", WINDOWS_TASK_NAME, "/XML", tmpPath, "/F"], QUIET);
@@ -3896,22 +3918,22 @@ async function uninstallService() {
3896
3918
  process.exit(1);
3897
3919
  }
3898
3920
  }
3899
- var import_node_os2, import_node_fs5, import_node_path4, import_node_child_process, SERVICE_LABEL, SYSTEMD_SERVICE_NAME, SERVICE_ANY_LOCATION_ENV, QUIET, WINDOWS_TASK_NAME, SERVICE_QUERY_TIMEOUT_MILLIS;
3921
+ var import_node_os2, import_node_fs5, import_node_path5, import_node_child_process, SERVICE_ANY_LOCATION_ENV, QUIET, WINDOWS_TASK_NAME, SERVICE_QUERY_TIMEOUT_MILLIS;
3900
3922
  var init_serviceInstaller = __esm({
3901
3923
  "src/daemon/lifecycle/serviceInstaller.ts"() {
3902
3924
  "use strict";
3903
3925
  init_cjs_shims();
3904
3926
  import_node_os2 = __toESM(require("os"), 1);
3905
3927
  import_node_fs5 = __toESM(require("fs"), 1);
3906
- import_node_path4 = __toESM(require("path"), 1);
3928
+ import_node_path5 = __toESM(require("path"), 1);
3907
3929
  import_node_child_process = require("child_process");
3908
3930
  init_logger();
3909
3931
  init_printer();
3910
3932
  init_util();
3911
3933
  init_daemonManager();
3912
3934
  init_installKind();
3913
- SERVICE_LABEL = "io.pinggy.agent";
3914
- SYSTEMD_SERVICE_NAME = "pinggy";
3935
+ init_servicePaths();
3936
+ init_servicePaths();
3915
3937
  SERVICE_ANY_LOCATION_ENV = "PINGGY_SERVICE_ANY_LOCATION";
3916
3938
  QUIET = { stdio: ["ignore", "ignore", "pipe"] };
3917
3939
  WINDOWS_TASK_NAME = "PinggyDaemon";
@@ -4032,6 +4054,8 @@ var init_options = __esm({
4032
4054
  all: { type: "boolean", description: "Start all auto-start tunnels" },
4033
4055
  // `pinggy device login` and `connect` only. Their agent runs in the daemon unless this is set.
4034
4056
  foreground: { type: "boolean", description: "Run the device agent in this terminal", hidden: true },
4057
+ // `pinggy device login`, `connect` and `start` only: on or off, the answer to the file access question.
4058
+ files: { type: "string", description: "Allow file access from the dashboard: on or off", hidden: true },
4035
4059
  // `pinggy update` only.
4036
4060
  check: { type: "boolean", description: "Print the latest version and change nothing", hidden: true },
4037
4061
  rollback: { type: "boolean", description: "Go back to the previous version", hidden: true },
@@ -4473,7 +4497,7 @@ function noDiskSpace(running) {
4473
4497
  }
4474
4498
  function ensureFreeSpace(request2, contentLength, dependencies) {
4475
4499
  const factor = request2.assetName.endsWith(".exe") ? WINDOWS_FREE_SPACE_FACTOR : UNIX_FREE_SPACE_FACTOR;
4476
- const freeBytes = dependencies.freeBytes(import_node_path5.default.dirname(request2.tempPath));
4500
+ const freeBytes = dependencies.freeBytes(import_node_path6.default.dirname(request2.tempPath));
4477
4501
  if (freeBytes !== null && freeBytes < contentLength * factor + FREE_SPACE_MARGIN_BYTES) {
4478
4502
  throw noDiskSpace(request2.runningVersion);
4479
4503
  }
@@ -4549,7 +4573,7 @@ async function downloadAndVerify(request2, dependencies = defaultDownloadDepende
4549
4573
  throw error;
4550
4574
  }
4551
4575
  }
4552
- var import_node_crypto2, import_node_child_process3, import_node_fs7, import_node_path5, UpdateErrorCode, BAD_RELEASE_CODES, UpdateError, BINARY_RUN_TIMEOUT_MILLIS, DEVICE_TOKEN_ENV, VERSION_LINE, runPinggyBinary, ASSET_NAMES, MAX_REDIRECTS, IDLE_TIMEOUT_MILLIS, FREE_SPACE_MARGIN_BYTES, WINDOWS_FREE_SPACE_FACTOR, UNIX_FREE_SPACE_FACTOR, EXECUTABLE_MODE2, USER_AGENT2, SUMS_LINE, defaultDownloadDependencies;
4576
+ var import_node_crypto2, import_node_child_process3, import_node_fs7, import_node_path6, UpdateErrorCode, BAD_RELEASE_CODES, UpdateError, BINARY_RUN_TIMEOUT_MILLIS, DEVICE_TOKEN_ENV, VERSION_LINE, runPinggyBinary, ASSET_NAMES, MAX_REDIRECTS, IDLE_TIMEOUT_MILLIS, FREE_SPACE_MARGIN_BYTES, WINDOWS_FREE_SPACE_FACTOR, UNIX_FREE_SPACE_FACTOR, EXECUTABLE_MODE2, USER_AGENT2, SUMS_LINE, defaultDownloadDependencies;
4553
4577
  var init_binaryUpdater = __esm({
4554
4578
  "src/update/binaryUpdater.ts"() {
4555
4579
  "use strict";
@@ -4557,7 +4581,7 @@ var init_binaryUpdater = __esm({
4557
4581
  import_node_crypto2 = __toESM(require("crypto"), 1);
4558
4582
  import_node_child_process3 = require("child_process");
4559
4583
  import_node_fs7 = __toESM(require("fs"), 1);
4560
- import_node_path5 = __toESM(require("path"), 1);
4584
+ import_node_path6 = __toESM(require("path"), 1);
4561
4585
  init_latestRelease();
4562
4586
  init_util();
4563
4587
  UpdateErrorCode = {
@@ -4749,17 +4773,17 @@ function removeStaleUpdateFiles(execPath = process.execPath, operations = realSt
4749
4773
  }
4750
4774
  }
4751
4775
  }
4752
- var import_node_fs8, import_node_path6, WINDOWS_PATH, BACKUP_MARKER, NEW_FILE_SUFFIX, OLD_FILE_SUFFIX, RETRYABLE_RENAME_CODES, RENAME_RETRY_INTERVAL_MILLIS, RENAME_RETRY_LIMIT_MILLIS, POST_SWAP_WAIT_MILLIS, INSTALL_COMMAND, realWindowsFileOperations, realStaleFileOperations;
4776
+ var import_node_fs8, import_node_path7, WINDOWS_PATH, BACKUP_MARKER, NEW_FILE_SUFFIX, OLD_FILE_SUFFIX, RETRYABLE_RENAME_CODES, RENAME_RETRY_INTERVAL_MILLIS, RENAME_RETRY_LIMIT_MILLIS, POST_SWAP_WAIT_MILLIS, INSTALL_COMMAND, realWindowsFileOperations, realStaleFileOperations;
4753
4777
  var init_windowsSwap = __esm({
4754
4778
  "src/update/windowsSwap.ts"() {
4755
4779
  "use strict";
4756
4780
  init_cjs_shims();
4757
4781
  import_node_fs8 = __toESM(require("fs"), 1);
4758
- import_node_path6 = __toESM(require("path"), 1);
4782
+ import_node_path7 = __toESM(require("path"), 1);
4759
4783
  init_daemonManager();
4760
4784
  init_binaryUpdater();
4761
4785
  init_util();
4762
- WINDOWS_PATH = import_node_path6.default.win32;
4786
+ WINDOWS_PATH = import_node_path7.default.win32;
4763
4787
  BACKUP_MARKER = ".prev";
4764
4788
  NEW_FILE_SUFFIX = ".new.exe";
4765
4789
  OLD_FILE_SUFFIX = ".old";
@@ -5048,17 +5072,17 @@ function fsyncPath(target, flags) {
5048
5072
  }
5049
5073
  }
5050
5074
  function unixDownloadPath(layout) {
5051
- return import_node_path7.default.posix.join(layout.versionsDirectory, `${DOWNLOAD_PREFIX}${process.pid}`);
5075
+ return import_node_path8.default.posix.join(layout.versionsDirectory, `${DOWNLOAD_PREFIX}${process.pid}`);
5052
5076
  }
5053
5077
  function versionDirectory(layout, version) {
5054
- return import_node_path7.default.posix.join(layout.versionsDirectory, version);
5078
+ return import_node_path8.default.posix.join(layout.versionsDirectory, version);
5055
5079
  }
5056
5080
  function versionBinaryPath(layout, version) {
5057
- return import_node_path7.default.posix.join(versionDirectory(layout, version), BINARY_NAME);
5081
+ return import_node_path8.default.posix.join(versionDirectory(layout, version), BINARY_NAME);
5058
5082
  }
5059
5083
  function readLinkVersion(layout) {
5060
5084
  try {
5061
- const version = import_node_path7.default.posix.basename(import_node_path7.default.posix.dirname(import_node_fs11.default.readlinkSync(layout.link)));
5085
+ const version = import_node_path8.default.posix.basename(import_node_path8.default.posix.dirname(import_node_fs11.default.readlinkSync(layout.link)));
5062
5086
  return parseVersion(version) ? version : null;
5063
5087
  } catch {
5064
5088
  return null;
@@ -5073,14 +5097,14 @@ function highestVersionBelow(layout, ceiling) {
5073
5097
  }
5074
5098
  function moveLink(layout, version, environment) {
5075
5099
  import_node_fs11.default.mkdirSync(layout.binDirectory, { recursive: true });
5076
- const temporaryLink = import_node_path7.default.posix.join(layout.binDirectory, `${LINK_TEMP_PREFIX}${process.pid}`);
5100
+ const temporaryLink = import_node_path8.default.posix.join(layout.binDirectory, `${LINK_TEMP_PREFIX}${process.pid}`);
5077
5101
  import_node_fs11.default.rmSync(temporaryLink, { force: true });
5078
5102
  import_node_fs11.default.symlinkSync(versionBinaryPath(layout, version), temporaryLink);
5079
5103
  import_node_fs11.default.renameSync(temporaryLink, layout.link);
5080
5104
  environment.fsyncDirectory(layout.binDirectory);
5081
5105
  }
5082
5106
  function convertPlainFile(layout, execPath, runningVersion, environment) {
5083
- const temporaryPath = import_node_path7.default.posix.join(layout.versionsDirectory, `${CONVERT_PREFIX}${process.pid}`);
5107
+ const temporaryPath = import_node_path8.default.posix.join(layout.versionsDirectory, `${CONVERT_PREFIX}${process.pid}`);
5084
5108
  import_node_fs11.default.copyFileSync(execPath, temporaryPath);
5085
5109
  import_node_fs11.default.chmodSync(temporaryPath, EXECUTABLE_MODE3);
5086
5110
  environment.fsyncFile(temporaryPath);
@@ -5095,7 +5119,7 @@ function removeDeadProcessTemp(directory, prefix, environment) {
5095
5119
  for (const name of import_node_fs11.default.readdirSync(directory)) {
5096
5120
  const pidText = name.startsWith(prefix) ? name.slice(prefix.length) : "";
5097
5121
  if (/^\d+$/.test(pidText) && !environment.isAlive(Number(pidText))) {
5098
- import_node_fs11.default.rmSync(import_node_path7.default.posix.join(directory, name), { force: true });
5122
+ import_node_fs11.default.rmSync(import_node_path8.default.posix.join(directory, name), { force: true });
5099
5123
  }
5100
5124
  }
5101
5125
  }
@@ -5171,13 +5195,13 @@ function rollbackUnixVersion(layout, environment = realUnixSwapEnvironment) {
5171
5195
  }
5172
5196
  return { from: current, to: previous };
5173
5197
  }
5174
- var import_node_fs11, import_node_path7, BINARY_NAME, DOWNLOAD_PREFIX, CONVERT_PREFIX, LINK_TEMP_PREFIX, EXECUTABLE_MODE3, realUnixSwapEnvironment;
5198
+ var import_node_fs11, import_node_path8, BINARY_NAME, DOWNLOAD_PREFIX, CONVERT_PREFIX, LINK_TEMP_PREFIX, EXECUTABLE_MODE3, realUnixSwapEnvironment;
5175
5199
  var init_unixLinkSwap = __esm({
5176
5200
  "src/update/unixLinkSwap.ts"() {
5177
5201
  "use strict";
5178
5202
  init_cjs_shims();
5179
5203
  import_node_fs11 = __toESM(require("fs"), 1);
5180
- import_node_path7 = __toESM(require("path"), 1);
5204
+ import_node_path8 = __toESM(require("path"), 1);
5181
5205
  init_daemonManager();
5182
5206
  init_serviceInstaller();
5183
5207
  init_binaryUpdater();
@@ -5201,7 +5225,7 @@ var init_unixLinkSwap = __esm({
5201
5225
 
5202
5226
  // src/install/pinggyOnPath.ts
5203
5227
  function pathModule(platform3) {
5204
- return platform3 === "win32" ? import_node_path8.default.win32 : import_node_path8.default.posix;
5228
+ return platform3 === "win32" ? import_node_path9.default.win32 : import_node_path9.default.posix;
5205
5229
  }
5206
5230
  function pathFolders(platform3, pathValue) {
5207
5231
  const separator = platform3 === "win32" ? ";" : ":";
@@ -5223,16 +5247,16 @@ function findOnPath(names, lookup) {
5223
5247
  }
5224
5248
  function npmCopyFor(commandPath, lookup) {
5225
5249
  if (lookup.platform === "win32") {
5226
- const folder = import_node_path8.default.win32.dirname(commandPath);
5227
- const packageFolder = import_node_path8.default.win32.join(folder, "node_modules", NPM_PACKAGE);
5228
- const isPackage = lookup.files.isFile(import_node_path8.default.win32.join(packageFolder, "package.json"));
5250
+ const folder = import_node_path9.default.win32.dirname(commandPath);
5251
+ const packageFolder = import_node_path9.default.win32.join(folder, "node_modules", NPM_PACKAGE);
5252
+ const isPackage = lookup.files.isFile(import_node_path9.default.win32.join(packageFolder, "package.json"));
5229
5253
  return isPackage && !lookup.files.isLink(packageFolder) ? { prefix: folder, packageFolder } : null;
5230
5254
  }
5231
5255
  const realPath2 = lookup.files.realPath(commandPath);
5232
5256
  const segmentStart = realPath2?.indexOf(UNIX_NPM_SEGMENT) ?? -1;
5233
5257
  if (realPath2 === null || segmentStart < 0) return null;
5234
5258
  const prefix = realPath2.slice(0, segmentStart);
5235
- return { prefix, packageFolder: import_node_path8.default.posix.join(prefix, "lib", "node_modules", NPM_PACKAGE) };
5259
+ return { prefix, packageFolder: import_node_path9.default.posix.join(prefix, "lib", "node_modules", NPM_PACKAGE) };
5236
5260
  }
5237
5261
  function findPinggyCommand(lookup) {
5238
5262
  const names = lookup.platform === "win32" ? windowsCommandNames(NPM_PACKAGE, lookup.pathExtensions) : [NPM_PACKAGE];
@@ -5284,13 +5308,13 @@ function processPathLookup() {
5284
5308
  files: realPathFileSystem(process.platform)
5285
5309
  };
5286
5310
  }
5287
- var import_node_fs12, import_node_path8, NPM_PACKAGE, UNIX_NPM_SEGMENT, DEFAULT_PATH_EXTENSIONS, POWERSHELL_SCRIPT_EXTENSION, CURRENT_FOLDER;
5311
+ var import_node_fs12, import_node_path9, NPM_PACKAGE, UNIX_NPM_SEGMENT, DEFAULT_PATH_EXTENSIONS, POWERSHELL_SCRIPT_EXTENSION, CURRENT_FOLDER;
5288
5312
  var init_pinggyOnPath = __esm({
5289
5313
  "src/install/pinggyOnPath.ts"() {
5290
5314
  "use strict";
5291
5315
  init_cjs_shims();
5292
5316
  import_node_fs12 = __toESM(require("fs"), 1);
5293
- import_node_path8 = __toESM(require("path"), 1);
5317
+ import_node_path9 = __toESM(require("path"), 1);
5294
5318
  NPM_PACKAGE = "pinggy";
5295
5319
  UNIX_NPM_SEGMENT = `/lib/node_modules/${NPM_PACKAGE}/`;
5296
5320
  DEFAULT_PATH_EXTENSIONS = ".COM;.EXE;.BAT;.CMD";
@@ -5377,13 +5401,13 @@ function warnIfShadowed(environment, home) {
5377
5401
  if (found === null) return;
5378
5402
  let expectedFolder;
5379
5403
  if (environment.platform === "win32") {
5380
- expectedFolder = import_node_path9.default.win32.dirname(installPathFor(environment, home));
5381
- if (samePath(import_node_path9.default.win32.dirname(found.commandPath), expectedFolder, "win32")) return;
5404
+ expectedFolder = import_node_path10.default.win32.dirname(installPathFor(environment, home));
5405
+ if (samePath(import_node_path10.default.win32.dirname(found.commandPath), expectedFolder, "win32")) return;
5382
5406
  } else {
5383
- expectedFolder = import_node_path9.default.posix.join(home, LINK_DIRECTORY);
5384
- const folders = pathFolders(environment.platform, environment.variables.PATH ?? "").map((folder2) => import_node_path9.default.posix.normalize(`${folder2}/`));
5407
+ expectedFolder = import_node_path10.default.posix.join(home, LINK_DIRECTORY);
5408
+ const folders = pathFolders(environment.platform, environment.variables.PATH ?? "").map((folder2) => import_node_path10.default.posix.normalize(`${folder2}/`));
5385
5409
  if (!folders.includes(`${expectedFolder}/`)) return;
5386
- if (found.commandPath === import_node_path9.default.posix.join(expectedFolder, NPM_PACKAGE2)) return;
5410
+ if (found.commandPath === import_node_path10.default.posix.join(expectedFolder, NPM_PACKAGE2)) return;
5387
5411
  }
5388
5412
  const folder = shown(expectedFolder, environment, home);
5389
5413
  environment.print(`Another pinggy, ${shown(found.commandPath, environment, home)}, comes before ${folder} on PATH, so the pinggy command runs it.`);
@@ -5439,8 +5463,8 @@ function installHome(platform3, variables) {
5439
5463
  function isInstalledCopy(platform3, execPath, home, variables) {
5440
5464
  if (platform3 === "win32") {
5441
5465
  if (home === null) return false;
5442
- const installFolder = import_node_path9.default.win32.dirname(installerBinaryPath(platform3, home, variables));
5443
- return samePath(import_node_path9.default.win32.dirname(execPath), installFolder, platform3);
5466
+ const installFolder = import_node_path10.default.win32.dirname(installerBinaryPath(platform3, home, variables));
5467
+ return samePath(import_node_path10.default.win32.dirname(execPath), installFolder, platform3);
5444
5468
  }
5445
5469
  const kind = detectInstallKind(createInstallProbe());
5446
5470
  return kind === InstallKind.UnixLayout || kind === InstallKind.UnixPlainFile;
@@ -5483,7 +5507,7 @@ async function realInstalledBinary(platform3, home, installPath) {
5483
5507
  }
5484
5508
  function readNpmVersion(npm) {
5485
5509
  try {
5486
- const parsed = JSON.parse(import_node_fs13.default.readFileSync(import_node_path9.default.join(npm.packageFolder, "package.json"), "utf-8"));
5510
+ const parsed = JSON.parse(import_node_fs13.default.readFileSync(import_node_path10.default.join(npm.packageFolder, "package.json"), "utf-8"));
5487
5511
  return typeof parsed.version === "string" && parseVersion(parsed.version) ? parsed.version : null;
5488
5512
  } catch {
5489
5513
  return null;
@@ -5545,14 +5569,14 @@ function installerEnvironment(platform3, execPath) {
5545
5569
  }
5546
5570
  function windowsPowerShell() {
5547
5571
  const systemRoot = process.env.SystemRoot;
5548
- return systemRoot ? import_node_path9.default.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";
5572
+ return systemRoot ? import_node_path10.default.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "powershell.exe";
5549
5573
  }
5550
5574
  async function runEmbeddedInstaller(platform3, execPath) {
5551
5575
  const scriptName = platform3 === "win32" ? "install.ps1" : "install.sh";
5552
- const temporaryFolder = import_node_fs13.default.mkdtempSync(import_node_path9.default.join(import_node_os5.default.tmpdir(), "pinggy-install-"));
5576
+ const temporaryFolder = import_node_fs13.default.mkdtempSync(import_node_path10.default.join(import_node_os5.default.tmpdir(), "pinggy-install-"));
5553
5577
  try {
5554
- const scriptPath = import_node_path9.default.join(temporaryFolder, scriptName);
5555
- import_node_fs13.default.writeFileSync(scriptPath, import_node_fs13.default.readFileSync(import_node_path9.default.join(SCRIPTS_DIRECTORY, scriptName)), { mode: 384 });
5578
+ const scriptPath = import_node_path10.default.join(temporaryFolder, scriptName);
5579
+ import_node_fs13.default.writeFileSync(scriptPath, import_node_fs13.default.readFileSync(import_node_path10.default.join(SCRIPTS_DIRECTORY, scriptName)), { mode: 384 });
5556
5580
  const options = { stdio: OUTPUT_ONLY, env: installerEnvironment(platform3, execPath) };
5557
5581
  if (platform3 !== "win32") return await waitForExit("/bin/sh", [scriptPath], options) === 0;
5558
5582
  const command = `iex ([IO.File]::ReadAllText('${scriptPath.replace(/'/g, "''")}'))`;
@@ -5577,17 +5601,17 @@ function canWrite(folder) {
5577
5601
  function findNpm(npm, lookup) {
5578
5602
  if (lookup.platform === "win32") {
5579
5603
  const onPath2 = findOnPath(["npm.cmd"], lookup);
5580
- const inPrefix2 = import_node_path9.default.win32.join(npm.prefix, "npm.cmd");
5604
+ const inPrefix2 = import_node_path10.default.win32.join(npm.prefix, "npm.cmd");
5581
5605
  return onPath2 ?? (lookup.files.isFile(inPrefix2) ? inPrefix2 : null);
5582
5606
  }
5583
5607
  const onPath = findOnPath(["npm"], lookup);
5584
- const inPrefix = import_node_path9.default.posix.join(npm.prefix, "bin", "npm");
5608
+ const inPrefix = import_node_path10.default.posix.join(npm.prefix, "bin", "npm");
5585
5609
  return onPath ?? (lookup.files.isExecutableFile(inPrefix) ? inPrefix : null);
5586
5610
  }
5587
5611
  async function removeNpmCopy(npm) {
5588
5612
  const lookup = processPathLookup();
5589
5613
  if (lookup.platform !== "win32") {
5590
- const folders = [import_node_path9.default.posix.join(npm.prefix, "lib", "node_modules"), import_node_path9.default.posix.join(npm.prefix, "bin")];
5614
+ const folders = [import_node_path10.default.posix.join(npm.prefix, "lib", "node_modules"), import_node_path10.default.posix.join(npm.prefix, "bin")];
5591
5615
  if (!folders.every(canWrite)) return NpmRemoval.NotWritable;
5592
5616
  }
5593
5617
  const npmPath = findNpm(npm, lookup);
@@ -5637,7 +5661,7 @@ function realEnvironment2() {
5637
5661
  print: (line) => printer_default.print(line)
5638
5662
  };
5639
5663
  }
5640
- var import_node_child_process5, import_node_fs13, import_node_os5, import_node_path9, import_node_readline, import_node_url2, UPDATE_SUBCOMMAND2, NPM_PACKAGE2, LINK_DIRECTORY, NO_ANSWER, INTERRUPTED_EXIT_CODE, VERSION_RUN_TIMEOUT_MILLIS, OUTPUT_ONLY, INSTALL_ONLY_ENV, BINARY_URL_ENV, VERSION_ENV, BUNDLE_DIRECTORY, SCRIPTS_DIRECTORY, SelfInstallAnswer, NpmRemoval, runForVersion;
5664
+ var import_node_child_process5, import_node_fs13, import_node_os5, import_node_path10, import_node_readline, import_node_url2, UPDATE_SUBCOMMAND2, NPM_PACKAGE2, LINK_DIRECTORY, NO_ANSWER, INTERRUPTED_EXIT_CODE, VERSION_RUN_TIMEOUT_MILLIS, OUTPUT_ONLY, INSTALL_ONLY_ENV, BINARY_URL_ENV, VERSION_ENV, BUNDLE_DIRECTORY, SCRIPTS_DIRECTORY, SelfInstallAnswer, NpmRemoval, runForVersion;
5641
5665
  var init_selfInstall = __esm({
5642
5666
  "src/install/selfInstall.ts"() {
5643
5667
  "use strict";
@@ -5645,7 +5669,7 @@ var init_selfInstall = __esm({
5645
5669
  import_node_child_process5 = require("child_process");
5646
5670
  import_node_fs13 = __toESM(require("fs"), 1);
5647
5671
  import_node_os5 = __toESM(require("os"), 1);
5648
- import_node_path9 = __toESM(require("path"), 1);
5672
+ import_node_path10 = __toESM(require("path"), 1);
5649
5673
  import_node_readline = require("readline");
5650
5674
  import_node_url2 = require("url");
5651
5675
  init_daemonManager();
@@ -5664,7 +5688,7 @@ var init_selfInstall = __esm({
5664
5688
  init_pinggyOnPath();
5665
5689
  UPDATE_SUBCOMMAND2 = "update";
5666
5690
  NPM_PACKAGE2 = "pinggy";
5667
- LINK_DIRECTORY = import_node_path9.default.posix.join(".local", "bin");
5691
+ LINK_DIRECTORY = import_node_path10.default.posix.join(".local", "bin");
5668
5692
  NO_ANSWER = /^\s*n/i;
5669
5693
  INTERRUPTED_EXIT_CODE = 130;
5670
5694
  VERSION_RUN_TIMEOUT_MILLIS = 1e4;
@@ -5672,8 +5696,8 @@ var init_selfInstall = __esm({
5672
5696
  INSTALL_ONLY_ENV = "PINGGY_INSTALL_ONLY";
5673
5697
  BINARY_URL_ENV = "PINGGY_BINARY_URL";
5674
5698
  VERSION_ENV = "PINGGY_VERSION";
5675
- BUNDLE_DIRECTORY = import_node_path9.default.dirname((0, import_node_url2.fileURLToPath)(importMetaUrl));
5676
- SCRIPTS_DIRECTORY = import_node_path9.default.join(BUNDLE_DIRECTORY, "..", "scripts", "install");
5699
+ BUNDLE_DIRECTORY = import_node_path10.default.dirname((0, import_node_url2.fileURLToPath)(importMetaUrl));
5700
+ SCRIPTS_DIRECTORY = import_node_path10.default.join(BUNDLE_DIRECTORY, "..", "scripts", "install");
5677
5701
  SelfInstallAnswer = {
5678
5702
  Yes: "yes",
5679
5703
  No: "no",
@@ -7130,10 +7154,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
7130
7154
  }
7131
7155
  function storeJson(config, saveconf) {
7132
7156
  if (saveconf) {
7133
- const path20 = saveconf;
7157
+ const path23 = saveconf;
7134
7158
  try {
7135
- import_fs7.default.writeFileSync(path20, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
7136
- logger.info(`Configuration saved to ${path20}`);
7159
+ import_fs7.default.writeFileSync(path23, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
7160
+ logger.info(`Configuration saved to ${path23}`);
7137
7161
  } catch (err) {
7138
7162
  const msg = err instanceof Error ? err.message : String(err);
7139
7163
  logger.error("Error loading configuration:", msg);
@@ -9791,6 +9815,8 @@ function printDeviceHelp() {
9791
9815
  console.log(" --token <TOKEN> Device token from the dashboard");
9792
9816
  console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
9793
9817
  console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname");
9818
+ console.log(" --files on|off login, connect and start: allow or refuse file access from the");
9819
+ console.log(" dashboard. Without it, the first run in a terminal asks");
9794
9820
  console.log(" -f remove only: remove without asking\n");
9795
9821
  console.log("Environment:");
9796
9822
  console.log(" DEVICE_AGENT_TOKEN connect and start: the device token, when --token is not given.");
@@ -9824,14 +9850,21 @@ function readDeviceIdentity() {
9824
9850
  }
9825
9851
  }
9826
9852
  function writeDeviceIdentity(identity) {
9853
+ const written = keepStoredFileManager(identity, readDeviceIdentity());
9827
9854
  ensurePinggyConfigDir();
9828
9855
  const filePath = getDeviceConfigPath();
9829
- import_fs9.default.writeFileSync(filePath, JSON.stringify(identity, null, 2), {
9856
+ import_fs9.default.writeFileSync(filePath, JSON.stringify(written, null, 2), {
9830
9857
  encoding: "utf-8",
9831
9858
  mode: SECRET_FILE_MODE
9832
9859
  });
9833
9860
  import_fs9.default.chmodSync(filePath, SECRET_FILE_MODE);
9834
9861
  }
9862
+ function keepStoredFileManager(identity, stored) {
9863
+ if (identity.file_manager !== void 0 || !stored || stored.token !== identity.token || typeof stored.file_manager !== "boolean") {
9864
+ return identity;
9865
+ }
9866
+ return { ...identity, file_manager: stored.file_manager };
9867
+ }
9835
9868
  function clearDeviceIdentity() {
9836
9869
  const filePath = getDeviceConfigPath();
9837
9870
  if (!import_fs9.default.existsSync(filePath)) {
@@ -9865,8 +9898,8 @@ function request(ch, op, payload) {
9865
9898
  function response(to, op, payload) {
9866
9899
  return { v: PROTOCOL_VERSION, kind: "res", ch: to.ch, op, id: to.id, seq: 0, ts: nowSeconds(), payload };
9867
9900
  }
9868
- function event(ch, op, payload) {
9869
- return { v: PROTOCOL_VERSION, kind: "event", ch, op, id: "", seq: 0, ts: nowSeconds(), payload };
9901
+ function event(ch, op, payload, id = "") {
9902
+ return { v: PROTOCOL_VERSION, kind: "event", ch, op, id, seq: 0, ts: nowSeconds(), payload };
9870
9903
  }
9871
9904
  function parseEnvelope(raw) {
9872
9905
  try {
@@ -9926,6 +9959,12 @@ var init_device_schema = __esm({
9926
9959
  terminal_idle_timeout_seconds: import_zod3.z.number().optional(),
9927
9960
  // Optional: without it the agent keeps the window brake and never skips output.
9928
9961
  terminal_resync: import_zod3.z.boolean().optional(),
9962
+ // Optional: a dashboard that predates the file manager sends none, and every file request is refused.
9963
+ file_manager_enabled: import_zod3.z.boolean().optional(),
9964
+ // No default on the agent. Without it, every copy, move and delete answers file_busy rather than running unbounded.
9965
+ file_max_concurrent_operations: import_zod3.z.number().optional(),
9966
+ // Optional: without it nothing waits, and a copy, move or delete past the running limit answers file_busy.
9967
+ file_max_queued_operations: import_zod3.z.number().optional(),
9929
9968
  // Optional: a dashboard older than these sends neither, and the agent prints only the device id.
9930
9969
  email: import_zod3.z.string().optional(),
9931
9970
  device_url: import_zod3.z.string().optional()
@@ -9990,6 +10029,19 @@ var init_deviceAgentReporter = __esm({
9990
10029
  });
9991
10030
 
9992
10031
  // src/devices/collectors/systemInfo.ts
10032
+ function agentUser() {
10033
+ const uid = process.getuid?.();
10034
+ let username;
10035
+ try {
10036
+ username = import_os3.default.userInfo().username || void 0;
10037
+ } catch {
10038
+ username = void 0;
10039
+ }
10040
+ return {
10041
+ ...username === void 0 ? {} : { username },
10042
+ ...uid === void 0 ? {} : { uid }
10043
+ };
10044
+ }
9993
10045
  function collectSystemInfo() {
9994
10046
  const cpus = import_os3.default.cpus();
9995
10047
  return {
@@ -10003,7 +10055,8 @@ function collectSystemInfo() {
10003
10055
  // os.cpus() is empty on some Android and container builds.
10004
10056
  cpu_model: cpus[0]?.model?.trim() || UNKNOWN_CPU_MODEL,
10005
10057
  cpu_cores: cpus.length,
10006
- total_memory_bytes: import_os3.default.totalmem()
10058
+ total_memory_bytes: import_os3.default.totalmem(),
10059
+ ...agentUser()
10007
10060
  };
10008
10061
  }
10009
10062
  var import_os3, UNKNOWN_CPU_MODEL;
@@ -10548,192 +10601,2826 @@ var init_reconnect = __esm({
10548
10601
  }
10549
10602
  });
10550
10603
 
10551
- // src/devices/terminal/terminal_schema.ts
10552
- function clampGrid(requested, fallback) {
10553
- if (requested === void 0 || !Number.isFinite(requested)) return fallback;
10554
- return Math.max(MIN_GRID, Math.min(MAX_GRID, Math.trunc(requested)));
10604
+ // src/devices/files/file_schema.ts
10605
+ function fileError(code, message) {
10606
+ return { error: { code, message } };
10555
10607
  }
10556
- var import_zod4, CHANNEL_TERMINAL, OP_OPEN, OP_OPENED, OP_CLOSE, OP_DATA, OP_ACK, OP_EXIT, OP_RESIZE, OP_SIGNAL, OP_CONTEXT, OP_SNAPSHOT, OP_RESYNC, OP_ACTIVITY, TERMINAL_SIGNALS, MIN_GRID, MAX_GRID, CLOSE_REASON_USER_CLOSED, CLOSE_REASON_IDLE_TIMEOUT, ERROR_INVALID_PAYLOAD2, ERROR_TERMINAL_LIMIT_REACHED, ERROR_TERMINAL_DISABLED, ERROR_SHELL_NOT_ALLOWED, ERROR_SPAWN_FAILED, TerminalOpenSchema, TerminalCloseSchema, TerminalResizeSchema, TerminalInputSchema, TerminalSignalSchema, TerminalAckSchema, TerminalSnapshotRequestSchema;
10557
- var init_terminal_schema = __esm({
10558
- "src/devices/terminal/terminal_schema.ts"() {
10608
+ var import_zod4, CHANNEL_FILE, OP_LIST, OP_STAT, OP_DELETE, OP_MKDIR, OP_COPY, OP_MOVE, OP_PROGRESS, ERROR_INVALID_PAYLOAD2, ERROR_UNSUPPORTED_OP2, ERROR_FILE_MANAGER_DISABLED, ERROR_FILE_ACCESS_OFF, ERROR_INVALID_PATH, ERROR_PATH_NOT_FOUND, ERROR_NOT_A_DIRECTORY, ERROR_PERMISSION_DENIED, ERROR_FILE_TIMEOUT, ERROR_FILE_OPERATION_FAILED, ERROR_PROTECTED_PATH, ERROR_MOUNT_POINT, ERROR_FILE_BUSY, ERROR_FILE_EXISTS, ERROR_INVALID_NAME, ERROR_INVALID_DESTINATION, ERROR_NO_SPACE, ERROR_SPECIAL_FILE, SORT_BY_NAME, SORT_BY_SIZE, SORT_BY_MODIFIED, SORT_BY_CREATED, SORT_ORDER_ASC, SORT_ORDER_DESC, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT, MAX_PATH_BYTES, MAX_NAME_BYTES, ON_CONFLICT_FAIL, ON_CONFLICT_SKIP, ON_CONFLICT_KEEP_BOTH, ON_CONFLICT_REPLACE, FileListRequestSchema, FileStatRequestSchema, FileDeleteRequestSchema, FileMkdirRequestSchema, FileCopyRequestSchema;
10609
+ var init_file_schema = __esm({
10610
+ "src/devices/files/file_schema.ts"() {
10559
10611
  "use strict";
10560
10612
  init_cjs_shims();
10561
10613
  import_zod4 = require("zod");
10562
- CHANNEL_TERMINAL = "terminal";
10563
- OP_OPEN = "open";
10564
- OP_OPENED = "opened";
10565
- OP_CLOSE = "close";
10566
- OP_DATA = "data";
10567
- OP_ACK = "ack";
10568
- OP_EXIT = "exit";
10569
- OP_RESIZE = "resize";
10570
- OP_SIGNAL = "signal";
10571
- OP_CONTEXT = "context";
10572
- OP_SNAPSHOT = "snapshot";
10573
- OP_RESYNC = "resync";
10574
- OP_ACTIVITY = "activity";
10575
- TERMINAL_SIGNALS = ["INT", "TERM", "QUIT", "HUP"];
10576
- MIN_GRID = 1;
10577
- MAX_GRID = 1e3;
10578
- CLOSE_REASON_USER_CLOSED = "user_closed";
10579
- CLOSE_REASON_IDLE_TIMEOUT = "idle_timeout";
10614
+ CHANNEL_FILE = "file";
10615
+ OP_LIST = "list";
10616
+ OP_STAT = "stat";
10617
+ OP_DELETE = "delete";
10618
+ OP_MKDIR = "mkdir";
10619
+ OP_COPY = "copy";
10620
+ OP_MOVE = "move";
10621
+ OP_PROGRESS = "progress";
10580
10622
  ERROR_INVALID_PAYLOAD2 = "invalid_payload";
10581
- ERROR_TERMINAL_LIMIT_REACHED = "terminal_limit_reached";
10582
- ERROR_TERMINAL_DISABLED = "terminal_disabled";
10583
- ERROR_SHELL_NOT_ALLOWED = "shell_not_allowed";
10584
- ERROR_SPAWN_FAILED = "spawn_failed";
10585
- TerminalOpenSchema = import_zod4.z.object({
10586
- terminal_id: import_zod4.z.string().min(1),
10587
- cols: import_zod4.z.number().int().optional(),
10588
- rows: import_zod4.z.number().int().optional(),
10589
- shell: import_zod4.z.string().nullable().optional(),
10590
- cwd: import_zod4.z.string().nullable().optional()
10591
- });
10592
- TerminalCloseSchema = import_zod4.z.object({
10593
- terminal_id: import_zod4.z.string().min(1),
10594
- reason: import_zod4.z.string().optional()
10623
+ ERROR_UNSUPPORTED_OP2 = "unsupported_op";
10624
+ ERROR_FILE_MANAGER_DISABLED = "file_manager_disabled";
10625
+ ERROR_FILE_ACCESS_OFF = "file_access_off";
10626
+ ERROR_INVALID_PATH = "invalid_path";
10627
+ ERROR_PATH_NOT_FOUND = "path_not_found";
10628
+ ERROR_NOT_A_DIRECTORY = "not_a_directory";
10629
+ ERROR_PERMISSION_DENIED = "permission_denied";
10630
+ ERROR_FILE_TIMEOUT = "file_timeout";
10631
+ ERROR_FILE_OPERATION_FAILED = "file_operation_failed";
10632
+ ERROR_PROTECTED_PATH = "protected_path";
10633
+ ERROR_MOUNT_POINT = "mount_point";
10634
+ ERROR_FILE_BUSY = "file_busy";
10635
+ ERROR_FILE_EXISTS = "file_exists";
10636
+ ERROR_INVALID_NAME = "invalid_name";
10637
+ ERROR_INVALID_DESTINATION = "invalid_destination";
10638
+ ERROR_NO_SPACE = "no_space";
10639
+ ERROR_SPECIAL_FILE = "special_file";
10640
+ SORT_BY_NAME = "name";
10641
+ SORT_BY_SIZE = "size";
10642
+ SORT_BY_MODIFIED = "modified";
10643
+ SORT_BY_CREATED = "created";
10644
+ SORT_ORDER_ASC = "asc";
10645
+ SORT_ORDER_DESC = "desc";
10646
+ DEFAULT_LIST_LIMIT = 200;
10647
+ MAX_LIST_LIMIT = 500;
10648
+ MAX_PATH_BYTES = 4096;
10649
+ MAX_NAME_BYTES = 255;
10650
+ ON_CONFLICT_FAIL = "fail";
10651
+ ON_CONFLICT_SKIP = "skip";
10652
+ ON_CONFLICT_KEEP_BOTH = "keep_both";
10653
+ ON_CONFLICT_REPLACE = "replace";
10654
+ FileListRequestSchema = import_zod4.z.object({
10655
+ path: import_zod4.z.string().optional(),
10656
+ offset: import_zod4.z.number().int().min(0).optional(),
10657
+ limit: import_zod4.z.number().int().min(1).max(MAX_LIST_LIMIT).optional(),
10658
+ sort_by: import_zod4.z.enum([SORT_BY_NAME, SORT_BY_SIZE, SORT_BY_MODIFIED, SORT_BY_CREATED]).optional(),
10659
+ sort_order: import_zod4.z.enum([SORT_ORDER_ASC, SORT_ORDER_DESC]).optional(),
10660
+ include_hidden: import_zod4.z.boolean().optional()
10595
10661
  });
10596
- TerminalResizeSchema = import_zod4.z.object({
10597
- terminal_id: import_zod4.z.string().min(1),
10598
- cols: import_zod4.z.number().int(),
10599
- rows: import_zod4.z.number().int()
10662
+ FileStatRequestSchema = import_zod4.z.object({
10663
+ path: import_zod4.z.string(),
10664
+ include_hidden: import_zod4.z.boolean().optional()
10600
10665
  });
10601
- TerminalInputSchema = import_zod4.z.object({
10602
- terminal_id: import_zod4.z.string().min(1),
10603
- data: import_zod4.z.string()
10666
+ FileDeleteRequestSchema = import_zod4.z.object({
10667
+ path: import_zod4.z.string()
10604
10668
  });
10605
- TerminalSignalSchema = import_zod4.z.object({
10606
- terminal_id: import_zod4.z.string().min(1),
10607
- signal: import_zod4.z.enum(TERMINAL_SIGNALS)
10669
+ FileMkdirRequestSchema = import_zod4.z.object({
10670
+ path: import_zod4.z.string()
10608
10671
  });
10609
- TerminalAckSchema = import_zod4.z.object({
10610
- terminal_id: import_zod4.z.string().min(1),
10611
- ack_seq: import_zod4.z.number().optional(),
10612
- ack_bytes: import_zod4.z.number()
10613
- });
10614
- TerminalSnapshotRequestSchema = import_zod4.z.object({
10615
- terminal_id: import_zod4.z.string().min(1),
10616
- snapshot_id: import_zod4.z.string().min(1)
10672
+ FileCopyRequestSchema = import_zod4.z.object({
10673
+ source_path: import_zod4.z.string(),
10674
+ destination_path: import_zod4.z.string(),
10675
+ on_conflict: import_zod4.z.enum([ON_CONFLICT_FAIL, ON_CONFLICT_SKIP, ON_CONFLICT_KEEP_BOTH, ON_CONFLICT_REPLACE]).optional()
10617
10676
  });
10618
10677
  }
10619
10678
  });
10620
10679
 
10621
- // src/devices/terminal/flowWindow.ts
10622
- var FlowWindow;
10623
- var init_flowWindow = __esm({
10624
- "src/devices/terminal/flowWindow.ts"() {
10680
+ // src/devices/files/fileSystem.ts
10681
+ function pathsFor(platform3) {
10682
+ return platform3 === "win32" ? import_path9.default.win32 : import_path9.default.posix;
10683
+ }
10684
+ function pathProblem(requested, paths) {
10685
+ if (requested.includes("\0")) {
10686
+ return "The path holds a NUL byte.";
10687
+ }
10688
+ if (Buffer.byteLength(requested, "utf8") > MAX_PATH_BYTES) {
10689
+ return `The path is longer than ${MAX_PATH_BYTES} bytes.`;
10690
+ }
10691
+ if (!paths.isAbsolute(requested)) {
10692
+ return "The path must be absolute.";
10693
+ }
10694
+ return null;
10695
+ }
10696
+ function nameProblem(name, platform3) {
10697
+ if (name.length === 0) {
10698
+ return "A name is empty.";
10699
+ }
10700
+ if (Buffer.byteLength(name, "utf8") > MAX_NAME_BYTES) {
10701
+ return `A name is longer than ${MAX_NAME_BYTES} bytes.`;
10702
+ }
10703
+ if (name === "." || name === "..") {
10704
+ return "A name cannot be . or ..";
10705
+ }
10706
+ if (name.includes("\0")) {
10707
+ return "A name holds a NUL byte.";
10708
+ }
10709
+ if (name.includes("/") || platform3 === "win32" && name.includes("\\")) {
10710
+ return "A name holds a path separator.";
10711
+ }
10712
+ return null;
10713
+ }
10714
+ function windowsNameProblem(name, subject = "A folder name") {
10715
+ if (WINDOWS_FORBIDDEN_CHARACTERS.test(name)) {
10716
+ return `${subject} on Windows cannot hold : * ? " < > |`;
10717
+ }
10718
+ if (WINDOWS_TRAILING_DOT_OR_SPACE.test(name)) {
10719
+ return `${subject} on Windows cannot end with a dot or a space.`;
10720
+ }
10721
+ const stem = name.split(EXTENSION_SEPARATOR)[0].toUpperCase();
10722
+ if (WINDOWS_DEVICE_NAMES.has(stem)) {
10723
+ return `${stem} is a device name on Windows.`;
10724
+ }
10725
+ return null;
10726
+ }
10727
+ function isRoot(resolved, paths) {
10728
+ return paths.dirname(resolved) === resolved;
10729
+ }
10730
+ function resolvedItem(requested, paths) {
10731
+ const resolved = paths.resolve(requested);
10732
+ return { path: resolved, parent: paths.dirname(resolved), name: paths.basename(resolved) };
10733
+ }
10734
+ function withTrimmedName(item) {
10735
+ const name = item.name.trim();
10736
+ if (name === item.name || name.length === 0) {
10737
+ return { ...item, name };
10738
+ }
10739
+ return { ...item, name, path: item.path.slice(0, item.path.length - item.name.length) + name };
10740
+ }
10741
+ function errorCodeOf(err) {
10742
+ return typeof err === "object" && err !== null && "code" in err && typeof err.code === "string" ? err.code : void 0;
10743
+ }
10744
+ function failureMessage(err, fallback) {
10745
+ return sanitizeErrorMessage(err instanceof Error ? err.message : String(err)) ?? fallback;
10746
+ }
10747
+ function entryTypeOf(stats) {
10748
+ if (stats.isSymbolicLink()) return "symlink";
10749
+ if (stats.isDirectory()) return "directory";
10750
+ if (stats.isFile()) return "file";
10751
+ return "other";
10752
+ }
10753
+ function targetTypeOf(stats) {
10754
+ if (stats.isDirectory()) return "directory";
10755
+ if (stats.isFile()) return "file";
10756
+ return "other";
10757
+ }
10758
+ function epochSeconds(millis) {
10759
+ return Math.floor(millis / MILLIS_PER_SECOND);
10760
+ }
10761
+ function utf8Bytes(value) {
10762
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
10763
+ }
10764
+ async function readLinkTarget(linkPath, reader) {
10765
+ const target = {};
10766
+ try {
10767
+ target.linkTarget = await reader.readlink(linkPath);
10768
+ } catch {
10769
+ }
10770
+ try {
10771
+ target.targetStats = await reader.stat(linkPath);
10772
+ target.targetType = targetTypeOf(target.targetStats);
10773
+ } catch (err) {
10774
+ const code = errorCodeOf(err);
10775
+ if (code === "ENOENT" || code === "ENOTDIR") {
10776
+ target.targetType = "missing";
10777
+ }
10778
+ }
10779
+ return target;
10780
+ }
10781
+ function callTimeoutError(millis) {
10782
+ const seconds = Math.round(millis / MILLIS_PER_SECOND);
10783
+ return new FileCallTimeoutError(`A filesystem call took longer than ${seconds} s.`);
10784
+ }
10785
+ function callWithTimeout(work, millis) {
10786
+ return new Promise((resolve, reject) => {
10787
+ const timer = setTimeout(() => reject(callTimeoutError(millis)), millis);
10788
+ work.then((value) => {
10789
+ clearTimeout(timer);
10790
+ resolve(value);
10791
+ }, (err) => {
10792
+ clearTimeout(timer);
10793
+ reject(err);
10794
+ });
10795
+ });
10796
+ }
10797
+ function withTimeout(work, millis, fallback) {
10798
+ return new Promise((resolve) => {
10799
+ const timer = setTimeout(() => resolve(fallback), millis);
10800
+ work.then((value) => {
10801
+ clearTimeout(timer);
10802
+ resolve(value);
10803
+ }, () => {
10804
+ clearTimeout(timer);
10805
+ resolve(fallback);
10806
+ });
10807
+ });
10808
+ }
10809
+ var import_fs10, import_os5, import_path9, machineFileSystem, machineFileSystemDependencies, machineFileSystemRemover, machineFileSystemMaker, NEW_FILE_MODE, CREATE_ONLY_IF_FREE, machineFileSystemCopier, HIDDEN_NAME_PREFIX, MILLIS_PER_SECOND, WINDOWS_FORBIDDEN_CHARACTERS, WINDOWS_TRAILING_DOT_OR_SPACE, WINDOWS_NUMBERED_DEVICES, WINDOWS_DEVICE_NUMBERS, WINDOWS_DEVICE_NAMES, EXTENSION_SEPARATOR, MESSAGE_NAME_TAKEN, FileCallTimeoutError;
10810
+ var init_fileSystem = __esm({
10811
+ "src/devices/files/fileSystem.ts"() {
10625
10812
  "use strict";
10626
10813
  init_cjs_shims();
10627
- FlowWindow = class {
10628
- constructor(windowBytes) {
10629
- this.sentBytes = 0;
10630
- this.ackedBytes = 0;
10631
- if (!Number.isFinite(windowBytes) || windowBytes <= 0) {
10632
- throw new Error("A terminal flow window needs a positive size from welcome");
10633
- }
10634
- this.windowBytes = Math.trunc(windowBytes);
10635
- }
10636
- /** How many more raw bytes may go out before the browser has to catch up. */
10637
- remaining() {
10638
- return Math.max(0, this.windowBytes - (this.sentBytes - this.ackedBytes));
10639
- }
10640
- /** False means stop reading the pty. Nothing else is an acceptable response. */
10641
- isOpen() {
10642
- return this.remaining() > 0;
10643
- }
10644
- recordSent(byteCount) {
10645
- if (!Number.isFinite(byteCount) || byteCount <= 0) return;
10646
- this.sentBytes += Math.trunc(byteCount);
10814
+ import_fs10 = __toESM(require("fs"), 1);
10815
+ import_os5 = __toESM(require("os"), 1);
10816
+ import_path9 = __toESM(require("path"), 1);
10817
+ init_tunnelList();
10818
+ init_file_schema();
10819
+ machineFileSystem = {
10820
+ readdir: (folder) => import_fs10.default.promises.readdir(folder, { withFileTypes: true }),
10821
+ lstat: (target) => import_fs10.default.promises.lstat(target),
10822
+ stat: (target) => import_fs10.default.promises.stat(target),
10823
+ readlink: (target) => import_fs10.default.promises.readlink(target),
10824
+ access: (target, mode) => import_fs10.default.promises.access(target, mode),
10825
+ homedir: () => import_os5.default.homedir()
10826
+ };
10827
+ machineFileSystemDependencies = {
10828
+ fs: machineFileSystem,
10829
+ platform: process.platform
10830
+ };
10831
+ machineFileSystemRemover = {
10832
+ lstat: (target) => import_fs10.default.promises.lstat(target, { bigint: true }),
10833
+ stat: (target) => import_fs10.default.promises.stat(target, { bigint: true }),
10834
+ readdir: (folder) => import_fs10.default.promises.readdir(folder),
10835
+ unlink: (target) => import_fs10.default.promises.unlink(target),
10836
+ rmdir: (target) => import_fs10.default.promises.rmdir(target),
10837
+ chmod: (target, mode) => import_fs10.default.promises.chmod(target, mode),
10838
+ realpath: (target) => import_fs10.default.promises.realpath(target)
10839
+ };
10840
+ machineFileSystemMaker = {
10841
+ mkdir: async (target) => {
10842
+ await import_fs10.default.promises.mkdir(target);
10647
10843
  }
10648
- /**
10649
- * Cumulative totals, never increments, so a dropped ack self-heals on the next one.
10650
- *
10651
- * A browser is not a trusted input. An ack beyond what was sent is clamped rather than believed,
10652
- * and one that arrives out of order never moves the counter backwards.
10653
- */
10654
- recordAck(ackBytes) {
10655
- if (!Number.isFinite(ackBytes)) return;
10656
- const clamped = Math.min(Math.max(Math.trunc(ackBytes), 0), this.sentBytes);
10657
- if (clamped > this.ackedBytes) {
10658
- this.ackedBytes = clamped;
10844
+ };
10845
+ NEW_FILE_MODE = 384;
10846
+ CREATE_ONLY_IF_FREE = "wx";
10847
+ machineFileSystemCopier = {
10848
+ lstat: (target) => import_fs10.default.promises.lstat(target, { bigint: true }),
10849
+ stat: (target) => import_fs10.default.promises.stat(target, { bigint: true }),
10850
+ realpath: (target) => import_fs10.default.promises.realpath(target),
10851
+ readdir: (folder) => import_fs10.default.promises.readdir(folder),
10852
+ mkdir: async (target) => {
10853
+ await import_fs10.default.promises.mkdir(target);
10854
+ },
10855
+ openToRead: (target) => import_fs10.default.promises.open(target, "r"),
10856
+ createFile: (target) => import_fs10.default.promises.open(target, CREATE_ONLY_IF_FREE, NEW_FILE_MODE),
10857
+ read: async (handle, buffer) => (await handle.read(buffer, 0, buffer.length, null)).bytesRead,
10858
+ write: async (handle, buffer, length) => {
10859
+ let written = 0;
10860
+ while (written < length) {
10861
+ written += (await handle.write(buffer, written, length - written, null)).bytesWritten;
10659
10862
  }
10863
+ },
10864
+ close: (handle) => handle.close(),
10865
+ readlink: (target) => import_fs10.default.promises.readlink(target),
10866
+ symlink: (linkText, target, type) => import_fs10.default.promises.symlink(linkText, target, type),
10867
+ chmod: (target, mode) => import_fs10.default.promises.chmod(target, mode),
10868
+ utimes: (target, accessed, modified) => import_fs10.default.promises.utimes(target, accessed, modified),
10869
+ rename: (from, to) => import_fs10.default.promises.rename(from, to),
10870
+ unlink: (target) => import_fs10.default.promises.unlink(target),
10871
+ freeBytes: async (folder) => {
10872
+ const stats = await import_fs10.default.promises.statfs(folder, { bigint: true });
10873
+ return stats.bavail * stats.bsize;
10660
10874
  }
10661
- get sent() {
10662
- return this.sentBytes;
10663
- }
10664
- get acked() {
10665
- return this.ackedBytes;
10666
- }
10667
- get size() {
10668
- return this.windowBytes;
10669
- }
10875
+ };
10876
+ HIDDEN_NAME_PREFIX = ".";
10877
+ MILLIS_PER_SECOND = 1e3;
10878
+ WINDOWS_FORBIDDEN_CHARACTERS = /[:*?"<>|]/;
10879
+ WINDOWS_TRAILING_DOT_OR_SPACE = /[. ]$/;
10880
+ WINDOWS_NUMBERED_DEVICES = ["COM", "LPT"];
10881
+ WINDOWS_DEVICE_NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9];
10882
+ WINDOWS_DEVICE_NAMES = /* @__PURE__ */ new Set([
10883
+ "CON",
10884
+ "PRN",
10885
+ "AUX",
10886
+ "NUL",
10887
+ ...WINDOWS_NUMBERED_DEVICES.flatMap((device) => WINDOWS_DEVICE_NUMBERS.map((number) => `${device}${number}`))
10888
+ ]);
10889
+ EXTENSION_SEPARATOR = ".";
10890
+ MESSAGE_NAME_TAKEN = "A file or folder with this name already exists.";
10891
+ FileCallTimeoutError = class extends Error {
10670
10892
  };
10671
10893
  }
10672
10894
  });
10673
10895
 
10674
- // src/devices/terminal/frameSplitter.ts
10675
- function rawBundleBytes(maxFrameBytes) {
10676
- const available = maxFrameBytes - ENVELOPE_OVERHEAD_BYTES;
10677
- if (available <= 0) {
10678
- throw new Error("max_frame_bytes leaves no room for a terminal payload");
10679
- }
10680
- return Math.floor(available * BASE64_NUMERATOR / BASE64_DENOMINATOR);
10896
+ // src/devices/files/fileCallGate.ts
10897
+ function gatedReader(reader, gate, timeoutMillis) {
10898
+ return {
10899
+ readdir: (folder) => gate.run(() => reader.readdir(folder), timeoutMillis),
10900
+ lstat: (target) => gate.run(() => reader.lstat(target), timeoutMillis),
10901
+ stat: (target) => gate.run(() => reader.stat(target), timeoutMillis),
10902
+ readlink: (target) => gate.run(() => reader.readlink(target), timeoutMillis),
10903
+ access: (target, mode) => gate.run(() => reader.access(target, mode), timeoutMillis),
10904
+ homedir: () => reader.homedir()
10905
+ };
10681
10906
  }
10682
- var ENVELOPE_OVERHEAD_BYTES, BASE64_NUMERATOR, BASE64_DENOMINATOR, BUNDLE_MILLIS, FrameSplitter;
10683
- var init_frameSplitter = __esm({
10684
- "src/devices/terminal/frameSplitter.ts"() {
10907
+ function gatedRemover(remover, gate, timeoutMillis) {
10908
+ return {
10909
+ lstat: (target) => gate.run(() => remover.lstat(target), timeoutMillis),
10910
+ stat: (target) => gate.run(() => remover.stat(target), timeoutMillis),
10911
+ readdir: (folder) => gate.run(() => remover.readdir(folder), timeoutMillis),
10912
+ unlink: (target) => gate.run(() => remover.unlink(target), timeoutMillis),
10913
+ rmdir: (target) => gate.run(() => remover.rmdir(target), timeoutMillis),
10914
+ chmod: (target, mode) => gate.run(() => remover.chmod(target, mode), timeoutMillis),
10915
+ realpath: (target) => gate.run(() => remover.realpath(target), timeoutMillis)
10916
+ };
10917
+ }
10918
+ function gatedMaker(maker, gate, timeoutMillis) {
10919
+ return {
10920
+ mkdir: (target) => gate.run(() => maker.mkdir(target), timeoutMillis)
10921
+ };
10922
+ }
10923
+ function gatedCopier(copier, gate, timeoutMillis) {
10924
+ return {
10925
+ lstat: (target) => gate.run(() => copier.lstat(target), timeoutMillis),
10926
+ stat: (target) => gate.run(() => copier.stat(target), timeoutMillis),
10927
+ realpath: (target) => gate.run(() => copier.realpath(target), timeoutMillis),
10928
+ readdir: (folder) => gate.run(() => copier.readdir(folder), timeoutMillis),
10929
+ mkdir: (target) => gate.run(() => copier.mkdir(target), timeoutMillis),
10930
+ openToRead: (target) => gate.run(() => copier.openToRead(target), timeoutMillis),
10931
+ createFile: (target) => gate.run(() => copier.createFile(target), timeoutMillis),
10932
+ read: (handle, buffer) => gate.run(() => copier.read(handle, buffer), timeoutMillis),
10933
+ write: (handle, buffer, length) => gate.run(() => copier.write(handle, buffer, length), timeoutMillis),
10934
+ close: (handle) => gate.run(() => copier.close(handle), timeoutMillis),
10935
+ readlink: (target) => gate.run(() => copier.readlink(target), timeoutMillis),
10936
+ symlink: (linkText, target, type) => gate.run(() => copier.symlink(linkText, target, type), timeoutMillis),
10937
+ chmod: (target, mode) => gate.run(() => copier.chmod(target, mode), timeoutMillis),
10938
+ utimes: (target, accessed, modified) => gate.run(
10939
+ () => copier.utimes(target, accessed, modified),
10940
+ timeoutMillis
10941
+ ),
10942
+ rename: (from, to) => gate.run(() => copier.rename(from, to), timeoutMillis),
10943
+ unlink: (target) => gate.run(() => copier.unlink(target), timeoutMillis),
10944
+ freeBytes: (folder) => gate.run(() => copier.freeBytes(folder), timeoutMillis)
10945
+ };
10946
+ }
10947
+ var MESSAGE_DRIVE_STOPPED, FileCallsStuckError, FileCallGate;
10948
+ var init_fileCallGate = __esm({
10949
+ "src/devices/files/fileCallGate.ts"() {
10685
10950
  "use strict";
10686
10951
  init_cjs_shims();
10687
- ENVELOPE_OVERHEAD_BYTES = 512;
10688
- BASE64_NUMERATOR = 3;
10689
- BASE64_DENOMINATOR = 4;
10690
- BUNDLE_MILLIS = 8;
10691
- FrameSplitter = class {
10692
- constructor(emit, bundleBytes, bundleMillis = BUNDLE_MILLIS) {
10693
- this.emit = emit;
10694
- this.bundleBytes = bundleBytes;
10695
- this.bundleMillis = bundleMillis;
10696
- this.pending = [];
10697
- this.pendingBytes = 0;
10698
- if (!Number.isFinite(bundleBytes) || bundleBytes <= 0) {
10699
- throw new Error("A frame splitter needs a positive bundle size");
10700
- }
10952
+ init_fileSystem();
10953
+ MESSAGE_DRIVE_STOPPED = "A drive on the device stopped answering. Try again once it is back.";
10954
+ FileCallsStuckError = class extends FileCallTimeoutError {
10955
+ constructor() {
10956
+ super(MESSAGE_DRIVE_STOPPED);
10701
10957
  }
10702
- /** A chunk over the cap is split across frames, never truncated. */
10703
- push(chunk) {
10704
- if (chunk.length === 0) return;
10705
- this.pending.push(chunk);
10706
- this.pendingBytes += chunk.length;
10707
- while (this.pendingBytes >= this.bundleBytes) {
10708
- this.emitBytes(this.bundleBytes);
10709
- }
10710
- if (this.pendingBytes > 0) {
10711
- this.arm();
10712
- } else {
10713
- this.disarm();
10958
+ };
10959
+ FileCallGate = class {
10960
+ constructor(places) {
10961
+ this.places = places;
10962
+ this.running = 0;
10963
+ this.abandoned = 0;
10964
+ /** In arrival order: a Set iterates as it was filled. */
10965
+ this.waiting = /* @__PURE__ */ new Set();
10966
+ if (!Number.isInteger(places) || places < 1) {
10967
+ throw new Error(`The file call gate needs at least 1 place, not ${places}.`);
10968
+ }
10969
+ }
10970
+ /** `work`'s outcome, or a {@link FileCallTimeoutError} once `timeoutMillis` pass from now. */
10971
+ run(work, timeoutMillis) {
10972
+ if (this.isStuck()) {
10973
+ return Promise.reject(new FileCallsStuckError());
10714
10974
  }
10975
+ return new Promise((resolve, reject) => {
10976
+ let answered = false;
10977
+ let holdsPlace = false;
10978
+ let isAbandoned = false;
10979
+ const answer = (outcome) => {
10980
+ if (!answered) {
10981
+ answered = true;
10982
+ clearTimeout(timer);
10983
+ outcome();
10984
+ }
10985
+ };
10986
+ const call = {
10987
+ begin: () => {
10988
+ holdsPlace = true;
10989
+ this.running += 1;
10990
+ let pending;
10991
+ try {
10992
+ pending = work();
10993
+ } catch (err) {
10994
+ pending = Promise.reject(err);
10995
+ }
10996
+ pending.then((value) => answer(() => resolve(value)), (err) => answer(() => reject(err))).finally(() => this.release(isAbandoned));
10997
+ },
10998
+ refuse: (err) => answer(() => reject(err))
10999
+ };
11000
+ const timer = setTimeout(() => {
11001
+ if (holdsPlace) {
11002
+ isAbandoned = true;
11003
+ this.abandoned += 1;
11004
+ } else {
11005
+ this.waiting.delete(call);
11006
+ }
11007
+ answer(() => reject(callTimeoutError(timeoutMillis)));
11008
+ if (this.isStuck()) {
11009
+ this.refuseWaiting();
11010
+ }
11011
+ }, timeoutMillis);
11012
+ if (this.running < this.places) {
11013
+ call.begin();
11014
+ } else {
11015
+ this.waiting.add(call);
11016
+ }
11017
+ });
10715
11018
  }
10716
- /** Sends whatever is held, if anything. Used when the terminal closes and by the timer. */
10717
- flush() {
10718
- this.disarm();
10719
- if (this.pendingBytes > 0) {
10720
- this.emitBytes(this.pendingBytes);
11019
+ release(wasAbandoned) {
11020
+ this.running -= 1;
11021
+ if (wasAbandoned) {
11022
+ this.abandoned -= 1;
11023
+ }
11024
+ for (const call of this.waiting) {
11025
+ if (this.running >= this.places) {
11026
+ return;
11027
+ }
11028
+ this.waiting.delete(call);
11029
+ call.begin();
10721
11030
  }
10722
11031
  }
10723
- dispose() {
10724
- this.disarm();
10725
- this.pending = [];
10726
- this.pendingBytes = 0;
11032
+ isStuck() {
11033
+ return this.abandoned >= this.places;
10727
11034
  }
10728
- get buffered() {
10729
- return this.pendingBytes;
11035
+ refuseWaiting() {
11036
+ const refused = [...this.waiting];
11037
+ this.waiting.clear();
11038
+ refused.forEach((call) => call.refuse(new FileCallsStuckError()));
10730
11039
  }
10731
- emitBytes(byteCount) {
10732
- const joined = Buffer.concat(this.pending, this.pendingBytes);
10733
- const frame = joined.subarray(0, byteCount);
10734
- const rest = joined.subarray(byteCount);
10735
- this.pending = rest.length > 0 ? [rest] : [];
10736
- this.pendingBytes = rest.length;
11040
+ };
11041
+ }
11042
+ });
11043
+
11044
+ // src/devices/files/fileProtectedPaths.ts
11045
+ function systemFoldersFor(platform3, environment) {
11046
+ if (platform3 === "win32") {
11047
+ return WINDOWS_SYSTEM_FOLDER_VARIABLES.map(([variable, fallback]) => environment[variable] || fallback);
11048
+ }
11049
+ return platform3 === "darwin" ? MACOS_SYSTEM_FOLDERS : LINUX_SYSTEM_FOLDERS;
11050
+ }
11051
+ function accountsFolderFor(platform3, environment) {
11052
+ if (platform3 === "win32") {
11053
+ const publicFolder = environment[WINDOWS_PUBLIC_FOLDER_VARIABLE];
11054
+ return publicFolder ? import_path10.default.win32.dirname(publicFolder) : WINDOWS_ACCOUNTS_FOLDER;
11055
+ }
11056
+ return platform3 === "darwin" ? MACOS_ACCOUNTS_FOLDER : POSIX_ACCOUNTS_FOLDER;
11057
+ }
11058
+ function agentFilesFor(platform3, home, environment, runningProgram, script) {
11059
+ const files = [installerBinaryPath(platform3, home, environment), runningProgram];
11060
+ if (script) {
11061
+ files.push(script);
11062
+ }
11063
+ const autostartFile = autostartFilePath(platform3, home);
11064
+ if (autostartFile) {
11065
+ files.push(autostartFile);
11066
+ }
11067
+ return [...new Set(files)];
11068
+ }
11069
+ function machineProtectedSources() {
11070
+ const home = import_os6.default.homedir();
11071
+ const script = isPackagedBinary() ? void 0 : process.argv[1];
11072
+ return {
11073
+ home,
11074
+ configFolder: getPinggyConfigDir(),
11075
+ systemFolders: systemFoldersFor(process.platform, process.env),
11076
+ accountsFolder: accountsFolderFor(process.platform, process.env),
11077
+ agentFiles: agentFilesFor(process.platform, home, process.env, process.execPath, script)
11078
+ };
11079
+ }
11080
+ function identityOf(stats) {
11081
+ return `${stats.dev}:${stats.ino}`;
11082
+ }
11083
+ function selfAndAncestors(target, paths) {
11084
+ const chain = [];
11085
+ let current = paths.resolve(target);
11086
+ for (; ; ) {
11087
+ chain.push(current);
11088
+ const parent = paths.dirname(current);
11089
+ if (parent === current) {
11090
+ return chain;
11091
+ }
11092
+ current = parent;
11093
+ }
11094
+ }
11095
+ function identityOrNull(read, callTimeoutMillis) {
11096
+ return callWithTimeout(read, callTimeoutMillis).then(identityOf, (err) => {
11097
+ if (err instanceof FileCallTimeoutError) {
11098
+ throw err;
11099
+ }
11100
+ return null;
11101
+ });
11102
+ }
11103
+ async function identitiesOf(target, remover, callTimeoutMillis) {
11104
+ const identities = await Promise.all([remover.lstat(target), remover.stat(target)].map((read) => identityOrNull(read, callTimeoutMillis)));
11105
+ return identities.filter((identity) => identity !== null);
11106
+ }
11107
+ async function realPathOrNull(target, remover, callTimeoutMillis) {
11108
+ try {
11109
+ return await callWithTimeout(remover.realpath(target), callTimeoutMillis);
11110
+ } catch (err) {
11111
+ if (err instanceof FileCallTimeoutError) {
11112
+ throw err;
11113
+ }
11114
+ return null;
11115
+ }
11116
+ }
11117
+ async function agentFileChains(files, paths, remover, callTimeoutMillis) {
11118
+ const realPaths = await Promise.all(files.map((file) => realPathOrNull(file, remover, callTimeoutMillis)));
11119
+ return files.flatMap((file, index) => {
11120
+ const realPath2 = realPaths[index];
11121
+ return realPath2 === null ? [] : [...selfAndAncestors(file, paths), ...selfAndAncestors(realPath2, paths)];
11122
+ });
11123
+ }
11124
+ async function addFolders(reasons, folders, message, remover, callTimeoutMillis) {
11125
+ const identities = await Promise.all(folders.map((folder) => identitiesOf(folder, remover, callTimeoutMillis)));
11126
+ for (const identity of identities.flat()) {
11127
+ reasons.set(identity, message);
11128
+ }
11129
+ }
11130
+ async function readProtectedSet(sources, paths, remover, callTimeoutMillis) {
11131
+ const reasons = /* @__PURE__ */ new Map();
11132
+ const agentChains = await agentFileChains(sources.agentFiles, paths, remover, callTimeoutMillis);
11133
+ await addFolders(reasons, agentChains, MESSAGE_PINGGY_PROGRAM, remover, callTimeoutMillis);
11134
+ const systemChains = sources.systemFolders.flatMap((folder) => selfAndAncestors(folder, paths));
11135
+ await addFolders(reasons, systemChains, MESSAGE_SYSTEM_FOLDER, remover, callTimeoutMillis);
11136
+ await addFolders(
11137
+ reasons,
11138
+ selfAndAncestors(sources.accountsFolder, paths),
11139
+ MESSAGE_ACCOUNTS_FOLDER,
11140
+ remover,
11141
+ callTimeoutMillis
11142
+ );
11143
+ const pinggyChains = [...selfAndAncestors(sources.home, paths), ...selfAndAncestors(sources.configFolder, paths)];
11144
+ await addFolders(reasons, pinggyChains, MESSAGE_PINGGY_FOLDER, remover, callTimeoutMillis);
11145
+ const [configFolder, accountsFolder] = await Promise.all([sources.configFolder, sources.accountsFolder].map((folder) => identityOrNull(remover.stat(folder), callTimeoutMillis)));
11146
+ return { reasons, configFolder, accountsFolder };
11147
+ }
11148
+ async function isInsideConfigFolder(directory, protectedSet, paths, remover, callTimeoutMillis) {
11149
+ if (protectedSet.configFolder === null) {
11150
+ return false;
11151
+ }
11152
+ const chain = selfAndAncestors(directory, paths);
11153
+ const identities = await Promise.all(chain.map((folder) => identityOrNull(remover.stat(folder), callTimeoutMillis)));
11154
+ return identities.includes(protectedSet.configFolder);
11155
+ }
11156
+ var import_os6, import_path10, MESSAGE_PINGGY_FOLDER, MESSAGE_PINGGY_PROGRAM, MESSAGE_SYSTEM_FOLDER, MESSAGE_ACCOUNTS_FOLDER, MESSAGE_ACCOUNT_FOLDER, LINUX_SYSTEM_FOLDERS, MACOS_SYSTEM_FOLDERS, WINDOWS_SYSTEM_FOLDER_VARIABLES, POSIX_ACCOUNTS_FOLDER, MACOS_ACCOUNTS_FOLDER, WINDOWS_ACCOUNTS_FOLDER, WINDOWS_PUBLIC_FOLDER_VARIABLE;
11157
+ var init_fileProtectedPaths = __esm({
11158
+ "src/devices/files/fileProtectedPaths.ts"() {
11159
+ "use strict";
11160
+ init_cjs_shims();
11161
+ import_os6 = __toESM(require("os"), 1);
11162
+ import_path10 = __toESM(require("path"), 1);
11163
+ init_servicePaths();
11164
+ init_configDir();
11165
+ init_nodePtyRuntime();
11166
+ init_fileSystem();
11167
+ MESSAGE_PINGGY_FOLDER = "Pinggy keeps this folder so the device stays connected.";
11168
+ MESSAGE_PINGGY_PROGRAM = "Pinggy needs this to keep the device connected.";
11169
+ MESSAGE_SYSTEM_FOLDER = "This is a system folder.";
11170
+ MESSAGE_ACCOUNTS_FOLDER = "This folder holds the accounts on this device.";
11171
+ MESSAGE_ACCOUNT_FOLDER = "This is an account's home folder.";
11172
+ LINUX_SYSTEM_FOLDERS = ["/bin", "/boot", "/etc", "/lib", "/lib64", "/sbin", "/usr", "/var"];
11173
+ MACOS_SYSTEM_FOLDERS = ["/System", "/Library", "/Applications", "/usr", "/bin", "/sbin", "/private"];
11174
+ WINDOWS_SYSTEM_FOLDER_VARIABLES = [
11175
+ ["SystemRoot", "C:\\Windows"],
11176
+ ["ProgramFiles", "C:\\Program Files"],
11177
+ ["ProgramFiles(x86)", "C:\\Program Files (x86)"],
11178
+ ["ProgramData", "C:\\ProgramData"]
11179
+ ];
11180
+ POSIX_ACCOUNTS_FOLDER = "/home";
11181
+ MACOS_ACCOUNTS_FOLDER = "/Users";
11182
+ WINDOWS_ACCOUNTS_FOLDER = "C:\\Users";
11183
+ WINDOWS_PUBLIC_FOLDER_VARIABLE = "PUBLIC";
11184
+ }
11185
+ });
11186
+
11187
+ // src/devices/files/fileDelete.ts
11188
+ async function prepareDelete(request2, dependencies) {
11189
+ const paths = pathsFor(dependencies.platform);
11190
+ const pathIssue = pathProblem(request2.path, paths);
11191
+ if (pathIssue) {
11192
+ return fileError(ERROR_INVALID_PATH, pathIssue);
11193
+ }
11194
+ const item = resolvedItem(request2.path, paths);
11195
+ const { remover, callTimeoutMillis } = dependencies;
11196
+ let stats;
11197
+ let parentStats;
11198
+ try {
11199
+ stats = await callWithTimeout(remover.lstat(item.path), callTimeoutMillis);
11200
+ parentStats = await callWithTimeout(remover.stat(item.parent), callTimeoutMillis);
11201
+ } catch (err) {
11202
+ return { error: deleteFailure(err) };
11203
+ }
11204
+ let protectedSet;
11205
+ let insideConfigFolder;
11206
+ try {
11207
+ protectedSet = await readProtectedSet(dependencies.protectedSources, paths, remover, callTimeoutMillis);
11208
+ insideConfigFolder = await isInsideConfigFolder(item.parent, protectedSet, paths, remover, callTimeoutMillis);
11209
+ } catch (err) {
11210
+ const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
11211
+ return fileError(code, failureMessage(err, MESSAGE_PROTECTED_UNREAD));
11212
+ }
11213
+ if (insideConfigFolder) {
11214
+ return fileError(ERROR_PROTECTED_PATH, MESSAGE_PINGGY_FOLDER);
11215
+ }
11216
+ if (protectedSet.accountsFolder !== null && identityOf(parentStats) === protectedSet.accountsFolder) {
11217
+ return fileError(ERROR_PROTECTED_PATH, MESSAGE_ACCOUNT_FOLDER);
11218
+ }
11219
+ const reason = protectedSet.reasons.get(identityOf(stats));
11220
+ if (reason) {
11221
+ return fileError(ERROR_PROTECTED_PATH, reason);
11222
+ }
11223
+ if (stats.dev !== parentStats.dev) {
11224
+ return fileError(ERROR_MOUNT_POINT, MESSAGE_SELECTED_MOUNT);
11225
+ }
11226
+ return { target: item.path, name: item.name, stats, protectedSet };
11227
+ }
11228
+ async function runDelete(prepared, progress, dependencies) {
11229
+ const context = {
11230
+ device: prepared.stats.dev,
11231
+ protectedSet: prepared.protectedSet,
11232
+ progress,
11233
+ dependencies,
11234
+ paths: pathsFor(dependencies.platform)
11235
+ };
11236
+ let result = {};
11237
+ try {
11238
+ if (!await removeEntry(prepared.target, prepared.stats, context)) {
11239
+ result = fileError(ERROR_MOUNT_POINT, MESSAGE_MOUNT_INSIDE);
11240
+ }
11241
+ } catch (err) {
11242
+ result = { error: deleteFailure(err) };
11243
+ }
11244
+ progress.items_done += 1;
11245
+ return result;
11246
+ }
11247
+ function removeTree(target, stats, protectedSet, dependencies) {
11248
+ const context = {
11249
+ device: stats.dev,
11250
+ protectedSet,
11251
+ progress: { files_done: 0 },
11252
+ dependencies,
11253
+ paths: pathsFor(dependencies.platform)
11254
+ };
11255
+ return removeEntry(target, stats, context);
11256
+ }
11257
+ async function removeEntry(target, stats, context) {
11258
+ if (!stats.isDirectory()) {
11259
+ if (await removeWith(target, (entry) => context.dependencies.remover.unlink(entry), context)) {
11260
+ context.progress.files_done += 1;
11261
+ }
11262
+ return true;
11263
+ }
11264
+ return removeFolder(target, context);
11265
+ }
11266
+ async function removeFolder(folder, context) {
11267
+ const { remover, callTimeoutMillis } = context.dependencies;
11268
+ const removeFolderItself = (entry) => remover.rmdir(entry);
11269
+ try {
11270
+ if (await removeWith(folder, removeFolderItself, context)) {
11271
+ context.progress.files_done += 1;
11272
+ }
11273
+ return true;
11274
+ } catch (err) {
11275
+ if (!isNotEmpty(err)) {
11276
+ throw err;
11277
+ }
11278
+ }
11279
+ let names;
11280
+ try {
11281
+ names = await callWithTimeout(remover.readdir(folder), callTimeoutMillis);
11282
+ } catch (err) {
11283
+ if (isGone(err)) {
11284
+ return true;
11285
+ }
11286
+ throw err;
11287
+ }
11288
+ let removedAll = true;
11289
+ for (const name of names) {
11290
+ if (!await removeChild(context.paths.join(folder, name), context)) {
11291
+ removedAll = false;
11292
+ }
11293
+ }
11294
+ if (!removedAll) {
11295
+ return false;
11296
+ }
11297
+ if (await removeWith(folder, removeFolderItself, context)) {
11298
+ context.progress.files_done += 1;
11299
+ }
11300
+ return true;
11301
+ }
11302
+ async function removeChild(child, context) {
11303
+ let stats;
11304
+ try {
11305
+ stats = await callWithTimeout(
11306
+ context.dependencies.remover.lstat(child),
11307
+ context.dependencies.callTimeoutMillis
11308
+ );
11309
+ } catch (err) {
11310
+ if (isGone(err)) {
11311
+ return true;
11312
+ }
11313
+ throw err;
11314
+ }
11315
+ const reason = context.protectedSet.reasons.get(identityOf(stats));
11316
+ if (reason) {
11317
+ throw new ProtectedEntryError(reason);
11318
+ }
11319
+ if (stats.isDirectory() && stats.dev !== context.device) {
11320
+ return false;
11321
+ }
11322
+ return removeEntry(child, stats, context);
11323
+ }
11324
+ async function removeWith(target, remove, context) {
11325
+ const { remover, callTimeoutMillis, platform: platform3 } = context.dependencies;
11326
+ try {
11327
+ await callWithTimeout(remove(target), callTimeoutMillis);
11328
+ return true;
11329
+ } catch (err) {
11330
+ if (isGone(err)) {
11331
+ return false;
11332
+ }
11333
+ if (platform3 !== "win32" || errorCodeOf(err) !== "EPERM") {
11334
+ throw err;
11335
+ }
11336
+ try {
11337
+ await callWithTimeout(remover.chmod(target, WINDOWS_WRITABLE_MODE), callTimeoutMillis);
11338
+ } catch {
11339
+ throw err;
11340
+ }
11341
+ }
11342
+ try {
11343
+ await callWithTimeout(remove(target), callTimeoutMillis);
11344
+ return true;
11345
+ } catch (err) {
11346
+ if (isGone(err)) {
11347
+ return false;
11348
+ }
11349
+ throw err;
11350
+ }
11351
+ }
11352
+ function isGone(err) {
11353
+ return errorCodeOf(err) === "ENOENT";
11354
+ }
11355
+ function isNotEmpty(err) {
11356
+ const code = errorCodeOf(err);
11357
+ return code === "ENOTEMPTY" || code === "EEXIST";
11358
+ }
11359
+ function deleteFailure(err) {
11360
+ if (err instanceof FileCallTimeoutError) {
11361
+ return { code: ERROR_FILE_TIMEOUT, message: err.message };
11362
+ }
11363
+ if (err instanceof ProtectedEntryError) {
11364
+ return { code: ERROR_PROTECTED_PATH, message: err.message };
11365
+ }
11366
+ const message = failureMessage(err, MESSAGE_DELETE_FAILED);
11367
+ switch (errorCodeOf(err)) {
11368
+ case "ENOENT":
11369
+ case "ENOTDIR":
11370
+ return { code: ERROR_PATH_NOT_FOUND, message };
11371
+ case "EACCES":
11372
+ case "EPERM":
11373
+ case "EROFS":
11374
+ return { code: ERROR_PERMISSION_DENIED, message };
11375
+ default:
11376
+ return { code: ERROR_FILE_OPERATION_FAILED, message };
11377
+ }
11378
+ }
11379
+ var WINDOWS_WRITABLE_MODE, MESSAGE_DELETE_FAILED, MESSAGE_PROTECTED_UNREAD, MESSAGE_SELECTED_MOUNT, MESSAGE_MOUNT_INSIDE, ProtectedEntryError;
11380
+ var init_fileDelete = __esm({
11381
+ "src/devices/files/fileDelete.ts"() {
11382
+ "use strict";
11383
+ init_cjs_shims();
11384
+ init_file_schema();
11385
+ init_fileProtectedPaths();
11386
+ init_fileSystem();
11387
+ WINDOWS_WRITABLE_MODE = 438;
11388
+ MESSAGE_DELETE_FAILED = "The item could not be deleted.";
11389
+ MESSAGE_PROTECTED_UNREAD = "The protected folders could not be read in time.";
11390
+ MESSAGE_SELECTED_MOUNT = "This folder is a mounted disk. Open it to delete what is inside.";
11391
+ MESSAGE_MOUNT_INSIDE = "Another disk is mounted inside. Pinggy left it in place.";
11392
+ ProtectedEntryError = class extends Error {
11393
+ };
11394
+ }
11395
+ });
11396
+
11397
+ // src/devices/files/fileCopy.ts
11398
+ function randomHiddenNameSuffix() {
11399
+ return import_crypto3.default.randomBytes(HIDDEN_SUFFIX_BYTES).toString("hex");
11400
+ }
11401
+ async function prepareCopy(request2, dependencies) {
11402
+ try {
11403
+ return await checkedCopy(request2, dependencies);
11404
+ } catch (err) {
11405
+ return refusalOf(err);
11406
+ }
11407
+ }
11408
+ function refusalOf(err) {
11409
+ if (err instanceof RequestRefusal) {
11410
+ return err.refusal;
11411
+ }
11412
+ const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
11413
+ return fileError(code, failureMessage(err, MESSAGE_FOLDER_UNREADABLE));
11414
+ }
11415
+ async function checkedCopy(request2, dependencies) {
11416
+ const { copier, platform: platform3 } = dependencies;
11417
+ const paths = pathsFor(platform3);
11418
+ const { source, destination } = resolvedItems(request2, paths);
11419
+ checkTargetName(destination.name, platform3);
11420
+ const sourceStats = await sourceItemStats(source.path, copier, MESSAGE_COPY_FAILED);
11421
+ if (isSpecial(sourceStats)) {
11422
+ throw new RequestRefusal(fileError(ERROR_SPECIAL_FILE, MESSAGE_SPECIAL_SELECTED));
11423
+ }
11424
+ const destinationStats = await folderStats(destination.parent, copier);
11425
+ await refuseIntoItself(sourceStats, destination.parent, dependencies, MESSAGE_INTO_ITSELF);
11426
+ const onConflict = request2.on_conflict ?? ON_CONFLICT_FAIL;
11427
+ if (onConflict === ON_CONFLICT_FAIL || onConflict === ON_CONFLICT_REPLACE) {
11428
+ const target = await lstatOrNull(destination.path, copier);
11429
+ if (onConflict === ON_CONFLICT_FAIL && target !== null) {
11430
+ throw new RequestRefusal(targetTakenRefusal());
11431
+ }
11432
+ if (onConflict === ON_CONFLICT_REPLACE && target !== null && identityOf(target) === identityOf(sourceStats)) {
11433
+ throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_ITSELF));
11434
+ }
11435
+ if (onConflict === ON_CONFLICT_REPLACE) {
11436
+ await refuseReplacingAHolder(target, source.parent, dependencies);
11437
+ }
11438
+ }
11439
+ const replaceGuard = onConflict === ON_CONFLICT_REPLACE ? await removalGuard(
11440
+ destination.parent,
11441
+ destinationStats,
11442
+ await readProtectedFolders(dependencies),
11443
+ dependencies
11444
+ ) : null;
11445
+ return {
11446
+ source: source.path,
11447
+ sourceStats,
11448
+ sourceName: source.name,
11449
+ destinationDirectory: destination.parent,
11450
+ targetName: destination.name,
11451
+ onConflict,
11452
+ destinationDevice: destinationStats.dev,
11453
+ replaceGuard
11454
+ };
11455
+ }
11456
+ function resolvedItems(request2, paths) {
11457
+ for (const requested of [request2.source_path, request2.destination_path]) {
11458
+ const issue = pathProblem(requested, paths);
11459
+ if (issue) {
11460
+ throw new RequestRefusal(fileError(ERROR_INVALID_PATH, issue));
11461
+ }
11462
+ }
11463
+ const source = resolvedItem(request2.source_path, paths);
11464
+ const requestedDestination = resolvedItem(request2.destination_path, paths);
11465
+ const destination = requestedDestination.name === source.name ? requestedDestination : withTrimmedName(requestedDestination);
11466
+ if (isRoot(source.path, paths) || isRoot(destination.path, paths)) {
11467
+ throw new RequestRefusal(fileError(ERROR_INVALID_PATH, MESSAGE_ROOT));
11468
+ }
11469
+ return { source, destination };
11470
+ }
11471
+ function checkTargetName(targetName, platform3) {
11472
+ const nameIssue = nameProblem(targetName, platform3);
11473
+ if (nameIssue) {
11474
+ throw new RequestRefusal(fileError(ERROR_INVALID_PAYLOAD2, nameIssue));
11475
+ }
11476
+ const windowsIssue = platform3 === "win32" ? windowsNameProblem(targetName, "A name") : null;
11477
+ if (windowsIssue) {
11478
+ throw new RequestRefusal(fileError(ERROR_INVALID_NAME, windowsIssue));
11479
+ }
11480
+ }
11481
+ async function sourceItemStats(source, copier, fallbackMessage) {
11482
+ try {
11483
+ return await copier.lstat(source);
11484
+ } catch (err) {
11485
+ throw new RequestRefusal({ error: copyFailure(err, fallbackMessage) });
11486
+ }
11487
+ }
11488
+ async function folderStats(folder, copier) {
11489
+ let stats;
11490
+ try {
11491
+ stats = await copier.stat(folder);
11492
+ } catch (err) {
11493
+ if (err instanceof FileCallTimeoutError) {
11494
+ throw err;
11495
+ }
11496
+ throw new RequestRefusal(folderFailure(err));
11497
+ }
11498
+ if (!stats.isDirectory()) {
11499
+ throw new RequestRefusal(fileError(ERROR_NOT_A_DIRECTORY, MESSAGE_NOT_A_FOLDER));
11500
+ }
11501
+ return stats;
11502
+ }
11503
+ function folderFailure(err) {
11504
+ const message = failureMessage(err, MESSAGE_FOLDER_UNREADABLE);
11505
+ switch (errorCodeOf(err)) {
11506
+ case "ENOENT":
11507
+ case "ENOTDIR":
11508
+ return fileError(ERROR_PATH_NOT_FOUND, message);
11509
+ case "EACCES":
11510
+ case "EPERM":
11511
+ return fileError(ERROR_PERMISSION_DENIED, message);
11512
+ default:
11513
+ return fileError(ERROR_FILE_OPERATION_FAILED, message);
11514
+ }
11515
+ }
11516
+ async function refuseIntoItself(source, destinationDirectory, dependencies, message) {
11517
+ if (await folderHolds(source, destinationDirectory, dependencies)) {
11518
+ throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, message));
11519
+ }
11520
+ }
11521
+ async function refuseReplacingAHolder(target, sourceDirectory, dependencies) {
11522
+ if (await folderHolds(target, sourceDirectory, dependencies)) {
11523
+ throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_HOLDER));
11524
+ }
11525
+ }
11526
+ async function folderHolds(candidate, folder, dependencies) {
11527
+ if (candidate === null || !candidate.isDirectory()) {
11528
+ return false;
11529
+ }
11530
+ const { copier } = dependencies;
11531
+ const paths = pathsFor(dependencies.platform);
11532
+ const realFolder = await copier.realpath(folder);
11533
+ const chain = new Set(await Promise.all(selfAndAncestors(realFolder, paths).map((each) => identityOrNull2(copier.stat(each)))));
11534
+ return chain.has(identityOf(candidate));
11535
+ }
11536
+ function targetTakenRefusal() {
11537
+ return fileError(ERROR_FILE_EXISTS, MESSAGE_TARGET_TAKEN);
11538
+ }
11539
+ async function readProtectedFolders(dependencies) {
11540
+ const { remover, callTimeoutMillis, protectedSources } = dependencies;
11541
+ try {
11542
+ return await readProtectedSet(protectedSources, pathsFor(dependencies.platform), remover, callTimeoutMillis);
11543
+ } catch (err) {
11544
+ throw protectedUnread(err);
11545
+ }
11546
+ }
11547
+ async function removalGuard(folder, stats, protectedSet, dependencies) {
11548
+ const { remover, callTimeoutMillis } = dependencies;
11549
+ try {
11550
+ const insideConfigFolder = await isInsideConfigFolder(
11551
+ folder,
11552
+ protectedSet,
11553
+ pathsFor(dependencies.platform),
11554
+ remover,
11555
+ callTimeoutMillis
11556
+ );
11557
+ const inAccountsFolder = protectedSet.accountsFolder !== null && identityOf(stats) === protectedSet.accountsFolder;
11558
+ return { protectedSet, insideConfigFolder, inAccountsFolder };
11559
+ } catch (err) {
11560
+ throw protectedUnread(err);
11561
+ }
11562
+ }
11563
+ function protectedUnread(err) {
11564
+ const code = err instanceof FileCallTimeoutError ? ERROR_FILE_TIMEOUT : ERROR_FILE_OPERATION_FAILED;
11565
+ return new RequestRefusal(fileError(code, failureMessage(err, MESSAGE_PROTECTED_UNREAD2)));
11566
+ }
11567
+ async function runCopy(prepared, progress, dependencies) {
11568
+ const counted = Object.assign(progress, { bytes_done: progress.bytes_done ?? 0 });
11569
+ const totals = await countSource(prepared, dependencies);
11570
+ counted.files_total = totals.files;
11571
+ counted.bytes_total = totals.bytes;
11572
+ const noSpace = await noSpaceRefusal(totals.bytes, prepared.destinationDirectory, dependencies.copier);
11573
+ if (noSpace) {
11574
+ return noSpace;
11575
+ }
11576
+ const walk = {
11577
+ copier: dependencies.copier,
11578
+ paths: pathsFor(dependencies.platform),
11579
+ platform: dependencies.platform,
11580
+ progress: counted,
11581
+ specialFilesLeftOut: 0
11582
+ };
11583
+ const outcome = await copyItem(prepared, walk, dependencies);
11584
+ counted.items_done += 1;
11585
+ return outcomeAnswer(outcome);
11586
+ }
11587
+ function outcomeAnswer(outcome) {
11588
+ if (outcome === SKIPPED) {
11589
+ return { skipped: true };
11590
+ }
11591
+ return outcome === null ? {} : { error: outcome };
11592
+ }
11593
+ async function noSpaceRefusal(neededBytes, destinationDirectory, copier) {
11594
+ const freeBytes = await copier.freeBytes(destinationDirectory).catch(() => null);
11595
+ if (freeBytes === null || BigInt(neededBytes) <= freeBytes) {
11596
+ return null;
11597
+ }
11598
+ return fileError(ERROR_NO_SPACE, `The copy needs ${formatBytes(neededBytes)}. The destination disk has ${formatBytes(freeBytes)} free.`);
11599
+ }
11600
+ async function countSource(prepared, dependencies) {
11601
+ const { copier } = dependencies;
11602
+ const paths = pathsFor(dependencies.platform);
11603
+ const totals = newCountTotals();
11604
+ const target = paths.join(prepared.destinationDirectory, prepared.targetName);
11605
+ if (prepared.onConflict === ON_CONFLICT_SKIP && await lstatOrNull(target, copier).catch(() => null)) {
11606
+ return totals;
11607
+ }
11608
+ await countEntry(prepared.source, totals, copier, paths, null);
11609
+ return totals;
11610
+ }
11611
+ function newCountTotals() {
11612
+ return { files: 0, bytes: 0, specialFiles: 0, mountedDisks: 0 };
11613
+ }
11614
+ async function countEntry(entry, totals, copier, paths, stopAtDevice) {
11615
+ let stats;
11616
+ try {
11617
+ stats = await copier.lstat(entry);
11618
+ } catch {
11619
+ return;
11620
+ }
11621
+ if (isSpecial(stats)) {
11622
+ totals.specialFiles += 1;
11623
+ return;
11624
+ }
11625
+ if (stats.isDirectory() && stopAtDevice !== null && stats.dev !== stopAtDevice) {
11626
+ totals.mountedDisks += 1;
11627
+ return;
11628
+ }
11629
+ totals.files += 1;
11630
+ if (stats.isFile()) {
11631
+ totals.bytes += Number(stats.size);
11632
+ return;
11633
+ }
11634
+ if (!stats.isDirectory()) {
11635
+ return;
11636
+ }
11637
+ let children;
11638
+ try {
11639
+ children = await copier.readdir(entry);
11640
+ } catch {
11641
+ return;
11642
+ }
11643
+ for (const child of children) {
11644
+ await countEntry(paths.join(entry, child), totals, copier, paths, stopAtDevice);
11645
+ }
11646
+ }
11647
+ async function copyItem(prepared, walk, dependencies) {
11648
+ try {
11649
+ if (prepared.onConflict === ON_CONFLICT_REPLACE) {
11650
+ const refusal = await replaceTarget(prepared, walk, dependencies);
11651
+ if (refusal) {
11652
+ return refusal;
11653
+ }
11654
+ } else if (await copyToFreeName(
11655
+ prepared.source,
11656
+ prepared.sourceStats,
11657
+ prepared.targetName,
11658
+ prepared,
11659
+ walk
11660
+ ) === SKIPPED) {
11661
+ return SKIPPED;
11662
+ }
11663
+ } catch (err) {
11664
+ return copyFailure(err, MESSAGE_COPY_FAILED);
11665
+ }
11666
+ return walk.specialFilesLeftOut > 0 ? specialFilesLeftOut(walk.specialFilesLeftOut) : null;
11667
+ }
11668
+ async function copyToFreeName(source, stats, targetName, prepared, walk) {
11669
+ let candidate = targetName;
11670
+ for (let number = 1; ; number++) {
11671
+ try {
11672
+ await copyEntry(source, stats, walk.paths.join(prepared.destinationDirectory, candidate), walk, true);
11673
+ return null;
11674
+ } catch (err) {
11675
+ if (!(err instanceof TakenError)) {
11676
+ throw err;
11677
+ }
11678
+ if (prepared.onConflict === ON_CONFLICT_SKIP) {
11679
+ return SKIPPED;
11680
+ }
11681
+ if (prepared.onConflict !== ON_CONFLICT_KEEP_BOTH || number > MAX_KEEP_BOTH_NUMBER) {
11682
+ throw err;
11683
+ }
11684
+ candidate = keepBothName(targetName, stats.isDirectory(), number);
11685
+ }
11686
+ }
11687
+ }
11688
+ async function replaceTarget(prepared, walk, dependencies) {
11689
+ const { copier, paths } = walk;
11690
+ const { source, sourceStats: stats, targetName } = prepared;
11691
+ const guard = prepared.replaceGuard;
11692
+ const target = paths.join(prepared.destinationDirectory, targetName);
11693
+ const existing = await lstatOrNull(target, copier);
11694
+ if (existing === null) {
11695
+ await copyEntry(source, stats, target, walk, true);
11696
+ return null;
11697
+ }
11698
+ const refusal = replaceRefusal(existing, stats, prepared.destinationDevice, guard);
11699
+ if (refusal) {
11700
+ return refusal;
11701
+ }
11702
+ const suffix = dependencies.hiddenNameSuffix();
11703
+ const hiddenCopy = paths.join(prepared.destinationDirectory, hiddenName(targetName, HIDDEN_COPY_MARK, suffix));
11704
+ try {
11705
+ await copyEntry(source, stats, hiddenCopy, walk, true);
11706
+ } catch (err) {
11707
+ if (!(err instanceof TakenError)) {
11708
+ await removeQuietly2(hiddenCopy, guard.protectedSet, dependencies);
11709
+ }
11710
+ throw err;
11711
+ }
11712
+ let oldName;
11713
+ try {
11714
+ oldName = await swapIn(
11715
+ hiddenCopy,
11716
+ prepared.destinationDirectory,
11717
+ targetName,
11718
+ existing,
11719
+ stats.isDirectory(),
11720
+ suffix,
11721
+ copier,
11722
+ paths
11723
+ );
11724
+ } catch (err) {
11725
+ await removeQuietly2(hiddenCopy, guard.protectedSet, dependencies);
11726
+ throw err;
11727
+ }
11728
+ if (oldName === null) {
11729
+ return null;
11730
+ }
11731
+ return removeOld(
11732
+ paths.join(prepared.destinationDirectory, oldName),
11733
+ oldName,
11734
+ existing,
11735
+ guard.protectedSet,
11736
+ dependencies,
11737
+ MESSAGE_COPY_IN_PLACE
11738
+ );
11739
+ }
11740
+ async function swapIn(incoming, folder, targetName, existing, incomingIsFolder, suffix, copier, paths) {
11741
+ const target = paths.join(folder, targetName);
11742
+ if (!existing.isDirectory() && !incomingIsFolder) {
11743
+ await copier.rename(incoming, target);
11744
+ return null;
11745
+ }
11746
+ const oldName = hiddenName(targetName, HIDDEN_OLD_MARK, suffix);
11747
+ const hiddenOld = paths.join(folder, oldName);
11748
+ await copier.rename(target, hiddenOld);
11749
+ try {
11750
+ await copier.rename(incoming, target);
11751
+ } catch (err) {
11752
+ await copier.rename(hiddenOld, target).catch(() => void 0);
11753
+ throw err;
11754
+ }
11755
+ return oldName;
11756
+ }
11757
+ function replaceRefusal(existing, source, destinationDevice, guard) {
11758
+ if (identityOf(existing) === identityOf(source)) {
11759
+ return { code: ERROR_INVALID_DESTINATION, message: MESSAGE_REPLACE_ITSELF };
11760
+ }
11761
+ return protectedRefusal(existing, destinationDevice, guard, MESSAGE_REPLACE_MOUNT);
11762
+ }
11763
+ function protectedRefusal(stats, folderDevice, guard, mountMessage) {
11764
+ if (guard.insideConfigFolder) {
11765
+ return { code: ERROR_PROTECTED_PATH, message: MESSAGE_PINGGY_FOLDER };
11766
+ }
11767
+ if (guard.inAccountsFolder) {
11768
+ return { code: ERROR_PROTECTED_PATH, message: MESSAGE_ACCOUNT_FOLDER };
11769
+ }
11770
+ const reason = guard.protectedSet.reasons.get(identityOf(stats));
11771
+ if (reason) {
11772
+ return { code: ERROR_PROTECTED_PATH, message: reason };
11773
+ }
11774
+ if (stats.dev !== folderDevice) {
11775
+ return { code: ERROR_MOUNT_POINT, message: mountMessage };
11776
+ }
11777
+ return null;
11778
+ }
11779
+ async function removeOld(hiddenOld, oldName, existing, protectedSet, dependencies, inPlaceMessage) {
11780
+ try {
11781
+ if (await removeTree(hiddenOld, existing, protectedSet, deleteDependencies(dependencies))) {
11782
+ return null;
11783
+ }
11784
+ return { code: ERROR_MOUNT_POINT, message: `${inPlaceMessage} ${oldName}: ${REASON_MOUNT_INSIDE}` };
11785
+ } catch (err) {
11786
+ const failure2 = deleteFailure(err);
11787
+ const message = sanitizeErrorMessage(`${inPlaceMessage} ${oldName}: ${failure2.message}`) ?? failure2.message;
11788
+ return { code: failure2.code, message };
11789
+ }
11790
+ }
11791
+ async function removeQuietly2(entry, protectedSet, dependencies) {
11792
+ try {
11793
+ const stats = await dependencies.remover.lstat(entry);
11794
+ await removeTree(entry, stats, protectedSet, deleteDependencies(dependencies));
11795
+ } catch {
11796
+ }
11797
+ }
11798
+ function deleteDependencies(dependencies) {
11799
+ const { remover, platform: platform3, protectedSources, callTimeoutMillis } = dependencies;
11800
+ return { remover, platform: platform3, protectedSources, callTimeoutMillis };
11801
+ }
11802
+ async function copyEntry(source, stats, target, walk, top) {
11803
+ if (stats.isSymbolicLink()) {
11804
+ await copyLink(source, target, walk, top);
11805
+ } else if (stats.isDirectory()) {
11806
+ await copyFolder(source, stats, target, walk, top);
11807
+ } else if (stats.isFile()) {
11808
+ await copyFile2(source, stats, target, walk, top);
11809
+ } else {
11810
+ walk.specialFilesLeftOut += 1;
11811
+ }
11812
+ }
11813
+ async function copyFile2(source, stats, target, walk, top) {
11814
+ const { copier, progress } = walk;
11815
+ const reader = await copier.openToRead(source);
11816
+ let writer;
11817
+ try {
11818
+ writer = await created(copier.createFile(target), top);
11819
+ } catch (err) {
11820
+ await closeQuietly(reader, copier);
11821
+ throw err;
11822
+ }
11823
+ const buffer = Buffer.allocUnsafe(Math.min(COPY_PIECE_BYTES, Math.max(SMALL_PIECE_BYTES, Number(stats.size) + 1)));
11824
+ try {
11825
+ for (; ; ) {
11826
+ const bytesRead = await copier.read(reader, buffer);
11827
+ if (bytesRead === 0) {
11828
+ break;
11829
+ }
11830
+ await copier.write(writer, buffer, bytesRead);
11831
+ progress.bytes_done += bytesRead;
11832
+ }
11833
+ await copier.close(writer);
11834
+ } catch (err) {
11835
+ await closeQuietly(writer, copier);
11836
+ await copier.unlink(target).catch(() => void 0);
11837
+ throw err;
11838
+ } finally {
11839
+ await closeQuietly(reader, copier);
11840
+ }
11841
+ await keepModeAndTimes(target, stats, copier);
11842
+ progress.files_done += 1;
11843
+ }
11844
+ async function copyFolder(source, stats, target, walk, top) {
11845
+ const { copier, paths } = walk;
11846
+ await created(copier.mkdir(target), top);
11847
+ walk.progress.files_done += 1;
11848
+ for (const child of await copier.readdir(source)) {
11849
+ const childSource = paths.join(source, child);
11850
+ let childStats;
11851
+ try {
11852
+ childStats = await copier.lstat(childSource);
11853
+ } catch (err) {
11854
+ if (errorCodeOf(err) === "ENOENT") {
11855
+ continue;
11856
+ }
11857
+ throw err;
11858
+ }
11859
+ await copyEntry(childSource, childStats, paths.join(target, child), walk, false);
11860
+ }
11861
+ await keepModeAndTimes(target, stats, copier);
11862
+ }
11863
+ async function copyLink(source, target, walk, top) {
11864
+ const { copier } = walk;
11865
+ const linkText = await copier.readlink(source);
11866
+ const type = walk.platform === "win32" ? await linkTypeOf(source, copier) : LINK_TYPE_FILE;
11867
+ await created(copier.symlink(linkText, target, type), top);
11868
+ walk.progress.files_done += 1;
11869
+ }
11870
+ async function linkTypeOf(link, copier) {
11871
+ try {
11872
+ return (await copier.stat(link)).isDirectory() ? LINK_TYPE_FOLDER : LINK_TYPE_FILE;
11873
+ } catch (err) {
11874
+ if (err instanceof FileCallTimeoutError) {
11875
+ throw err;
11876
+ }
11877
+ return LINK_TYPE_FILE;
11878
+ }
11879
+ }
11880
+ async function keepModeAndTimes(target, stats, copier) {
11881
+ await copier.utimes(target, stats.atime, stats.mtime).catch(() => void 0);
11882
+ await copier.chmod(target, Number(stats.mode & PERMISSION_BITS)).catch(() => void 0);
11883
+ }
11884
+ async function created(making, top) {
11885
+ try {
11886
+ return await making;
11887
+ } catch (err) {
11888
+ if (top && errorCodeOf(err) === "EEXIST") {
11889
+ throw new TakenError(MESSAGE_NAME_TAKEN);
11890
+ }
11891
+ throw err;
11892
+ }
11893
+ }
11894
+ async function closeQuietly(handle, copier) {
11895
+ await copier.close(handle).catch(() => void 0);
11896
+ }
11897
+ function keepBothName(name, isFolder, number) {
11898
+ const suffix = ` (${number})`;
11899
+ const dot = isFolder ? -1 : name.lastIndexOf(EXTENSION_SEPARATOR2);
11900
+ let stem = dot > 0 ? name.slice(0, dot) : name;
11901
+ let extension = dot > 0 ? name.slice(dot) : "";
11902
+ if (Buffer.byteLength(suffix + extension, "utf8") >= MAX_NAME_BYTES) {
11903
+ stem = name;
11904
+ extension = "";
11905
+ }
11906
+ const room = MAX_NAME_BYTES - Buffer.byteLength(suffix + extension, "utf8");
11907
+ return `${cutToBytes(stem, room)}${suffix}${extension}`;
11908
+ }
11909
+ function hiddenName(targetName, mark, suffix) {
11910
+ const tail = `.pinggy-${mark}-${suffix}`;
11911
+ const room = MAX_NAME_BYTES - Buffer.byteLength(HIDDEN_NAME_PREFIX2 + tail, "utf8");
11912
+ return `${HIDDEN_NAME_PREFIX2}${cutToBytes(targetName, room)}${tail}`;
11913
+ }
11914
+ function cutToBytes(text, maxBytes) {
11915
+ let bytes = 0;
11916
+ let kept = "";
11917
+ for (const character of text) {
11918
+ const characterBytes = Buffer.byteLength(character, "utf8");
11919
+ if (bytes + characterBytes > maxBytes) {
11920
+ break;
11921
+ }
11922
+ kept += character;
11923
+ bytes += characterBytes;
11924
+ }
11925
+ return kept;
11926
+ }
11927
+ function formatBytes(bytes) {
11928
+ let value = Number(bytes);
11929
+ let unit = 0;
11930
+ while (value >= BYTES_PER_UNIT && unit < BYTE_UNITS.length - 1) {
11931
+ value /= BYTES_PER_UNIT;
11932
+ unit += 1;
11933
+ }
11934
+ if (unit > 0) {
11935
+ return `${value.toFixed(1)} ${BYTE_UNITS[unit]}`;
11936
+ }
11937
+ return value === 1 ? `1 ${BYTE_UNIT_SINGULAR}` : `${value} ${BYTE_UNITS[0]}`;
11938
+ }
11939
+ function isSpecial(stats) {
11940
+ return !stats.isFile() && !stats.isDirectory() && !stats.isSymbolicLink();
11941
+ }
11942
+ function specialFilesLeftOut(count) {
11943
+ const message = count === 1 ? "1 socket, pipe or device file inside was left out." : `${count} sockets, pipes or device files inside were left out.`;
11944
+ return { code: ERROR_SPECIAL_FILE, message };
11945
+ }
11946
+ async function lstatOrNull(target, copier) {
11947
+ try {
11948
+ return await copier.lstat(target);
11949
+ } catch (err) {
11950
+ if (err instanceof FileCallTimeoutError) {
11951
+ throw err;
11952
+ }
11953
+ return null;
11954
+ }
11955
+ }
11956
+ async function identityOrNull2(read) {
11957
+ try {
11958
+ return identityOf(await read);
11959
+ } catch (err) {
11960
+ if (err instanceof FileCallTimeoutError) {
11961
+ throw err;
11962
+ }
11963
+ return null;
11964
+ }
11965
+ }
11966
+ function copyFailure(err, fallbackMessage) {
11967
+ if (err instanceof TakenError) {
11968
+ return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
11969
+ }
11970
+ if (err instanceof FileCallTimeoutError) {
11971
+ return { code: ERROR_FILE_TIMEOUT, message: err.message };
11972
+ }
11973
+ const message = failureMessage(err, fallbackMessage);
11974
+ switch (errorCodeOf(err)) {
11975
+ case "ENOENT":
11976
+ case "ENOTDIR":
11977
+ return { code: ERROR_PATH_NOT_FOUND, message };
11978
+ case "EEXIST":
11979
+ return { code: ERROR_FILE_EXISTS, message };
11980
+ case "EACCES":
11981
+ case "EPERM":
11982
+ case "EROFS":
11983
+ return { code: ERROR_PERMISSION_DENIED, message };
11984
+ case "ENOSPC":
11985
+ case "EDQUOT":
11986
+ return { code: ERROR_NO_SPACE, message };
11987
+ default:
11988
+ return { code: ERROR_FILE_OPERATION_FAILED, message };
11989
+ }
11990
+ }
11991
+ var import_crypto3, COPY_PIECE_BYTES, SMALL_PIECE_BYTES, PERMISSION_BITS, MAX_KEEP_BOTH_NUMBER, EXTENSION_SEPARATOR2, HIDDEN_NAME_PREFIX2, HIDDEN_COPY_MARK, HIDDEN_OLD_MARK, HIDDEN_SUFFIX_BYTES, LINK_TYPE_FILE, LINK_TYPE_FOLDER, BYTES_PER_UNIT, BYTE_UNITS, BYTE_UNIT_SINGULAR, MESSAGE_FOLDER_UNREADABLE, MESSAGE_NOT_A_FOLDER, MESSAGE_ROOT, MESSAGE_INTO_ITSELF, MESSAGE_REPLACE_ITSELF, MESSAGE_REPLACE_HOLDER, MESSAGE_TARGET_TAKEN, MESSAGE_PROTECTED_UNREAD2, MESSAGE_SPECIAL_SELECTED, MESSAGE_REPLACE_MOUNT, MESSAGE_COPY_FAILED, MESSAGE_COPY_IN_PLACE, REASON_MOUNT_INSIDE, TakenError, RequestRefusal, SKIPPED;
11992
+ var init_fileCopy = __esm({
11993
+ "src/devices/files/fileCopy.ts"() {
11994
+ "use strict";
11995
+ init_cjs_shims();
11996
+ import_crypto3 = __toESM(require("crypto"), 1);
11997
+ init_tunnelList();
11998
+ init_file_schema();
11999
+ init_fileDelete();
12000
+ init_fileProtectedPaths();
12001
+ init_fileSystem();
12002
+ COPY_PIECE_BYTES = 1024 * 1024;
12003
+ SMALL_PIECE_BYTES = 4096;
12004
+ PERMISSION_BITS = 0o777n;
12005
+ MAX_KEEP_BOTH_NUMBER = 1e3;
12006
+ EXTENSION_SEPARATOR2 = ".";
12007
+ HIDDEN_NAME_PREFIX2 = ".";
12008
+ HIDDEN_COPY_MARK = "copy";
12009
+ HIDDEN_OLD_MARK = "old";
12010
+ HIDDEN_SUFFIX_BYTES = 4;
12011
+ LINK_TYPE_FILE = "file";
12012
+ LINK_TYPE_FOLDER = "dir";
12013
+ BYTES_PER_UNIT = 1e3;
12014
+ BYTE_UNITS = ["bytes", "KB", "MB", "GB", "TB", "PB"];
12015
+ BYTE_UNIT_SINGULAR = "byte";
12016
+ MESSAGE_FOLDER_UNREADABLE = "The folder could not be read.";
12017
+ MESSAGE_NOT_A_FOLDER = "The path is not a folder.";
12018
+ MESSAGE_ROOT = "A drive or filesystem root cannot be copied or moved.";
12019
+ MESSAGE_INTO_ITSELF = "A folder cannot be copied into itself.";
12020
+ MESSAGE_REPLACE_ITSELF = "An item cannot replace itself.";
12021
+ MESSAGE_REPLACE_HOLDER = "An item cannot replace a folder that holds it.";
12022
+ MESSAGE_TARGET_TAKEN = "1 item already exists in the destination.";
12023
+ MESSAGE_PROTECTED_UNREAD2 = "The protected folders could not be read in time.";
12024
+ MESSAGE_SPECIAL_SELECTED = "This is a socket, pipe or device file. Pinggy cannot copy it.";
12025
+ MESSAGE_REPLACE_MOUNT = "This item is a mounted disk. Pinggy does not replace it.";
12026
+ MESSAGE_COPY_FAILED = "The item could not be copied.";
12027
+ MESSAGE_COPY_IN_PLACE = "The copy is in place. The old one stays as";
12028
+ REASON_MOUNT_INSIDE = "a disk is mounted inside it.";
12029
+ TakenError = class extends Error {
12030
+ };
12031
+ RequestRefusal = class extends Error {
12032
+ constructor(refusal) {
12033
+ super(refusal.error.message);
12034
+ this.refusal = refusal;
12035
+ }
12036
+ };
12037
+ SKIPPED = "skipped";
12038
+ }
12039
+ });
12040
+
12041
+ // src/devices/files/fileList.ts
12042
+ function folderReadFailure(err) {
12043
+ const message = failureMessage(err, MESSAGE_LIST_FAILED);
12044
+ if (err instanceof FileCallTimeoutError) {
12045
+ return fileError(ERROR_FILE_TIMEOUT, message);
12046
+ }
12047
+ switch (errorCodeOf(err)) {
12048
+ case "ENOENT":
12049
+ return fileError(ERROR_PATH_NOT_FOUND, message);
12050
+ case "ENOTDIR":
12051
+ return fileError(ERROR_NOT_A_DIRECTORY, message);
12052
+ case "EACCES":
12053
+ case "EPERM":
12054
+ return fileError(ERROR_PERMISSION_DENIED, message);
12055
+ default:
12056
+ return fileError(ERROR_FILE_OPERATION_FAILED, message);
12057
+ }
12058
+ }
12059
+ function compareNames(left, right) {
12060
+ const byCollator = NAME_COLLATOR.compare(left, right);
12061
+ if (byCollator !== 0) return byCollator;
12062
+ if (left === right) return 0;
12063
+ return left < right ? -1 : 1;
12064
+ }
12065
+ async function readSortKeys(folder, dirents, dependencies, paths) {
12066
+ const keys = /* @__PURE__ */ new Map();
12067
+ await Promise.all(dirents.map(async (dirent) => {
12068
+ try {
12069
+ const stats = await dependencies.fs.lstat(paths.join(folder, dirent.name));
12070
+ keys.set(dirent.name, {
12071
+ sizeBytes: stats.isFile() ? stats.size : 0,
12072
+ modifiedMillis: stats.mtimeMs,
12073
+ createdMillis: stats.birthtimeMs
12074
+ });
12075
+ } catch {
12076
+ keys.set(dirent.name, { sizeBytes: 0, modifiedMillis: 0, createdMillis: 0 });
12077
+ }
12078
+ }));
12079
+ return keys;
12080
+ }
12081
+ function sortDirents(dirents, sortBy, descending, keys) {
12082
+ const direction = descending ? -1 : 1;
12083
+ return [...dirents].sort((left, right) => {
12084
+ const leftIsFolder = left.isDirectory();
12085
+ if (leftIsFolder !== right.isDirectory()) {
12086
+ return leftIsFolder ? -1 : 1;
12087
+ }
12088
+ let order = 0;
12089
+ if (keys && sortBy === SORT_BY_SIZE && !leftIsFolder) {
12090
+ order = keys.get(left.name).sizeBytes - keys.get(right.name).sizeBytes;
12091
+ } else if (keys && sortBy === SORT_BY_MODIFIED) {
12092
+ order = keys.get(left.name).modifiedMillis - keys.get(right.name).modifiedMillis;
12093
+ } else if (keys && sortBy === SORT_BY_CREATED) {
12094
+ order = keys.get(left.name).createdMillis - keys.get(right.name).createdMillis;
12095
+ }
12096
+ if (order === 0) {
12097
+ order = compareNames(left.name, right.name);
12098
+ }
12099
+ return order * direction;
12100
+ });
12101
+ }
12102
+ async function describeEntry(folder, dirent, dependencies, paths) {
12103
+ const fullPath = paths.join(folder, dirent.name);
12104
+ let stats;
12105
+ try {
12106
+ stats = await dependencies.fs.lstat(fullPath);
12107
+ } catch {
12108
+ return { name: dirent.name, type: "unknown" };
12109
+ }
12110
+ const type = entryTypeOf(stats);
12111
+ const entry = { name: dirent.name, type, modified_at: epochSeconds(stats.mtimeMs) };
12112
+ if (stats.birthtimeMs > 0) {
12113
+ entry.created_at = epochSeconds(stats.birthtimeMs);
12114
+ }
12115
+ if (type === "file") {
12116
+ entry.size_bytes = stats.size;
12117
+ }
12118
+ if (dirent.name.startsWith(HIDDEN_NAME_PREFIX)) {
12119
+ entry.hidden = true;
12120
+ }
12121
+ if (type === "symlink") {
12122
+ const { linkTarget, targetType } = await readLinkTarget(fullPath, dependencies.fs);
12123
+ if (linkTarget !== void 0) {
12124
+ entry.link_target = linkTarget;
12125
+ }
12126
+ if (targetType !== void 0) {
12127
+ entry.target_type = targetType;
12128
+ }
12129
+ }
12130
+ return entry;
12131
+ }
12132
+ async function listRoots(dependencies) {
12133
+ if (dependencies.platform !== "win32") {
12134
+ return [POSIX_ROOT];
12135
+ }
12136
+ const drives = [...WINDOWS_DRIVE_LETTERS].map((letter) => `${letter}:\\`);
12137
+ const answers = await Promise.all(drives.map((drive) => withTimeout(
12138
+ dependencies.fs.access(drive).then(() => true),
12139
+ ROOT_PROBE_TIMEOUT_MILLIS,
12140
+ false
12141
+ )));
12142
+ return drives.filter((_drive, index) => answers[index]);
12143
+ }
12144
+ async function listFolder(request2, maxPayloadBytes, dependencies = machineFileSystemDependencies) {
12145
+ try {
12146
+ return await listFolderOrThrow(request2, maxPayloadBytes, dependencies);
12147
+ } catch (err) {
12148
+ return folderReadFailure(err);
12149
+ }
12150
+ }
12151
+ async function listFolderOrThrow(request2, maxPayloadBytes, dependencies) {
12152
+ const paths = pathsFor(dependencies.platform);
12153
+ const firstOpen = request2.path === void 0;
12154
+ let folder;
12155
+ if (request2.path === void 0) {
12156
+ folder = paths.resolve(dependencies.fs.homedir());
12157
+ } else {
12158
+ const problem = pathProblem(request2.path, paths);
12159
+ if (problem) {
12160
+ return fileError(ERROR_INVALID_PATH, problem);
12161
+ }
12162
+ folder = paths.resolve(request2.path);
12163
+ }
12164
+ let dirents;
12165
+ try {
12166
+ dirents = await dependencies.fs.readdir(folder);
12167
+ } catch (err) {
12168
+ return folderReadFailure(err);
12169
+ }
12170
+ const visible = request2.include_hidden ? dirents : dirents.filter((dirent) => !dirent.name.startsWith(HIDDEN_NAME_PREFIX));
12171
+ const sortBy = request2.sort_by ?? SORT_BY_NAME;
12172
+ const keys = sortBy === SORT_BY_NAME ? null : await readSortKeys(folder, visible, dependencies, paths);
12173
+ const sorted = sortDirents(visible, sortBy, request2.sort_order === SORT_ORDER_DESC, keys);
12174
+ const offset = request2.offset ?? 0;
12175
+ const limit = request2.limit ?? DEFAULT_LIST_LIMIT;
12176
+ const page = sorted.slice(offset, offset + limit);
12177
+ const described = await Promise.all(page.map((dirent) => describeEntry(folder, dirent, dependencies, paths)));
12178
+ const parent = paths.dirname(folder);
12179
+ const answer = {
12180
+ path: folder,
12181
+ ...parent !== folder ? { parent } : {},
12182
+ separator: paths.sep,
12183
+ total: visible.length,
12184
+ offset,
12185
+ entries: []
12186
+ };
12187
+ if (firstOpen) {
12188
+ answer.home = folder;
12189
+ answer.roots = await listRoots(dependencies);
12190
+ }
12191
+ let payloadBytes = utf8Bytes({ ...answer, next_offset: WIDEST_NEXT_OFFSET });
12192
+ for (const entry of described) {
12193
+ const entryBytes = utf8Bytes(entry) + (answer.entries.length > 0 ? 1 : 0);
12194
+ if (payloadBytes + entryBytes > maxPayloadBytes) {
12195
+ break;
12196
+ }
12197
+ answer.entries.push(entry);
12198
+ payloadBytes += entryBytes;
12199
+ }
12200
+ if (described.length > 0 && answer.entries.length === 0) {
12201
+ return fileError(ERROR_FILE_OPERATION_FAILED, "The next entry does not fit in 1 frame.");
12202
+ }
12203
+ const nextOffset = offset + answer.entries.length;
12204
+ if (nextOffset < visible.length) {
12205
+ answer.next_offset = nextOffset;
12206
+ }
12207
+ return answer;
12208
+ }
12209
+ var ROOT_PROBE_TIMEOUT_MILLIS, WINDOWS_DRIVE_LETTERS, POSIX_ROOT, WIDEST_NEXT_OFFSET, NAME_COLLATOR, MESSAGE_LIST_FAILED;
12210
+ var init_fileList = __esm({
12211
+ "src/devices/files/fileList.ts"() {
12212
+ "use strict";
12213
+ init_cjs_shims();
12214
+ init_file_schema();
12215
+ init_fileSystem();
12216
+ ROOT_PROBE_TIMEOUT_MILLIS = 2e3;
12217
+ WINDOWS_DRIVE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
12218
+ POSIX_ROOT = "/";
12219
+ WIDEST_NEXT_OFFSET = Number.MAX_SAFE_INTEGER;
12220
+ NAME_COLLATOR = new Intl.Collator(void 0, { numeric: true, sensitivity: "base" });
12221
+ MESSAGE_LIST_FAILED = "The folder could not be read.";
12222
+ }
12223
+ });
12224
+
12225
+ // src/devices/files/fileMkdir.ts
12226
+ async function makeFolder(request2, dependencies) {
12227
+ const { maker, platform: platform3, callTimeoutMillis } = dependencies;
12228
+ const paths = pathsFor(platform3);
12229
+ const pathIssue = pathProblem(request2.path, paths);
12230
+ if (pathIssue) {
12231
+ return fileError(ERROR_INVALID_PATH, pathIssue);
12232
+ }
12233
+ const item = withTrimmedName(resolvedItem(request2.path, paths));
12234
+ if (!isRoot(item.path, paths)) {
12235
+ const nameIssue = nameProblem(item.name, platform3);
12236
+ if (nameIssue) {
12237
+ return fileError(ERROR_INVALID_PAYLOAD2, nameIssue);
12238
+ }
12239
+ const windowsIssue = platform3 === "win32" ? windowsNameProblem(item.name) : null;
12240
+ if (windowsIssue) {
12241
+ return fileError(ERROR_INVALID_NAME, windowsIssue);
12242
+ }
12243
+ }
12244
+ try {
12245
+ await callWithTimeout(maker.mkdir(item.path), callTimeoutMillis);
12246
+ } catch (err) {
12247
+ return mkdirFailure(err);
12248
+ }
12249
+ return { path: item.path };
12250
+ }
12251
+ function mkdirFailure(err) {
12252
+ if (err instanceof FileCallTimeoutError) {
12253
+ return fileError(ERROR_FILE_TIMEOUT, err.message);
12254
+ }
12255
+ const message = failureMessage(err, MESSAGE_MKDIR_FAILED);
12256
+ switch (errorCodeOf(err)) {
12257
+ case "EEXIST":
12258
+ return fileError(ERROR_FILE_EXISTS, MESSAGE_NAME_TAKEN);
12259
+ case "ENOENT":
12260
+ return fileError(ERROR_PATH_NOT_FOUND, message);
12261
+ case "ENOTDIR":
12262
+ return fileError(ERROR_NOT_A_DIRECTORY, message);
12263
+ case "EACCES":
12264
+ case "EPERM":
12265
+ case "EROFS":
12266
+ return fileError(ERROR_PERMISSION_DENIED, message);
12267
+ default:
12268
+ return fileError(ERROR_FILE_OPERATION_FAILED, message);
12269
+ }
12270
+ }
12271
+ var MESSAGE_MKDIR_FAILED;
12272
+ var init_fileMkdir = __esm({
12273
+ "src/devices/files/fileMkdir.ts"() {
12274
+ "use strict";
12275
+ init_cjs_shims();
12276
+ init_file_schema();
12277
+ init_fileSystem();
12278
+ MESSAGE_MKDIR_FAILED = "The folder could not be made.";
12279
+ }
12280
+ });
12281
+
12282
+ // src/devices/files/fileMove.ts
12283
+ async function prepareMove(request2, dependencies) {
12284
+ try {
12285
+ return await checkedMove(request2, dependencies);
12286
+ } catch (err) {
12287
+ return refusalOf(err);
12288
+ }
12289
+ }
12290
+ async function checkedMove(request2, dependencies) {
12291
+ const { copier, platform: platform3 } = dependencies;
12292
+ const paths = pathsFor(platform3);
12293
+ const { source, destination } = resolvedItems(request2, paths);
12294
+ checkTargetName(destination.name, platform3);
12295
+ const sourceStats = await sourceItemStats(source.path, copier, MESSAGE_MOVE_FAILED);
12296
+ const sourceFolderStats = await folderStats(source.parent, copier);
12297
+ const destinationStats = await folderStats(destination.parent, copier);
12298
+ const sameFolder = identityOf(sourceFolderStats) === identityOf(destinationStats);
12299
+ await refuseIntoItself(sourceStats, destination.parent, dependencies, MESSAGE_INTO_ITSELF2);
12300
+ if (sameFolder && destination.name === source.name) {
12301
+ throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_ALREADY_HERE));
12302
+ }
12303
+ const protectedSet = await readProtectedFolders(dependencies);
12304
+ const sourceGuard = await removalGuard(source.parent, sourceFolderStats, protectedSet, dependencies);
12305
+ const sourceRefusal = protectedRefusal(sourceStats, sourceFolderStats.dev, sourceGuard, MESSAGE_SELECTED_MOUNT2);
12306
+ if (sourceRefusal) {
12307
+ throw new RequestRefusal({ error: sourceRefusal });
12308
+ }
12309
+ const onConflict = request2.on_conflict ?? ON_CONFLICT_FAIL;
12310
+ if (onConflict === ON_CONFLICT_FAIL || onConflict === ON_CONFLICT_REPLACE) {
12311
+ await checkTarget(onConflict, source, destination, sourceStats, sameFolder, dependencies);
12312
+ }
12313
+ const replaceGuard = onConflict === ON_CONFLICT_REPLACE ? await removalGuard(destination.parent, destinationStats, protectedSet, dependencies) : null;
12314
+ return {
12315
+ source: source.path,
12316
+ sourceStats,
12317
+ sourceName: source.name,
12318
+ destinationDirectory: destination.parent,
12319
+ targetName: destination.name,
12320
+ onConflict,
12321
+ destinationDevice: destinationStats.dev,
12322
+ sameFolder,
12323
+ acrossDisks: sourceFolderStats.dev !== destinationStats.dev,
12324
+ sourceGuard,
12325
+ replaceGuard
12326
+ };
12327
+ }
12328
+ async function checkTarget(onConflict, source, destination, sourceStats, sameFolder, dependencies) {
12329
+ const target = await lstatOrNull(destination.path, dependencies.copier);
12330
+ if (target === null || isCaseOnlyRename(sameFolder, source.name, destination.name, sourceStats, target)) {
12331
+ return;
12332
+ }
12333
+ if (onConflict === ON_CONFLICT_REPLACE) {
12334
+ if (identityOf(target) === identityOf(sourceStats)) {
12335
+ throw new RequestRefusal(fileError(ERROR_INVALID_DESTINATION, MESSAGE_REPLACE_ITSELF));
12336
+ }
12337
+ await refuseReplacingAHolder(target, source.parent, dependencies);
12338
+ return;
12339
+ }
12340
+ throw new RequestRefusal(targetTakenRefusal());
12341
+ }
12342
+ function isCaseOnlyRename(sameFolder, name, targetName, source, target) {
12343
+ return sameFolder && source !== null && name !== targetName && foldedName(name) === foldedName(targetName) && identityOf(source) === identityOf(target);
12344
+ }
12345
+ function foldedName(name) {
12346
+ return name.normalize("NFC").toLowerCase();
12347
+ }
12348
+ function moveProgress(prepared) {
12349
+ const progress = {
12350
+ items_done: 0,
12351
+ items_total: 1,
12352
+ files_done: 0,
12353
+ bytes_done: 0,
12354
+ current_name: prepared.sourceName
12355
+ };
12356
+ if (!prepared.acrossDisks) {
12357
+ progress.files_total = 1;
12358
+ progress.bytes_total = 0;
12359
+ }
12360
+ return progress;
12361
+ }
12362
+ async function runMove(prepared, progress, dependencies) {
12363
+ const counted = Object.assign(progress, { bytes_done: progress.bytes_done ?? 0 });
12364
+ const item = {
12365
+ name: prepared.sourceName,
12366
+ targetName: prepared.targetName,
12367
+ source: prepared.source,
12368
+ stats: prepared.sourceStats
12369
+ };
12370
+ if (prepared.acrossDisks) {
12371
+ const refusal = await countAcross(item, prepared, counted, dependencies);
12372
+ if (refusal) {
12373
+ return refusal;
12374
+ }
12375
+ }
12376
+ const outcome = await moveItem(item, prepared, counted, dependencies);
12377
+ counted.items_done += 1;
12378
+ return outcomeAnswer(outcome);
12379
+ }
12380
+ async function countAcross(item, prepared, progress, dependencies) {
12381
+ const paths = pathsFor(dependencies.platform);
12382
+ const target = paths.join(prepared.destinationDirectory, item.targetName);
12383
+ if (prepared.onConflict === ON_CONFLICT_SKIP && await lstatOrNull(target, dependencies.copier).catch(() => null)) {
12384
+ progress.files_total = 0;
12385
+ progress.bytes_total = 0;
12386
+ return null;
12387
+ }
12388
+ const totals = await countItem(item, dependencies);
12389
+ const refusal = countRefusal(totals, item.stats);
12390
+ if (refusal) {
12391
+ return { error: refusal };
12392
+ }
12393
+ progress.files_total = totals.files;
12394
+ progress.bytes_total = totals.bytes;
12395
+ return noSpaceRefusal(totals.bytes, prepared.destinationDirectory, dependencies.copier);
12396
+ }
12397
+ async function countItem(item, dependencies) {
12398
+ const totals = newCountTotals();
12399
+ await countEntry(item.source, totals, dependencies.copier, pathsFor(dependencies.platform), item.stats.dev);
12400
+ return totals;
12401
+ }
12402
+ function countRefusal(totals, stats) {
12403
+ if (totals.mountedDisks > 0) {
12404
+ return { code: ERROR_MOUNT_POINT, message: MESSAGE_MOUNT_INSIDE2 };
12405
+ }
12406
+ if (isSpecial(stats)) {
12407
+ return { code: ERROR_SPECIAL_FILE, message: MESSAGE_SPECIAL_SELECTED2 };
12408
+ }
12409
+ return totals.specialFiles > 0 ? specialInside(totals.specialFiles) : null;
12410
+ }
12411
+ function specialInside(count) {
12412
+ const message = count === 1 ? "This folder holds 1 socket, pipe or device file, which cannot be moved to another disk." : `This folder holds ${count} sockets, pipes or device files, which cannot be moved to another disk.`;
12413
+ return { code: ERROR_SPECIAL_FILE, message };
12414
+ }
12415
+ async function moveItem(item, prepared, progress, dependencies) {
12416
+ if (prepared.acrossDisks) {
12417
+ return moveAcross(item, prepared, progress, dependencies);
12418
+ }
12419
+ try {
12420
+ const placement = await placeAt(item.source, item, prepared, dependencies, dependencies.hiddenNameSuffix());
12421
+ if (!placement.placed) {
12422
+ return placement.outcome;
12423
+ }
12424
+ progress.files_done += 1;
12425
+ return placement.oldStays;
12426
+ } catch (err) {
12427
+ if (errorCodeOf(err) !== "EXDEV") {
12428
+ return moveFailure(err);
12429
+ }
12430
+ }
12431
+ const totals = await countItem(item, dependencies);
12432
+ const refusal = countRefusal(totals, item.stats);
12433
+ if (refusal) {
12434
+ return refusal;
12435
+ }
12436
+ progress.files_total = (progress.files_total ?? 0) + totals.files - 1;
12437
+ progress.bytes_total = (progress.bytes_total ?? 0) + totals.bytes;
12438
+ return moveAcross(item, prepared, progress, dependencies);
12439
+ }
12440
+ async function moveAcross(item, prepared, progress, dependencies) {
12441
+ const { copier, platform: platform3 } = dependencies;
12442
+ const paths = pathsFor(platform3);
12443
+ const { protectedSet } = prepared.sourceGuard;
12444
+ try {
12445
+ const settledFirst = await targetBeforeCopy(item, prepared, dependencies);
12446
+ if (settledFirst) {
12447
+ return settledFirst;
12448
+ }
12449
+ } catch (err) {
12450
+ return moveFailure(err);
12451
+ }
12452
+ const suffix = dependencies.hiddenNameSuffix();
12453
+ const hiddenCopy = paths.join(prepared.destinationDirectory, hiddenName(item.targetName, HIDDEN_MOVE_MARK, suffix));
12454
+ const walk = { copier, paths, platform: platform3, progress, specialFilesLeftOut: 0 };
12455
+ let placement;
12456
+ try {
12457
+ await copyEntry(item.source, item.stats, hiddenCopy, walk, true);
12458
+ if (walk.specialFilesLeftOut > 0) {
12459
+ await removeQuietly2(hiddenCopy, protectedSet, dependencies);
12460
+ return specialInside(walk.specialFilesLeftOut);
12461
+ }
12462
+ placement = await placeAt(hiddenCopy, item, prepared, dependencies, suffix);
12463
+ } catch (err) {
12464
+ if (!(err instanceof TakenError)) {
12465
+ await removeQuietly2(hiddenCopy, protectedSet, dependencies);
12466
+ }
12467
+ return moveFailure(err);
12468
+ }
12469
+ if (!placement.placed) {
12470
+ await removeQuietly2(hiddenCopy, protectedSet, dependencies);
12471
+ return placement.outcome;
12472
+ }
12473
+ return await removeOriginal(item, protectedSet, dependencies) ?? placement.oldStays;
12474
+ }
12475
+ async function targetBeforeCopy(item, prepared, dependencies) {
12476
+ if (prepared.onConflict === ON_CONFLICT_KEEP_BOTH) {
12477
+ return null;
12478
+ }
12479
+ const paths = pathsFor(dependencies.platform);
12480
+ const existing = await lstatOrNull(
12481
+ paths.join(prepared.destinationDirectory, item.targetName),
12482
+ dependencies.copier
12483
+ );
12484
+ if (existing === null) {
12485
+ return null;
12486
+ }
12487
+ switch (prepared.onConflict) {
12488
+ case ON_CONFLICT_SKIP:
12489
+ return SKIPPED;
12490
+ case ON_CONFLICT_REPLACE:
12491
+ return replaceRefusal(existing, item.stats, prepared.destinationDevice, prepared.replaceGuard);
12492
+ default:
12493
+ return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
12494
+ }
12495
+ }
12496
+ async function placeAt(incoming, item, prepared, dependencies, suffix) {
12497
+ const { copier } = dependencies;
12498
+ const paths = pathsFor(dependencies.platform);
12499
+ const target = paths.join(prepared.destinationDirectory, item.targetName);
12500
+ const existing = await lstatOrNull(target, copier);
12501
+ if (existing === null || isCaseOnlyRename(prepared.sameFolder, item.name, item.targetName, item.stats, existing)) {
12502
+ await copier.rename(incoming, target);
12503
+ return PLACED;
12504
+ }
12505
+ switch (prepared.onConflict) {
12506
+ case ON_CONFLICT_SKIP:
12507
+ return { placed: false, outcome: SKIPPED };
12508
+ case ON_CONFLICT_KEEP_BOTH:
12509
+ return placeUnderFreeName(incoming, item, prepared, dependencies);
12510
+ case ON_CONFLICT_REPLACE:
12511
+ return replaceAt(incoming, existing, item, prepared, dependencies, suffix);
12512
+ default:
12513
+ return { placed: false, outcome: { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN } };
12514
+ }
12515
+ }
12516
+ async function placeUnderFreeName(incoming, item, prepared, dependencies) {
12517
+ const paths = pathsFor(dependencies.platform);
12518
+ for (let number = 1; number <= MAX_KEEP_BOTH_NUMBER; number++) {
12519
+ const candidate = paths.join(
12520
+ prepared.destinationDirectory,
12521
+ keepBothName(item.targetName, item.stats.isDirectory(), number)
12522
+ );
12523
+ if (await lstatOrNull(candidate, dependencies.copier) === null) {
12524
+ await dependencies.copier.rename(incoming, candidate);
12525
+ return PLACED;
12526
+ }
12527
+ }
12528
+ return { placed: false, outcome: { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN } };
12529
+ }
12530
+ async function replaceAt(incoming, existing, item, prepared, dependencies, suffix) {
12531
+ const guard = prepared.replaceGuard;
12532
+ const refusal = replaceRefusal(existing, item.stats, prepared.destinationDevice, guard);
12533
+ if (refusal) {
12534
+ return { placed: false, outcome: refusal };
12535
+ }
12536
+ const paths = pathsFor(dependencies.platform);
12537
+ const oldName = await swapIn(
12538
+ incoming,
12539
+ prepared.destinationDirectory,
12540
+ item.targetName,
12541
+ existing,
12542
+ item.stats.isDirectory(),
12543
+ suffix,
12544
+ dependencies.copier,
12545
+ paths
12546
+ );
12547
+ if (oldName === null) {
12548
+ return PLACED;
12549
+ }
12550
+ const oldStays = await removeOld(
12551
+ paths.join(prepared.destinationDirectory, oldName),
12552
+ oldName,
12553
+ existing,
12554
+ guard.protectedSet,
12555
+ dependencies,
12556
+ MESSAGE_MOVED_IN_PLACE
12557
+ );
12558
+ return { placed: true, oldStays };
12559
+ }
12560
+ async function removeOriginal(item, protectedSet, dependencies) {
12561
+ try {
12562
+ if (await removeTree(item.source, item.stats, protectedSet, deleteDependencies(dependencies))) {
12563
+ return null;
12564
+ }
12565
+ return { code: ERROR_MOUNT_POINT, message: `${MESSAGE_ORIGINAL_STAYS} ${REASON_MOUNT_INSIDE}` };
12566
+ } catch (err) {
12567
+ const failure2 = deleteFailure(err);
12568
+ const message = sanitizeErrorMessage(`${MESSAGE_ORIGINAL_STAYS} ${failure2.message}`) ?? failure2.message;
12569
+ return { code: failure2.code, message };
12570
+ }
12571
+ }
12572
+ function moveFailure(err) {
12573
+ switch (errorCodeOf(err)) {
12574
+ case "EBUSY":
12575
+ return { code: ERROR_PERMISSION_DENIED, message: failureMessage(err, MESSAGE_MOVE_FAILED) };
12576
+ case "ENOTEMPTY":
12577
+ case "EISDIR":
12578
+ return { code: ERROR_FILE_EXISTS, message: MESSAGE_NAME_TAKEN };
12579
+ default:
12580
+ return copyFailure(err, MESSAGE_MOVE_FAILED);
12581
+ }
12582
+ }
12583
+ var HIDDEN_MOVE_MARK, MESSAGE_INTO_ITSELF2, MESSAGE_ALREADY_HERE, MESSAGE_SELECTED_MOUNT2, MESSAGE_MOUNT_INSIDE2, MESSAGE_SPECIAL_SELECTED2, MESSAGE_MOVED_IN_PLACE, MESSAGE_ORIGINAL_STAYS, MESSAGE_MOVE_FAILED, PLACED;
12584
+ var init_fileMove = __esm({
12585
+ "src/devices/files/fileMove.ts"() {
12586
+ "use strict";
12587
+ init_cjs_shims();
12588
+ init_tunnelList();
12589
+ init_file_schema();
12590
+ init_fileCopy();
12591
+ init_fileDelete();
12592
+ init_fileProtectedPaths();
12593
+ init_fileSystem();
12594
+ HIDDEN_MOVE_MARK = "move";
12595
+ MESSAGE_INTO_ITSELF2 = "A folder cannot be moved into itself.";
12596
+ MESSAGE_ALREADY_HERE = "The item is already in this folder.";
12597
+ MESSAGE_SELECTED_MOUNT2 = "This folder is a mounted disk. Open it to move what is inside.";
12598
+ MESSAGE_MOUNT_INSIDE2 = "Another disk is mounted inside. Pinggy does not move it to another disk.";
12599
+ MESSAGE_SPECIAL_SELECTED2 = "This is a socket, pipe or device file. Pinggy cannot move it to another disk.";
12600
+ MESSAGE_MOVED_IN_PLACE = "The item is in place. The old one stays as";
12601
+ MESSAGE_ORIGINAL_STAYS = "The item is in its new place. The original could not be fully removed:";
12602
+ MESSAGE_MOVE_FAILED = "The item could not be moved.";
12603
+ PLACED = { placed: true, oldStays: null };
12604
+ }
12605
+ });
12606
+
12607
+ // src/devices/files/fileStat.ts
12608
+ function lstatFailure(err) {
12609
+ const message = failureMessage(err, MESSAGE_STAT_FAILED);
12610
+ if (err instanceof FileCallTimeoutError) {
12611
+ return fileError(ERROR_FILE_TIMEOUT, message);
12612
+ }
12613
+ switch (errorCodeOf(err)) {
12614
+ case "ENOENT":
12615
+ case "ENOTDIR":
12616
+ return fileError(ERROR_PATH_NOT_FOUND, message);
12617
+ case "EACCES":
12618
+ case "EPERM":
12619
+ return fileError(ERROR_PERMISSION_DENIED, message);
12620
+ default:
12621
+ return fileError(ERROR_FILE_OPERATION_FAILED, message);
12622
+ }
12623
+ }
12624
+ function modeDigits(mode) {
12625
+ return (mode & PERMISSION_BITS_MASK).toString(OCTAL_RADIX).padStart(MODE_DIGITS, "0");
12626
+ }
12627
+ async function hasAccess(target, mode, dependencies) {
12628
+ try {
12629
+ await dependencies.fs.access(target, mode);
12630
+ return true;
12631
+ } catch {
12632
+ return false;
12633
+ }
12634
+ }
12635
+ async function countEntries(folder, includeHidden, dependencies) {
12636
+ try {
12637
+ const dirents = await dependencies.fs.readdir(folder);
12638
+ return includeHidden ? dirents.length : dirents.filter((dirent) => !dirent.name.startsWith(HIDDEN_NAME_PREFIX)).length;
12639
+ } catch {
12640
+ return void 0;
12641
+ }
12642
+ }
12643
+ async function statPath(request2, maxPayloadBytes, dependencies = machineFileSystemDependencies) {
12644
+ try {
12645
+ return await statPathOrThrow(request2, maxPayloadBytes, dependencies);
12646
+ } catch (err) {
12647
+ return fileError(ERROR_FILE_OPERATION_FAILED, failureMessage(err, MESSAGE_STAT_FAILED));
12648
+ }
12649
+ }
12650
+ async function statPathOrThrow(request2, maxPayloadBytes, dependencies) {
12651
+ const paths = pathsFor(dependencies.platform);
12652
+ const problem = pathProblem(request2.path, paths);
12653
+ if (problem) {
12654
+ return fileError(ERROR_INVALID_PATH, problem);
12655
+ }
12656
+ const target = paths.resolve(request2.path);
12657
+ let stats;
12658
+ try {
12659
+ stats = await dependencies.fs.lstat(target);
12660
+ } catch (err) {
12661
+ return lstatFailure(err);
12662
+ }
12663
+ const type = entryTypeOf(stats);
12664
+ const name = paths.basename(target) || target;
12665
+ const onWindows = dependencies.platform === "win32";
12666
+ const answer = {
12667
+ path: target,
12668
+ name,
12669
+ type,
12670
+ ...type === "file" ? { size_bytes: stats.size } : {},
12671
+ modified_at: epochSeconds(stats.mtimeMs),
12672
+ accessed_at: epochSeconds(stats.atimeMs),
12673
+ // 0 is a filesystem with no birth time. Some report the change time instead, which cannot be told apart.
12674
+ ...stats.birthtimeMs > 0 ? { created_at: epochSeconds(stats.birthtimeMs) } : {},
12675
+ ...name.startsWith(HIDDEN_NAME_PREFIX) ? { hidden: true } : {}
12676
+ };
12677
+ if (!onWindows) {
12678
+ answer.mode = modeDigits(stats.mode);
12679
+ answer.uid = stats.uid;
12680
+ answer.gid = stats.gid;
12681
+ }
12682
+ if (!onWindows && type !== "symlink") {
12683
+ const [readable, writable, executable] = await Promise.all([
12684
+ hasAccess(target, import_fs11.default.constants.R_OK, dependencies),
12685
+ hasAccess(target, import_fs11.default.constants.W_OK, dependencies),
12686
+ hasAccess(target, import_fs11.default.constants.X_OK, dependencies)
12687
+ ]);
12688
+ Object.assign(answer, { readable, writable, executable });
12689
+ }
12690
+ if (type === "directory") {
12691
+ const entryCount = await countEntries(target, request2.include_hidden === true, dependencies);
12692
+ if (entryCount !== void 0) {
12693
+ answer.entry_count = entryCount;
12694
+ }
12695
+ }
12696
+ if (type === "symlink") {
12697
+ const { linkTarget, targetType, targetStats } = await readLinkTarget(target, dependencies.fs);
12698
+ if (linkTarget !== void 0) {
12699
+ answer.link_target = linkTarget;
12700
+ }
12701
+ if (targetType !== void 0) {
12702
+ answer.target_type = targetType;
12703
+ }
12704
+ if (targetStats?.isFile()) {
12705
+ answer.target_size_bytes = targetStats.size;
12706
+ }
12707
+ }
12708
+ if (utf8Bytes(answer) > maxPayloadBytes) {
12709
+ delete answer.link_target;
12710
+ }
12711
+ if (utf8Bytes(answer) > maxPayloadBytes) {
12712
+ return fileError(ERROR_FILE_OPERATION_FAILED, MESSAGE_TOO_LARGE);
12713
+ }
12714
+ return answer;
12715
+ }
12716
+ var import_fs11, PERMISSION_BITS_MASK, OCTAL_RADIX, MODE_DIGITS, MESSAGE_STAT_FAILED, MESSAGE_TOO_LARGE;
12717
+ var init_fileStat = __esm({
12718
+ "src/devices/files/fileStat.ts"() {
12719
+ "use strict";
12720
+ init_cjs_shims();
12721
+ import_fs11 = __toESM(require("fs"), 1);
12722
+ init_file_schema();
12723
+ init_fileSystem();
12724
+ PERMISSION_BITS_MASK = 4095;
12725
+ OCTAL_RADIX = 8;
12726
+ MODE_DIGITS = 4;
12727
+ MESSAGE_STAT_FAILED = "The path could not be read.";
12728
+ MESSAGE_TOO_LARGE = "The details are too large to send.";
12729
+ }
12730
+ });
12731
+
12732
+ // src/devices/files/fileHandler.ts
12733
+ function afterThisTurn(work) {
12734
+ return Promise.resolve().then(work);
12735
+ }
12736
+ function sameProgress(left, right) {
12737
+ return left.items_done === right.items_done && left.files_done === right.files_done && left.bytes_done === right.bytes_done && left.files_total === right.files_total && left.bytes_total === right.bytes_total && left.current_name === right.current_name;
12738
+ }
12739
+ function invalidPayload() {
12740
+ return fileError(ERROR_INVALID_PAYLOAD2, "The file request could not be read.");
12741
+ }
12742
+ function busy(limit, waiting) {
12743
+ if (limit <= 0) {
12744
+ return fileError(ERROR_FILE_BUSY, "The dashboard allows no file operations on this device.");
12745
+ }
12746
+ const noun = limit === 1 ? "file operation" : "file operations";
12747
+ const running = `The device is already running ${limit} ${noun}`;
12748
+ if (waiting <= 0) {
12749
+ return fileError(ERROR_FILE_BUSY, `${running}.`);
12750
+ }
12751
+ const verb = waiting === 1 ? "is" : "are";
12752
+ return fileError(ERROR_FILE_BUSY, `${running}, and ${waiting} more ${verb} waiting.`);
12753
+ }
12754
+ var DEFAULT_READ_TIMEOUT_MILLIS, DEFAULT_DELETE_CALL_TIMEOUT_MILLIS, DEFAULT_MKDIR_TIMEOUT_MILLIS, DEFAULT_COPY_CALL_TIMEOUT_MILLIS, DEFAULT_FILE_CALL_PLACES, MILLIS_PER_SECOND2, PROGRESS_TICK_MILLIS, PROGRESS_KEEPALIVE_TICKS, QUEUED_KEEPALIVE_MILLIS, NULL_PAYLOAD_BYTES, OUTCOME_ANSWERED, FILE_ACCESS_OFF_MESSAGE, HANDLED_OPS, FileHandler;
12755
+ var init_fileHandler = __esm({
12756
+ "src/devices/files/fileHandler.ts"() {
12757
+ "use strict";
12758
+ init_cjs_shims();
12759
+ init_logger();
12760
+ init_envelope();
12761
+ init_file_schema();
12762
+ init_fileCallGate();
12763
+ init_fileCopy();
12764
+ init_fileDelete();
12765
+ init_fileList();
12766
+ init_fileMkdir();
12767
+ init_fileMove();
12768
+ init_fileProtectedPaths();
12769
+ init_fileStat();
12770
+ init_fileSystem();
12771
+ DEFAULT_READ_TIMEOUT_MILLIS = 2e4;
12772
+ DEFAULT_DELETE_CALL_TIMEOUT_MILLIS = 2e4;
12773
+ DEFAULT_MKDIR_TIMEOUT_MILLIS = 2e4;
12774
+ DEFAULT_COPY_CALL_TIMEOUT_MILLIS = 2e4;
12775
+ DEFAULT_FILE_CALL_PLACES = 2;
12776
+ MILLIS_PER_SECOND2 = 1e3;
12777
+ PROGRESS_TICK_MILLIS = 1e3;
12778
+ PROGRESS_KEEPALIVE_TICKS = 5;
12779
+ QUEUED_KEEPALIVE_MILLIS = PROGRESS_TICK_MILLIS * PROGRESS_KEEPALIVE_TICKS;
12780
+ NULL_PAYLOAD_BYTES = Buffer.byteLength("null", "utf8");
12781
+ OUTCOME_ANSWERED = "answered";
12782
+ FILE_ACCESS_OFF_MESSAGE = "File access is off on this device. To allow it, run on the device: pinggy device connect --files on";
12783
+ HANDLED_OPS = /* @__PURE__ */ new Set([OP_LIST, OP_STAT, OP_DELETE, OP_MKDIR, OP_COPY, OP_MOVE]);
12784
+ FileHandler = class {
12785
+ constructor(dependencies) {
12786
+ this.dependencies = dependencies;
12787
+ this.enabled = false;
12788
+ this.maxFrameBytes = 0;
12789
+ this.maxConcurrentOperations = 0;
12790
+ this.maxQueuedOperations = 0;
12791
+ this.runningOperations = 0;
12792
+ /** Oldest first. The first is the next to start. */
12793
+ this.waitingOperations = [];
12794
+ this.queuedKeepalive = null;
12795
+ const gate = new FileCallGate(dependencies.fileCallPlaces ?? DEFAULT_FILE_CALL_PLACES);
12796
+ const fileSystem = dependencies.fileSystem ?? machineFileSystemDependencies;
12797
+ this.gatedFileSystem = {
12798
+ platform: fileSystem.platform,
12799
+ fs: gatedReader(fileSystem.fs, gate, this.readTimeoutMillis())
12800
+ };
12801
+ this.gatedRemover = gatedRemover(
12802
+ dependencies.remover ?? machineFileSystemRemover,
12803
+ gate,
12804
+ this.deleteCallTimeoutMillis()
12805
+ );
12806
+ this.gatedMaker = gatedMaker(dependencies.maker ?? machineFileSystemMaker, gate, this.mkdirTimeoutMillis());
12807
+ this.gatedCopier = gatedCopier(
12808
+ dependencies.copier ?? machineFileSystemCopier,
12809
+ gate,
12810
+ this.copyCallTimeoutMillis()
12811
+ );
12812
+ }
12813
+ /**
12814
+ * From each `welcome`. `max_frame_bytes` is the dashboard's cap on 1 frame from this agent. Without
12815
+ * `file_max_concurrent_operations`, no delete, copy or move runs, and without `file_max_queued_operations`, none
12816
+ * waits. Requests already waiting keep their place: more slots start them, and no slot at all refuses them with
12817
+ * `file_busy`, since none would ever start.
12818
+ */
12819
+ configure(fileManagerEnabled, maxFrameBytes, maxConcurrentOperations, maxQueuedOperations) {
12820
+ this.enabled = fileManagerEnabled === true;
12821
+ this.maxFrameBytes = maxFrameBytes;
12822
+ this.maxConcurrentOperations = maxConcurrentOperations ?? 0;
12823
+ this.maxQueuedOperations = maxQueuedOperations ?? 0;
12824
+ this.admitWaiting();
12825
+ }
12826
+ async handle(envelope) {
12827
+ if (envelope.kind !== "req") {
12828
+ return;
12829
+ }
12830
+ if (!HANDLED_OPS.has(envelope.op)) {
12831
+ this.answer(envelope, fileError(ERROR_UNSUPPORTED_OP2, `Unsupported operation: file/${envelope.op}`));
12832
+ return;
12833
+ }
12834
+ if (!this.enabled) {
12835
+ this.answer(envelope, fileError(ERROR_FILE_MANAGER_DISABLED, "The file manager is disabled."));
12836
+ return;
12837
+ }
12838
+ if (this.dependencies.fileAccessAllowed?.() === false) {
12839
+ this.answer(envelope, fileError(ERROR_FILE_ACCESS_OFF, FILE_ACCESS_OFF_MESSAGE));
12840
+ return;
12841
+ }
12842
+ this.answer(envelope, await this.run(envelope));
12843
+ }
12844
+ run(envelope) {
12845
+ switch (envelope.op) {
12846
+ case OP_LIST:
12847
+ return this.list(envelope);
12848
+ case OP_STAT:
12849
+ return this.stat(envelope);
12850
+ case OP_MKDIR:
12851
+ return this.mkdir(envelope);
12852
+ case OP_COPY:
12853
+ return this.copy(envelope);
12854
+ case OP_MOVE:
12855
+ return this.move(envelope);
12856
+ default:
12857
+ return this.delete(envelope);
12858
+ }
12859
+ }
12860
+ list(envelope) {
12861
+ const parsed = FileListRequestSchema.safeParse(envelope.payload);
12862
+ if (!parsed.success) {
12863
+ return Promise.resolve(invalidPayload());
12864
+ }
12865
+ const listing = afterThisTurn(() => listFolder(parsed.data, this.payloadBudget(envelope), this.fileSystem()));
12866
+ return withTimeout(listing, this.readTimeoutMillis(), this.timedOut("The folder"));
12867
+ }
12868
+ stat(envelope) {
12869
+ const parsed = FileStatRequestSchema.safeParse(envelope.payload);
12870
+ if (!parsed.success) {
12871
+ return Promise.resolve(invalidPayload());
12872
+ }
12873
+ const details = afterThisTurn(() => statPath(parsed.data, this.payloadBudget(envelope), this.fileSystem()));
12874
+ return withTimeout(details, this.readTimeoutMillis(), this.timedOut("The path"));
12875
+ }
12876
+ mkdir(envelope) {
12877
+ const parsed = FileMkdirRequestSchema.safeParse(envelope.payload);
12878
+ if (!parsed.success) {
12879
+ return Promise.resolve(invalidPayload());
12880
+ }
12881
+ return makeFolder(parsed.data, {
12882
+ maker: this.gatedMaker,
12883
+ platform: this.fileSystem().platform,
12884
+ callTimeoutMillis: this.mkdirTimeoutMillis()
12885
+ });
12886
+ }
12887
+ delete(envelope) {
12888
+ const parsed = FileDeleteRequestSchema.safeParse(envelope.payload);
12889
+ if (!parsed.success) {
12890
+ return Promise.resolve(invalidPayload());
12891
+ }
12892
+ return this.inSlot(envelope, "delete", () => this.deleteInSlot(envelope, parsed.data));
12893
+ }
12894
+ copy(envelope) {
12895
+ const parsed = FileCopyRequestSchema.safeParse(envelope.payload);
12896
+ if (!parsed.success) {
12897
+ return Promise.resolve(invalidPayload());
12898
+ }
12899
+ return this.inSlot(envelope, "copy", () => this.copyInSlot(envelope, parsed.data));
12900
+ }
12901
+ move(envelope) {
12902
+ const parsed = FileCopyRequestSchema.safeParse(envelope.payload);
12903
+ if (!parsed.success) {
12904
+ return Promise.resolve(invalidPayload());
12905
+ }
12906
+ return this.inSlot(envelope, "move", () => this.moveInSlot(envelope, parsed.data));
12907
+ }
12908
+ /** Holds 1 slot from {@link takeSlot} to the answer. */
12909
+ async inSlot(envelope, operation, work) {
12910
+ const refusal = await this.takeSlot(envelope);
12911
+ if (refusal) {
12912
+ return refusal;
12913
+ }
12914
+ try {
12915
+ return await work();
12916
+ } catch (err) {
12917
+ logger.warn(`Device agent file ${operation} stopped`, { id: envelope.id, code: errorCodeOf(err) });
12918
+ return fileError(ERROR_FILE_OPERATION_FAILED, `The ${operation} stopped unexpectedly.`);
12919
+ } finally {
12920
+ this.runningOperations -= 1;
12921
+ this.admitWaiting();
12922
+ }
12923
+ }
12924
+ /**
12925
+ * Null once this request holds a slot: at once when 1 is free and nobody waits, else when its turn in line
12926
+ * comes. `file_busy` at once when the line is full, or no slot is allowed.
12927
+ */
12928
+ takeSlot(envelope) {
12929
+ if (this.runningOperations < this.maxConcurrentOperations && this.waitingOperations.length === 0) {
12930
+ this.runningOperations += 1;
12931
+ return Promise.resolve(null);
12932
+ }
12933
+ if (this.maxConcurrentOperations <= 0 || this.waitingOperations.length >= this.maxQueuedOperations) {
12934
+ return Promise.resolve(busy(this.maxConcurrentOperations, this.waitingOperations.length));
12935
+ }
12936
+ return new Promise((admit) => {
12937
+ this.waitingOperations.push({ envelope, admit });
12938
+ this.sendQueuedPosition(envelope, this.waitingOperations.length);
12939
+ this.startQueuedKeepalive();
12940
+ });
12941
+ }
12942
+ /**
12943
+ * Hands each free slot to the oldest request waiting, and counts it as running at once, so a request that
12944
+ * arrives before the waiting one resumes cannot take its slot. Those still waiting hear their new place.
12945
+ */
12946
+ admitWaiting() {
12947
+ if (this.waitingOperations.length === 0) {
12948
+ return;
12949
+ }
12950
+ if (this.maxConcurrentOperations <= 0) {
12951
+ const refusal = busy(this.maxConcurrentOperations, 0);
12952
+ this.waitingOperations.splice(0).forEach((waiting) => waiting.admit(refusal));
12953
+ this.stopQueuedKeepalive();
12954
+ return;
12955
+ }
12956
+ let admitted = 0;
12957
+ while (this.waitingOperations.length > 0 && this.runningOperations < this.maxConcurrentOperations) {
12958
+ this.runningOperations += 1;
12959
+ this.waitingOperations.shift().admit(null);
12960
+ admitted += 1;
12961
+ }
12962
+ if (this.waitingOperations.length === 0) {
12963
+ this.stopQueuedKeepalive();
12964
+ } else if (admitted > 0) {
12965
+ this.sendQueuedPositions();
12966
+ }
12967
+ }
12968
+ sendQueuedPosition(envelope, position) {
12969
+ const payload = { queued_position: position };
12970
+ this.dependencies.send(event(CHANNEL_FILE, OP_PROGRESS, payload, envelope.id));
12971
+ }
12972
+ sendQueuedPositions() {
12973
+ this.waitingOperations.forEach((waiting, index) => this.sendQueuedPosition(waiting.envelope, index + 1));
12974
+ }
12975
+ /** 1 timer for the whole line, running only while someone waits. */
12976
+ startQueuedKeepalive() {
12977
+ if (this.queuedKeepalive === null) {
12978
+ this.queuedKeepalive = setInterval(() => this.sendQueuedPositions(), QUEUED_KEEPALIVE_MILLIS);
12979
+ }
12980
+ }
12981
+ stopQueuedKeepalive() {
12982
+ if (this.queuedKeepalive !== null) {
12983
+ clearInterval(this.queuedKeepalive);
12984
+ this.queuedKeepalive = null;
12985
+ }
12986
+ }
12987
+ /** A refusal from the checks sends no counted `progress`: nothing was deleted, and the answer comes at once. */
12988
+ async deleteInSlot(envelope, request2) {
12989
+ const dependencies = this.deleteDependencies();
12990
+ const prepared = await prepareDelete(request2, dependencies);
12991
+ if ("error" in prepared) {
12992
+ return prepared;
12993
+ }
12994
+ const progress = { items_done: 0, items_total: 1, files_done: 0, current_name: prepared.name };
12995
+ const stopProgress = this.startProgress(envelope, progress);
12996
+ try {
12997
+ return await runDelete(prepared, progress, dependencies);
12998
+ } finally {
12999
+ stopProgress();
13000
+ }
13001
+ }
13002
+ /**
13003
+ * A refusal from the checks sends no counted `progress`: nothing was copied, and the answer comes at once.
13004
+ * `progress` starts before the count, so a large tree keeps the browser's timer alive while it is counted, and a
13005
+ * `no_space` answer follows it.
13006
+ */
13007
+ async copyInSlot(envelope, request2) {
13008
+ const dependencies = this.copyDependencies();
13009
+ const prepared = await prepareCopy(request2, dependencies);
13010
+ if ("error" in prepared) {
13011
+ return prepared;
13012
+ }
13013
+ const progress = {
13014
+ items_done: 0,
13015
+ items_total: 1,
13016
+ files_done: 0,
13017
+ bytes_done: 0,
13018
+ current_name: prepared.sourceName
13019
+ };
13020
+ const stopProgress = this.startProgress(envelope, progress);
13021
+ try {
13022
+ return await runCopy(prepared, progress, dependencies);
13023
+ } finally {
13024
+ stopProgress();
13025
+ }
13026
+ }
13027
+ /**
13028
+ * As for a copy. On 1 disk the first `progress` already holds the totals, since there is nothing to count. To
13029
+ * another disk it starts before the count, as a copy's does.
13030
+ */
13031
+ async moveInSlot(envelope, request2) {
13032
+ const dependencies = this.copyDependencies();
13033
+ const prepared = await prepareMove(request2, dependencies);
13034
+ if ("error" in prepared) {
13035
+ return prepared;
13036
+ }
13037
+ const progress = moveProgress(prepared);
13038
+ const stopProgress = this.startProgress(envelope, progress);
13039
+ try {
13040
+ return await runMove(prepared, progress, dependencies);
13041
+ } finally {
13042
+ stopProgress();
13043
+ }
13044
+ }
13045
+ /** Sends 1 `progress` now, then from a timer. Returns the stop, which the answer waits for. */
13046
+ startProgress(envelope, progress) {
13047
+ let lastSent = this.sendProgress(envelope, progress);
13048
+ let ticksSinceSent = 0;
13049
+ const timer = setInterval(() => {
13050
+ ticksSinceSent += 1;
13051
+ if (sameProgress(progress, lastSent) && ticksSinceSent < PROGRESS_KEEPALIVE_TICKS) {
13052
+ return;
13053
+ }
13054
+ lastSent = this.sendProgress(envelope, progress);
13055
+ ticksSinceSent = 0;
13056
+ }, PROGRESS_TICK_MILLIS);
13057
+ return () => clearInterval(timer);
13058
+ }
13059
+ /** Sends a snapshot, since the op keeps counting into `progress`. Returns the snapshot sent. */
13060
+ sendProgress(envelope, progress) {
13061
+ const snapshot = { ...progress };
13062
+ this.dependencies.send(event(CHANNEL_FILE, OP_PROGRESS, snapshot, envelope.id));
13063
+ return snapshot;
13064
+ }
13065
+ deleteDependencies() {
13066
+ return {
13067
+ remover: this.gatedRemover,
13068
+ platform: this.fileSystem().platform,
13069
+ protectedSources: this.dependencies.protectedSources ?? machineProtectedSources(),
13070
+ callTimeoutMillis: this.deleteCallTimeoutMillis()
13071
+ };
13072
+ }
13073
+ copyDependencies() {
13074
+ return {
13075
+ ...this.deleteDependencies(),
13076
+ copier: this.gatedCopier,
13077
+ hiddenNameSuffix: this.dependencies.hiddenNameSuffix ?? randomHiddenNameSuffix
13078
+ };
13079
+ }
13080
+ fileSystem() {
13081
+ return this.gatedFileSystem;
13082
+ }
13083
+ deleteCallTimeoutMillis() {
13084
+ return this.dependencies.deleteCallTimeoutMillis ?? DEFAULT_DELETE_CALL_TIMEOUT_MILLIS;
13085
+ }
13086
+ copyCallTimeoutMillis() {
13087
+ return this.dependencies.copyCallTimeoutMillis ?? DEFAULT_COPY_CALL_TIMEOUT_MILLIS;
13088
+ }
13089
+ mkdirTimeoutMillis() {
13090
+ return this.dependencies.mkdirTimeoutMillis ?? DEFAULT_MKDIR_TIMEOUT_MILLIS;
13091
+ }
13092
+ readTimeoutMillis() {
13093
+ return this.dependencies.readTimeoutMillis ?? DEFAULT_READ_TIMEOUT_MILLIS;
13094
+ }
13095
+ /** "The folder took longer than 20 s to read." */
13096
+ timedOut(subject) {
13097
+ const seconds = Math.round(this.readTimeoutMillis() / MILLIS_PER_SECOND2);
13098
+ return fileError(ERROR_FILE_TIMEOUT, `${subject} took longer than ${seconds} s to read.`);
13099
+ }
13100
+ /** What is left of `max_frame_bytes` once the answer's envelope is counted. */
13101
+ payloadBudget(envelope) {
13102
+ const envelopeBytes = Buffer.byteLength(JSON.stringify(response(envelope, envelope.op, null)), "utf8");
13103
+ return this.maxFrameBytes - (envelopeBytes - NULL_PAYLOAD_BYTES);
13104
+ }
13105
+ answer(envelope, result) {
13106
+ logger.debug("Device agent file request", {
13107
+ op: envelope.op,
13108
+ id: envelope.id,
13109
+ outcome: "error" in result ? result.error.code : OUTCOME_ANSWERED
13110
+ });
13111
+ this.dependencies.send(response(envelope, envelope.op, result));
13112
+ }
13113
+ };
13114
+ }
13115
+ });
13116
+
13117
+ // src/devices/login/prompts.ts
13118
+ function createTerminalPrompter(input, output) {
13119
+ return {
13120
+ async ask(question, signal) {
13121
+ const readline = (0, import_promises.createInterface)({ input, output, terminal: true });
13122
+ try {
13123
+ return await readline.question(marked(question), signal ? { signal } : {});
13124
+ } finally {
13125
+ readline.close();
13126
+ }
13127
+ },
13128
+ async askHidden(question, signal) {
13129
+ output.write(marked(question));
13130
+ const readline = (0, import_promises.createInterface)({ input, output: discardingOutput(), terminal: true });
13131
+ try {
13132
+ const answer = await readline.question("", signal ? { signal } : {});
13133
+ output.write("\n");
13134
+ return answer;
13135
+ } finally {
13136
+ readline.close();
13137
+ }
13138
+ }
13139
+ };
13140
+ }
13141
+ function isInteractiveTerminal() {
13142
+ return process.stdin.isTTY === true;
13143
+ }
13144
+ function isCtrlCAtPrompt(err) {
13145
+ return err instanceof Error && err.name === ABORT_ERROR_NAME;
13146
+ }
13147
+ function marked(question) {
13148
+ return `${QUESTION_MARKER} ${question}`;
13149
+ }
13150
+ function discardingOutput() {
13151
+ return new import_stream.Writable({
13152
+ write(_chunk, _encoding, callback) {
13153
+ callback();
13154
+ }
13155
+ });
13156
+ }
13157
+ var import_picocolors7, import_promises, import_stream, QUESTION_MARKER, terminalPrompter, ABORT_ERROR_NAME;
13158
+ var init_prompts = __esm({
13159
+ "src/devices/login/prompts.ts"() {
13160
+ "use strict";
13161
+ init_cjs_shims();
13162
+ import_picocolors7 = __toESM(require("picocolors"), 1);
13163
+ import_promises = require("readline/promises");
13164
+ import_stream = require("stream");
13165
+ QUESTION_MARKER = import_picocolors7.default.cyan(import_picocolors7.default.bold("\u2192"));
13166
+ terminalPrompter = createTerminalPrompter(process.stdin, process.stdout);
13167
+ ABORT_ERROR_NAME = "AbortError";
13168
+ }
13169
+ });
13170
+
13171
+ // src/devices/fileAccess.ts
13172
+ function machineFileAccessDependencies() {
13173
+ return {
13174
+ prompter: terminalPrompter,
13175
+ isInteractive: isInteractiveTerminal,
13176
+ writeIdentity: writeDeviceIdentity,
13177
+ print: (message) => printer_default.print(message)
13178
+ };
13179
+ }
13180
+ function parseFilesFlag(value) {
13181
+ if (value === void 0) {
13182
+ return void 0;
13183
+ }
13184
+ switch (value.trim().toLowerCase()) {
13185
+ case FILES_FLAG_ON:
13186
+ return true;
13187
+ case FILES_FLAG_OFF:
13188
+ return false;
13189
+ default:
13190
+ return null;
13191
+ }
13192
+ }
13193
+ async function settleFileAccess(flag, token, stored, dependencies) {
13194
+ const storedForToken = stored?.token === token ? stored : null;
13195
+ let answer = flag;
13196
+ if (answer === void 0) {
13197
+ if (typeof storedForToken?.file_manager === "boolean" || !dependencies.isInteractive()) {
13198
+ return void 0;
13199
+ }
13200
+ answer = !NO_ANSWER2.test((await dependencies.prompter.ask(FILE_ACCESS_QUESTION)).trim());
13201
+ }
13202
+ if (storedForToken) {
13203
+ dependencies.writeIdentity({ ...storedForToken, file_manager: answer });
13204
+ }
13205
+ dependencies.print(answer ? FILE_ACCESS_ON_MESSAGE : FILE_ACCESS_OFF_MESSAGE2);
13206
+ return answer;
13207
+ }
13208
+ function fileAccessAllowed() {
13209
+ return readDeviceIdentity()?.file_manager !== false;
13210
+ }
13211
+ function describeFileAccess(identity) {
13212
+ if (identity.file_manager === true) {
13213
+ return "on";
13214
+ }
13215
+ if (identity.file_manager === false) {
13216
+ return "off";
13217
+ }
13218
+ return "on, not asked yet";
13219
+ }
13220
+ var FILE_ACCESS_QUESTION, INVALID_FILES_FLAG_MESSAGE, FILES_FLAG_ON, FILES_FLAG_OFF, NO_ANSWER2, FILE_ACCESS_ON_MESSAGE, FILE_ACCESS_OFF_MESSAGE2;
13221
+ var init_fileAccess = __esm({
13222
+ "src/devices/fileAccess.ts"() {
13223
+ "use strict";
13224
+ init_cjs_shims();
13225
+ init_printer();
13226
+ init_deviceIdentity();
13227
+ init_prompts();
13228
+ FILE_ACCESS_QUESTION = "Allow file access from the Pinggy dashboard? Your account can browse, copy, move and delete this machine's files from the browser. [Y/n] ";
13229
+ INVALID_FILES_FLAG_MESSAGE = "--files takes on or off.";
13230
+ FILES_FLAG_ON = "on";
13231
+ FILES_FLAG_OFF = "off";
13232
+ NO_ANSWER2 = /^n/i;
13233
+ FILE_ACCESS_ON_MESSAGE = "File access is on. To turn it off, run: pinggy device connect --files off";
13234
+ FILE_ACCESS_OFF_MESSAGE2 = "File access is off. To allow it, run: pinggy device connect --files on";
13235
+ }
13236
+ });
13237
+
13238
+ // src/devices/terminal/terminal_schema.ts
13239
+ function clampGrid(requested, fallback) {
13240
+ if (requested === void 0 || !Number.isFinite(requested)) return fallback;
13241
+ return Math.max(MIN_GRID, Math.min(MAX_GRID, Math.trunc(requested)));
13242
+ }
13243
+ var import_zod5, CHANNEL_TERMINAL, OP_OPEN, OP_OPENED, OP_CLOSE, OP_DATA, OP_ACK, OP_EXIT, OP_RESIZE, OP_SIGNAL, OP_CONTEXT, OP_SNAPSHOT, OP_RESYNC, OP_ACTIVITY, TERMINAL_SIGNALS, MIN_GRID, MAX_GRID, CLOSE_REASON_USER_CLOSED, CLOSE_REASON_IDLE_TIMEOUT, ERROR_INVALID_PAYLOAD3, ERROR_TERMINAL_LIMIT_REACHED, ERROR_TERMINAL_DISABLED, ERROR_SHELL_NOT_ALLOWED, ERROR_SPAWN_FAILED, TerminalOpenSchema, TerminalCloseSchema, TerminalResizeSchema, TerminalInputSchema, TerminalSignalSchema, TerminalAckSchema, TerminalSnapshotRequestSchema;
13244
+ var init_terminal_schema = __esm({
13245
+ "src/devices/terminal/terminal_schema.ts"() {
13246
+ "use strict";
13247
+ init_cjs_shims();
13248
+ import_zod5 = require("zod");
13249
+ CHANNEL_TERMINAL = "terminal";
13250
+ OP_OPEN = "open";
13251
+ OP_OPENED = "opened";
13252
+ OP_CLOSE = "close";
13253
+ OP_DATA = "data";
13254
+ OP_ACK = "ack";
13255
+ OP_EXIT = "exit";
13256
+ OP_RESIZE = "resize";
13257
+ OP_SIGNAL = "signal";
13258
+ OP_CONTEXT = "context";
13259
+ OP_SNAPSHOT = "snapshot";
13260
+ OP_RESYNC = "resync";
13261
+ OP_ACTIVITY = "activity";
13262
+ TERMINAL_SIGNALS = ["INT", "TERM", "QUIT", "HUP"];
13263
+ MIN_GRID = 1;
13264
+ MAX_GRID = 1e3;
13265
+ CLOSE_REASON_USER_CLOSED = "user_closed";
13266
+ CLOSE_REASON_IDLE_TIMEOUT = "idle_timeout";
13267
+ ERROR_INVALID_PAYLOAD3 = "invalid_payload";
13268
+ ERROR_TERMINAL_LIMIT_REACHED = "terminal_limit_reached";
13269
+ ERROR_TERMINAL_DISABLED = "terminal_disabled";
13270
+ ERROR_SHELL_NOT_ALLOWED = "shell_not_allowed";
13271
+ ERROR_SPAWN_FAILED = "spawn_failed";
13272
+ TerminalOpenSchema = import_zod5.z.object({
13273
+ terminal_id: import_zod5.z.string().min(1),
13274
+ cols: import_zod5.z.number().int().optional(),
13275
+ rows: import_zod5.z.number().int().optional(),
13276
+ shell: import_zod5.z.string().nullable().optional(),
13277
+ cwd: import_zod5.z.string().nullable().optional()
13278
+ });
13279
+ TerminalCloseSchema = import_zod5.z.object({
13280
+ terminal_id: import_zod5.z.string().min(1),
13281
+ reason: import_zod5.z.string().optional()
13282
+ });
13283
+ TerminalResizeSchema = import_zod5.z.object({
13284
+ terminal_id: import_zod5.z.string().min(1),
13285
+ cols: import_zod5.z.number().int(),
13286
+ rows: import_zod5.z.number().int()
13287
+ });
13288
+ TerminalInputSchema = import_zod5.z.object({
13289
+ terminal_id: import_zod5.z.string().min(1),
13290
+ data: import_zod5.z.string()
13291
+ });
13292
+ TerminalSignalSchema = import_zod5.z.object({
13293
+ terminal_id: import_zod5.z.string().min(1),
13294
+ signal: import_zod5.z.enum(TERMINAL_SIGNALS)
13295
+ });
13296
+ TerminalAckSchema = import_zod5.z.object({
13297
+ terminal_id: import_zod5.z.string().min(1),
13298
+ ack_seq: import_zod5.z.number().optional(),
13299
+ ack_bytes: import_zod5.z.number()
13300
+ });
13301
+ TerminalSnapshotRequestSchema = import_zod5.z.object({
13302
+ terminal_id: import_zod5.z.string().min(1),
13303
+ snapshot_id: import_zod5.z.string().min(1)
13304
+ });
13305
+ }
13306
+ });
13307
+
13308
+ // src/devices/terminal/flowWindow.ts
13309
+ var FlowWindow;
13310
+ var init_flowWindow = __esm({
13311
+ "src/devices/terminal/flowWindow.ts"() {
13312
+ "use strict";
13313
+ init_cjs_shims();
13314
+ FlowWindow = class {
13315
+ constructor(windowBytes) {
13316
+ this.sentBytes = 0;
13317
+ this.ackedBytes = 0;
13318
+ if (!Number.isFinite(windowBytes) || windowBytes <= 0) {
13319
+ throw new Error("A terminal flow window needs a positive size from welcome");
13320
+ }
13321
+ this.windowBytes = Math.trunc(windowBytes);
13322
+ }
13323
+ /** How many more raw bytes may go out before the browser has to catch up. */
13324
+ remaining() {
13325
+ return Math.max(0, this.windowBytes - (this.sentBytes - this.ackedBytes));
13326
+ }
13327
+ /** False means stop reading the pty. Nothing else is an acceptable response. */
13328
+ isOpen() {
13329
+ return this.remaining() > 0;
13330
+ }
13331
+ recordSent(byteCount) {
13332
+ if (!Number.isFinite(byteCount) || byteCount <= 0) return;
13333
+ this.sentBytes += Math.trunc(byteCount);
13334
+ }
13335
+ /**
13336
+ * Cumulative totals, never increments, so a dropped ack self-heals on the next one.
13337
+ *
13338
+ * A browser is not a trusted input. An ack beyond what was sent is clamped rather than believed,
13339
+ * and one that arrives out of order never moves the counter backwards.
13340
+ */
13341
+ recordAck(ackBytes) {
13342
+ if (!Number.isFinite(ackBytes)) return;
13343
+ const clamped = Math.min(Math.max(Math.trunc(ackBytes), 0), this.sentBytes);
13344
+ if (clamped > this.ackedBytes) {
13345
+ this.ackedBytes = clamped;
13346
+ }
13347
+ }
13348
+ get sent() {
13349
+ return this.sentBytes;
13350
+ }
13351
+ get acked() {
13352
+ return this.ackedBytes;
13353
+ }
13354
+ get size() {
13355
+ return this.windowBytes;
13356
+ }
13357
+ };
13358
+ }
13359
+ });
13360
+
13361
+ // src/devices/terminal/frameSplitter.ts
13362
+ function rawBundleBytes(maxFrameBytes) {
13363
+ const available = maxFrameBytes - ENVELOPE_OVERHEAD_BYTES;
13364
+ if (available <= 0) {
13365
+ throw new Error("max_frame_bytes leaves no room for a terminal payload");
13366
+ }
13367
+ return Math.floor(available * BASE64_NUMERATOR / BASE64_DENOMINATOR);
13368
+ }
13369
+ var ENVELOPE_OVERHEAD_BYTES, BASE64_NUMERATOR, BASE64_DENOMINATOR, BUNDLE_MILLIS, FrameSplitter;
13370
+ var init_frameSplitter = __esm({
13371
+ "src/devices/terminal/frameSplitter.ts"() {
13372
+ "use strict";
13373
+ init_cjs_shims();
13374
+ ENVELOPE_OVERHEAD_BYTES = 512;
13375
+ BASE64_NUMERATOR = 3;
13376
+ BASE64_DENOMINATOR = 4;
13377
+ BUNDLE_MILLIS = 8;
13378
+ FrameSplitter = class {
13379
+ constructor(emit, bundleBytes, bundleMillis = BUNDLE_MILLIS) {
13380
+ this.emit = emit;
13381
+ this.bundleBytes = bundleBytes;
13382
+ this.bundleMillis = bundleMillis;
13383
+ this.pending = [];
13384
+ this.pendingBytes = 0;
13385
+ if (!Number.isFinite(bundleBytes) || bundleBytes <= 0) {
13386
+ throw new Error("A frame splitter needs a positive bundle size");
13387
+ }
13388
+ }
13389
+ /** A chunk over the cap is split across frames, never truncated. */
13390
+ push(chunk) {
13391
+ if (chunk.length === 0) return;
13392
+ this.pending.push(chunk);
13393
+ this.pendingBytes += chunk.length;
13394
+ while (this.pendingBytes >= this.bundleBytes) {
13395
+ this.emitBytes(this.bundleBytes);
13396
+ }
13397
+ if (this.pendingBytes > 0) {
13398
+ this.arm();
13399
+ } else {
13400
+ this.disarm();
13401
+ }
13402
+ }
13403
+ /** Sends whatever is held, if anything. Used when the terminal closes and by the timer. */
13404
+ flush() {
13405
+ this.disarm();
13406
+ if (this.pendingBytes > 0) {
13407
+ this.emitBytes(this.pendingBytes);
13408
+ }
13409
+ }
13410
+ dispose() {
13411
+ this.disarm();
13412
+ this.pending = [];
13413
+ this.pendingBytes = 0;
13414
+ }
13415
+ get buffered() {
13416
+ return this.pendingBytes;
13417
+ }
13418
+ emitBytes(byteCount) {
13419
+ const joined = Buffer.concat(this.pending, this.pendingBytes);
13420
+ const frame = joined.subarray(0, byteCount);
13421
+ const rest = joined.subarray(byteCount);
13422
+ this.pending = rest.length > 0 ? [rest] : [];
13423
+ this.pendingBytes = rest.length;
10737
13424
  this.emit(frame);
10738
13425
  }
10739
13426
  arm() {
@@ -10779,7 +13466,7 @@ function displayCwd(rawCwd, resolvedHome) {
10779
13466
  }
10780
13467
  function resolvedHomeDirectory() {
10781
13468
  try {
10782
- return import_fs10.default.realpathSync(import_os5.default.homedir());
13469
+ return import_fs12.default.realpathSync(import_os7.default.homedir());
10783
13470
  } catch {
10784
13471
  return null;
10785
13472
  }
@@ -10798,14 +13485,14 @@ async function readFromProc(shellPids) {
10798
13485
  await Promise.all(shellPids.map(async (shellPid) => {
10799
13486
  const groups = await readProcGroups(shellPid);
10800
13487
  if (!groups) return;
10801
- const cwd = await readOrNull(() => import_fs10.default.promises.readlink(`/proc/${shellPid}/cwd`));
10802
- const foregroundName = groups.foregroundGroupId === groups.shellGroupId ? null : await readOrNull(() => import_fs10.default.promises.readFile(`/proc/${groups.foregroundGroupId}/comm`, "utf8"));
13488
+ const cwd = await readOrNull(() => import_fs12.default.promises.readlink(`/proc/${shellPid}/cwd`));
13489
+ const foregroundName = groups.foregroundGroupId === groups.shellGroupId ? null : await readOrNull(() => import_fs12.default.promises.readFile(`/proc/${groups.foregroundGroupId}/comm`, "utf8"));
10803
13490
  contexts.set(shellPid, { cwd, foregroundName });
10804
13491
  }));
10805
13492
  return contexts;
10806
13493
  }
10807
13494
  async function readProcGroups(shellPid) {
10808
- const stat = await readOrNull(() => import_fs10.default.promises.readFile(`/proc/${shellPid}/stat`, "utf8"));
13495
+ const stat = await readOrNull(() => import_fs12.default.promises.readFile(`/proc/${shellPid}/stat`, "utf8"));
10809
13496
  if (stat === null) return null;
10810
13497
  const afterName = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
10811
13498
  const shellGroupId = Number.parseInt(afterName[2], 10);
@@ -10873,14 +13560,14 @@ async function readOrNull(read) {
10873
13560
  return null;
10874
13561
  }
10875
13562
  }
10876
- var import_child_process2, import_fs10, import_os5, SHELL_CONTEXT_POLL_MILLIS, MAX_CWD_CHARACTERS, MAX_COMMAND_CHARACTERS, PROCESS_READ_TIMEOUT_MILLIS, HOME_PREFIX, ShellContextTracker;
13563
+ var import_child_process2, import_fs12, import_os7, SHELL_CONTEXT_POLL_MILLIS, MAX_CWD_CHARACTERS, MAX_COMMAND_CHARACTERS, PROCESS_READ_TIMEOUT_MILLIS, HOME_PREFIX, ShellContextTracker;
10877
13564
  var init_shellContext = __esm({
10878
13565
  "src/devices/terminal/shellContext.ts"() {
10879
13566
  "use strict";
10880
13567
  init_cjs_shims();
10881
13568
  import_child_process2 = require("child_process");
10882
- import_fs10 = __toESM(require("fs"), 1);
10883
- import_os5 = __toESM(require("os"), 1);
13569
+ import_fs12 = __toESM(require("fs"), 1);
13570
+ import_os7 = __toESM(require("os"), 1);
10884
13571
  SHELL_CONTEXT_POLL_MILLIS = 5e3;
10885
13572
  MAX_CWD_CHARACTERS = 1024;
10886
13573
  MAX_COMMAND_CHARACTERS = 64;
@@ -11040,7 +13727,7 @@ var init_screenMirror = __esm({
11040
13727
 
11041
13728
  // src/devices/terminal/terminalHandler.ts
11042
13729
  function positiveMillis(seconds) {
11043
- return seconds !== void 0 && Number.isFinite(seconds) && seconds > 0 ? seconds * MILLIS_PER_SECOND : void 0;
13730
+ return seconds !== void 0 && Number.isFinite(seconds) && seconds > 0 ? seconds * MILLIS_PER_SECOND3 : void 0;
11044
13731
  }
11045
13732
  function splitIntoParts(bytes, partBytes) {
11046
13733
  const parts = [];
@@ -11053,18 +13740,18 @@ function errorName2(err) {
11053
13740
  return err instanceof Error ? err.name : typeof err;
11054
13741
  }
11055
13742
  function signalName(signal) {
11056
- for (const [name, number] of Object.entries(import_os6.default.constants.signals)) {
13743
+ for (const [name, number] of Object.entries(import_os8.default.constants.signals)) {
11057
13744
  if (number === signal) return name.replace(/^SIG/, "");
11058
13745
  }
11059
13746
  return String(signal);
11060
13747
  }
11061
- var import_crypto3, import_os6, DEFAULT_COLS, DEFAULT_ROWS, EXPIRY_CHECK_MILLIS, MILLIS_PER_SECOND, RESYNC_MIN_INTERVAL_MILLIS, MIRROR_HIGH_WATER_BYTES, MIRROR_LOW_WATER_BYTES, ACTIVITY_REPORT_MILLIS, DEFAULT_SKIP_TUNING, TerminalHandler;
13748
+ var import_crypto4, import_os8, DEFAULT_COLS, DEFAULT_ROWS, EXPIRY_CHECK_MILLIS, MILLIS_PER_SECOND3, RESYNC_MIN_INTERVAL_MILLIS, MIRROR_HIGH_WATER_BYTES, MIRROR_LOW_WATER_BYTES, ACTIVITY_REPORT_MILLIS, DEFAULT_SKIP_TUNING, TerminalHandler;
11062
13749
  var init_terminalHandler = __esm({
11063
13750
  "src/devices/terminal/terminalHandler.ts"() {
11064
13751
  "use strict";
11065
13752
  init_cjs_shims();
11066
- import_crypto3 = require("crypto");
11067
- import_os6 = __toESM(require("os"), 1);
13753
+ import_crypto4 = require("crypto");
13754
+ import_os8 = __toESM(require("os"), 1);
11068
13755
  init_logger();
11069
13756
  init_envelope();
11070
13757
  init_terminal_schema();
@@ -11075,7 +13762,7 @@ var init_terminalHandler = __esm({
11075
13762
  DEFAULT_COLS = 80;
11076
13763
  DEFAULT_ROWS = 24;
11077
13764
  EXPIRY_CHECK_MILLIS = 5e3;
11078
- MILLIS_PER_SECOND = 1e3;
13765
+ MILLIS_PER_SECOND3 = 1e3;
11079
13766
  RESYNC_MIN_INTERVAL_MILLIS = 1e3;
11080
13767
  MIRROR_HIGH_WATER_BYTES = 1024 * 1024;
11081
13768
  MIRROR_LOW_WATER_BYTES = 256 * 1024;
@@ -11281,7 +13968,7 @@ var init_terminalHandler = __esm({
11281
13968
  open(envelope) {
11282
13969
  const parsed = TerminalOpenSchema.safeParse(envelope.payload);
11283
13970
  if (!parsed.success) {
11284
- this.refuse(envelope, null, ERROR_INVALID_PAYLOAD2, "open payload could not be read.");
13971
+ this.refuse(envelope, null, ERROR_INVALID_PAYLOAD3, "open payload could not be read.");
11285
13972
  return;
11286
13973
  }
11287
13974
  const request2 = parsed.data;
@@ -11588,7 +14275,7 @@ var init_terminalHandler = __esm({
11588
14275
  return;
11589
14276
  }
11590
14277
  if (screen && this.bundleBytes !== void 0) {
11591
- const resyncId = (0, import_crypto3.randomUUID)();
14278
+ const resyncId = (0, import_crypto4.randomUUID)();
11592
14279
  const parts = splitIntoParts(Buffer.from(screen.text, "utf-8"), this.bundleBytes);
11593
14280
  parts.forEach((part, index) => {
11594
14281
  const payload = {
@@ -11912,11 +14599,11 @@ function ensureSpawnHelperExecutable(packageRoot) {
11912
14599
  function resolveCwd(requested) {
11913
14600
  if (requested) {
11914
14601
  try {
11915
- if (import_fs11.default.statSync(requested).isDirectory()) return requested;
14602
+ if (import_fs13.default.statSync(requested).isDirectory()) return requested;
11916
14603
  } catch {
11917
14604
  }
11918
14605
  }
11919
- return import_os7.default.homedir();
14606
+ return import_os9.default.homedir();
11920
14607
  }
11921
14608
  function spawnPty(request2) {
11922
14609
  const pty = loadNodePty();
@@ -11960,14 +14647,14 @@ function spawnPty(request2) {
11960
14647
  }
11961
14648
  };
11962
14649
  }
11963
- var import_child_process3, import_fs11, import_os7, loadedPty, TERM_NAME;
14650
+ var import_child_process3, import_fs13, import_os9, loadedPty, TERM_NAME;
11964
14651
  var init_ptySession = __esm({
11965
14652
  "src/devices/terminal/ptySession.ts"() {
11966
14653
  "use strict";
11967
14654
  init_cjs_shims();
11968
14655
  import_child_process3 = require("child_process");
11969
- import_fs11 = __toESM(require("fs"), 1);
11970
- import_os7 = __toESM(require("os"), 1);
14656
+ import_fs13 = __toESM(require("fs"), 1);
14657
+ import_os9 = __toESM(require("os"), 1);
11971
14658
  init_logger();
11972
14659
  init_nodePtyRuntime();
11973
14660
  TERM_NAME = "xterm-256color";
@@ -11978,7 +14665,7 @@ var init_ptySession = __esm({
11978
14665
  function readShellEnvironment() {
11979
14666
  let etcShells = null;
11980
14667
  try {
11981
- etcShells = import_fs12.default.readFileSync(ETC_SHELLS_PATH, "utf8");
14668
+ etcShells = import_fs14.default.readFileSync(ETC_SHELLS_PATH, "utf8");
11982
14669
  } catch {
11983
14670
  etcShells = null;
11984
14671
  }
@@ -11986,9 +14673,9 @@ function readShellEnvironment() {
11986
14673
  platform: process.platform,
11987
14674
  loginShell: process.env.SHELL,
11988
14675
  etcShells,
11989
- exists: (path20) => {
14676
+ exists: (path23) => {
11990
14677
  try {
11991
- return import_fs12.default.statSync(path20).isFile();
14678
+ return import_fs14.default.statSync(path23).isFile();
11992
14679
  } catch {
11993
14680
  return false;
11994
14681
  }
@@ -12019,12 +14706,12 @@ function resolveShell(requested, environment) {
12019
14706
  const firstUsable = allowed.find(usable);
12020
14707
  return firstUsable ? { shell: firstUsable } : { error: "No allowed shell exists on this machine." };
12021
14708
  }
12022
- var import_fs12, FALLBACK_UNIX_SHELLS, WINDOWS_SHELLS, ETC_SHELLS_PATH;
14709
+ var import_fs14, FALLBACK_UNIX_SHELLS, WINDOWS_SHELLS, ETC_SHELLS_PATH;
12023
14710
  var init_shellAllowlist = __esm({
12024
14711
  "src/devices/terminal/shellAllowlist.ts"() {
12025
14712
  "use strict";
12026
14713
  init_cjs_shims();
12027
- import_fs12 = __toESM(require("fs"), 1);
14714
+ import_fs14 = __toESM(require("fs"), 1);
12028
14715
  FALLBACK_UNIX_SHELLS = ["/bin/bash", "/bin/zsh", "/bin/sh", "/usr/bin/bash", "/usr/bin/zsh"];
12029
14716
  WINDOWS_SHELLS = ["powershell.exe", "cmd.exe"];
12030
14717
  ETC_SHELLS_PATH = "/etc/shells";
@@ -12034,7 +14721,7 @@ var init_shellAllowlist = __esm({
12034
14721
  // src/devices/foregroundAgent.ts
12035
14722
  function readRecordFile(filePath) {
12036
14723
  try {
12037
- const record = JSON.parse(import_fs13.default.readFileSync(filePath, "utf-8"));
14724
+ const record = JSON.parse(import_fs15.default.readFileSync(filePath, "utf-8"));
12038
14725
  return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
12039
14726
  } catch {
12040
14727
  return null;
@@ -12042,7 +14729,7 @@ function readRecordFile(filePath) {
12042
14729
  }
12043
14730
  function deleteRecordFile(filePath) {
12044
14731
  try {
12045
- import_fs13.default.unlinkSync(filePath);
14732
+ import_fs15.default.unlinkSync(filePath);
12046
14733
  } catch (err) {
12047
14734
  logger.debug("No foreground agent record to delete", { error: errorMessage(err) });
12048
14735
  }
@@ -12072,7 +14759,7 @@ function recordForegroundAgent(onRecordDeleted) {
12072
14759
  };
12073
14760
  try {
12074
14761
  ensurePinggyConfigDir();
12075
- import_fs13.default.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
14762
+ import_fs15.default.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
12076
14763
  } catch (err) {
12077
14764
  logger.warn(
12078
14765
  "Could not write device-agent.json. pinggy device remove cannot stop this agent.",
@@ -12081,7 +14768,7 @@ function recordForegroundAgent(onRecordDeleted) {
12081
14768
  return () => void 0;
12082
14769
  }
12083
14770
  const timer = setInterval(() => {
12084
- if (!import_fs13.default.existsSync(filePath)) {
14771
+ if (!import_fs15.default.existsSync(filePath)) {
12085
14772
  clearInterval(timer);
12086
14773
  onRecordDeleted();
12087
14774
  }
@@ -12128,12 +14815,12 @@ function foregroundAgentRefusal(record = readForegroundAgent()) {
12128
14815
  }
12129
14816
  return `This machine already runs as a device in another terminal (PID ${record.pid}). Press Ctrl+C in that terminal first.`;
12130
14817
  }
12131
- var import_fs13, RECORD_CHECK_INTERVAL_MILLIS, STOP_WAIT_MILLIS, STOP_POLL_INTERVAL_MILLIS;
14818
+ var import_fs15, RECORD_CHECK_INTERVAL_MILLIS, STOP_WAIT_MILLIS, STOP_POLL_INTERVAL_MILLIS;
12132
14819
  var init_foregroundAgent = __esm({
12133
14820
  "src/devices/foregroundAgent.ts"() {
12134
14821
  "use strict";
12135
14822
  init_cjs_shims();
12136
- import_fs13 = __toESM(require("fs"), 1);
14823
+ import_fs15 = __toESM(require("fs"), 1);
12137
14824
  init_configDir();
12138
14825
  init_daemonManager();
12139
14826
  init_bootId();
@@ -12174,8 +14861,8 @@ function sleep2(millis, state) {
12174
14861
  function buildHello(terminalHandler) {
12175
14862
  return {
12176
14863
  agent_version: getVersion(),
12177
- os: import_os8.default.platform(),
12178
- hostname: import_os8.default.hostname(),
14864
+ os: import_os10.default.platform(),
14865
+ hostname: import_os10.default.hostname(),
12179
14866
  capabilities: buildCapabilities(isTerminalSupported(), isScreenMirrorSupported()),
12180
14867
  terminals: terminalHandler.held()
12181
14868
  };
@@ -12194,11 +14881,13 @@ function startMetricsReporting(intervalSeconds, collect, send) {
12194
14881
  clearInterval(timer);
12195
14882
  };
12196
14883
  }
12197
- function identityForRun(token, server, stored) {
12198
- if (stored?.token === token) {
12199
- return { ...stored, server };
14884
+ function identityForRun(token, server, stored, fileManager) {
14885
+ const identity = stored?.token === token ? { ...stored, server } : { device_agent_id: null, token, server, enrolled_at: null };
14886
+ delete identity.file_manager;
14887
+ if (fileManager !== void 0) {
14888
+ identity.file_manager = fileManager;
12200
14889
  }
12201
- return { device_agent_id: null, token, server, enrolled_at: null };
14890
+ return identity;
12202
14891
  }
12203
14892
  function startDeviceAgent(token, manage, options = {}) {
12204
14893
  const server = manage || DEFAULT_SERVER;
@@ -12209,7 +14898,7 @@ function startDeviceAgent(token, manage, options = {}) {
12209
14898
  const context = {
12210
14899
  wsUrl: buildDeviceAgentWsUrl(manage),
12211
14900
  server,
12212
- identity: identityForRun(token, server, stored),
14901
+ identity: identityForRun(token, server, stored, options.fileManager),
12213
14902
  reconnectPolicy: options.reconnectPolicy ?? new ReconnectPolicy(),
12214
14903
  handshakeTimeoutMillis: options.handshakeTimeoutMillis ?? HANDSHAKE_TIMEOUT_MILLIS,
12215
14904
  terminalHandler: new TerminalHandler({
@@ -12220,6 +14909,7 @@ function startDeviceAgent(token, manage, options = {}) {
12220
14909
  readShellContexts: processTableReader(),
12221
14910
  resolvedHome: resolvedHomeDirectory()
12222
14911
  }),
14912
+ fileHandler: new FileHandler({ send: (frame) => connection.send?.(frame), fileAccessAllowed }),
12223
14913
  connection,
12224
14914
  reporter,
12225
14915
  writeIdentity: options.writeIdentity ?? writeDeviceIdentity,
@@ -12285,7 +14975,7 @@ function fail(context, error) {
12285
14975
  return "terminal";
12286
14976
  }
12287
14977
  function connectOnce(context) {
12288
- const { identity, reconnectPolicy, terminalHandler, connection, reporter, state, options } = context;
14978
+ const { identity, reconnectPolicy, terminalHandler, fileHandler, connection, reporter, state, options } = context;
12289
14979
  return new Promise((resolve) => {
12290
14980
  const ws = new import_ws3.default(context.wsUrl, { headers: { [TOKEN_HEADER]: identity.token } });
12291
14981
  let heartbeat = null;
@@ -12370,7 +15060,7 @@ function connectOnce(context) {
12370
15060
  const startHeartbeat = (intervalSeconds) => {
12371
15061
  heartbeat = setInterval(
12372
15062
  () => sendFrame(
12373
- event(CHANNEL_SYSTEM, OP_HEARTBEAT, { uptime_seconds: Math.floor(import_os8.default.uptime()) })
15063
+ event(CHANNEL_SYSTEM, OP_HEARTBEAT, { uptime_seconds: Math.floor(import_os10.default.uptime()) })
12374
15064
  ),
12375
15065
  intervalSeconds * 1e3
12376
15066
  );
@@ -12392,6 +15082,12 @@ function connectOnce(context) {
12392
15082
  welcome.terminal_resync
12393
15083
  );
12394
15084
  terminalHandler.resumeAll();
15085
+ fileHandler.configure(
15086
+ welcome.file_manager_enabled,
15087
+ welcome.max_frame_bytes,
15088
+ welcome.file_max_concurrent_operations,
15089
+ welcome.file_max_queued_operations
15090
+ );
12395
15091
  startHeartbeat(welcome.heartbeat_interval_seconds);
12396
15092
  startPongWatchdog(welcome.heartbeat_interval_seconds);
12397
15093
  sendFrame(event(CHANNEL_DEVICE, OP_INFO, collectSystemInfo()));
@@ -12415,6 +15111,10 @@ function connectOnce(context) {
12415
15111
  terminalHandler.handle(envelope);
12416
15112
  return;
12417
15113
  }
15114
+ if (envelope.ch === CHANNEL_FILE) {
15115
+ void fileHandler.handle(envelope);
15116
+ return;
15117
+ }
12418
15118
  if (envelope.ch === CHANNEL_TUNNEL) {
12419
15119
  void handleTunnelAction(envelope, (frame) => connection.send?.(frame), options.tunnelActions).then(() => stopTunnels?.pollNow());
12420
15120
  return;
@@ -12510,13 +15210,13 @@ function describeDisconnect(reason) {
12510
15210
  message: DISCONNECT_MESSAGES[reason] ?? `Disconnected by the dashboard: ${reason}. Re-enrol this device to continue.`
12511
15211
  };
12512
15212
  }
12513
- var import_ws3, import_os8, CLOSE_CODE_REVOKED, CLOSE_CODE_NORMAL, CLOSE_TIMEOUT_MILLIS, TOKEN_HEADER, DEFAULT_SERVER, ERROR_ALREADY_CONNECTED, AGENT_ERROR_UNAUTHORIZED, AGENT_ERROR_HANDSHAKE_REFUSED, AGENT_ERROR_DISCONNECTED, AGENT_ERROR_NOT_CONNECTED, UNAUTHORIZED_STORED_TOKEN_MESSAGE, UNAUTHORIZED_NEW_TOKEN_MESSAGE, HANDSHAKE_TIMEOUT_MILLIS, PONG_GRACE_INTERVALS, BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, CAPABILITY_TERMINAL_RESYNC, DISCONNECT_REASON_SHUTDOWN, DISCONNECT_MESSAGES;
15213
+ var import_ws3, import_os10, CLOSE_CODE_REVOKED, CLOSE_CODE_NORMAL, CLOSE_TIMEOUT_MILLIS, TOKEN_HEADER, DEFAULT_SERVER, ERROR_ALREADY_CONNECTED, AGENT_ERROR_UNAUTHORIZED, AGENT_ERROR_HANDSHAKE_REFUSED, AGENT_ERROR_DISCONNECTED, AGENT_ERROR_NOT_CONNECTED, UNAUTHORIZED_STORED_TOKEN_MESSAGE, UNAUTHORIZED_NEW_TOKEN_MESSAGE, HANDSHAKE_TIMEOUT_MILLIS, PONG_GRACE_INTERVALS, BASE_CAPABILITIES, CAPABILITY_TERMINAL, CAPABILITY_TERMINAL_SNAPSHOT, CAPABILITY_TERMINAL_RESYNC, DISCONNECT_REASON_SHUTDOWN, DISCONNECT_MESSAGES;
12514
15214
  var init_deviceAgent = __esm({
12515
15215
  "src/devices/deviceAgent.ts"() {
12516
15216
  "use strict";
12517
15217
  init_cjs_shims();
12518
15218
  import_ws3 = __toESM(require("ws"), 1);
12519
- import_os8 = __toESM(require("os"), 1);
15219
+ import_os10 = __toESM(require("os"), 1);
12520
15220
  init_logger();
12521
15221
  init_util();
12522
15222
  init_envelope();
@@ -12528,6 +15228,9 @@ var init_deviceAgent = __esm({
12528
15228
  init_tunnelList();
12529
15229
  init_tunnelActions();
12530
15230
  init_reconnect();
15231
+ init_file_schema();
15232
+ init_fileHandler();
15233
+ init_fileAccess();
12531
15234
  init_terminal_schema();
12532
15235
  init_terminalHandler();
12533
15236
  init_screenMirror();
@@ -12551,7 +15254,14 @@ var init_deviceAgent = __esm({
12551
15254
  UNAUTHORIZED_NEW_TOKEN_MESSAGE = "The dashboard refused this device token. Check the token, or copy the install command from the dashboard again.";
12552
15255
  HANDSHAKE_TIMEOUT_MILLIS = 3e4;
12553
15256
  PONG_GRACE_INTERVALS = 2;
12554
- BASE_CAPABILITIES = ["tunnel", "stats", "tunnel_control", "tunnel_update", "saved_config_update"];
15257
+ BASE_CAPABILITIES = [
15258
+ "tunnel",
15259
+ "stats",
15260
+ "tunnel_control",
15261
+ "tunnel_update",
15262
+ "saved_config_update",
15263
+ "file_manager"
15264
+ ];
12555
15265
  CAPABILITY_TERMINAL = "terminal";
12556
15266
  CAPABILITY_TERMINAL_SNAPSHOT = "terminal_snapshot";
12557
15267
  CAPABILITY_TERMINAL_RESYNC = "terminal_resync";
@@ -12565,34 +15275,34 @@ var init_deviceAgent = __esm({
12565
15275
  });
12566
15276
 
12567
15277
  // src/devices/login/login_schema.ts
12568
- var import_zod5, LoginStartedSchema, LoginStatus, LoginAnswerSchema, LoginErrorSchema, LoginErrorType;
15278
+ var import_zod6, LoginStartedSchema, LoginStatus, LoginAnswerSchema, LoginErrorSchema, LoginErrorType;
12569
15279
  var init_login_schema = __esm({
12570
15280
  "src/devices/login/login_schema.ts"() {
12571
15281
  "use strict";
12572
15282
  init_cjs_shims();
12573
- import_zod5 = require("zod");
12574
- LoginStartedSchema = import_zod5.z.object({
12575
- device_code: import_zod5.z.string().min(1),
12576
- match_code: import_zod5.z.string().min(1).optional(),
12577
- expires_in_seconds: import_zod5.z.number().int().positive(),
12578
- poll_interval_seconds: import_zod5.z.number().int().positive()
15283
+ import_zod6 = require("zod");
15284
+ LoginStartedSchema = import_zod6.z.object({
15285
+ device_code: import_zod6.z.string().min(1),
15286
+ match_code: import_zod6.z.string().min(1).optional(),
15287
+ expires_in_seconds: import_zod6.z.number().int().positive(),
15288
+ poll_interval_seconds: import_zod6.z.number().int().positive()
12579
15289
  });
12580
15290
  LoginStatus = {
12581
15291
  Pending: "pending",
12582
15292
  MfaRequired: "mfa_required",
12583
15293
  Approved: "approved"
12584
15294
  };
12585
- LoginAnswerSchema = import_zod5.z.object({
12586
- status: import_zod5.z.enum([LoginStatus.Pending, LoginStatus.MfaRequired, LoginStatus.Approved]),
12587
- token: import_zod5.z.string().min(1).optional(),
12588
- device_agent_id: import_zod5.z.string().min(1).optional(),
12589
- device_name: import_zod5.z.string().optional(),
12590
- open_url: import_zod5.z.string().optional(),
12591
- device_url: import_zod5.z.string().optional()
15295
+ LoginAnswerSchema = import_zod6.z.object({
15296
+ status: import_zod6.z.enum([LoginStatus.Pending, LoginStatus.MfaRequired, LoginStatus.Approved]),
15297
+ token: import_zod6.z.string().min(1).optional(),
15298
+ device_agent_id: import_zod6.z.string().min(1).optional(),
15299
+ device_name: import_zod6.z.string().optional(),
15300
+ open_url: import_zod6.z.string().optional(),
15301
+ device_url: import_zod6.z.string().optional()
12592
15302
  });
12593
- LoginErrorSchema = import_zod5.z.object({
12594
- error_type: import_zod5.z.string(),
12595
- errors: import_zod5.z.array(import_zod5.z.string()).default([])
15303
+ LoginErrorSchema = import_zod6.z.object({
15304
+ error_type: import_zod6.z.string(),
15305
+ errors: import_zod6.z.array(import_zod6.z.string()).default([])
12596
15306
  });
12597
15307
  LoginErrorType = {
12598
15308
  /** A wrong code or authenticator code, with attempts left. Asked again. */
@@ -12615,8 +15325,8 @@ function buildDashboardHttpUrl(manage) {
12615
15325
  }
12616
15326
  function createDeviceLoginApi(manage, fetchImpl = fetch) {
12617
15327
  const baseUrl = buildDashboardHttpUrl(manage);
12618
- async function post(path20, body, schema) {
12619
- const response2 = await fetchImpl(`${baseUrl}/${path20}`, {
15328
+ async function post(path23, body, schema) {
15329
+ const response2 = await fetchImpl(`${baseUrl}/${path23}`, {
12620
15330
  method: "POST",
12621
15331
  headers: { "Content-Type": "application/json", Accept: "application/json" },
12622
15332
  body: JSON.stringify(body)
@@ -12684,56 +15394,6 @@ var init_loginApi = __esm({
12684
15394
  }
12685
15395
  });
12686
15396
 
12687
- // src/devices/login/prompts.ts
12688
- function createTerminalPrompter(input, output) {
12689
- return {
12690
- async ask(question, signal) {
12691
- const readline = (0, import_promises.createInterface)({ input, output, terminal: true });
12692
- try {
12693
- return await readline.question(marked(question), signal ? { signal } : {});
12694
- } finally {
12695
- readline.close();
12696
- }
12697
- },
12698
- async askHidden(question, signal) {
12699
- output.write(marked(question));
12700
- const readline = (0, import_promises.createInterface)({ input, output: discardingOutput(), terminal: true });
12701
- try {
12702
- const answer = await readline.question("", signal ? { signal } : {});
12703
- output.write("\n");
12704
- return answer;
12705
- } finally {
12706
- readline.close();
12707
- }
12708
- }
12709
- };
12710
- }
12711
- function isInteractiveTerminal() {
12712
- return process.stdin.isTTY === true;
12713
- }
12714
- function marked(question) {
12715
- return `${QUESTION_MARKER} ${question}`;
12716
- }
12717
- function discardingOutput() {
12718
- return new import_stream.Writable({
12719
- write(_chunk, _encoding, callback) {
12720
- callback();
12721
- }
12722
- });
12723
- }
12724
- var import_picocolors7, import_promises, import_stream, QUESTION_MARKER, terminalPrompter;
12725
- var init_prompts = __esm({
12726
- "src/devices/login/prompts.ts"() {
12727
- "use strict";
12728
- init_cjs_shims();
12729
- import_picocolors7 = __toESM(require("picocolors"), 1);
12730
- import_promises = require("readline/promises");
12731
- import_stream = require("stream");
12732
- QUESTION_MARKER = import_picocolors7.default.cyan(import_picocolors7.default.bold("\u2192"));
12733
- terminalPrompter = createTerminalPrompter(process.stdin, process.stdout);
12734
- }
12735
- });
12736
-
12737
15397
  // src/devices/login/deviceLogin.ts
12738
15398
  function machineDeviceLoginDependencies() {
12739
15399
  return {
@@ -12745,9 +15405,9 @@ function machineDeviceLoginDependencies() {
12745
15405
  runAgent: (token, manage) => runDeviceAgent(token, manage),
12746
15406
  renderQr: async (url) => (await createQrCodes([url]))[0],
12747
15407
  machine: () => ({
12748
- hostname: import_os9.default.hostname(),
12749
- os: import_os9.default.platform(),
12750
- arch: import_os9.default.arch(),
15408
+ hostname: import_os11.default.hostname(),
15409
+ os: import_os11.default.platform(),
15410
+ arch: import_os11.default.arch(),
12751
15411
  agent_version: getVersion()
12752
15412
  }),
12753
15413
  print: (message) => printer_default.print(message),
@@ -12766,9 +15426,6 @@ async function runDeviceLogin(options, dependencies = machineDeviceLoginDependen
12766
15426
  return EXIT_FAILED;
12767
15427
  }
12768
15428
  }
12769
- function isCtrlCAtPrompt(err) {
12770
- return err instanceof Error && err.name === ABORT_ERROR_NAME;
12771
- }
12772
15429
  async function signInAndRunAgent(options, dependencies) {
12773
15430
  if (!dependencies.isInteractive()) {
12774
15431
  dependencies.printError(NO_TERMINAL_MESSAGE);
@@ -12781,6 +15438,7 @@ async function signInAndRunAgent(options, dependencies) {
12781
15438
  `This machine is already enrolled as ${stored.device_agent_id ?? "a device"} on ${stored.server}. Add it again as a new device? [y/N] `
12782
15439
  );
12783
15440
  if (!YES_ANSWER.test(answer.trim())) {
15441
+ await settleFileAccess(options.fileManager, stored.token, stored, dependencies);
12784
15442
  return await dependencies.runAgent(stored.token, manage, false) ?? EXIT_OK;
12785
15443
  }
12786
15444
  }
@@ -12813,13 +15471,25 @@ async function signInAndRunAgent(options, dependencies) {
12813
15471
  dependencies.printError("The dashboard approved the sign-in without a device token. Update pinggy and try again.");
12814
15472
  return EXIT_FAILED;
12815
15473
  }
12816
- dependencies.writeIdentity({
15474
+ const identity = {
12817
15475
  device_agent_id: approved.device_agent_id,
12818
15476
  token: approved.token,
12819
15477
  server: manage || DEFAULT_SERVER2,
12820
15478
  enrolled_at: null
12821
- });
15479
+ };
12822
15480
  dependencies.print(`${RESULT_MARKER} Signed in as ${email}. Added device ${approved.device_name ?? approved.device_agent_id}.`);
15481
+ let fileManager;
15482
+ try {
15483
+ fileManager = await settleFileAccess(options.fileManager, identity.token, null, dependencies);
15484
+ } catch (err) {
15485
+ if (!isCtrlCAtPrompt(err)) {
15486
+ throw err;
15487
+ }
15488
+ dependencies.writeIdentity(identity);
15489
+ dependencies.print(import_picocolors8.default.yellow("Cancelled. This machine is signed in, and its agent did not start. To start it, run: pinggy device connect"));
15490
+ return EXIT_FAILED;
15491
+ }
15492
+ dependencies.writeIdentity({ ...identity, file_manager: fileManager });
12823
15493
  await printDeviceLink(approved, linkMinutes, dependencies);
12824
15494
  return await dependencies.runAgent(approved.token, manage, true) ?? EXIT_OK;
12825
15495
  }
@@ -12840,7 +15510,7 @@ async function waitForApproval(api, deviceCode, pollIntervalSeconds, dependencie
12840
15510
  const polled = pollUntilApproved(
12841
15511
  api,
12842
15512
  deviceCode,
12843
- pollIntervalSeconds * MILLIS_PER_SECOND2,
15513
+ pollIntervalSeconds * MILLIS_PER_SECOND4,
12844
15514
  controller.signal,
12845
15515
  dependencies
12846
15516
  );
@@ -12975,12 +15645,12 @@ function sleepUnlessAborted(millis, signal) {
12975
15645
  signal.addEventListener("abort", onAbort, { once: true });
12976
15646
  });
12977
15647
  }
12978
- var import_os9, import_picocolors8, EXIT_OK, EXIT_FAILED, DEFAULT_SERVER2, YES_ANSWER, RESULT_MARKER, SECONDS_PER_MINUTE, MILLIS_PER_SECOND2, FIRST_SERVER_ERROR_STATUS, NO_TERMINAL_MESSAGE, ABORT_ERROR_NAME;
15648
+ var import_os11, import_picocolors8, EXIT_OK, EXIT_FAILED, DEFAULT_SERVER2, YES_ANSWER, RESULT_MARKER, SECONDS_PER_MINUTE, MILLIS_PER_SECOND4, FIRST_SERVER_ERROR_STATUS, NO_TERMINAL_MESSAGE;
12979
15649
  var init_deviceLogin = __esm({
12980
15650
  "src/devices/login/deviceLogin.ts"() {
12981
15651
  "use strict";
12982
15652
  init_cjs_shims();
12983
- import_os9 = __toESM(require("os"), 1);
15653
+ import_os11 = __toESM(require("os"), 1);
12984
15654
  import_picocolors8 = __toESM(require("picocolors"), 1);
12985
15655
  init_printer();
12986
15656
  init_util();
@@ -12990,6 +15660,7 @@ var init_deviceLogin = __esm({
12990
15660
  init_deviceIdentity();
12991
15661
  init_loginApi();
12992
15662
  init_login_schema();
15663
+ init_fileAccess();
12993
15664
  init_prompts();
12994
15665
  EXIT_OK = 0;
12995
15666
  EXIT_FAILED = 1;
@@ -12997,10 +15668,9 @@ var init_deviceLogin = __esm({
12997
15668
  YES_ANSWER = /^y(es)?$/i;
12998
15669
  RESULT_MARKER = import_picocolors8.default.green(import_picocolors8.default.bold("\u2192"));
12999
15670
  SECONDS_PER_MINUTE = 60;
13000
- MILLIS_PER_SECOND2 = 1e3;
15671
+ MILLIS_PER_SECOND4 = 1e3;
13001
15672
  FIRST_SERVER_ERROR_STATUS = 500;
13002
15673
  NO_TERMINAL_MESSAGE = "pinggy device login needs a terminal to type the email and the code. On a machine without one, add the device in the dashboard and run: pinggy device connect --token <TOKEN>";
13003
- ABORT_ERROR_NAME = "AbortError";
13004
15674
  }
13005
15675
  });
13006
15676
 
@@ -13014,9 +15684,10 @@ function machineBackgroundAgentDependencies() {
13014
15684
  forgetSavedAgent: forgetDeviceAgent,
13015
15685
  ensureDaemon: ensureDaemonRunning,
13016
15686
  client: (port) => new IPCClient(port, "cli"),
13017
- verify: (token, manage) => startDeviceAgent(token, manage, {
15687
+ verify: (token, manage, fileManager) => startDeviceAgent(token, manage, {
13018
15688
  verifyOnly: true,
13019
- reporter: verifyingReporter
15689
+ reporter: verifyingReporter,
15690
+ fileManager
13020
15691
  }).done,
13021
15692
  sleep: (millis) => new Promise((resolve) => setTimeout(resolve, millis)),
13022
15693
  now: () => Date.now(),
@@ -13054,7 +15725,7 @@ async function readBackgroundAgent(dependencies) {
13054
15725
  }
13055
15726
  async function startAgentInBackground(target, dependencies, options = {}) {
13056
15727
  if (differsFromStored(target, dependencies.readIdentity())) {
13057
- const verified = await dependencies.verify(target.token, target.manage);
15728
+ const verified = await dependencies.verify(target.token, target.manage, options.fileManager);
13058
15729
  if (verified.error || !verified.welcomed) {
13059
15730
  dependencies.printError(verified.error?.message ?? "The device did not connect. Nothing changed.");
13060
15731
  return EXIT_FAILED;
@@ -13628,7 +16299,7 @@ function newestLogFile(q) {
13628
16299
  const nameMatch = parsed.name !== void 0 && parsed.name === q;
13629
16300
  const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
13630
16301
  if (nameMatch || idMatch) {
13631
- const filePath = import_node_path10.default.join(logDir, file);
16302
+ const filePath = import_node_path11.default.join(logDir, file);
13632
16303
  matches.push({ ...parsed, path: filePath, mtime: import_node_fs14.default.statSync(filePath).mtimeMs });
13633
16304
  }
13634
16305
  }
@@ -13648,13 +16319,13 @@ function resolveStoppedLogPath(q) {
13648
16319
  }
13649
16320
  return { status: "not-found" };
13650
16321
  }
13651
- var import_node_fs14, import_node_path10, TUNNEL_ORIGINS, UUID_RE;
16322
+ var import_node_fs14, import_node_path11, TUNNEL_ORIGINS, UUID_RE;
13652
16323
  var init_logPaths = __esm({
13653
16324
  "src/daemon/logPaths.ts"() {
13654
16325
  "use strict";
13655
16326
  init_cjs_shims();
13656
16327
  import_node_fs14 = __toESM(require("fs"), 1);
13657
- import_node_path10 = __toESM(require("path"), 1);
16328
+ import_node_path11 = __toESM(require("path"), 1);
13658
16329
  init_configStore();
13659
16330
  init_configDir();
13660
16331
  TUNNEL_ORIGINS = ["app", "cli", "remote", "device"];
@@ -14072,7 +16743,7 @@ function resolveConnectTarget(flagToken, environmentToken, manage, stored) {
14072
16743
  }
14073
16744
  return null;
14074
16745
  }
14075
- async function handleDevice(args, background = machineBackgroundAgentDependencies()) {
16746
+ async function handleDevice(args, background = machineBackgroundAgentDependencies(), fileAccess = machineFileAccessDependencies()) {
14076
16747
  const environmentToken = takeEnvironmentToken();
14077
16748
  if (args.length === 0) {
14078
16749
  printDeviceHelp();
@@ -14087,19 +16758,28 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
14087
16758
  process.exit(1);
14088
16759
  }
14089
16760
  const inBackground = !values.foreground;
16761
+ const fileManager = parseFilesFlag(values.files);
16762
+ if (fileManager === null) {
16763
+ printer_default.error(INVALID_FILES_FLAG_MESSAGE);
16764
+ process.exit(1);
16765
+ }
14090
16766
  switch (verb) {
14091
16767
  case DeviceVerb.Login:
14092
- exitUnlessOk(await handleDeviceLogin(values.manage, values.name, inBackground, background));
16768
+ exitUnlessOk(await handleDeviceLogin(
16769
+ { manage: values.manage, name: values.name, fileManager },
16770
+ inBackground,
16771
+ background
16772
+ ));
14093
16773
  return;
14094
16774
  case DeviceVerb.Connect:
14095
16775
  case DeviceVerb.Start:
14096
- exitUnlessOk(await handleDeviceConnect(
14097
- values.token,
16776
+ exitUnlessOk(await handleDeviceConnect({
16777
+ flagToken: values.token,
14098
16778
  environmentToken,
14099
- values.manage,
16779
+ manage: values.manage,
14100
16780
  inBackground,
14101
- background
14102
- ));
16781
+ fileManager
16782
+ }, background, fileAccess));
14103
16783
  return;
14104
16784
  case DeviceVerb.Stop:
14105
16785
  exitUnlessOk(await stopAgentInBackground(background));
@@ -14152,29 +16832,38 @@ function mayRunInBackground(background) {
14152
16832
  }
14153
16833
  return true;
14154
16834
  }
14155
- async function handleDeviceLogin(manage, name, inBackground, background) {
16835
+ async function handleDeviceLogin(options, inBackground, background) {
14156
16836
  if (!inBackground) {
14157
16837
  if (!await mayRunInForeground(background)) return EXIT_FAILED;
14158
- return runDeviceLogin({ manage, name });
16838
+ return runDeviceLogin(options);
14159
16839
  }
14160
16840
  if (!mayRunInBackground(background)) return EXIT_FAILED;
14161
- return runDeviceLogin({ manage, name }, {
16841
+ return runDeviceLogin(options, {
14162
16842
  ...machineDeviceLoginDependencies(),
14163
16843
  runAgent: (token, agentManage, signInShown) => startAgentInBackground({ token, manage: agentManage }, background, { signInShown })
14164
16844
  });
14165
16845
  }
14166
- async function handleDeviceConnect(flagToken, environmentToken, manage, inBackground, background) {
14167
- const target = resolveConnectTarget(flagToken, environmentToken, manage, background.readIdentity());
16846
+ async function handleDeviceConnect(request2, background, fileAccess) {
16847
+ const stored = background.readIdentity();
16848
+ const target = resolveConnectTarget(request2.flagToken, request2.environmentToken, request2.manage, stored);
14168
16849
  if (!target) {
14169
16850
  printer_default.error("This machine is not enrolled. Sign it in with your email:\n pinggy device login\nOr add a device in the dashboard, then run:\n pinggy device connect --token <TOKEN>");
14170
16851
  return EXIT_FAILED;
14171
16852
  }
14172
- if (inBackground) {
14173
- if (!mayRunInBackground(background)) return EXIT_FAILED;
14174
- return startAgentInBackground(target, background);
16853
+ const mayRun = request2.inBackground ? mayRunInBackground(background) : await mayRunInForeground(background);
16854
+ if (!mayRun) return EXIT_FAILED;
16855
+ let fileManager;
16856
+ try {
16857
+ fileManager = await settleFileAccess(request2.fileManager, target.token, stored, fileAccess);
16858
+ } catch (err) {
16859
+ if (!isCtrlCAtPrompt(err)) throw err;
16860
+ fileAccess.print(import_picocolors14.default.yellow("Cancelled. Nothing changed."));
16861
+ return EXIT_FAILED;
16862
+ }
16863
+ if (request2.inBackground) {
16864
+ return startAgentInBackground(target, background, { fileManager });
14175
16865
  }
14176
- if (!await mayRunInForeground(background)) return EXIT_FAILED;
14177
- await runDeviceAgent(target.token, target.manage);
16866
+ await runDeviceAgent(target.token, target.manage, { fileManager });
14178
16867
  return EXIT_OK;
14179
16868
  }
14180
16869
  async function handleDeviceStatus(background) {
@@ -14192,6 +16881,7 @@ async function handleDeviceStatus(background) {
14192
16881
  printer_default.print(` Token ${maskToken(identity.token)}`);
14193
16882
  printer_default.print(` Enrolled ${identity.enrolled_at ?? import_picocolors14.default.gray("never")}`);
14194
16883
  printer_default.print(` Autostart ${background.hasSavedAgent() ? "on, starts with the daemon" : import_picocolors14.default.gray("off")}`);
16884
+ printer_default.print(` Files ${describeFileAccess(identity)}`);
14195
16885
  if (foreground) {
14196
16886
  printer_default.print(` Foreground running in another terminal, PID ${foreground.pid}`);
14197
16887
  }
@@ -14214,6 +16904,8 @@ var init_deviceCommand = __esm({
14214
16904
  init_backgroundAgent();
14215
16905
  init_foregroundAgent();
14216
16906
  init_removeDevice();
16907
+ init_fileAccess();
16908
+ init_prompts();
14217
16909
  DeviceVerb = {
14218
16910
  Login: "login",
14219
16911
  Connect: "connect",
@@ -15036,7 +17728,7 @@ async function main() {
15036
17728
  await runUpdateChild2();
15037
17729
  process.exit(0);
15038
17730
  }
15039
- if (isPackagedBinary() && (0, import_os10.platform)() === "win32") removeStaleUpdateFiles();
17731
+ if (isPackagedBinary() && (0, import_os12.platform)() === "win32") removeStaleUpdateFiles();
15040
17732
  const { questionShown } = await offerSelfInstall({ rawArgs, values });
15041
17733
  startBackgroundUpdate({ rawArgs, values, hasAnyArgs, installQuestionShown: questionShown });
15042
17734
  if (isSubcommand(rawArgs)) {
@@ -15045,7 +17737,7 @@ async function main() {
15045
17737
  }
15046
17738
  if (!hasAnyArgs || values.help) {
15047
17739
  printHelpMessage();
15048
- if (questionShown && !hasAnyArgs && (0, import_os10.platform)() === "win32") await waitForEnterToClose();
17740
+ if (questionShown && !hasAnyArgs && (0, import_os12.platform)() === "win32") await waitForEnterToClose();
15049
17741
  return;
15050
17742
  }
15051
17743
  if (values.version) {
@@ -15058,7 +17750,7 @@ async function main() {
15058
17750
  printer_default.fatal(error);
15059
17751
  }
15060
17752
  }
15061
- var import_url2, import_process, import_os10, import_fs14, currentFile, entryFile;
17753
+ var import_url2, import_process, import_os12, import_fs16, currentFile, entryFile;
15062
17754
  var init_main = __esm({
15063
17755
  "src/main.ts"() {
15064
17756
  "use strict";
@@ -15077,8 +17769,8 @@ var init_main = __esm({
15077
17769
  init_handler();
15078
17770
  import_url2 = require("url");
15079
17771
  import_process = require("process");
15080
- import_os10 = require("os");
15081
- import_fs14 = require("fs");
17772
+ import_os12 = require("os");
17773
+ import_fs16 = require("fs");
15082
17774
  init_remoteManagement();
15083
17775
  init_buildAndStartTunnel();
15084
17776
  init_subcommands();
@@ -15088,7 +17780,7 @@ var init_main = __esm({
15088
17780
  currentFile = (0, import_url2.fileURLToPath)(importMetaUrl);
15089
17781
  entryFile = null;
15090
17782
  try {
15091
- entryFile = import_process.argv[1] ? (0, import_fs14.realpathSync)(import_process.argv[1]) : null;
17783
+ entryFile = import_process.argv[1] ? (0, import_fs16.realpathSync)(import_process.argv[1]) : null;
15092
17784
  } catch (e) {
15093
17785
  entryFile = null;
15094
17786
  }
@@ -15130,7 +17822,7 @@ var init_wsProtocol = __esm({
15130
17822
 
15131
17823
  // src/daemon/lifecycle/stateStore.ts
15132
17824
  function getStatePath() {
15133
- return import_node_path11.default.join(getPinggyConfigDir(), STATE_FILENAME);
17825
+ return import_node_path12.default.join(getPinggyConfigDir(), STATE_FILENAME);
15134
17826
  }
15135
17827
  function loadDaemonState() {
15136
17828
  const statePath = getStatePath();
@@ -15176,13 +17868,13 @@ function restorableTunnelCount() {
15176
17868
  const state = loadDaemonState();
15177
17869
  return state ? state.tunnels.filter((t) => t.mode === "detached").length : 0;
15178
17870
  }
15179
- var import_node_fs18, import_node_path11, STATE_FILENAME;
17871
+ var import_node_fs18, import_node_path12, STATE_FILENAME;
15180
17872
  var init_stateStore = __esm({
15181
17873
  "src/daemon/lifecycle/stateStore.ts"() {
15182
17874
  "use strict";
15183
17875
  init_cjs_shims();
15184
17876
  import_node_fs18 = __toESM(require("fs"), 1);
15185
- import_node_path11 = __toESM(require("path"), 1);
17877
+ import_node_path12 = __toESM(require("path"), 1);
15186
17878
  init_configDir();
15187
17879
  init_logger();
15188
17880
  init_util();
@@ -15201,14 +17893,14 @@ function parseBody(method, body) {
15201
17893
  if (!body) return {};
15202
17894
  return JSON.parse(body);
15203
17895
  }
15204
- var import_node_http3, import_node_fs19, import_node_path12, import_ws4, IPCServer;
17896
+ var import_node_http3, import_node_fs19, import_node_path13, import_ws4, IPCServer;
15205
17897
  var init_ipcServer = __esm({
15206
17898
  "src/daemon/ipc/ipcServer.ts"() {
15207
17899
  "use strict";
15208
17900
  init_cjs_shims();
15209
17901
  import_node_http3 = __toESM(require("http"), 1);
15210
17902
  import_node_fs19 = __toESM(require("fs"), 1);
15211
- import_node_path12 = __toESM(require("path"), 1);
17903
+ import_node_path13 = __toESM(require("path"), 1);
15212
17904
  import_ws4 = require("ws");
15213
17905
  init_main();
15214
17906
  init_logger();
@@ -15371,7 +18063,7 @@ var init_ipcServer = __esm({
15371
18063
  if (n) activeNames.add(n);
15372
18064
  }
15373
18065
  for (const file of files) {
15374
- const filePath = import_node_path12.default.join(logDir, file);
18066
+ const filePath = import_node_path13.default.join(logDir, file);
15375
18067
  const stat = import_node_fs19.default.statSync(filePath);
15376
18068
  const parsed = parseTunnelLogFilename(file);
15377
18069
  if (!parsed) continue;