@cldmv/node-android-tv-remote 2.1.0 → 2.1.7

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.
@@ -1,49 +1,51 @@
1
1
  /**
2
+ *
2
3
  * @Project: @cldmv/node-android-tv-remote
3
4
  * @Filename: /src/lib/android-tv-remote.mjs
4
- * @Date: 2025-10-15 10:19:05 -07:00 (1760548745)
5
- * @Author: Nate Hyson <CLDMV>
5
+ * @Date: 2025-10-15T10:19:05-07:00 (1760548745)
6
+ * @Author: Nate Corcoran <CLDMV>
6
7
  * @Email: <Shinrai@users.noreply.github.com>
7
8
  * -----
8
- * @Last modified by: Nate Hyson <CLDMV> (Shinrai@users.noreply.github.com)
9
- * @Last modified time: 2025-10-15 21:09:09 -07:00 (1760587749)
9
+ * @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
10
+ * @Last modified time: 2026-10-02T12:16:15-07:00 (1790968575)
10
11
  * -----
11
- * @Copyright: Copyright (c) 2013-2025 Catalyzed Motivation Inc. All rights reserved.
12
+ * @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
13
+ *
12
14
  */
13
15
 
14
16
  /**
15
17
  * Android TV Remote module - Event-driven ADB remote control for Android TV devices.
16
- *
18
+ *
17
19
  * @module android-tv-remote
18
- *
20
+ *
19
21
  * @description
20
22
  * This module provides an event-driven interface for controlling Android TV devices via ADB.
21
23
  * All operations emit events instead of console logging, allowing for better integration
22
24
  * and programmatic handling of device communication.
23
- *
25
+ *
24
26
  * @example
25
27
  * // ESM usage with event handling
26
28
  * import createRemote from "@cldmv/node-android-tv-remote";
27
- *
29
+ *
28
30
  * const remote = createRemote({ ip: "192.168.1.100" });
29
- *
31
+ *
30
32
  * // Listen for log events
31
33
  * remote.on('log', (data) => {
32
34
  * console.log(`[${data.level}] ${data.message}`, data.source);
33
35
  * });
34
- *
36
+ *
35
37
  * // Listen for errors
36
38
  * remote.on('error', (data) => {
37
39
  * console.error(`Error from ${data.source}:`, data.error.message);
38
40
  * });
39
- *
41
+ *
40
42
  * // Use the remote
41
43
  * await remote.press.home();
42
- *
44
+ *
43
45
  * @example
44
46
  * // Static create method
45
47
  * import { createAndroidTVRemote } from "@cldmv/node-android-tv-remote";
46
- *
48
+ *
47
49
  * const remote = await createAndroidTVRemote({ ip: "192.168.1.100" });
48
50
  * remote.on('log', console.log);
49
51
  * await remote.press.play();
@@ -100,12 +102,12 @@
100
102
  * @property {Object} keyboard - Keyboard interface for all keys, with text and keycode fallback.
101
103
  * @property {Object} keyboard.key - Contains all key functions.
102
104
  * @property {Object} keyboard.key.shift - Contains all shifted key functions.
103
- *
105
+ *
104
106
  * @property {function(string, Function): Remote} on - Add event listener. Returns remote instance for chaining.
105
107
  * @property {function(string, Function): Remote} off - Remove event listener. Returns remote instance for chaining.
106
108
  * @property {function(string, Function): Remote} once - Add one-time event listener. Returns remote instance for chaining.
107
109
  * @property {function(string, ...any): boolean} emit - Emit an event. Returns true if event had listeners.
108
- *
110
+ *
109
111
  * @fires Remote#log - Emitted for informational messages, warnings, and debug info.
110
112
  * @fires Remote#error - Emitted when errors occur during ADB operations.
111
113
  * @fires Remote#screencap-start - Emitted when screenshot capture begins.
@@ -114,7 +116,7 @@
114
116
  * @fires Remote#screencap-ready - Emitted when final processed stream is ready.
115
117
  * @fires Remote#screencap-saved - Emitted when screenshot is saved to file.
116
118
  * @fires Remote#screencap-complete - Emitted when entire screenshot operation is complete.
117
- *
119
+ *
118
120
  * @example
119
121
  * // Event handling examples
120
122
  * remote.on('log', (data) => {
@@ -126,11 +128,11 @@
126
128
  * console.log(`INFO [${data.source}]: ${data.message}`);
127
129
  * }
128
130
  * });
129
- *
131
+ *
130
132
  * remote.on('error', (data) => {
131
133
  * console.error(`FATAL ERROR from ${data.source}:`);
132
134
  * console.error(data.error.stack || data.error.message);
133
- *
135
+ *
134
136
  * // Handle specific error types
135
137
  * if (data.error.message.includes('device unauthorized')) {
136
138
  * console.log('Please authorize ADB on your Android TV device');
@@ -141,9 +143,14 @@
141
143
  import adbkit from "@devicefarmer/adbkit";
142
144
  import { EventEmitter } from "events";
143
145
  import { createWriteStream } from "fs";
144
- import { pipeline } from "stream/promises";
145
146
  import sharp from "sharp";
146
- const Adb = adbkit.Adb;
147
+ // @devicefarmer/adbkit is plain CJS (`exports.default` / `exports.Adb` both
148
+ // getter re-exports of the same class). Under plain Node's ESM/CJS interop,
149
+ // the default import resolves to `module.exports` (so `.Adb` holds the
150
+ // class); under Vite/Rollup-based CJS interop (e.g. vitest with the module
151
+ // inlined), the default import unwraps straight to the class itself. Cover
152
+ // both shapes rather than assuming one.
153
+ const Adb = adbkit.Adb ?? adbkit;
147
154
 
148
155
  /**
149
156
  * Wraps an async function to support both promise and callback styles.
@@ -183,7 +190,7 @@ function emitLog(level, message, source = "android-tv-remote", data = null) {
183
190
  ...(data && { data })
184
191
  });
185
192
  }
186
-
193
+
187
194
  /**
188
195
  * Emit an error event with structured data.
189
196
  * @private
@@ -195,14 +202,12 @@ function emitError(error, source = "android-tv-remote", message = null) {
195
202
  // Filter out libspng/PNG processing errors that occur after disconnection
196
203
  // These are common when background operations try to process data after disconnect
197
204
  const errorMsg = error.message || "";
198
- if (errorMsg.includes('libspng') ||
199
- errorMsg.includes('pngload_buffer') ||
200
- errorMsg.includes('read error')) {
205
+ if (errorMsg.includes("libspng") || errorMsg.includes("pngload_buffer") || errorMsg.includes("read error")) {
201
206
  // Log as debug instead of error to avoid noise
202
207
  emitLog("debug", `PNG processing error (likely post-disconnect): ${errorMsg}`, source);
203
208
  return;
204
209
  }
205
-
210
+
206
211
  emitter.emit("error", {
207
212
  error,
208
213
  source,
@@ -210,7 +215,7 @@ function emitError(error, source = "android-tv-remote", message = null) {
210
215
  timestamp: new Date().toISOString()
211
216
  });
212
217
  }
213
-
218
+
214
219
  /**
215
220
  * Handles disconnect and connection errors, emits helpful messages.
216
221
  * Also provides onboarding steps for common authentication and connection issues.
@@ -229,25 +234,49 @@ function handleDisconnectError(err) {
229
234
 
230
235
  if (err.message && (err.message.includes("device unauthorized") || err.message.includes("failed to authenticate"))) {
231
236
  emitError(err, "handleDisconnectError", "Device unauthorized - authentication required");
232
- emitLog("error", "Your device is unauthorized or failed to authenticate. Please check your TV and accept the authorization dialog to allow this system to connect via ADB.", "handleDisconnectError");
233
- emitLog("info", "If you do not see a prompt, try disconnecting and reconnecting the device, or reboot your TV.", "handleDisconnectError");
234
- emitLog("info", "If the problem persists, remove the device from the list of authorized ADB devices in Developer Options and try again.", "handleDisconnectError");
235
- emitLog("info", "Tip: In Developer Options on your TV, try toggling 'ADB Debugging' off and then back on. This often resolves authentication issues.", "handleDisconnectError");
237
+ emitLog(
238
+ "error",
239
+ "Your device is unauthorized or failed to authenticate. Please check your TV and accept the authorization dialog to allow this system to connect via ADB.",
240
+ "handleDisconnectError"
241
+ );
242
+ emitLog(
243
+ "info",
244
+ "If you do not see a prompt, try disconnecting and reconnecting the device, or reboot your TV.",
245
+ "handleDisconnectError"
246
+ );
247
+ emitLog(
248
+ "info",
249
+ "If the problem persists, remove the device from the list of authorized ADB devices in Developer Options and try again.",
250
+ "handleDisconnectError"
251
+ );
252
+ emitLog(
253
+ "info",
254
+ "Tip: In Developer Options on your TV, try toggling 'ADB Debugging' off and then back on. This often resolves authentication issues.",
255
+ "handleDisconnectError"
256
+ );
236
257
  }
237
-
258
+
238
259
  if (err.message && (err.message.includes("actively refused") || err.message.includes("No connection could be made"))) {
239
260
  emitError(err, "handleDisconnectError", "Connection refused - ADB not enabled");
240
- emitLog("error", "The device refused the connection. To enable ADB, follow these steps on your Android TV or Fire TV:", "handleDisconnectError");
261
+ emitLog(
262
+ "error",
263
+ "The device refused the connection. To enable ADB, follow these steps on your Android TV or Fire TV:",
264
+ "handleDisconnectError"
265
+ );
241
266
  emitLog("info", "1. Open Settings > Device Preferences > About (or My Fire TV > About)", "handleDisconnectError");
242
267
  emitLog("info", "2. Scroll to 'Build' and press OK 7 times to enable Developer Options", "handleDisconnectError");
243
268
  emitLog("info", "3. Go back to Settings > Device Preferences > Developer Options", "handleDisconnectError");
244
- emitLog("info", "4. Enable 'Developer Options' if needed, then enable 'ADB Debugging' and 'Apps from Unknown Sources'", "handleDisconnectError");
269
+ emitLog(
270
+ "info",
271
+ "4. Enable 'Developer Options' if needed, then enable 'ADB Debugging' and 'Apps from Unknown Sources'",
272
+ "handleDisconnectError"
273
+ );
245
274
  emitLog("info", "5. Ensure your TV and computer are on the same network", "handleDisconnectError");
246
275
  emitLog("info", "6. On your computer, run: adb connect <device-ip>:5555", "handleDisconnectError");
247
276
  emitLog("info", "7. Accept the authorization prompt on your TV", "handleDisconnectError");
248
277
  emitLog("info", "If you do not see 'Developer Options', repeat step 2 until it appears.", "handleDisconnectError");
249
278
  }
250
-
279
+
251
280
  return err;
252
281
  }
253
282
 
@@ -272,16 +301,32 @@ function getShiftedCharacter(keyName, char) {
272
301
  if (/^[a-z]$/.test(char)) {
273
302
  return char.toUpperCase();
274
303
  }
275
-
304
+
276
305
  // Handle shifted symbols
277
306
  const shiftMap = {
278
- '1': '!', '2': '@', '3': '#', '4': '$', '5': '%',
279
- '6': '^', '7': '&', '8': '*', '9': '(', '0': ')',
280
- '-': '_', '=': '+', '[': '{', ']': '}', '\\': '|',
281
- ';': ':', "'": '"', ',': '<', '.': '>', '/': '?',
282
- '`': '~'
307
+ "1": "!",
308
+ "2": "@",
309
+ "3": "#",
310
+ "4": "$",
311
+ "5": "%",
312
+ "6": "^",
313
+ "7": "&",
314
+ "8": "*",
315
+ "9": "(",
316
+ "0": ")",
317
+ "-": "_",
318
+ "=": "+",
319
+ "[": "{",
320
+ "]": "}",
321
+ "\\": "|",
322
+ ";": ":",
323
+ "'": '"',
324
+ ",": "<",
325
+ ".": ">",
326
+ "/": "?",
327
+ "`": "~"
283
328
  };
284
-
329
+
285
330
  return shiftMap[char] || char;
286
331
  }
287
332
 
@@ -315,7 +360,7 @@ export default async function createRemote(config) {
315
360
  const device = client.getDevice(host);
316
361
  let connected = false;
317
362
  let backgroundOperations = new Set();
318
-
363
+
319
364
  /**
320
365
  * Local emitError function that has access to connection state
321
366
  * @private
@@ -326,18 +371,16 @@ export default async function createRemote(config) {
326
371
  function localEmitError(error, source = "android-tv-remote", message = null) {
327
372
  // Filter out libspng/PNG processing errors that occur after disconnection
328
373
  const errorMsg = error.message || "";
329
- if (!connected && (errorMsg.includes('libspng') ||
330
- errorMsg.includes('pngload_buffer') ||
331
- errorMsg.includes('read error'))) {
374
+ if (!connected && (errorMsg.includes("libspng") || errorMsg.includes("pngload_buffer") || errorMsg.includes("read error"))) {
332
375
  // Log as debug instead of error to avoid noise
333
376
  emitLog("debug", `PNG processing error (post-disconnect): ${errorMsg}`, source);
334
377
  return;
335
378
  }
336
-
379
+
337
380
  // Use global emitError for other cases
338
381
  emitError(error, source, message);
339
382
  }
340
-
383
+
341
384
  const autoConnect = config.autoConnect !== false; // default true
342
385
  const autoDisconnect = config.autoDisconnect === true; // default false
343
386
  const disconnectTimeout = typeof config.disconnectTimeout === "number" ? config.disconnectTimeout : 10;
@@ -537,23 +580,33 @@ export default async function createRemote(config) {
537
580
  disconnectTimer = null;
538
581
  }
539
582
  stopHeartbeat();
540
-
583
+
541
584
  // Wait for all background operations to complete before disconnecting
542
585
  if (backgroundOperations.size > 0) {
543
- if (!quiet) emitLog("info", `🔄 [DISCONNECT] Waiting for ${backgroundOperations.size} background operations to complete...`, "disconnect");
586
+ if (!quiet)
587
+ emitLog("info", `🔄 [DISCONNECT] Waiting for ${backgroundOperations.size} background operations to complete...`, "disconnect");
544
588
  const waitStartTime = performance.now();
545
589
  try {
546
590
  await Promise.allSettled([...backgroundOperations]);
547
591
  const waitEndTime = performance.now();
548
- if (!quiet) emitLog("info", `✅ [DISCONNECT] All background operations completed in ${(waitEndTime - waitStartTime).toFixed(2)}ms`, "disconnect");
592
+ if (!quiet)
593
+ emitLog(
594
+ "info",
595
+ `✅ [DISCONNECT] All background operations completed in ${(waitEndTime - waitStartTime).toFixed(2)}ms`,
596
+ "disconnect"
597
+ );
549
598
  } catch (error) {
550
599
  const waitEndTime = performance.now();
551
- emitLog("warn", `⚠️ [DISCONNECT] Some background operations failed after ${(waitEndTime - waitStartTime).toFixed(2)}ms: ${error.message}`, "disconnect");
600
+ emitLog(
601
+ "warn",
602
+ `⚠️ [DISCONNECT] Some background operations failed after ${(waitEndTime - waitStartTime).toFixed(2)}ms: ${error.message}`,
603
+ "disconnect"
604
+ );
552
605
  }
553
606
  } else {
554
607
  if (!quiet) emitLog("info", `✅ [DISCONNECT] No background operations to wait for`, "disconnect");
555
608
  }
556
-
609
+
557
610
  try {
558
611
  await client.disconnect(ip, port);
559
612
  connected = false;
@@ -694,7 +747,7 @@ export default async function createRemote(config) {
694
747
  * remote.initPromise.then(() => { ... }).catch((err) => { ... });
695
748
  */
696
749
  initPromise,
697
-
750
+
698
751
  /**
699
752
  * Add event listener.
700
753
  * @public
@@ -709,7 +762,7 @@ export default async function createRemote(config) {
709
762
  emitter.on(event, listener);
710
763
  return remoteApi;
711
764
  },
712
-
765
+
713
766
  /**
714
767
  * Remove event listener.
715
768
  * @public
@@ -723,7 +776,7 @@ export default async function createRemote(config) {
723
776
  emitter.off(event, listener);
724
777
  return remoteApi;
725
778
  },
726
-
779
+
727
780
  /**
728
781
  * Add one-time event listener.
729
782
  * @public
@@ -737,7 +790,7 @@ export default async function createRemote(config) {
737
790
  emitter.once(event, listener);
738
791
  return remoteApi;
739
792
  },
740
-
793
+
741
794
  /**
742
795
  * Emit an event.
743
796
  * @public
@@ -788,7 +841,7 @@ export default async function createRemote(config) {
788
841
  get isConnected() {
789
842
  return isConnected();
790
843
  },
791
-
844
+
792
845
  /**
793
846
  * Returns the last screencap data (PNG stream) captured by screencap() or thumbnail().
794
847
  * Updated every time a screenshot is taken, regardless of options used.
@@ -797,7 +850,7 @@ export default async function createRemote(config) {
797
850
  * @example
798
851
  * await remote.screencap({ filepath: './screenshot.png' });
799
852
  * console.log('Last screencap stream:', remote.lastScreencapData);
800
- *
853
+ *
801
854
  * // Use the cached stream data
802
855
  * if (remote.lastScreencapData) {
803
856
  * remote.lastScreencapData.pipe(someOtherStream);
@@ -817,27 +870,25 @@ export default async function createRemote(config) {
817
870
  * await remote.setSettings(); // Set all optimal settings
818
871
  * await remote.setSettings('get'); // Get current settings values
819
872
  */
820
- async setSettings(mode = 'set') {
873
+ async setSettings(mode = "set") {
821
874
  try {
822
- emitLog("info", `=== ${mode === 'set' ? 'Configuring' : 'Retrieving'} Android TV settings ===`, "setSettings");
823
-
875
+ emitLog("info", `=== ${mode === "set" ? "Configuring" : "Retrieving"} Android TV settings ===`, "setSettings");
876
+
824
877
  await ensureConnected();
825
-
878
+
826
879
  // Core settings for power management and display
827
880
  const coreSettings = [
828
881
  { ns: "system", key: "screen_off_timeout", value: 2147483647 },
829
882
  { ns: "secure", key: "sleep_timeout", value: 0 },
830
883
  { ns: "global", key: "stay_on_while_plugged_in", value: 3 }
831
884
  ];
832
-
885
+
833
886
  // Process core settings
834
887
  for (const item of coreSettings) {
835
- const cmd = mode === "set"
836
- ? `settings put ${item.ns} ${item.key} ${item.value}`
837
- : `settings get ${item.ns} ${item.key}`;
838
-
888
+ const cmd = mode === "set" ? `settings put ${item.ns} ${item.key} ${item.value}` : `settings get ${item.ns} ${item.key}`;
889
+
839
890
  const result = await device.shell(cmd).then(Adb.util.readAll);
840
-
891
+
841
892
  if (!quiet) {
842
893
  if (mode === "set") {
843
894
  emitLog("info", `Set ${item.ns} ${item.key} to ${item.value}`, "setSettings");
@@ -846,27 +897,26 @@ export default async function createRemote(config) {
846
897
  }
847
898
  }
848
899
  }
849
-
900
+
850
901
  // Additional settings (only applied in set mode)
851
- if (mode === 'set') {
902
+ if (mode === "set") {
852
903
  emitLog("info", "Setting additional display and power settings", "setSettings");
853
-
904
+
854
905
  const additionalSettings = [
855
- "settings put system screen_brightness_mode 0", // Manual brightness
856
- "settings put system screen_brightness 255", // Max brightness
857
- "svc power stayon true" // Stay on while plugged
906
+ "settings put system screen_brightness_mode 0", // Manual brightness
907
+ "settings put system screen_brightness 255", // Max brightness
908
+ "svc power stayon true" // Stay on while plugged
858
909
  ];
859
-
910
+
860
911
  for (const cmd of additionalSettings) {
861
912
  if (!quiet) emitLog("info", `Running: ${cmd}`, "setSettings");
862
913
  await device.shell(cmd);
863
914
  }
864
915
  }
865
-
866
- emitLog("info", `✅ Android TV settings ${mode === 'set' ? 'configured' : 'retrieved'} successfully`, "setSettings");
867
-
916
+
917
+ emitLog("info", `✅ Android TV settings ${mode === "set" ? "configured" : "retrieved"} successfully`, "setSettings");
868
918
  } catch (error) {
869
- localEmitError(error, "setSettings", `Failed to ${mode === 'set' ? 'configure' : 'retrieve'} Android TV settings`);
919
+ localEmitError(error, "setSettings", `Failed to ${mode === "set" ? "configure" : "retrieve"} Android TV settings`);
870
920
  throw error;
871
921
  }
872
922
  },
@@ -923,7 +973,7 @@ export default async function createRemote(config) {
923
973
 
924
974
  // Determine what commands need to be sent
925
975
  const commandsToSend = [];
926
-
976
+
927
977
  if (initialPowerState.mIsPowered !== "true") {
928
978
  emitLog("info", `Device not powered (${initialPowerState.mIsPowered}), will send POWER keycode`, "ensureAwake");
929
979
  commandsToSend.push({ keycode: keycodes.power, reason: "power on device" });
@@ -948,18 +998,18 @@ export default async function createRemote(config) {
948
998
  // Send required commands
949
999
  if (commandsToSend.length > 0) {
950
1000
  emitLog("info", `Sending ${commandsToSend.length} keycode(s)...`, "ensureAwake");
951
-
1001
+
952
1002
  for (const cmd of commandsToSend) {
953
1003
  emitLog("info", `Sending keycode ${cmd.keycode} to ${cmd.reason}`, "ensureAwake");
954
1004
  await inputKeycode(cmd.keycode);
955
-
1005
+
956
1006
  // Brief delay between commands
957
- await new Promise(resolve => setTimeout(resolve, 500));
1007
+ await new Promise((resolve) => setTimeout(resolve, 500));
958
1008
  }
959
1009
 
960
1010
  // Wait for commands to take effect
961
1011
  emitLog("info", "Waiting for commands to take effect...", "ensureAwake");
962
- await new Promise(resolve => setTimeout(resolve, 3000));
1012
+ await new Promise((resolve) => setTimeout(resolve, 3000));
963
1013
  }
964
1014
 
965
1015
  // Verify final state
@@ -986,16 +1036,15 @@ export default async function createRemote(config) {
986
1036
  for (const issue of issues) {
987
1037
  emitLog("warn", issue, "ensureAwake");
988
1038
  }
989
-
1039
+
990
1040
  // Only throw error if critical issues persist
991
1041
  emitError(
992
- new Error(`ensureAwake failed with ${issues.length} persistent issue(s): ${issues.join(', ')}`),
993
- "ensureAwake",
1042
+ new Error(`ensureAwake failed with ${issues.length} persistent issue(s): ${issues.join(", ")}`),
1043
+ "ensureAwake",
994
1044
  "Device may not be fully responsive"
995
1045
  );
996
1046
  return false;
997
1047
  }
998
-
999
1048
  } catch (error) {
1000
1049
  emitError(error, "ensureAwake", "Failed to ensure device is awake");
1001
1050
  throw error;
@@ -1013,9 +1062,10 @@ export default async function createRemote(config) {
1013
1062
  * await remote.connect();
1014
1063
  * remote.connect((err) => { ... });
1015
1064
  */
1016
- connect: /**
1017
- * @type {(cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1018
- */ (connectWrapped),
1065
+ connect:
1066
+ /**
1067
+ * @type {(cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1068
+ */ (connectWrapped),
1019
1069
 
1020
1070
  /**
1021
1071
  * Disconnect from the device. Supports both promise and callback styles.
@@ -1028,9 +1078,10 @@ export default async function createRemote(config) {
1028
1078
  * await remote.disconnect();
1029
1079
  * remote.disconnect((err) => { ... });
1030
1080
  */
1031
- disconnect: /**
1032
- * @type {(cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1033
- */ (disconnectWrapped),
1081
+ disconnect:
1082
+ /**
1083
+ * @type {(cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1084
+ */ (disconnectWrapped),
1034
1085
 
1035
1086
  /**
1036
1087
  * Send a keycode. Supports both promise and callback styles.
@@ -1042,9 +1093,10 @@ export default async function createRemote(config) {
1042
1093
  * await remote.inputKeycode(23);
1043
1094
  * remote.inputKeycode(23, (err) => { ... });
1044
1095
  */
1045
- inputKeycode: /**
1046
- * @type {(code: number, cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1047
- */ (inputKeycodeWrapped),
1096
+ inputKeycode:
1097
+ /**
1098
+ * @type {(code: number, cb?: (err?: Error, result?: any) => any) => Promise<any> | undefined}
1099
+ */ (inputKeycodeWrapped),
1048
1100
 
1049
1101
  /**
1050
1102
  * Reboots the Android TV device using ADB's native reboot method.
@@ -1058,12 +1110,12 @@ export default async function createRemote(config) {
1058
1110
  async reboot() {
1059
1111
  try {
1060
1112
  emitLog("info", "=== Starting device reboot ===", "reboot");
1061
-
1113
+
1062
1114
  // Ensure we're connected before sending reboot command
1063
1115
  await ensureConnected();
1064
-
1116
+
1065
1117
  emitLog("info", "Sending reboot command to device", "reboot");
1066
-
1118
+
1067
1119
  // Use the native device.reboot() method with timeout handling
1068
1120
  let result;
1069
1121
  try {
@@ -1080,7 +1132,7 @@ export default async function createRemote(config) {
1080
1132
  }
1081
1133
  }
1082
1134
  emitLog("warn", "Device will reboot shortly and connection will be lost", "reboot");
1083
-
1135
+
1084
1136
  // Wait a moment for command to take effect, then disconnect
1085
1137
  setTimeout(() => {
1086
1138
  emitLog("info", "Device should be rebooting now - connection will be terminated", "reboot");
@@ -1091,10 +1143,9 @@ export default async function createRemote(config) {
1091
1143
 
1092
1144
  emitLog("info", "=== Device reboot initiated ===", "reboot");
1093
1145
  return result;
1094
-
1095
1146
  } catch (error) {
1096
1147
  emitError(error, "reboot", "Failed to reboot device");
1097
-
1148
+
1098
1149
  // Provide helpful error messages for common issues
1099
1150
  if (error.message && error.message.includes("unauthorized")) {
1100
1151
  emitLog("error", "Device unauthorized - ensure ADB debugging is enabled and device is authorized", "reboot");
@@ -1105,7 +1156,7 @@ export default async function createRemote(config) {
1105
1156
  } else if (error.message && error.message.includes("timeout")) {
1106
1157
  emitLog("warn", "Reboot command timed out - this may be normal behavior during reboot", "reboot");
1107
1158
  }
1108
-
1159
+
1109
1160
  throw error;
1110
1161
  }
1111
1162
  },
@@ -1115,7 +1166,7 @@ export default async function createRemote(config) {
1115
1166
  * @public
1116
1167
  * @param {Object} [options={}] - Screenshot options
1117
1168
  * @param {number} [options.width] - Target width for resizing (optional)
1118
- * @param {number} [options.height] - Target height for resizing (optional)
1169
+ * @param {number} [options.height] - Target height for resizing (optional)
1119
1170
  * @param {string} [options.filepath] - File path to save screenshot (optional)
1120
1171
  * @returns {Promise<ReadableStream|void>} Returns PNG stream if no filepath, void if saved to file
1121
1172
  * @fires Remote#screencap-start - Emitted when screenshot capture begins
@@ -1129,16 +1180,16 @@ export default async function createRemote(config) {
1129
1180
  * @example
1130
1181
  * // Basic screenshot - returns stream
1131
1182
  * const pngStream = await remote.screencap();
1132
- *
1183
+ *
1133
1184
  * // Screenshot with resizing
1134
1185
  * const resizedStream = await remote.screencap({ width: 1280, height: 720 });
1135
- *
1186
+ *
1136
1187
  * // Screenshot saved to file
1137
1188
  * await remote.screencap({ filepath: './screenshot.png' });
1138
- *
1189
+ *
1139
1190
  * // Screenshot with resizing and file save
1140
1191
  * await remote.screencap({ width: 640, height: 360, filepath: './thumb.png' });
1141
- *
1192
+ *
1142
1193
  * // Event-driven usage (non-blocking)
1143
1194
  * remote.screencap({ width: 1280, filepath: './shot.png' });
1144
1195
  * remote.on('screencap-complete', (data) => {
@@ -1148,27 +1199,27 @@ export default async function createRemote(config) {
1148
1199
  async screencap(options = {}) {
1149
1200
  const startTime = performance.now();
1150
1201
  const { width, height, filepath } = options;
1151
-
1202
+
1152
1203
  try {
1153
1204
  emitLog("info", "=== Taking device screenshot ===", "screencap");
1154
-
1205
+
1155
1206
  // Emit start event
1156
1207
  emitter.emit("screencap-start", {
1157
1208
  timestamp: new Date().toISOString(),
1158
1209
  options: { width, height, filepath }
1159
1210
  });
1160
-
1211
+
1161
1212
  // Ensure we're connected before taking screenshot
1162
1213
  await ensureConnected();
1163
-
1214
+
1164
1215
  emitLog("info", "Capturing screenshot using native screencap utility", "screencap");
1165
-
1216
+
1166
1217
  // Use the native device.screencap() method which should return PNG
1167
1218
  const screencapStream = await device.screencap();
1168
1219
  const captureTime = performance.now();
1169
-
1220
+
1170
1221
  emitLog("info", `✅ Screenshot captured successfully (${(captureTime - startTime).toFixed(2)}ms)`, "screencap");
1171
-
1222
+
1172
1223
  // Emit captured event
1173
1224
  emitter.emit("screencap-captured", {
1174
1225
  timestamp: new Date().toISOString(),
@@ -1177,44 +1228,44 @@ export default async function createRemote(config) {
1177
1228
 
1178
1229
  // Determine if we need Sharp processing (only for resizing)
1179
1230
  const needsSharpProcessing = width || height;
1180
-
1231
+
1181
1232
  // Handle file save without processing (direct PNG stream to file)
1182
1233
  if (filepath && !needsSharpProcessing) {
1183
1234
  const backgroundOperation = (async () => {
1184
1235
  try {
1185
1236
  const fileOpStartTime = performance.now();
1186
-
1237
+
1187
1238
  emitLog("info", `💾 [BACKGROUND] Starting direct save to: ${filepath}`, "screencap");
1188
-
1239
+
1189
1240
  // Direct pipe: ADB PNG stream -> File (no Sharp processing)
1190
1241
  const directPipeStartTime = performance.now();
1191
1242
  const writeStream = createWriteStream(filepath);
1192
-
1243
+
1193
1244
  // Store the raw PNG stream for user access
1194
1245
  lastScreencapData = screencapStream;
1195
-
1246
+
1196
1247
  emitLog("info", `🔄 [BACKGROUND] Piping stream to file...`, "screencap");
1197
1248
  screencapStream.pipe(writeStream);
1198
-
1249
+
1199
1250
  emitLog("info", `⏳ [BACKGROUND] Waiting for write stream to finish...`, "screencap");
1200
1251
  await new Promise((resolve, reject) => {
1201
- writeStream.on('finish', () => {
1252
+ writeStream.on("finish", () => {
1202
1253
  emitLog("info", `✅ [BACKGROUND] Write stream finished for ${filepath}`, "screencap");
1203
1254
  resolve();
1204
1255
  });
1205
- writeStream.on('error', (err) => {
1256
+ writeStream.on("error", (err) => {
1206
1257
  emitLog("error", `❌ [BACKGROUND] Write stream error for ${filepath}: ${err.message}`, "screencap");
1207
1258
  reject(err);
1208
1259
  });
1209
1260
  });
1210
-
1261
+
1211
1262
  const directPipeTime = performance.now() - directPipeStartTime;
1212
1263
  const totalFileOpTime = performance.now() - fileOpStartTime;
1213
1264
  const totalTime = performance.now() - startTime;
1214
-
1265
+
1215
1266
  emitLog("info", `✅ Screenshot saved directly to ${filepath}`, "screencap");
1216
1267
  emitLog("info", `⚡ Direct pipe timing: ${directPipeTime.toFixed(2)}ms (no Sharp processing!)`, "screencap");
1217
-
1268
+
1218
1269
  // Emit saved event with timing
1219
1270
  emitter.emit("screencap-saved", {
1220
1271
  timestamp: new Date().toISOString(),
@@ -1226,7 +1277,7 @@ export default async function createRemote(config) {
1226
1277
  total: totalTime
1227
1278
  }
1228
1279
  });
1229
-
1280
+
1230
1281
  // Emit complete event
1231
1282
  emitter.emit("screencap-complete", {
1232
1283
  timestamp: new Date().toISOString(),
@@ -1239,7 +1290,6 @@ export default async function createRemote(config) {
1239
1290
  total: totalTime
1240
1291
  }
1241
1292
  });
1242
-
1243
1293
  } catch (saveError) {
1244
1294
  emitLog("error", `💥 [BACKGROUND] Direct pipe error: ${saveError.message}`, "screencap");
1245
1295
  localEmitError(saveError, "screencap", `Failed to save screenshot directly to ${filepath}: ${saveError.message}`);
@@ -1248,16 +1298,16 @@ export default async function createRemote(config) {
1248
1298
  backgroundOperations.delete(backgroundOperation);
1249
1299
  }
1250
1300
  })();
1251
-
1301
+
1252
1302
  backgroundOperations.add(backgroundOperation);
1253
1303
  emitLog("info", "Direct PNG pipe started in background", "screencap");
1254
1304
  return; // Don't return a stream when saving to file
1255
1305
  }
1256
-
1306
+
1257
1307
  if (!needsSharpProcessing && !filepath) {
1258
1308
  // Store the raw PNG stream for user access
1259
1309
  lastScreencapData = screencapStream;
1260
-
1310
+
1261
1311
  // Return raw stream if no processing or file save needed
1262
1312
  emitLog("info", "Raw PNG stream ready (no processing needed)", "screencap");
1263
1313
  emitter.emit("screencap-ready", {
@@ -1272,7 +1322,7 @@ export default async function createRemote(config) {
1272
1322
  });
1273
1323
  return screencapStream;
1274
1324
  }
1275
-
1325
+
1276
1326
  // Process the image
1277
1327
  emitLog("info", "Processing screenshot image...", "screencap");
1278
1328
  emitter.emit("screencap-processing", {
@@ -1281,67 +1331,65 @@ export default async function createRemote(config) {
1281
1331
  height,
1282
1332
  filepath
1283
1333
  });
1284
-
1334
+
1285
1335
  const processStartTime = performance.now();
1286
-
1336
+
1287
1337
  // Create Sharp transform pipeline
1288
1338
  let sharpTransform = sharp();
1289
-
1339
+
1290
1340
  // Apply resizing if width or height specified
1291
1341
  if (width || height) {
1292
1342
  const resizeOptions = {
1293
- fit: 'inside', // Maintain aspect ratio
1343
+ fit: "inside", // Maintain aspect ratio
1294
1344
  withoutEnlargement: true // Don't upscale
1295
1345
  };
1296
1346
  if (width) resizeOptions.width = width;
1297
1347
  if (height) resizeOptions.height = height;
1298
-
1348
+
1299
1349
  sharpTransform = sharpTransform.resize(resizeOptions);
1300
- emitLog("info", `Resizing to ${width || 'auto'}x${height || 'auto'}`, "screencap");
1350
+ emitLog("info", `Resizing to ${width || "auto"}x${height || "auto"}`, "screencap");
1301
1351
  }
1302
-
1352
+
1303
1353
  // Ensure PNG format with fastest compression settings
1304
- sharpTransform = sharpTransform.png({
1354
+ sharpTransform = sharpTransform.png({
1305
1355
  compressionLevel: 1, // Fastest compression (0-9, lower = faster)
1306
- progressive: false // Disable progressive encoding
1356
+ progressive: false // Disable progressive encoding
1307
1357
  });
1308
-
1358
+
1309
1359
  if (filepath) {
1310
1360
  // Background process handles saving and updates lastScreencapData when done
1311
1361
  const backgroundOperation = (async () => {
1312
1362
  try {
1313
1363
  const fileOpStartTime = performance.now();
1314
- const writeStreamStartTime = performance.now();
1315
1364
  const writeStream = createWriteStream(filepath);
1316
- const writeStreamTime = performance.now() - writeStreamStartTime;
1317
-
1365
+
1318
1366
  // Process and save data, collecting it for lastScreencapData
1319
1367
  const chunks = [];
1320
1368
  const processedStream = screencapStream.pipe(sharpTransform);
1321
-
1369
+
1322
1370
  await new Promise((resolve, reject) => {
1323
- processedStream.on('data', (chunk) => {
1371
+ processedStream.on("data", (chunk) => {
1324
1372
  chunks.push(chunk);
1325
1373
  writeStream.write(chunk);
1326
1374
  });
1327
-
1328
- processedStream.on('end', () => {
1375
+
1376
+ processedStream.on("end", () => {
1329
1377
  writeStream.end();
1330
1378
  // Save processed data to lastScreencapData when done
1331
1379
  lastScreencapData = Buffer.concat(chunks);
1332
-
1380
+
1333
1381
  const totalFileOpTime = performance.now() - fileOpStartTime;
1334
1382
  const totalTime = performance.now() - startTime;
1335
-
1383
+
1336
1384
  emitLog("info", `✅ Screenshot saved to ${filepath}`, "screencap");
1337
1385
  emitLog("info", `⏱️ File save timing: ${totalFileOpTime.toFixed(2)}ms, Total: ${totalTime.toFixed(2)}ms`, "screencap");
1338
-
1386
+
1339
1387
  emitter.emit("screencap-saved", {
1340
1388
  timestamp: new Date().toISOString(),
1341
1389
  filepath,
1342
1390
  timing: { fileOperation: totalFileOpTime, total: totalTime }
1343
1391
  });
1344
-
1392
+
1345
1393
  emitter.emit("screencap-complete", {
1346
1394
  timestamp: new Date().toISOString(),
1347
1395
  filepath,
@@ -1350,26 +1398,27 @@ export default async function createRemote(config) {
1350
1398
  height,
1351
1399
  timing: { fileOperation: totalFileOpTime, total: totalTime }
1352
1400
  });
1353
-
1401
+
1354
1402
  resolve();
1355
1403
  });
1356
-
1357
- processedStream.on('error', (error) => {
1404
+
1405
+ processedStream.on("error", (error) => {
1358
1406
  reject(error);
1359
1407
  });
1360
1408
  });
1361
-
1362
1409
  } catch (saveError) {
1363
1410
  // Show full error details for debugging
1364
1411
  emitLog("error", `💥 [BACKGROUND SHARP] File save error: ${saveError.message}`, "screencap");
1365
1412
  emitLog("error", `💥 [BACKGROUND SHARP] Error stack: ${saveError.stack}`, "screencap");
1366
-
1413
+
1367
1414
  // Only suppress specific libspng/PNG processing errors that occur after disconnection
1368
- if (!connected && saveError.message && (
1369
- saveError.message.includes('libspng') ||
1370
- saveError.message.includes('pngload_buffer') ||
1371
- saveError.message.includes('read error')
1372
- )) {
1415
+ if (
1416
+ !connected &&
1417
+ saveError.message &&
1418
+ (saveError.message.includes("libspng") ||
1419
+ saveError.message.includes("pngload_buffer") ||
1420
+ saveError.message.includes("read error"))
1421
+ ) {
1373
1422
  emitLog("debug", `PNG processing error after disconnection (suppressed): ${filepath}`, "screencap");
1374
1423
  } else {
1375
1424
  // Emit all other errors with full details
@@ -1381,31 +1430,42 @@ export default async function createRemote(config) {
1381
1430
  backgroundOperations.delete(backgroundOperation);
1382
1431
  }
1383
1432
  })();
1384
-
1433
+
1385
1434
  // Track the background operation
1386
- backgroundOperations.add(backgroundOperation);
1435
+ backgroundOperations.add(backgroundOperation);
1387
1436
  emitLog("info", "Screenshot processing started in background", "screencap");
1388
1437
  return; // Don't return a stream when saving to file
1389
-
1390
1438
  } else {
1391
1439
  // Return processed stream
1392
1440
  const processedStream = screencapStream.pipe(sharpTransform);
1393
1441
  const processEndTime = performance.now();
1394
-
1442
+
1395
1443
  const streamCaptureTime = captureTime - startTime;
1396
1444
  const sharpProcessTime = processEndTime - processStartTime;
1397
1445
  const totalTime = processEndTime - startTime;
1398
-
1446
+
1399
1447
  // Debug timing variables
1400
- emitLog("debug", `🔍 Timing variables: captureTime=${captureTime}, startTime=${startTime}, processEndTime=${processEndTime}, processStartTime=${processStartTime}`, "screencap");
1401
-
1448
+ emitLog(
1449
+ "debug",
1450
+ `🔍 Timing variables: captureTime=${captureTime}, startTime=${startTime}, processEndTime=${processEndTime}, processStartTime=${processStartTime}`,
1451
+ "screencap"
1452
+ );
1453
+
1402
1454
  emitLog("info", `PNG stream processed and ready`, "screencap");
1403
1455
  try {
1404
- emitLog("info", `⏱️ Timing breakdown: Capture=${streamCaptureTime.toFixed(2)}ms, Sharp=${sharpProcessTime.toFixed(2)}ms, Total=${totalTime.toFixed(2)}ms`, "screencap");
1456
+ emitLog(
1457
+ "info",
1458
+ `⏱️ Timing breakdown: Capture=${streamCaptureTime.toFixed(2)}ms, Sharp=${sharpProcessTime.toFixed(2)}ms, Total=${totalTime.toFixed(2)}ms`,
1459
+ "screencap"
1460
+ );
1405
1461
  } catch (timingError) {
1406
- emitLog("error", `⚠️ Timing log error in stream processing: ${timingError.message}. Variables: streamCaptureTime=${streamCaptureTime}, sharpProcessTime=${sharpProcessTime}, totalTime=${totalTime}`, "screencap");
1462
+ emitLog(
1463
+ "error",
1464
+ `⚠️ Timing log error in stream processing: ${timingError.message}. Variables: streamCaptureTime=${streamCaptureTime}, sharpProcessTime=${sharpProcessTime}, totalTime=${totalTime}`,
1465
+ "screencap"
1466
+ );
1407
1467
  }
1408
-
1468
+
1409
1469
  // Emit ready event
1410
1470
  emitter.emit("screencap-ready", {
1411
1471
  timestamp: new Date().toISOString(),
@@ -1418,7 +1478,7 @@ export default async function createRemote(config) {
1418
1478
  total: totalTime
1419
1479
  }
1420
1480
  });
1421
-
1481
+
1422
1482
  // Emit complete event
1423
1483
  emitter.emit("screencap-complete", {
1424
1484
  timestamp: new Date().toISOString(),
@@ -1431,16 +1491,15 @@ export default async function createRemote(config) {
1431
1491
  total: totalTime
1432
1492
  }
1433
1493
  });
1434
-
1494
+
1435
1495
  // Store the processed stream for user access
1436
1496
  lastScreencapData = processedStream;
1437
-
1497
+
1438
1498
  return processedStream;
1439
1499
  }
1440
-
1441
1500
  } catch (error) {
1442
1501
  localEmitError(error, "screencap", "Failed to capture screenshot");
1443
-
1502
+
1444
1503
  // Provide helpful error messages for common issues
1445
1504
  if (error.message && error.message.includes("unauthorized")) {
1446
1505
  emitLog("error", "Device unauthorized - ensure ADB debugging is enabled and device is authorized", "screencap");
@@ -1451,7 +1510,7 @@ export default async function createRemote(config) {
1451
1510
  } else if (error.message && error.message.includes("ENOENT")) {
1452
1511
  emitLog("error", `File path error: ${error.message}`, "screencap");
1453
1512
  }
1454
-
1513
+
1455
1514
  throw error;
1456
1515
  }
1457
1516
  },
@@ -1475,13 +1534,13 @@ export default async function createRemote(config) {
1475
1534
  * @example
1476
1535
  * // Basic thumbnail with default 240px width
1477
1536
  * const thumbnailStream = await remote.thumbnail();
1478
- *
1537
+ *
1479
1538
  * // Thumbnail with custom dimensions
1480
1539
  * const customThumb = await remote.thumbnail({ width: 320, height: 180 });
1481
- *
1540
+ *
1482
1541
  * // Thumbnail saved to file
1483
1542
  * await remote.thumbnail({ filepath: './thumb.png' });
1484
- *
1543
+ *
1485
1544
  * // Thumbnail with custom size and file save
1486
1545
  * await remote.thumbnail({ width: 160, height: 90, filepath: './small-thumb.png' });
1487
1546
  */
@@ -1491,9 +1550,9 @@ export default async function createRemote(config) {
1491
1550
  width: 240,
1492
1551
  ...options
1493
1552
  };
1494
-
1495
- emitLog("info", `📸 Taking thumbnail screenshot (${thumbnailOptions.width}x${thumbnailOptions.height || 'auto'})`, "thumbnail");
1496
-
1553
+
1554
+ emitLog("info", `📸 Taking thumbnail screenshot (${thumbnailOptions.width}x${thumbnailOptions.height || "auto"})`, "thumbnail");
1555
+
1497
1556
  // Call screencap with thumbnail options
1498
1557
  return await this.screencap(thumbnailOptions);
1499
1558
  },
@@ -1512,23 +1571,22 @@ export default async function createRemote(config) {
1512
1571
  async waitBootComplete(timeout = 60000) {
1513
1572
  try {
1514
1573
  emitLog("info", "=== Waiting for device boot completion ===", "waitBootComplete");
1515
-
1574
+
1516
1575
  // Ensure we're connected before monitoring boot status
1517
1576
  await ensureConnected();
1518
-
1577
+
1519
1578
  emitLog("info", `Monitoring boot status (timeout: ${timeout}ms)`, "waitBootComplete");
1520
-
1579
+
1521
1580
  // Use the native device.waitBootComplete() method
1522
1581
  const result = await device.waitBootComplete();
1523
-
1582
+
1524
1583
  emitLog("info", "✅ Device boot completed successfully", "waitBootComplete");
1525
1584
  emitLog("info", "Device is now ready for operations", "waitBootComplete");
1526
1585
 
1527
1586
  return result;
1528
-
1529
1587
  } catch (error) {
1530
1588
  emitError(error, "waitBootComplete", "Failed while waiting for boot completion");
1531
-
1589
+
1532
1590
  // Provide helpful error messages for common issues
1533
1591
  if (error.message && error.message.includes("unauthorized")) {
1534
1592
  emitLog("error", "Device unauthorized - ensure ADB debugging is enabled and device is authorized", "waitBootComplete");
@@ -1539,7 +1597,7 @@ export default async function createRemote(config) {
1539
1597
  } else if (error.message && error.message.includes("connection")) {
1540
1598
  emitLog("error", "Connection lost while waiting for boot completion", "waitBootComplete");
1541
1599
  }
1542
-
1600
+
1543
1601
  throw error;
1544
1602
  }
1545
1603
  },
@@ -1742,7 +1800,7 @@ export default async function createRemote(config) {
1742
1800
  Object.keys(keyboardKeys).forEach((keyName) => {
1743
1801
  const char = keyboardKeys[keyName];
1744
1802
  const shiftedChar = getShiftedCharacter(keyName, char);
1745
-
1803
+
1746
1804
  // Only create shift function if the character actually changes when shifted
1747
1805
  if (shiftedChar !== char) {
1748
1806
  /**
@@ -1785,10 +1843,10 @@ export default async function createRemote(config) {
1785
1843
  * @public
1786
1844
  * @param {RemoteConfig} config - Configuration for the remote.
1787
1845
  * @returns {Promise<Remote>} Resolves with a ready remote instance.
1788
- *
1846
+ *
1789
1847
  * @description
1790
1848
  * Alias for createRemote() - both functions now return ready-to-use remote instances.
1791
- *
1849
+ *
1792
1850
  * @example
1793
1851
  * // ESM with event handling
1794
1852
  * const remote = await createAndroidTVRemote({ ip: "192.168.1.100" });