jsgotty 0.9.1 → 1.1.1

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/sz.js CHANGED
@@ -7,6 +7,7 @@ const {
7
7
  restoreStdin,
8
8
  setRawStdin,
9
9
  stderr,
10
+ appendDebugLog,
10
11
  writeOctets,
11
12
  } = require("./zmodem-node");
12
13
  const { BridgeInputParser, emitBridgeMessage } = require("./windows-bridge-node");
@@ -26,15 +27,39 @@ async function main() {
26
27
  }
27
28
 
28
29
  const totalBytes = files.reduce((sum, file) => sum + file.size, 0);
29
- const Zmodem = loadZmodem();
30
+ const Zmodem = await loadZmodem();
31
+ let writeQueue = Promise.resolve();
32
+ let queuedOutputBytes = 0;
33
+ let lastQueuedOutputLog = 0;
34
+ const completedDownloads = [];
35
+ const queueWriteOctets = (octets) => {
36
+ const length = Buffer.isBuffer(octets) ? octets.length : octets.length || 0;
37
+ queuedOutputBytes += length;
38
+ if (queuedOutputBytes - lastQueuedOutputLog >= 4 * 1024 * 1024) {
39
+ lastQueuedOutputLog = queuedOutputBytes;
40
+ debug(`sz debug: queued zmodem output ${queuedOutputBytes.toLocaleString()} bytes`);
41
+ }
42
+ writeQueue = writeQueue.then(() => writeOctets(octets));
43
+ writeQueue.catch((error) => fatal(1, error));
44
+ return writeQueue;
45
+ };
46
+ const waitForOutput = async (label = "") => {
47
+ if (label) {
48
+ debug(`sz debug: waiting output drain (${label}) queued=${queuedOutputBytes.toLocaleString()}`);
49
+ }
50
+ await writeQueue;
51
+ if (label) {
52
+ debug(`sz debug: output drained (${label})`);
53
+ }
54
+ };
30
55
  const sentry = new Zmodem.Sentry({
31
56
  to_terminal: () => {},
32
57
  on_detect: (detection) => {
33
- void handleDetection(detection, files, totalBytes).catch((error) => fatal(1, error));
58
+ void handleDetection(detection, files, totalBytes, waitForOutput).catch((error) => fatal(1, error));
34
59
  },
35
60
  on_retract: () => {},
36
61
  sender: (octets) => {
37
- void writeOctets(octets).catch((error) => fatal(1, error));
62
+ queueWriteOctets(octets);
38
63
  },
39
64
  });
40
65
 
@@ -48,6 +73,10 @@ async function main() {
48
73
  restoreStdin();
49
74
  if (error) {
50
75
  stderr(String(error && error.stack ? error.stack : error));
76
+ } else if (code === 0) {
77
+ for (const file of completedDownloads) {
78
+ stderr(`downloaded ${file.name} (${formatByteCount(file.size)})`);
79
+ }
51
80
  }
52
81
  process.exitCode = code;
53
82
  };
@@ -76,19 +105,26 @@ async function main() {
76
105
  stderr(`sz ready: waiting for receiver (${files.length} file${files.length > 1 ? "s" : ""})`);
77
106
  await writeOctets(Zmodem.Header.build("ZRQINIT").to_hex());
78
107
 
79
- async function handleDetection(detection, fileSpecs, allBytes) {
108
+ async function handleDetection(detection, fileSpecs, allBytes, waitForOutput) {
80
109
  const session = detection.confirm();
81
110
  if (session.type !== "send") {
82
111
  throw new Error(`unexpected session type: ${session.type}`);
83
112
  }
84
113
 
85
- session.on("session_end", () => finish(0));
114
+ session.on("session_end", () => {
115
+ debug("sz debug: session_end");
116
+ });
117
+ session.on("receive", (event) => {
118
+ if (event && event.NAME) {
119
+ debug(`sz debug: rx header ${event.NAME}`);
120
+ }
121
+ });
86
122
 
87
123
  let remainingBytes = allBytes;
88
124
 
89
125
  for (let index = 0; index < fileSpecs.length; index += 1) {
90
126
  const file = fileSpecs[index];
91
- stderr(`sending ${file.fullPath}`);
127
+ debug(`sending ${file.fullPath}`);
92
128
 
93
129
  const transfer = await session.send_offer({
94
130
  bytes_remaining: remainingBytes,
@@ -105,12 +141,16 @@ async function main() {
105
141
  continue;
106
142
  }
107
143
 
108
- await sendFilePayload(file.fullPath, transfer);
109
- stderr(`sent ${file.name}`);
144
+ const sentBytes = await sendFilePayload(file.fullPath, transfer, waitForOutput, file.size);
145
+ completedDownloads.push({ name: file.name, size: sentBytes });
146
+ debug(`sent ${file.name}`);
110
147
  remainingBytes -= file.size;
111
148
  }
112
149
 
150
+ debug("sz debug: closing session");
113
151
  await session.close();
152
+ await waitForOutput("session close");
153
+ finish(0);
114
154
  }
115
155
  }
116
156
 
@@ -180,9 +220,13 @@ function buildFileSpec(filePath) {
180
220
  };
181
221
  }
182
222
 
183
- async function sendFilePayload(filePath, transfer) {
223
+ async function sendFilePayload(filePath, transfer, waitForOutput, fileSize) {
184
224
  const fd = fs.openSync(filePath, "r");
185
225
  const buffer = Buffer.allocUnsafe(8192);
226
+ const maxPendingOutputBytes = 1024 * 1024;
227
+ let pendingOutputBytes = 0;
228
+ let sentBytes = 0;
229
+ let lastSentLog = 0;
186
230
 
187
231
  try {
188
232
  for (;;) {
@@ -191,12 +235,35 @@ async function sendFilePayload(filePath, transfer) {
191
235
  break;
192
236
  }
193
237
  transfer.send(buffer.subarray(0, bytesRead));
238
+ sentBytes += bytesRead;
239
+ if (sentBytes - lastSentLog >= 4 * 1024 * 1024 || sentBytes === fileSize) {
240
+ lastSentLog = sentBytes;
241
+ debug(`sz debug: file payload sent ${sentBytes.toLocaleString()}/${fileSize.toLocaleString()} bytes`);
242
+ }
243
+ pendingOutputBytes += bytesRead;
244
+ if (pendingOutputBytes >= maxPendingOutputBytes) {
245
+ await waitForOutput(`payload ${sentBytes.toLocaleString()}`);
246
+ pendingOutputBytes = 0;
247
+ }
194
248
  }
195
249
  } finally {
196
250
  fs.closeSync(fd);
197
251
  }
198
252
 
199
- await transfer.end();
253
+ debug("sz debug: transfer.end begin");
254
+ const endPromise = transfer.end();
255
+ await waitForOutput("transfer end");
256
+ await endPromise;
257
+ debug("sz debug: transfer.end complete");
258
+ return sentBytes;
259
+ }
260
+
261
+ function debug(message) {
262
+ appendDebugLog(message);
263
+ }
264
+
265
+ function formatByteCount(bytes) {
266
+ return `${Number(bytes || 0).toLocaleString()} bytes`;
200
267
  }
201
268
 
202
269
  main().catch((error) => {
package/viu.mjs CHANGED
@@ -3,10 +3,8 @@
3
3
  import fs from "fs";
4
4
  import os from "os";
5
5
  import path from "path";
6
- import { createRequire } from "module";
7
6
 
8
- const require = createRequire(import.meta.url);
9
- const { emitBridgeMessage } = require("./windows-bridge-node");
7
+ let emitBridgeMessage = null;
10
8
 
11
9
  const ESC = "\u001b";
12
10
  const ST = `${ESC}\\`;
@@ -294,6 +292,7 @@ function parseSvgSize(buffer) {
294
292
  }
295
293
 
296
294
  const widthMatch = sample.match(/\bwidth=["']([0-9.]+)(px)?["']/i);
295
+ //'"
297
296
  const heightMatch = sample.match(/\bheight=["']([0-9.]+)(px)?["']/i);
298
297
  if (widthMatch && heightMatch) {
299
298
  return {
@@ -363,7 +362,9 @@ function sniffImage(buffer, filePath, options = {}) {
363
362
  throw new Error("unsupported image format");
364
363
  }
365
364
 
366
- function main() {
365
+ async function main() {
366
+ emitBridgeMessage = (await import('./windows-bridge-node.js')).emitBridgeMessage;
367
+
367
368
  const args = process.argv.slice(2);
368
369
  const compat = args.includes("--compat");
369
370
  const positional = args.filter((arg) => arg !== "--compat");
@@ -379,9 +380,7 @@ function main() {
379
380
  writeKittyImage(buffer, image.mime, image.width, image.height, compat);
380
381
  }
381
382
 
382
- try {
383
- main();
384
- } catch (error) {
383
+ main().catch((error) => {
385
384
  stderr(String(error && error.stack ? error.stack : error));
386
385
  process.exitCode = 1;
387
- }
386
+ });
package/zmodem-node.js CHANGED
@@ -1,16 +1,34 @@
1
1
  const fs = require("fs");
2
2
  const path = require("path");
3
+ const os = require("os");
4
+ const { spawnSync } = require("child_process");
3
5
  const vm = require("vm");
4
6
 
5
7
  let cachedZmodem = null;
8
+ let savedTtyMode = null;
9
+ let ttyModeDepth = 0;
10
+ let rawOutputMode = false;
11
+ const defaultDebugLogPath = path.join(os.tmpdir(), "zmodem", "zmodem.log");
12
+ const debugLogPath = resolveDebugLogPath();
13
+ const singleExeHelpersPromise = globalThis.Bun
14
+ ? Promise.all([
15
+ import("./single-exe/compiled.js").catch(() => null),
16
+ import("./single-exe/assetsHelper.js").catch(() => null),
17
+ ])
18
+ : Promise.resolve([null, null]);
6
19
 
7
- function loadZmodem() {
20
+ async function loadZmodem() {
8
21
  if (cachedZmodem) {
9
22
  return cachedZmodem;
10
23
  }
11
24
 
12
- const bundlePath = path.join(__dirname, "static", "js", "zmodem.js");
13
- const source = fs.readFileSync(bundlePath, "utf8");
25
+ await globalThis.assetsLoaderPromise;
26
+ const [compiledHelper, assetsHelper] = await singleExeHelpersPromise;
27
+ const bundleAssetPath = assetsHelper?.assetPath?.("static", "js", "zmodem.js") ?? "static/js/zmodem.js";
28
+ const source =
29
+ assetsHelper?.readInternalAssetText?.(bundleAssetPath) ??
30
+ fs.readFileSync(path.join(compiledHelper?.REPO_ROOT ?? __dirname, "static", "js", "zmodem.js"), "utf8");
31
+ const bundlePath = path.join(compiledHelper?.REPO_ROOT ?? __dirname, "static", "js", "zmodem.js");
14
32
  const quietConsole = {
15
33
  debug() {},
16
34
  log() {},
@@ -52,7 +70,7 @@ function loadZmodem() {
52
70
 
53
71
  function writeOctets(octets) {
54
72
  let buffer = Buffer.isBuffer(octets) ? octets : Buffer.from(octets);
55
- if (process.stdout.isTTY && process.platform !== "win32") {
73
+ if (process.stdout.isTTY && process.platform !== "win32" && !rawOutputMode) {
56
74
  buffer = normalizeTtyOutput(buffer);
57
75
  }
58
76
  return new Promise((resolve, reject) => {
@@ -76,19 +94,148 @@ function normalizeTtyOutput(buffer) {
76
94
  }
77
95
 
78
96
  function setRawStdin() {
79
- if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
80
- process.stdin.setRawMode(true);
97
+ ttyModeDepth += 1;
98
+ if (ttyModeDepth === 1) {
99
+ savedTtyMode = saveAndSetRawTtyMode();
100
+ rawOutputMode = !!savedTtyMode;
101
+ debugTty(
102
+ `setRawStdin depth=${ttyModeDepth} stdinTTY=${!!process.stdin.isTTY} stdoutTTY=${!!process.stdout.isTTY} saved=${!!savedTtyMode} rawOutputMode=${rawOutputMode}`,
103
+ );
104
+ if (!savedTtyMode && process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
105
+ process.stdin.setRawMode(true);
106
+ debugTty("setRawStdin fallback=process.stdin.setRawMode(true)");
107
+ }
81
108
  }
82
109
  process.stdin.resume();
83
110
  }
84
111
 
85
112
  function restoreStdin() {
86
- if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
87
- process.stdin.setRawMode(false);
113
+ if (ttyModeDepth > 0) {
114
+ ttyModeDepth -= 1;
115
+ }
116
+ if (ttyModeDepth === 0) {
117
+ if (savedTtyMode) {
118
+ debugTty(`restoreStdin restoring stty mode ${savedTtyMode}`);
119
+ restoreTtyMode(savedTtyMode);
120
+ } else if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
121
+ debugTty("restoreStdin fallback=process.stdin.setRawMode(false)");
122
+ process.stdin.setRawMode(false);
123
+ }
124
+ savedTtyMode = null;
125
+ rawOutputMode = false;
88
126
  }
89
127
  process.stdin.pause();
90
128
  }
91
129
 
130
+ function saveAndSetRawTtyMode() {
131
+ if (process.platform === "win32" || !process.stdin.isTTY) {
132
+ debugTty(`saveAndSetRawTtyMode skipped platform=${process.platform} stdinTTY=${!!process.stdin.isTTY}`);
133
+ return null;
134
+ }
135
+
136
+ const tty = openControlTty();
137
+ if (tty === null) {
138
+ debugTty("saveAndSetRawTtyMode could not open /dev/tty");
139
+ return null;
140
+ }
141
+
142
+ try {
143
+ const saved = spawnSync("stty", ["-g"], {
144
+ encoding: "utf8",
145
+ stdio: [tty.fd, "pipe", "pipe"],
146
+ });
147
+ if (saved.status !== 0 || !saved.stdout.trim()) {
148
+ debugTty(`saveAndSetRawTtyMode stty -g failed status=${saved.status} stderr=${String(saved.stderr || "").trim()}`);
149
+ return null;
150
+ }
151
+
152
+ const mode = saved.stdout.trim();
153
+ debugTty(`saveAndSetRawTtyMode captured mode=${mode}`);
154
+ const raw = spawnSync("stty", ["raw", "-echo", "-opost", "-ixon", "-ixoff"], {
155
+ encoding: "utf8",
156
+ stdio: [tty.fd, "ignore", "pipe"],
157
+ });
158
+ if (raw.status !== 0) {
159
+ debugTty(`saveAndSetRawTtyMode stty raw failed status=${raw.status} stderr=${String(raw.stderr || "").trim()}`);
160
+ restoreTtyMode(mode);
161
+ return null;
162
+ }
163
+
164
+ debugTty("saveAndSetRawTtyMode raw mode enabled");
165
+ return mode;
166
+ } finally {
167
+ if (tty.close) {
168
+ tty.close();
169
+ }
170
+ }
171
+ }
172
+
173
+ function restoreTtyMode(mode) {
174
+ if (!mode || process.platform === "win32") {
175
+ debugTty(`restoreTtyMode skipped mode=${!!mode} platform=${process.platform}`);
176
+ return;
177
+ }
178
+
179
+ const tty = openControlTty();
180
+ if (tty === null) {
181
+ debugTty(`restoreTtyMode could not open /dev/tty for mode=${mode}`);
182
+ return;
183
+ }
184
+
185
+ try {
186
+ spawnSync("stty", [mode], {
187
+ encoding: "utf8",
188
+ stdio: [tty.fd, "ignore", "ignore"],
189
+ });
190
+ debugTty(`restoreTtyMode applied mode=${mode}`);
191
+ } finally {
192
+ if (tty.close) {
193
+ tty.close();
194
+ }
195
+ }
196
+ }
197
+
198
+ function openControlTty() {
199
+ try {
200
+ const fd = fs.openSync("/dev/tty", "r+");
201
+ return {
202
+ fd,
203
+ close: () => fs.closeSync(fd),
204
+ };
205
+ } catch {
206
+ if (typeof process.stdin.fd === "number") {
207
+ return {
208
+ fd: process.stdin.fd,
209
+ close: null,
210
+ };
211
+ }
212
+ return null;
213
+ }
214
+ }
215
+
216
+ function debugTty(message) {
217
+ appendDebugLog(message);
218
+ }
219
+
220
+ function appendDebugLog(message) {
221
+ if (!debugLogPath) {
222
+ return;
223
+ }
224
+ fs.mkdirSync(path.dirname(debugLogPath), { recursive: true });
225
+ fs.appendFileSync(debugLogPath, `${new Date().toISOString()} ${message}\n`);
226
+ }
227
+
228
+ function resolveDebugLogPath() {
229
+ const value = process.env.JSGOTTY_ZMODEM_LOG || "";
230
+ if (!value) {
231
+ return "";
232
+ }
233
+ if (/^(1|true|yes)$/i.test(value)) {
234
+ return defaultDebugLogPath;
235
+ }
236
+ return path.resolve(value);
237
+ }
238
+
92
239
  function stderr(message) {
93
240
  process.stderr.write(`${message}\n`);
94
241
  }
@@ -107,5 +254,7 @@ module.exports = {
107
254
  restoreStdin,
108
255
  setRawStdin,
109
256
  stderr,
257
+ debugLogPath,
258
+ appendDebugLog,
110
259
  writeOctets,
111
260
  };