ssh2-scp 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README-CN.md CHANGED
@@ -8,6 +8,7 @@
8
8
 
9
9
  - 通过 SSH2 shell/command 会话进行文件操作(无需 SFTP)
10
10
  - 支持所有常用文件系统操作
11
+ - 单文件传输全程流式处理,无文件大小限制
11
12
  - 支持非 UTF-8 编码(如 GBK),通过可选的 iconv-lite 实现
12
13
  - 同时支持 ESM 和 CJS 导出
13
14
  - 支持 TypeScript
@@ -151,6 +152,14 @@ await transfer.startTransfer()
151
152
  - `onProgress` - 进度回调函数 `(transferred, total) => void`
152
153
  - `onData` - 数据回调函数 `(count) => void`
153
154
 
155
+ ### 传输说明
156
+
157
+ - 两个方向都通过 exec 通道用 `dd` 全程流式传输,文件不需要放进内存,因此**没有文件大小限制**。此前的上传会先 `readFileSync` 整个文件,受 Node 的 `ERR_FS_FILE_TOO_LARGE` 限制,最大只能传 2 GiB。
158
+ - `pause()` / `resume()` 在上传和下载两个方向都可用。
159
+ - `destroy()` 会中止传输,并同时关闭远端的 `dd` 进程。
160
+ - 任一方向出错时 `startTransfer()` 都会 reject,包括本地写入失败(例如磁盘写满时的 `ENOSPC`)——这种情况以前会一直挂住且不报任何错误。
161
+ - 传输失败时,`getState().transferred` 只统计真正写入目标端的字节数。
162
+
154
163
  ## 文件夹传输
155
164
 
156
165
  `FolderTransfer` 会通过 SSH 命令通道流式传输 tar 归档。它直接从原始 `ssh2` `Client` 初始化,支持暂停/恢复,并同时支持 POSIX 服务器和带有 `tar` 的 Windows OpenSSH 服务器。
package/README.md CHANGED
@@ -8,6 +8,7 @@ Remote file system operations/file transfer over SSH2 session without SFTP
8
8
 
9
9
  - File operations via SSH2 shell/command session (no SFTP required)
10
10
  - Supports all common file system operations
11
+ - Streaming single-file transfer, with no file size limit
11
12
  - Non-UTF-8 encoding support (e.g. GBK) via optional iconv-lite
12
13
  - Both ESM and CJS exports
13
14
  - TypeScript support
@@ -151,6 +152,20 @@ await transfer.startTransfer()
151
152
  - `onProgress` - Progress callback `(transferred, total) => void`
152
153
  - `onData` - Data callback `(count) => void`
153
154
 
155
+ ### Transfer Notes
156
+
157
+ - Both directions are fully streamed through `dd` over the exec channel — the
158
+ file never has to fit in memory, so **there is no file size limit**. Uploads
159
+ used to `readFileSync` the whole file first, which capped them at 2 GiB with
160
+ Node's `ERR_FS_FILE_TOO_LARGE`.
161
+ - `pause()` / `resume()` work in both directions.
162
+ - `destroy()` aborts the transfer and closes the remote `dd` with it.
163
+ - `startTransfer()` rejects on failure, from either side. That includes a local
164
+ write error such as `ENOSPC` on a full disk — that case used to hang forever
165
+ with no error at all.
166
+ - On a failed transfer, `getState().transferred` only counts bytes that actually
167
+ reached the destination.
168
+
154
169
  ## Folder Transfer
155
170
 
156
171
  `FolderTransfer` streams a tar archive over the SSH command channel. It is initialized from a raw `ssh2` `Client`, supports pause/resume, and targets both POSIX servers and Windows OpenSSH servers that provide `tar`.
@@ -153,9 +153,15 @@ class SshFs {
153
153
  if (!line || i === 0) continue;
154
154
  const parts = line.split(/\s+/);
155
155
  if (parts.length < 9) continue;
156
- const name = parts.slice(8).join(" ");
157
- if (name === "." || name === "..") continue;
158
156
  const type = parts[0].charAt(0);
157
+ let name = parts.slice(8).join(" ");
158
+ if (type === "l") {
159
+ const arrow = name.indexOf(" -> ");
160
+ if (arrow > 0) {
161
+ name = name.slice(0, arrow);
162
+ }
163
+ }
164
+ if (name === "." || name === "..") continue;
159
165
  const mode = parseModeFromLongname(parts[0]);
160
166
  const owner = parseInt(parts[2], 10);
161
167
  const group = parseInt(parts[3], 10);
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const fs = require("fs");
4
4
  const path = require("path");
5
+ const stream = require("stream");
6
+ const promises = require("stream/promises");
5
7
  function _interopNamespaceDefault(e) {
6
8
  const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
7
9
  if (e) {
@@ -27,6 +29,8 @@ class Transfer {
27
29
  state;
28
30
  aborted = false;
29
31
  sshFs;
32
+ pauseTarget = null;
33
+ activeChannel = null;
30
34
  constructor(sshFs, options) {
31
35
  this.sshFs = sshFs;
32
36
  this.session = sshFs.session;
@@ -57,24 +61,23 @@ class Transfer {
57
61
  } catch (err) {
58
62
  this.state.error = err;
59
63
  throw err;
64
+ } finally {
65
+ this.pauseTarget = null;
66
+ this.activeChannel = null;
60
67
  }
61
68
  }
62
69
  async getRemoteFileSize(remotePath) {
63
70
  const output = await this.runExec(`stat -c %s "${remotePath}" 2>/dev/null || stat -f %z "${remotePath}" 2>/dev/null`);
64
71
  return parseInt(output.trim(), 10) || 0;
65
72
  }
66
- runExec(cmd, stdinData) {
73
+ runExec(cmd) {
67
74
  return new Promise((resolve, reject) => {
68
- this.session.exec(cmd, (err, stream) => {
75
+ this.session.exec(cmd, (err, stream2) => {
69
76
  if (err) {
70
77
  return reject(err);
71
78
  }
72
- if (stdinData) {
73
- stream.stdin.write(stdinData);
74
- stream.stdin.end();
75
- }
76
79
  let out = Buffer.from("");
77
- stream.on("close", () => {
80
+ stream2.on("close", () => {
78
81
  resolve(out.toString());
79
82
  }).on("data", (data) => {
80
83
  out = Buffer.concat([out, data]);
@@ -85,72 +88,178 @@ class Transfer {
85
88
  });
86
89
  }
87
90
  async download() {
88
- const { remotePath, localPath, onProgress, onData } = this.options;
91
+ const { remotePath, localPath } = this.options;
89
92
  const dir = path__namespace.dirname(localPath);
90
93
  if (!fs__namespace.existsSync(dir)) {
91
94
  fs__namespace.mkdirSync(dir, { recursive: true });
92
95
  }
93
96
  this.state.total = await this.getRemoteFileSize(remotePath);
94
- return new Promise((resolve, reject) => {
95
- const cmd = `dd if="${remotePath}" bs=${this.chunkSize} 2>/dev/null`;
96
- this.session.exec(cmd, (err, stream) => {
97
- if (err) {
98
- return reject(err);
99
- }
100
- const writeStream = fs__namespace.createWriteStream(localPath);
101
- let localTransferred = 0;
102
- stream.on("data", (data) => {
103
- if (this.state.paused || this.aborted) {
104
- return;
105
- }
106
- writeStream.write(data);
107
- localTransferred += data.length;
108
- this.state.transferred = localTransferred;
109
- if (onProgress) {
110
- onProgress(localTransferred, this.state.total);
111
- }
112
- if (onData) {
113
- onData(data.length);
114
- }
115
- });
116
- stream.on("close", () => {
117
- writeStream.end(() => {
118
- resolve();
119
- });
120
- });
121
- stream.on("error", (err2) => {
122
- this.state.error = err2;
123
- writeStream.end();
124
- reject(err2);
125
- });
126
- });
127
- });
97
+ const channel = await this.execStream(`dd if="${remotePath}" bs=${this.chunkSize}`);
98
+ this.activeChannel = channel;
99
+ this.pauseTarget = channel;
100
+ const closePromise = this.waitForChannelClose(channel);
101
+ const writeStream = fs__namespace.createWriteStream(localPath, { highWaterMark: this.chunkSize });
102
+ try {
103
+ await Promise.all([
104
+ promises.pipeline(this.channelToReadable(channel), this.createProgressStream(), writeStream),
105
+ closePromise
106
+ ]);
107
+ } catch (err) {
108
+ this.activeChannel?.close();
109
+ throw err;
110
+ }
128
111
  }
129
112
  async upload() {
130
- const { remotePath, localPath, onProgress, onData } = this.options;
131
- const fileContent = fs__namespace.readFileSync(localPath);
132
- this.state.total = fileContent.length;
133
- await this.runExec(`dd of="${remotePath}" bs=${this.chunkSize} 2>/dev/null`, fileContent);
134
- this.state.transferred = this.state.total;
135
- if (onProgress) {
136
- onProgress(this.state.total, this.state.total);
113
+ const { remotePath, localPath } = this.options;
114
+ const localStats = await fs__namespace.promises.stat(localPath);
115
+ if (!localStats.isFile()) {
116
+ throw new Error(`Local path is not a file: ${localPath}`);
137
117
  }
138
- if (onData) {
139
- onData(fileContent.length);
118
+ this.state.total = localStats.size;
119
+ const channel = await this.execStream(`dd of="${remotePath}" bs=${this.chunkSize}`);
120
+ this.activeChannel = channel;
121
+ const closePromise = this.waitForChannelClose(channel);
122
+ const readStream = fs__namespace.createReadStream(localPath, { highWaterMark: this.chunkSize });
123
+ this.pauseTarget = readStream;
124
+ try {
125
+ await Promise.all([
126
+ promises.pipeline(readStream, this.createProgressStream(), this.getChannelWritable(channel)),
127
+ closePromise
128
+ ]);
129
+ } catch (err) {
130
+ this.activeChannel?.close();
131
+ throw err;
140
132
  }
141
- this.state.completed = true;
142
133
  }
143
134
  pause() {
144
135
  this.state.paused = true;
136
+ this.pauseTarget?.pause();
145
137
  }
146
138
  resume() {
147
139
  this.state.paused = false;
140
+ this.pauseTarget?.resume();
148
141
  }
149
142
  getState() {
150
143
  return { ...this.state };
151
144
  }
152
145
  destroy() {
153
146
  this.aborted = true;
147
+ this.pauseTarget?.destroy?.(this.createAbortError());
148
+ this.activeChannel?.close();
149
+ }
150
+ createAbortError() {
151
+ return new Error("Transfer aborted");
152
+ }
153
+ /**
154
+ * Wrap an exec channel in a real `Readable` so it can be used as a
155
+ * `pipeline()` source.
156
+ *
157
+ * An ssh2 `ClientChannel` is a `Duplex` created with `emitClose: false`, so it
158
+ * never emits a stream `'close'` event. `pipeline()` (and `finished()`) wait
159
+ * for exactly that event to observe a source being torn down, which means:
160
+ *
161
+ * - when the destination fails, pipeline destroys the source, but the
162
+ * channel never reports the close and the pipeline promise stays pending
163
+ * **forever** — a full local disk hung the download with no error and no
164
+ * rejection at all;
165
+ * - calling `channel.close()` by hand does not help, because that only
166
+ * sends CHANNEL_CLOSE on the wire and still emits no stream event.
167
+ *
168
+ * Feeding the channel into a plain `Readable` (which does emit `'close'`)
169
+ * restores the normal semantics: pipeline can destroy it, the destroy closes
170
+ * the channel — which is what unblocks the remote `dd` — and the pipeline
171
+ * promise rejects with the original error.
172
+ */
173
+ channelToReadable(channel) {
174
+ const source = new stream.Readable({
175
+ highWaterMark: this.chunkSize,
176
+ read: () => {
177
+ if (!this.state.paused) {
178
+ channel.resume();
179
+ }
180
+ }
181
+ });
182
+ channel.on("data", (chunk) => {
183
+ if (!source.push(chunk)) {
184
+ channel.pause();
185
+ }
186
+ });
187
+ channel.on("end", () => source.push(null));
188
+ channel.on("error", (error) => source.destroy(error));
189
+ source.on("close", () => channel.close());
190
+ return source;
191
+ }
192
+ createProgressStream() {
193
+ return new stream.Transform({
194
+ highWaterMark: this.chunkSize,
195
+ transform: (chunk, _encoding, callback) => {
196
+ if (this.aborted) {
197
+ callback(this.createAbortError());
198
+ return;
199
+ }
200
+ const byteLength = Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(String(chunk));
201
+ this.state.transferred += byteLength;
202
+ if (this.options.onProgress) {
203
+ const visibleTransferred = this.state.total > 0 ? Math.min(this.state.transferred, this.state.total) : this.state.transferred;
204
+ this.options.onProgress(visibleTransferred, this.state.total);
205
+ }
206
+ if (this.options.onData) {
207
+ this.options.onData(byteLength);
208
+ }
209
+ callback(null, chunk);
210
+ }
211
+ });
212
+ }
213
+ getChannelWritable(channel) {
214
+ const withStdin = channel;
215
+ return withStdin.stdin || channel;
216
+ }
217
+ execStream(cmd) {
218
+ return new Promise((resolve, reject) => {
219
+ this.session.exec(cmd, (err, channel) => {
220
+ if (err) {
221
+ reject(err);
222
+ return;
223
+ }
224
+ resolve(channel);
225
+ });
226
+ });
227
+ }
228
+ waitForChannelClose(channel) {
229
+ return new Promise((resolve, reject) => {
230
+ let stderr = "";
231
+ let settled = false;
232
+ const settle = (error) => {
233
+ if (settled) {
234
+ return;
235
+ }
236
+ settled = true;
237
+ if (error) {
238
+ reject(error);
239
+ return;
240
+ }
241
+ resolve();
242
+ };
243
+ const handleExit = (code) => {
244
+ if (this.aborted) {
245
+ settle(this.createAbortError());
246
+ return;
247
+ }
248
+ if (typeof code === "number" && code !== 0) {
249
+ settle(new Error(stderr.trim() || `Remote command failed with exit code ${code}`));
250
+ return;
251
+ }
252
+ settle();
253
+ };
254
+ channel.stderr.on("data", (chunk) => {
255
+ stderr += chunk.toString();
256
+ });
257
+ channel.on("exit", handleExit);
258
+ channel.on("close", handleExit);
259
+ channel.on("error", (error) => {
260
+ settle(error);
261
+ });
262
+ });
154
263
  }
155
264
  }
156
265
  exports.Transfer = Transfer;
@@ -151,9 +151,15 @@ class SshFs {
151
151
  if (!line || i === 0) continue;
152
152
  const parts = line.split(/\s+/);
153
153
  if (parts.length < 9) continue;
154
- const name = parts.slice(8).join(" ");
155
- if (name === "." || name === "..") continue;
156
154
  const type = parts[0].charAt(0);
155
+ let name = parts.slice(8).join(" ");
156
+ if (type === "l") {
157
+ const arrow = name.indexOf(" -> ");
158
+ if (arrow > 0) {
159
+ name = name.slice(0, arrow);
160
+ }
161
+ }
162
+ if (name === "." || name === "..") continue;
157
163
  const mode = parseModeFromLongname(parts[0]);
158
164
  const owner = parseInt(parts[2], 10);
159
165
  const group = parseInt(parts[3], 10);
@@ -100,6 +100,8 @@ export declare class Transfer {
100
100
  private state;
101
101
  private aborted;
102
102
  private sshFs;
103
+ private pauseTarget;
104
+ private activeChannel;
103
105
  constructor(sshFs: SshFs, options: TransferOptions);
104
106
  startTransfer(): Promise<void>;
105
107
  private getRemoteFileSize;
@@ -110,6 +112,12 @@ export declare class Transfer {
110
112
  resume(): void;
111
113
  getState(): TransferState;
112
114
  destroy(): void;
115
+ private createAbortError;
116
+ private channelToReadable;
117
+ private createProgressStream;
118
+ private getChannelWritable;
119
+ private execStream;
120
+ private waitForChannelClose;
113
121
  }
114
122
 
115
123
  export declare interface TransferOptions {
@@ -1,5 +1,7 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
+ import { Readable, Transform } from "stream";
4
+ import { pipeline } from "stream/promises";
3
5
  class Transfer {
4
6
  session;
5
7
  options;
@@ -7,6 +9,8 @@ class Transfer {
7
9
  state;
8
10
  aborted = false;
9
11
  sshFs;
12
+ pauseTarget = null;
13
+ activeChannel = null;
10
14
  constructor(sshFs, options) {
11
15
  this.sshFs = sshFs;
12
16
  this.session = sshFs.session;
@@ -37,22 +41,21 @@ class Transfer {
37
41
  } catch (err) {
38
42
  this.state.error = err;
39
43
  throw err;
44
+ } finally {
45
+ this.pauseTarget = null;
46
+ this.activeChannel = null;
40
47
  }
41
48
  }
42
49
  async getRemoteFileSize(remotePath) {
43
50
  const output = await this.runExec(`stat -c %s "${remotePath}" 2>/dev/null || stat -f %z "${remotePath}" 2>/dev/null`);
44
51
  return parseInt(output.trim(), 10) || 0;
45
52
  }
46
- runExec(cmd, stdinData) {
53
+ runExec(cmd) {
47
54
  return new Promise((resolve, reject) => {
48
55
  this.session.exec(cmd, (err, stream) => {
49
56
  if (err) {
50
57
  return reject(err);
51
58
  }
52
- if (stdinData) {
53
- stream.stdin.write(stdinData);
54
- stream.stdin.end();
55
- }
56
59
  let out = Buffer.from("");
57
60
  stream.on("close", () => {
58
61
  resolve(out.toString());
@@ -65,72 +68,178 @@ class Transfer {
65
68
  });
66
69
  }
67
70
  async download() {
68
- const { remotePath, localPath, onProgress, onData } = this.options;
71
+ const { remotePath, localPath } = this.options;
69
72
  const dir = path.dirname(localPath);
70
73
  if (!fs.existsSync(dir)) {
71
74
  fs.mkdirSync(dir, { recursive: true });
72
75
  }
73
76
  this.state.total = await this.getRemoteFileSize(remotePath);
74
- return new Promise((resolve, reject) => {
75
- const cmd = `dd if="${remotePath}" bs=${this.chunkSize} 2>/dev/null`;
76
- this.session.exec(cmd, (err, stream) => {
77
- if (err) {
78
- return reject(err);
79
- }
80
- const writeStream = fs.createWriteStream(localPath);
81
- let localTransferred = 0;
82
- stream.on("data", (data) => {
83
- if (this.state.paused || this.aborted) {
84
- return;
85
- }
86
- writeStream.write(data);
87
- localTransferred += data.length;
88
- this.state.transferred = localTransferred;
89
- if (onProgress) {
90
- onProgress(localTransferred, this.state.total);
91
- }
92
- if (onData) {
93
- onData(data.length);
94
- }
95
- });
96
- stream.on("close", () => {
97
- writeStream.end(() => {
98
- resolve();
99
- });
100
- });
101
- stream.on("error", (err2) => {
102
- this.state.error = err2;
103
- writeStream.end();
104
- reject(err2);
105
- });
106
- });
107
- });
77
+ const channel = await this.execStream(`dd if="${remotePath}" bs=${this.chunkSize}`);
78
+ this.activeChannel = channel;
79
+ this.pauseTarget = channel;
80
+ const closePromise = this.waitForChannelClose(channel);
81
+ const writeStream = fs.createWriteStream(localPath, { highWaterMark: this.chunkSize });
82
+ try {
83
+ await Promise.all([
84
+ pipeline(this.channelToReadable(channel), this.createProgressStream(), writeStream),
85
+ closePromise
86
+ ]);
87
+ } catch (err) {
88
+ this.activeChannel?.close();
89
+ throw err;
90
+ }
108
91
  }
109
92
  async upload() {
110
- const { remotePath, localPath, onProgress, onData } = this.options;
111
- const fileContent = fs.readFileSync(localPath);
112
- this.state.total = fileContent.length;
113
- await this.runExec(`dd of="${remotePath}" bs=${this.chunkSize} 2>/dev/null`, fileContent);
114
- this.state.transferred = this.state.total;
115
- if (onProgress) {
116
- onProgress(this.state.total, this.state.total);
93
+ const { remotePath, localPath } = this.options;
94
+ const localStats = await fs.promises.stat(localPath);
95
+ if (!localStats.isFile()) {
96
+ throw new Error(`Local path is not a file: ${localPath}`);
117
97
  }
118
- if (onData) {
119
- onData(fileContent.length);
98
+ this.state.total = localStats.size;
99
+ const channel = await this.execStream(`dd of="${remotePath}" bs=${this.chunkSize}`);
100
+ this.activeChannel = channel;
101
+ const closePromise = this.waitForChannelClose(channel);
102
+ const readStream = fs.createReadStream(localPath, { highWaterMark: this.chunkSize });
103
+ this.pauseTarget = readStream;
104
+ try {
105
+ await Promise.all([
106
+ pipeline(readStream, this.createProgressStream(), this.getChannelWritable(channel)),
107
+ closePromise
108
+ ]);
109
+ } catch (err) {
110
+ this.activeChannel?.close();
111
+ throw err;
120
112
  }
121
- this.state.completed = true;
122
113
  }
123
114
  pause() {
124
115
  this.state.paused = true;
116
+ this.pauseTarget?.pause();
125
117
  }
126
118
  resume() {
127
119
  this.state.paused = false;
120
+ this.pauseTarget?.resume();
128
121
  }
129
122
  getState() {
130
123
  return { ...this.state };
131
124
  }
132
125
  destroy() {
133
126
  this.aborted = true;
127
+ this.pauseTarget?.destroy?.(this.createAbortError());
128
+ this.activeChannel?.close();
129
+ }
130
+ createAbortError() {
131
+ return new Error("Transfer aborted");
132
+ }
133
+ /**
134
+ * Wrap an exec channel in a real `Readable` so it can be used as a
135
+ * `pipeline()` source.
136
+ *
137
+ * An ssh2 `ClientChannel` is a `Duplex` created with `emitClose: false`, so it
138
+ * never emits a stream `'close'` event. `pipeline()` (and `finished()`) wait
139
+ * for exactly that event to observe a source being torn down, which means:
140
+ *
141
+ * - when the destination fails, pipeline destroys the source, but the
142
+ * channel never reports the close and the pipeline promise stays pending
143
+ * **forever** — a full local disk hung the download with no error and no
144
+ * rejection at all;
145
+ * - calling `channel.close()` by hand does not help, because that only
146
+ * sends CHANNEL_CLOSE on the wire and still emits no stream event.
147
+ *
148
+ * Feeding the channel into a plain `Readable` (which does emit `'close'`)
149
+ * restores the normal semantics: pipeline can destroy it, the destroy closes
150
+ * the channel — which is what unblocks the remote `dd` — and the pipeline
151
+ * promise rejects with the original error.
152
+ */
153
+ channelToReadable(channel) {
154
+ const source = new Readable({
155
+ highWaterMark: this.chunkSize,
156
+ read: () => {
157
+ if (!this.state.paused) {
158
+ channel.resume();
159
+ }
160
+ }
161
+ });
162
+ channel.on("data", (chunk) => {
163
+ if (!source.push(chunk)) {
164
+ channel.pause();
165
+ }
166
+ });
167
+ channel.on("end", () => source.push(null));
168
+ channel.on("error", (error) => source.destroy(error));
169
+ source.on("close", () => channel.close());
170
+ return source;
171
+ }
172
+ createProgressStream() {
173
+ return new Transform({
174
+ highWaterMark: this.chunkSize,
175
+ transform: (chunk, _encoding, callback) => {
176
+ if (this.aborted) {
177
+ callback(this.createAbortError());
178
+ return;
179
+ }
180
+ const byteLength = Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(String(chunk));
181
+ this.state.transferred += byteLength;
182
+ if (this.options.onProgress) {
183
+ const visibleTransferred = this.state.total > 0 ? Math.min(this.state.transferred, this.state.total) : this.state.transferred;
184
+ this.options.onProgress(visibleTransferred, this.state.total);
185
+ }
186
+ if (this.options.onData) {
187
+ this.options.onData(byteLength);
188
+ }
189
+ callback(null, chunk);
190
+ }
191
+ });
192
+ }
193
+ getChannelWritable(channel) {
194
+ const withStdin = channel;
195
+ return withStdin.stdin || channel;
196
+ }
197
+ execStream(cmd) {
198
+ return new Promise((resolve, reject) => {
199
+ this.session.exec(cmd, (err, channel) => {
200
+ if (err) {
201
+ reject(err);
202
+ return;
203
+ }
204
+ resolve(channel);
205
+ });
206
+ });
207
+ }
208
+ waitForChannelClose(channel) {
209
+ return new Promise((resolve, reject) => {
210
+ let stderr = "";
211
+ let settled = false;
212
+ const settle = (error) => {
213
+ if (settled) {
214
+ return;
215
+ }
216
+ settled = true;
217
+ if (error) {
218
+ reject(error);
219
+ return;
220
+ }
221
+ resolve();
222
+ };
223
+ const handleExit = (code) => {
224
+ if (this.aborted) {
225
+ settle(this.createAbortError());
226
+ return;
227
+ }
228
+ if (typeof code === "number" && code !== 0) {
229
+ settle(new Error(stderr.trim() || `Remote command failed with exit code ${code}`));
230
+ return;
231
+ }
232
+ settle();
233
+ };
234
+ channel.stderr.on("data", (chunk) => {
235
+ stderr += chunk.toString();
236
+ });
237
+ channel.on("exit", handleExit);
238
+ channel.on("close", handleExit);
239
+ channel.on("error", (error) => {
240
+ settle(error);
241
+ });
242
+ });
134
243
  }
135
244
  }
136
245
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh2-scp",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
4
4
  "description": "Remote file system operations over SSH2 session without SFTP",
5
5
  "scripts": {
6
6
  "build": "npm run build:esm && npm run build:cjs",