dsh-remote-vs 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16887,8 +16887,49 @@ const UPLOAD_MAX_BYTES = 2 * 1024 * 1024 * 1024;
16887
16887
  * so progress is the bound — any chunk resets this clock.
16888
16888
  */
16889
16889
  const DOWNLOAD_IDLE_MS = 6e4;
16890
- /** Chunk size for one download stream (one SFTP read at a time). */
16891
- const DOWNLOAD_CHUNK_BYTES = 256 * 1024;
16890
+ /** Upload progress bound (no body bytes and no write acknowledgements). */
16891
+ const UPLOAD_IDLE_MS = 6e4;
16892
+ /**
16893
+ * Parallel-transfer shape, shared by download and upload.
16894
+ *
16895
+ * A single `createReadStream`/`createWriteStream` keeps exactly ONE SFTP request
16896
+ * in flight per round trip; measured against a real host that cost about 8x
16897
+ * (4.4 MiB/s single stream vs 35.4 MiB/s for ssh2's pipelined fastGet on the
16898
+ * same link). 256 KiB chunks with 32 in-flight requests (8 MiB of app-side
16899
+ * buffers) are the same tuning ssh2's fastGet/fastPut use and bound the
16900
+ * per-transfer memory; on top of that ssh2 holds up to one 2 MiB channel window
16901
+ * per channel in flight, so a two-channel download peaks around 12 MiB.
16902
+ */
16903
+ const TRANSFER_CHUNK_BYTES = 256 * 1024;
16904
+ /**
16905
+ * Deadline for a download's one-shot metadata calls (`lstat`, `open`, `fstat`).
16906
+ *
16907
+ * Nothing is streaming while they run, so there is no progress signal to watch
16908
+ * and no idle watchdog can help: a server that never answers one would pin the
16909
+ * transfer, its channels and its slots forever. The streaming phase stays
16910
+ * progress-bounded (`DOWNLOAD_IDLE_MS`) because a big file on a slow link is
16911
+ * healthy for minutes.
16912
+ */
16913
+ const DOWNLOAD_META_TIMEOUT_MS = 6e4;
16914
+ /**
16915
+ * Deadline for the OPTIONAL second channel's handle open.
16916
+ *
16917
+ * This runs after the response headers are sent, so a hang here is worse than a
16918
+ * missing second channel: the client is already reading a 200 body. Short on
16919
+ * purpose — the fallback (one channel) is always correct.
16920
+ */
16921
+ const EXTRA_CHANNEL_TIMEOUT_MS = 1e4;
16922
+ /**
16923
+ * How long a handle close may take before it is abandoned.
16924
+ *
16925
+ * ssh2 only settles the CLOSE requests that were pending when a channel closed:
16926
+ * a close issued on an already-dead channel never calls back (the payload is
16927
+ * dropped or written to a stale recipient). Awaiting that forever would hang the
16928
+ * transfer AFTER its body was delivered and pin both the channels and their
16929
+ * slots — the session teardown that follows settles the request anyway, so the
16930
+ * wait is abandoned and the pool's `finally` proceeds.
16931
+ */
16932
+ const HANDLE_CLOSE_TIMEOUT_MS = 2e3;
16892
16933
  /**
16893
16934
  * Cap for both per-path memory sets below (levels confirmed to exist, listings
16894
16935
  * already reported as truncated). Each only ever saves round trips or a repeat
@@ -16911,6 +16952,26 @@ function remotePath(path) {
16911
16952
  return normalized;
16912
16953
  }
16913
16954
  /**
16955
+ * Reject when `promise` has not settled within `ms`.
16956
+ *
16957
+ * The download's one-shot calls (`lstat`, `open`, `fstat`, an extra channel's
16958
+ * handle) have no progress signal, so this is the only thing between a stalled
16959
+ * server and a response — and two SFTP channels — pinned forever.
16960
+ */
16961
+ function bounded(promise, ms, message) {
16962
+ return new Promise((resolve, reject) => {
16963
+ const timer = setTimeout(() => reject(new Error(message)), ms);
16964
+ timer.unref?.();
16965
+ promise.then((value) => {
16966
+ clearTimeout(timer);
16967
+ resolve(value);
16968
+ }, (error) => {
16969
+ clearTimeout(timer);
16970
+ reject(error instanceof Error ? error : new Error(String(error)));
16971
+ });
16972
+ });
16973
+ }
16974
+ /**
16914
16975
  * `Content-Disposition` for one attachment (RFC 6266 + RFC 5987).
16915
16976
  *
16916
16977
  * Receivers prefer `filename*` when both forms are present (RFC 6266 §4.3),
@@ -16936,7 +16997,7 @@ var RemoteFiles = class {
16936
16997
  }
16937
16998
  async list(alias, dir) {
16938
16999
  const path = remotePath(dir);
16939
- return this.pool.withSftp(alias, async (sftp) => {
17000
+ return this.pool.withBrowseSftp(alias, async (sftp) => {
16940
17001
  let rows;
16941
17002
  try {
16942
17003
  rows = await readdirAsync(sftp, path);
@@ -16957,14 +17018,14 @@ var RemoteFiles = class {
16957
17018
  }
16958
17019
  async stat(alias, file) {
16959
17020
  const path = remotePath(file);
16960
- return this.pool.withSftp(alias, async (sftp) => {
17021
+ return this.pool.withBrowseSftp(alias, async (sftp) => {
16961
17022
  const attrs = await lstatAsync(sftp, path);
16962
17023
  return toEntry(posix.dirname(path), posix.basename(path), attrs);
16963
17024
  });
16964
17025
  }
16965
17026
  async read(alias, file) {
16966
17027
  const path = remotePath(file);
16967
- return this.pool.withSftp(alias, async (sftp) => {
17028
+ return this.pool.withBrowseSftp(alias, async (sftp) => {
16968
17029
  const attrs = await lstatAsync(sftp, path).catch(async (error) => {
16969
17030
  throw await explainSftpFailure(sftp, path, "file", error) ?? error;
16970
17031
  });
@@ -17044,7 +17105,7 @@ var RemoteFiles = class {
17044
17105
  await unlinkAsync(sftp, partial).catch(() => void 0);
17045
17106
  throw await explainSftpFailure(sftp, path, "file", error) ?? error;
17046
17107
  }
17047
- });
17108
+ }, { timeoutMs: 0 });
17048
17109
  }
17049
17110
  /**
17050
17111
  * Stream one remote file into an HTTP response (download to the local machine).
@@ -17065,16 +17126,19 @@ var RemoteFiles = class {
17065
17126
  */
17066
17127
  async download(alias, file, res) {
17067
17128
  const path = remotePath(file);
17068
- await this.pool.withSftp(alias, async (sftp) => {
17069
- if (isDir((await lstatAsync(sftp, path).catch(async (error) => {
17129
+ await this.pool.withTransferSftp(alias, async (sftp, addChannel) => {
17130
+ if (isDir((await bounded(lstatAsync(sftp, path).catch(async (error) => {
17070
17131
  throw await explainSftpFailure(sftp, path, "file", error) ?? error;
17071
- })).mode)) throw new Error(`not a file: ${path} is a directory`);
17072
- const handle = await openAsync(sftp, path).catch(async (error) => {
17132
+ }), DOWNLOAD_META_TIMEOUT_MS, `listing ${path} timed out after ${DOWNLOAD_META_TIMEOUT_MS / 1e3}s`)).mode)) throw new Error(`not a file: ${path} is a directory`);
17133
+ const handle = await bounded(openAsync(sftp, path).catch(async (error) => {
17073
17134
  throw await explainFollowFailure(sftp, path, error) ?? error;
17074
- });
17075
- let streamed = false;
17135
+ }), DOWNLOAD_META_TIMEOUT_MS, `opening ${path} timed out after ${DOWNLOAD_META_TIMEOUT_MS / 1e3}s`);
17136
+ const channels = [{
17137
+ sftp,
17138
+ handle
17139
+ }];
17076
17140
  try {
17077
- const attrs = await fstatAsync(sftp, handle);
17141
+ const attrs = await bounded(fstatAsync(sftp, handle), DOWNLOAD_META_TIMEOUT_MS, `stat of ${path} timed out after ${DOWNLOAD_META_TIMEOUT_MS / 1e3}s`);
17078
17142
  if (isDir(attrs.mode)) throw new Error(`not a file: ${path} is a directory`);
17079
17143
  if (res.destroyed) return;
17080
17144
  res.writeHead(200, {
@@ -17088,60 +17152,24 @@ var RemoteFiles = class {
17088
17152
  res.end();
17089
17153
  return;
17090
17154
  }
17091
- const stream = sftp.createReadStream(path, {
17092
- handle,
17093
- start: 0,
17094
- end: attrs.size - 1,
17095
- highWaterMark: DOWNLOAD_CHUNK_BYTES
17096
- });
17097
- streamed = true;
17098
- await new Promise((resolve, reject) => {
17099
- let settled = false;
17100
- let idle;
17101
- const finish = (error) => {
17102
- if (settled) return;
17103
- settled = true;
17104
- if (idle !== void 0) clearTimeout(idle);
17105
- if (error === void 0) {
17106
- resolve();
17107
- return;
17108
- }
17109
- res.destroy(error);
17110
- reject(error);
17111
- };
17112
- const arm = () => {
17113
- if (idle !== void 0) clearTimeout(idle);
17114
- idle = setTimeout(() => {
17115
- if (stream.isPaused() || res.writableLength > 0) {
17116
- arm();
17117
- return;
17118
- }
17119
- try {
17120
- stream.destroy();
17121
- } catch {}
17122
- finish(/* @__PURE__ */ new Error(`download stalled: no bytes for ${DOWNLOAD_IDLE_MS / 1e3}s`));
17123
- }, DOWNLOAD_IDLE_MS);
17124
- };
17125
- stream.on("data", arm);
17126
- res.on("drain", arm);
17127
- stream.on("error", (error) => {
17128
- finish(error instanceof Error ? error : new Error(String(error)));
17129
- });
17130
- res.on("close", () => {
17131
- if (res.writableEnded) return;
17132
- try {
17133
- stream.destroy();
17134
- } catch {}
17135
- finish();
17136
- });
17137
- stream.on("end", () => finish());
17138
- arm();
17139
- stream.pipe(res);
17140
- });
17155
+ if (attrs.size >= 4194304) for (let extra = 1; extra < 2; extra += 1) {
17156
+ const channel = await addChannel();
17157
+ if (channel === void 0) break;
17158
+ try {
17159
+ const extraHandle = await bounded(openAsync(channel, path), EXTRA_CHANNEL_TIMEOUT_MS, `opening ${path} on the second channel timed out after ${EXTRA_CHANNEL_TIMEOUT_MS / 1e3}s`);
17160
+ channels.push({
17161
+ sftp: channel,
17162
+ handle: extraHandle
17163
+ });
17164
+ } catch {
17165
+ break;
17166
+ }
17167
+ }
17168
+ await pipeChannelsToResponse(channels, attrs.size, res);
17141
17169
  } finally {
17142
- if (!streamed) await closeAsync(sftp, handle);
17170
+ for (const channel of channels) await closeQuietly(channel.sftp, channel.handle);
17143
17171
  }
17144
- }, { timeoutMs: 0 });
17172
+ });
17145
17173
  }
17146
17174
  async mkdir(alias, dir) {
17147
17175
  const path = remotePath(dir);
@@ -17356,14 +17384,198 @@ function statAsync(sftp, path) {
17356
17384
  });
17357
17385
  });
17358
17386
  }
17359
- function openAsync(sftp, path) {
17387
+ function openAsync(sftp, path, flags = "r") {
17360
17388
  return new Promise((resolve, reject) => {
17361
- sftp.open(path, "r", (error, handle) => {
17389
+ sftp.open(path, flags, (error, handle) => {
17362
17390
  if (error !== void 0 && error !== null) reject(error);
17363
17391
  else resolve(handle);
17364
17392
  });
17365
17393
  });
17366
17394
  }
17395
+ /** Read exactly `buffer.length` bytes at `position` (SFTP may answer short reads). */
17396
+ async function readHandleFully(sftp, handle, buffer, position) {
17397
+ let filled = 0;
17398
+ while (filled < buffer.length) {
17399
+ const read = await new Promise((resolve, reject) => {
17400
+ sftp.read(handle, buffer.subarray(filled), 0, buffer.length - filled, position + filled, (error, bytesRead) => {
17401
+ if (error !== void 0 && error !== null) reject(error);
17402
+ else resolve(bytesRead);
17403
+ });
17404
+ });
17405
+ if (read <= 0) throw new Error(`short read at ${position + filled}`);
17406
+ filled += read;
17407
+ }
17408
+ }
17409
+ /**
17410
+ * Copy an open remote file into an HTTP response with a bounded parallel read
17411
+ * window spread over one or more SFTP channels.
17412
+ *
17413
+ * `res` must already carry its headers (including content-length). Workers pread
17414
+ * 256 KiB chunks out of order into a bounded map, and one ordered writer copies
17415
+ * them to the socket, so the response bytes stay ordered while up to
17416
+ * `TRANSFER_CONCURRENCY` READs stay in flight. The chunk index picks the channel
17417
+ * (`index % channels.length`) so the in-flight bytes are spread across the SSH
17418
+ * channel windows instead of queueing behind one 2 MiB window. A closed response
17419
+ * (user cancel) resolves quietly — the route treats that as a cancellation, not
17420
+ * an error — and a no-progress watchdog fails a silently dead transfer.
17421
+ */
17422
+ async function pipeChannelsToResponse(channels, size, res) {
17423
+ const chunkBytes = TRANSFER_CHUNK_BYTES;
17424
+ const totalChunks = Math.ceil(size / chunkBytes);
17425
+ const windowChunks = Math.min(32, totalChunks);
17426
+ const ready = /* @__PURE__ */ new Map();
17427
+ const chunkWaiters = /* @__PURE__ */ new Map();
17428
+ const slotWaiters = [];
17429
+ let slots = windowChunks;
17430
+ let nextRead = 0;
17431
+ let cancelled = false;
17432
+ let failure;
17433
+ let lastActivity = Date.now();
17434
+ const wakeSlots = () => {
17435
+ for (const wake of slotWaiters.splice(0)) wake();
17436
+ };
17437
+ const wakeChunks = () => {
17438
+ for (const wake of chunkWaiters.values()) wake();
17439
+ chunkWaiters.clear();
17440
+ };
17441
+ const signalChunk = (index) => {
17442
+ const wake = chunkWaiters.get(index);
17443
+ if (wake !== void 0) {
17444
+ chunkWaiters.delete(index);
17445
+ wake();
17446
+ }
17447
+ };
17448
+ const fail = (error) => {
17449
+ if (failure !== void 0) return;
17450
+ failure = error instanceof Error ? error : new Error(String(error));
17451
+ wakeSlots();
17452
+ wakeChunks();
17453
+ };
17454
+ const acquire = async () => {
17455
+ while (slots <= 0) await new Promise((resolve) => slotWaiters.push(resolve));
17456
+ slots -= 1;
17457
+ };
17458
+ const release = () => {
17459
+ slots += 1;
17460
+ const wake = slotWaiters.shift();
17461
+ if (wake !== void 0) wake();
17462
+ };
17463
+ /**
17464
+ * Channels whose READ failed. Their chunks are re-read on the first channel:
17465
+ * the extra channel is an optimisation, so losing it must degrade the transfer
17466
+ * to the single-channel shape it would have used anyway instead of failing a
17467
+ * download the first channel can still finish. (A channel that STALLS rather
17468
+ * than errors is not recoverable here: no bytes means the ordered writer has
17469
+ * nothing to reorder, and the no-progress watchdog ends the transfer.)
17470
+ */
17471
+ const failedChannels = /* @__PURE__ */ new Set();
17472
+ const primary = channels[0];
17473
+ const channelFor = (index) => {
17474
+ const slot = channels.length > 1 ? index % channels.length : 0;
17475
+ if (slot === 0 || failedChannels.has(slot)) return {
17476
+ ...primary,
17477
+ slot
17478
+ };
17479
+ return {
17480
+ ...channels[slot],
17481
+ slot
17482
+ };
17483
+ };
17484
+ const worker = async () => {
17485
+ for (;;) {
17486
+ if (cancelled || failure !== void 0) return;
17487
+ await acquire();
17488
+ if (cancelled || failure !== void 0) {
17489
+ release();
17490
+ return;
17491
+ }
17492
+ const index = nextRead++;
17493
+ if (index >= totalChunks) {
17494
+ release();
17495
+ return;
17496
+ }
17497
+ const start = index * chunkBytes;
17498
+ const length = Math.min(chunkBytes, size - start);
17499
+ const buffer = Buffer.allocUnsafe(length);
17500
+ try {
17501
+ const channel = channelFor(index);
17502
+ try {
17503
+ await readHandleFully(channel.sftp, channel.handle, buffer, start);
17504
+ } catch (error) {
17505
+ if (channel.slot === 0 || cancelled || failure !== void 0) throw error;
17506
+ failedChannels.add(channel.slot);
17507
+ await readHandleFully(primary.sftp, primary.handle, buffer, start);
17508
+ }
17509
+ } catch (error) {
17510
+ release();
17511
+ fail(error);
17512
+ return;
17513
+ }
17514
+ lastActivity = Date.now();
17515
+ ready.set(index, buffer);
17516
+ signalChunk(index);
17517
+ }
17518
+ };
17519
+ const waitChunk = (index) => new Promise((resolve) => {
17520
+ if (ready.has(index) || failure !== void 0) resolve();
17521
+ else chunkWaiters.set(index, resolve);
17522
+ });
17523
+ const waitDrain = () => new Promise((resolve) => {
17524
+ if (cancelled || failure !== void 0) {
17525
+ resolve();
17526
+ return;
17527
+ }
17528
+ res.once("drain", resolve);
17529
+ });
17530
+ const onResponseClose = () => {
17531
+ if (res.writableEnded) return;
17532
+ cancelled = true;
17533
+ wakeSlots();
17534
+ wakeChunks();
17535
+ };
17536
+ res.on("close", onResponseClose);
17537
+ const idle = setInterval(() => {
17538
+ if (cancelled || failure !== void 0) return;
17539
+ if (Date.now() - lastActivity < 6e4) return;
17540
+ if (res.writableLength > 0) {
17541
+ lastActivity = Date.now();
17542
+ return;
17543
+ }
17544
+ fail(/* @__PURE__ */ new Error(`download stalled: no bytes for ${DOWNLOAD_IDLE_MS / 1e3}s`));
17545
+ }, Math.min(5e3, DOWNLOAD_IDLE_MS));
17546
+ idle.unref?.();
17547
+ const workers = Array.from({ length: windowChunks }, () => worker());
17548
+ try {
17549
+ for (let index = 0; index < totalChunks; index += 1) {
17550
+ if (cancelled) break;
17551
+ if (failure !== void 0) break;
17552
+ if (!ready.has(index)) await waitChunk(index);
17553
+ if (cancelled) break;
17554
+ if (failure !== void 0) break;
17555
+ const buffer = ready.get(index);
17556
+ if (buffer === void 0) continue;
17557
+ ready.delete(index);
17558
+ if (!res.write(buffer)) await waitDrain();
17559
+ release();
17560
+ lastActivity = Date.now();
17561
+ }
17562
+ } finally {
17563
+ clearInterval(idle);
17564
+ res.removeListener("close", onResponseClose);
17565
+ const drained = Promise.all(workers.map((workerPromise) => workerPromise.catch(() => void 0)));
17566
+ if (failure !== void 0 || cancelled) {
17567
+ cancelled = true;
17568
+ wakeSlots();
17569
+ wakeChunks();
17570
+ await Promise.race([drained, new Promise((resolve) => setTimeout(resolve, 250))]);
17571
+ } else await drained;
17572
+ }
17573
+ if (failure !== void 0) {
17574
+ res.destroy(failure);
17575
+ throw failure;
17576
+ }
17577
+ if (!cancelled) res.end();
17578
+ }
17367
17579
  function fstatAsync(sftp, handle) {
17368
17580
  return new Promise((resolve, reject) => {
17369
17581
  sftp.fstat(handle, (error, attrs) => {
@@ -17382,6 +17594,19 @@ function closeAsync(sftp, handle) {
17382
17594
  });
17383
17595
  }
17384
17596
  /**
17597
+ * Close one handle, but never wait forever for a channel that is already gone.
17598
+ *
17599
+ * A close on a dead channel never calls back (see HANDLE_CLOSE_TIMEOUT_MS); the
17600
+ * session teardown that follows settles it, so abandoning the wait is safe and
17601
+ * keeps a delivered download (or a finished upload) from pinning its channels.
17602
+ */
17603
+ function closeQuietly(sftp, handle) {
17604
+ const abandoned = new Promise((resolve) => {
17605
+ setTimeout(resolve, HANDLE_CLOSE_TIMEOUT_MS).unref?.();
17606
+ });
17607
+ return Promise.race([closeAsync(sftp, handle), abandoned]);
17608
+ }
17609
+ /**
17385
17610
  * Explain an `open` failure after lstat already saw a symlink: lstat reports
17386
17611
  * the LINK's type, so "the thing at the end of the link is a directory" only
17387
17612
  * shows up after the follow. `stat` follows the link and answers the question
@@ -17453,11 +17678,18 @@ function writeFileAsync(sftp, path, data) {
17453
17678
  });
17454
17679
  }
17455
17680
  /**
17456
- * Pipe a readable request body into one remote file.
17681
+ * Stream one readable request body into a new remote file with a bounded
17682
+ * parallel write window.
17683
+ *
17684
+ * The mirror of `pipeChannelsToResponse`: incoming bytes are cut into
17685
+ * `TRANSFER_CHUNK_BYTES` pieces and up to `TRANSFER_CONCURRENCY` WRITEs are in
17686
+ * flight at their own offsets. A single `createWriteStream` keeps one WRITE per
17687
+ * round trip and was far slower on the same link (~1 MiB/s, so a 64 MiB body
17688
+ * could not even finish inside the old 60 s session deadline).
17457
17689
  *
17458
- * Destroys the write stream on any failure so a half-written upload cannot sit
17459
- * on the wire after the response has already been sent, and counts bytes while
17460
- * they pass so the caller can report and cap the transfer.
17690
+ * The producer is paused while more than two windows of chunks are waiting, so
17691
+ * Host memory stays bounded. Aborted clients (no `end`) fail instead of hanging:
17692
+ * a stuck upload used to pin the SFTP session and block every later operation.
17461
17693
  *
17462
17694
  * @param sftp - live SFTP session.
17463
17695
  * @param path - absolute remote destination.
@@ -17467,39 +17699,130 @@ function writeFileAsync(sftp, path, data) {
17467
17699
  */
17468
17700
  function streamIntoFile(sftp, path, source, maxBytes) {
17469
17701
  return new Promise((resolve, reject) => {
17470
- const out = sftp.createWriteStream(path);
17471
- let bytes = 0;
17702
+ const chunkBytes = TRANSFER_CHUNK_BYTES;
17703
+ const windowChunks = 32;
17704
+ const chunks = /* @__PURE__ */ new Map();
17705
+ let nextChunk = 0;
17706
+ let nextWrite = 0;
17707
+ let pendingWrites = 0;
17708
+ let received = 0;
17709
+ let carry;
17710
+ let handle;
17711
+ let ended = false;
17472
17712
  let settled = false;
17473
- const fail = (error) => {
17713
+ let lastActivity = Date.now();
17714
+ let idle;
17715
+ const finish = (error) => {
17474
17716
  if (settled) return;
17475
17717
  settled = true;
17718
+ if (idle !== void 0) clearInterval(idle);
17476
17719
  try {
17477
- out.destroy();
17720
+ source.pause();
17478
17721
  } catch {}
17479
- reject(error instanceof Error ? error : new Error(String(error)));
17722
+ if (error === void 0) {
17723
+ resolve(received);
17724
+ return;
17725
+ }
17726
+ try {
17727
+ source.destroy?.(error);
17728
+ } catch {}
17729
+ if (handle !== void 0) {
17730
+ const current = handle;
17731
+ handle = void 0;
17732
+ closeQuietly(sftp, current);
17733
+ }
17734
+ reject(error);
17735
+ };
17736
+ const pump = () => {
17737
+ const current = handle;
17738
+ if (settled || current === void 0) return;
17739
+ while (pendingWrites < windowChunks && chunks.has(nextWrite)) {
17740
+ const index = nextWrite++;
17741
+ const buffer = chunks.get(index);
17742
+ if (buffer === void 0) break;
17743
+ chunks.delete(index);
17744
+ pendingWrites += 1;
17745
+ sftp.write(current, buffer, 0, buffer.length, index * chunkBytes, (error) => {
17746
+ pendingWrites -= 1;
17747
+ if (settled) return;
17748
+ if (error !== void 0 && error !== null) {
17749
+ finish(error instanceof Error ? error : new Error(String(error)));
17750
+ return;
17751
+ }
17752
+ lastActivity = Date.now();
17753
+ pump();
17754
+ maybeFinish();
17755
+ try {
17756
+ if (chunks.size < windowChunks) source.resume();
17757
+ } catch {}
17758
+ });
17759
+ }
17760
+ };
17761
+ const maybeFinish = () => {
17762
+ if (settled || !ended) return;
17763
+ if (pendingWrites > 0 || chunks.size > 0) return;
17764
+ const current = handle;
17765
+ handle = void 0;
17766
+ if (current === void 0) {
17767
+ finish();
17768
+ return;
17769
+ }
17770
+ closeQuietly(sftp, current).then(() => finish(), () => finish());
17771
+ };
17772
+ const enqueue = (buffer) => {
17773
+ chunks.set(nextChunk, buffer);
17774
+ nextChunk += 1;
17775
+ try {
17776
+ if (chunks.size + pendingWrites >= windowChunks * 2) source.pause();
17777
+ } catch {}
17778
+ pump();
17779
+ };
17780
+ const pushData = (chunk) => {
17781
+ const data = carry === void 0 ? chunk : Buffer.concat([carry, chunk]);
17782
+ let offset = 0;
17783
+ while (data.length - offset >= chunkBytes) {
17784
+ enqueue(Buffer.from(data.subarray(offset, offset + chunkBytes)));
17785
+ offset += chunkBytes;
17786
+ }
17787
+ carry = offset < data.length ? Buffer.from(data.subarray(offset)) : void 0;
17480
17788
  };
17481
17789
  source.on("data", (chunk) => {
17482
- bytes += chunk.length;
17483
- if (bytes > maxBytes) {
17484
- try {
17485
- source.pause();
17486
- } catch {}
17487
- fail(/* @__PURE__ */ new Error(`upload exceeds the ${formatBytes(maxBytes)} limit`));
17790
+ if (settled) return;
17791
+ received += chunk.length;
17792
+ if (received > maxBytes) {
17793
+ finish(/* @__PURE__ */ new Error(`upload exceeds the ${formatBytes(maxBytes)} limit`));
17794
+ return;
17488
17795
  }
17796
+ lastActivity = Date.now();
17797
+ pushData(chunk);
17798
+ });
17799
+ source.on("end", () => {
17800
+ if (settled || ended) return;
17801
+ ended = true;
17802
+ if (carry !== void 0) {
17803
+ const tail = carry;
17804
+ carry = void 0;
17805
+ enqueue(tail);
17806
+ }
17807
+ maybeFinish();
17489
17808
  });
17490
- source.on("error", fail);
17491
- const aborted = () => fail(/* @__PURE__ */ new Error("upload aborted by the client"));
17809
+ source.on("error", (error) => finish(error instanceof Error ? error : new Error(String(error))));
17810
+ const aborted = () => finish(/* @__PURE__ */ new Error("upload aborted by the client"));
17492
17811
  source.on("aborted", aborted);
17493
17812
  source.on("close", () => {
17494
17813
  if (source.complete === false) aborted();
17495
17814
  });
17496
- out.on("error", fail);
17497
- out.on("close", () => {
17815
+ idle = setInterval(() => {
17498
17816
  if (settled) return;
17499
- settled = true;
17500
- resolve(bytes);
17501
- });
17502
- source.pipe(out);
17817
+ if (Date.now() - lastActivity < 6e4) return;
17818
+ finish(/* @__PURE__ */ new Error(`SFTP upload stalled: no progress for ${UPLOAD_IDLE_MS / 1e3}s`));
17819
+ }, Math.min(5e3, UPLOAD_IDLE_MS));
17820
+ idle.unref?.();
17821
+ openAsync(sftp, path, "w").then((opened) => {
17822
+ handle = opened;
17823
+ pump();
17824
+ maybeFinish();
17825
+ }, (error) => finish(error instanceof Error ? error : new Error(String(error))));
17503
17826
  });
17504
17827
  }
17505
17828
  /** Human-facing size for an upload cap ("2 GiB", "16 KiB"). */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-remote-vs",
3
3
  "description": "VSCode-style remote development for DSH: SSH host manager (key/password), helper deploy pipeline with version check, remote file explorer + editor + terminal in dsh-better-sidebar.",
4
- "version": "0.12.0",
4
+ "version": "0.13.0",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
7
7
  "dsh",
@@ -30,8 +30,12 @@ function detailText(task: DownloadTask, t: (key: string) => string): string {
30
30
  return task.via === 'browserDefault' ? t('downloads.browserDefault') : t('downloads.done')
31
31
  }
32
32
  const loaded = formatByteCount(task.loaded)
33
- if (task.total === undefined || task.total <= 0) return `${loaded} · ${t('downloads.indeterminate')}`
34
- return `${loaded} / ${formatByteCount(task.total)}`
33
+ const archive = task.directory || task.selection !== undefined
34
+ if (task.total !== undefined && task.total > 0) return `${loaded} / ${formatByteCount(task.total)}`
35
+ // An archive has no length by design (chunked tar). A plain FILE with no
36
+ // known total means a shell/proxy stripped content-length (DSH Desktop does)
37
+ // — saying "packaging…" there wrongly suggests we re-archive the file.
38
+ return `${loaded} · ${t(archive ? 'downloads.indeterminate' : 'downloads.sizeUnknown')}`
35
39
  }
36
40
 
37
41
  /** Percent for the bar, or `undefined` while the size is unknown (archives). */