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

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,31 +1,45 @@
1
- # Android TV Remote Node Module
1
+ # @cldmv/node-android-tv-remote
2
2
 
3
- [Keyboard Keys](./docs/KEYBOARD_KEYS.md) | [Keycodes](./docs/KEYCODES.md)
3
+ **@cldmv/node-android-tv-remote** is a modern, **event-driven** Node.js module for controlling Android TV devices via ADB. It supports sending keycodes, comprehensive keyboard input (71 characters with smart shift detection), remote control commands, screenshots and device management. It is designed for compatibility with a wide range of Android TV devices, including Fire TV, Chromecast with Google TV, Nvidia Shield and more.
4
4
 
5
- ---
5
+ Every remote is an event source: operations report through structured `log` events and failures through structured `error` events instead of writing to the console, so the library slots into an application's own logging and error handling.
6
+
7
+ > _Drive any Android TV from Node.js — keys, text, screenshots and power — over ADB._
6
8
 
7
- ## Table of Contents
9
+ [![npm version]][npm_version_url] [![npm downloads]][npm_downloads_url] [![GitHub downloads]][github_downloads_url] [![Last commit]][last_commit_url] [![npm last update]][npm_last_update_url] [![coverage]][coverage_url]
8
10
 
9
- - [Overview](#overview)
10
- - [Installation](#installation)
11
- - [Usage](#usage)
12
- - [API](#api)
13
- - [Supported Devices](#supported-devices)
14
- - [Keyboard Keys](./docs/KEYBOARD_KEYS.md)
15
- - [Keycodes](./docs/KEYCODES.md)
11
+ [![Contributors]][contributors_url] [![Sponsor shinrai]][sponsor_url]
16
12
 
17
13
  ---
18
14
 
19
- ## Overview
15
+ ## ✨ What's New
16
+
17
+ ### Latest: v2.1.8 (October 2026)
18
+
19
+ - **Independent remotes, and no crash on an unheard error** — each remote now has its own event emitter, so two TVs no longer receive each other's events. An `error` with no listener is logged (a `log` event with level `"error"`, and `NODE_DEBUG=android-tv-remote`) instead of thrown, while the failing call still rejects ([#46](https://github.com/CLDMV/node-android-tv-remote/pull/46)).
20
+ - **`npm run setup-device` works again** — the script, broken since v2.1.0, now runs the setup steps through the v2 remote ([#45](https://github.com/CLDMV/node-android-tv-remote/pull/45)). The package is also relicensed under Apache-2.0 ([#41](https://github.com/CLDMV/node-android-tv-remote/pull/41)).
21
+ - **Header tooling on fix-headers 2.2.0** — the `@cldmv/fix-headers` and `@cldmv/configs` dev dependencies move to 2.2.0 and 1.2.4, so `@Last modified by` now follows content edits only; no file was restamped ([#50](https://github.com/CLDMV/node-android-tv-remote/pull/50), [#52](https://github.com/CLDMV/node-android-tv-remote/pull/52)).
22
+ - [View full v2.1.8 Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.1.8.md)
20
23
 
21
- A modern, **event-driven** Node.js module for controlling Android TV devices via ADB. Supports sending keycodes, comprehensive keyboard input (71 characters with smart shift detection), and remote control commands. Designed for compatibility with a wide range of Android TV devices, including Fire TV, Chromecast with Google TV, and more.
24
+ ### Recent Releases
22
25
 
23
- ### Key Features
26
+ - **v2.1.7** (October 2026) — CommonJS entry loads the ESM build directly, fails clearly without `require(esm)`, and exports `createAndroidTVRemote` ([Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.1.7.md))
27
+ - **v2.1.6** (October 2026) — CI only: the in-repo PR mirror job runs instead of being skipped; `sharp` lockfile and `@cldmv/vitest-runner` bumps ([Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.1.6.md))
28
+ - **v2.1.5** (October 2026) — maintenance: v4.29.2 workflow sync with bundle-size measurement, required-check mirror fix, uniform file headers; no runtime change ([Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.1.5.md))
29
+ - **v2.1.4** (September 2026) — `@devicefarmer/adbkit` 3.3.9 in the lockfile, dead code removed from the screencap path, bot signing secrets wired into the release workflows ([Changelog](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/changelog/v2/v2.1.4.md))
30
+
31
+ > **Note:** v2.1.1 through v2.1.6 were released on GitHub but never published to npm; npm went from v2.1.0 straight to v2.1.7. See the changelogs for what changed in between, including the Node.js 20.9.0 floor from v2.1.1.
32
+
33
+ 📚 **For complete version history and detailed release notes, see the [docs/changelog/](https://github.com/CLDMV/node-android-tv-remote/tree/master/docs/changelog/) folder.**
34
+
35
+ ---
36
+
37
+ ## 🚀 Key Features
24
38
 
25
39
  - 🎯 **Event-driven architecture** - Comprehensive event system with structured data
26
40
  - ⌨️ **Comprehensive keyboard input** - 71 characters with smart shift detection and special symbols
27
41
  - 🔄 **ESM & CommonJS support** - Works with both `import` and `require`
28
- - 🛡️ **Error resilience** - Errors emit events instead of crashing your app
42
+ - 🛡️ **Error resilience** - Errors are reported as events instead of crashing your app; an `error` listener is optional (see [Event-Driven Usage](#event-driven-usage-recommended))
29
43
  - 🔗 **Method chaining** - Fluent API for event listener management
30
44
  - 📊 **Structured logging** - Timestamped, categorized log events with source tracking
31
45
  - 🚀 **Promise-based** - Modern async/await support with callback compatibility
@@ -34,9 +48,22 @@ A modern, **event-driven** Node.js module for controlling Android TV devices via
34
48
  - 🔄 **Device management** - Reboot, wake, settings configuration with event tracking
35
49
  - 📱 **Universal compatibility** - Works with Fire TV, Chromecast, Shield, and more
36
50
 
37
- ## Installation
51
+ ---
52
+
53
+ ## 📦 Installation
54
+
55
+ ### Requirements
56
+
57
+ - **Node.js 20.9.0 or higher** for ESM `import` (the package's `engines` floor, set by the `sharp` dependency).
58
+ - **`require()`** loads the ESM build through Node's `require(esm)`, so it needs **Node.js ^20.19.0 or >=22.12.0**. On older Node.js, load the package with `import()` instead.
59
+ - The **Android Debug Bridge (ADB)** binary installed and available in your system PATH (see below). A `postinstall` check prints install instructions when `adb` is missing.
60
+ - `sharp` installs a platform-specific prebuilt binary; the install environment must be able to fetch it.
38
61
 
39
- This module requires the Android Debug Bridge (ADB) binary to be installed and available in your system PATH.
62
+ ### Install
63
+
64
+ ```sh
65
+ npm install @cldmv/node-android-tv-remote
66
+ ```
40
67
 
41
68
  ### Install ADB
42
69
 
@@ -67,22 +94,16 @@ This module requires the Android Debug Bridge (ADB) binary to be installed and a
67
94
 
68
95
  > **Note:** You must accept the ADB authorization prompt on your Android TV device the first time you connect.
69
96
 
70
- ### Install the Node Module
71
-
72
- ```sh
73
- npm install android-tv-remote
74
- ```
75
-
76
- ## Usage
97
+ ---
77
98
 
78
- ### Basic Usage
99
+ ## 🚀 Quick Start
79
100
 
80
101
  ```js
81
102
  // ESM (Node.js with type: "module" in package.json)
82
- import createRemote from "android-tv-remote";
103
+ import createRemote from "@cldmv/node-android-tv-remote";
83
104
 
84
105
  // CommonJS
85
- const createRemote = require("android-tv-remote");
106
+ const createRemote = require("@cldmv/node-android-tv-remote");
86
107
 
87
108
  // Create remote (async function)
88
109
  const remote = await createRemote({ ip: "192.168.1.100" });
@@ -93,18 +114,32 @@ await remote.press.up();
93
114
  await remote.press.ok();
94
115
 
95
116
  // Or chain promises
96
- createRemote({ ip: "192.168.1.100" })
97
- .then((remote) => remote.press.home())
98
- .then(() => remote.press.up())
99
- .then(() => remote.press.ok());
117
+ createRemote({ ip: "192.168.1.100" }).then(async (remote) => {
118
+ await remote.press.home();
119
+ await remote.press.up();
120
+ await remote.press.ok();
121
+ });
100
122
  ```
101
123
 
124
+ `createAndroidTVRemote(config)` is an alias of `createRemote(config)`, exported by name from both entries:
125
+
126
+ ```js
127
+ import { createAndroidTVRemote } from "@cldmv/node-android-tv-remote";
128
+ // or: const { createAndroidTVRemote } = require("@cldmv/node-android-tv-remote");
129
+
130
+ const remote = await createAndroidTVRemote({ ip: "192.168.1.100" });
131
+ ```
132
+
133
+ ---
134
+
135
+ ## 🎯 Usage
136
+
102
137
  ### Event-Driven Usage (Recommended)
103
138
 
104
- This module uses an **event-driven architecture** instead of console logging. All operations emit structured events that you can listen to:
139
+ This module uses an **event-driven architecture** instead of console logging. All operations emit structured events that you can listen to. The remote is a Node.js event emitter, but an `error` event is only emitted when a listener is attached, so an `error` listener is optional. Without one, the error is emitted as a `log` event with `level: 'error'` and written to `NODE_DEBUG=android-tv-remote`. Register an `error` listener to handle failures yourself:
105
140
 
106
141
  ```js
107
- import createRemote from "android-tv-remote";
142
+ import createRemote from "@cldmv/node-android-tv-remote";
108
143
 
109
144
  const remote = await createRemote({ ip: "192.168.1.100" });
110
145
 
@@ -138,7 +173,7 @@ await remote.screencap({ filepath: "./screenshot.png" });
138
173
  The createRemote function is async and returns a Promise:
139
174
 
140
175
  ```js
141
- import createRemote from "android-tv-remote";
176
+ import createRemote from "@cldmv/node-android-tv-remote";
142
177
 
143
178
  // Async initialization with await
144
179
  const remote = await createRemote({ ip: "192.168.1.100" });
@@ -157,7 +192,7 @@ createRemote({ ip: "192.168.1.100" }).then((remote) => {
157
192
  Advanced screencap with resizing, thumbnails, and file saving:
158
193
 
159
194
  ```js
160
- import createRemote from "android-tv-remote";
195
+ import createRemote from "@cldmv/node-android-tv-remote";
161
196
 
162
197
  const remote = await createRemote({ ip: "192.168.1.100" });
163
198
 
@@ -201,7 +236,7 @@ remote.on("screencap-complete", (data) => {
201
236
  Comprehensive device control with event tracking:
202
237
 
203
238
  ```js
204
- import createRemote from "android-tv-remote";
239
+ import createRemote from "@cldmv/node-android-tv-remote";
205
240
 
206
241
  const remote = await createRemote({ ip: "192.168.1.100" });
207
242
 
@@ -239,7 +274,7 @@ remote.on("log", (data) => {
239
274
  Comprehensive text input with individual key support and smart shift detection:
240
275
 
241
276
  ```js
242
- import createRemote from "android-tv-remote";
277
+ import createRemote from "@cldmv/node-android-tv-remote";
243
278
 
244
279
  const remote = await createRemote({ ip: "192.168.1.100" });
245
280
 
@@ -324,7 +359,9 @@ await remote.keyboard.key.a.keycode(); // Sends keycode instead of character
324
359
  }
325
360
  ```
326
361
 
327
- ## API
362
+ ---
363
+
364
+ ## 🔧 API
328
365
 
329
366
  ### Main Methods
330
367
 
@@ -351,7 +388,7 @@ await remote.keyboard.key.a.keycode(); // Sends keycode instead of character
351
388
  ### Events
352
389
 
353
390
  - `log` - Emitted for all operations (info, warn, error, debug levels)
354
- - `error` - Emitted when errors occur (structured error data)
391
+ - `error` - Emitted when errors occur (structured error data). Each remote has its own listeners. With no `error` listener attached, the error is emitted as a `log` event with `level: 'error'` (the `Error` is in `data.error`) instead of throwing. The failing call still reports it: commands reject, and `connect()` / `disconnect()` resolve with the `Error` as before
355
392
  - `screencap-start` - Emitted when screenshot capture begins
356
393
  - `screencap-captured` - Emitted when raw screenshot is captured
357
394
  - `screencap-processing` - Emitted when image processing begins
@@ -367,7 +404,9 @@ await remote.keyboard.key.a.keycode(); // Sends keycode instead of character
367
404
 
368
405
  See JSDoc comments in source code for full API documentation.
369
406
 
370
- ## Supported Devices
407
+ ---
408
+
409
+ ## 📺 Supported Devices
371
410
 
372
411
  | Device | Supported | Native Remote Buttons |
373
412
  | ------------------------ | --------- | ------------------------------------------- |
@@ -378,10 +417,74 @@ See JSDoc comments in source code for full API documentation.
378
417
  | Xiaomi Mi Box | Yes | Home, Back, D-Pad, Volume |
379
418
  | Sony Bravia (Android TV) | Yes | Home, Back, D-Pad, Volume, Input |
380
419
 
381
- See [Keyboard Keys](./docs/KEYBOARD_KEYS.md) and [Keycodes](./docs/KEYCODES.md) for full lists.
420
+ See [Keyboard Keys](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/KEYBOARD_KEYS.md) and [Keycodes](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/KEYCODES.md) for full lists.
421
+
422
+ ---
423
+
424
+ ## 📚 Documentation
425
+
426
+ - **[Keyboard Keys](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/KEYBOARD_KEYS.md)** — every `keyboard.key` character and its shifted variant
427
+ - **[Keycodes](https://github.com/CLDMV/node-android-tv-remote/blob/master/docs/KEYCODES.md)** — the Android keycodes behind `press.<key>()` and `inputKeycode()`
428
+ - **[Changelog](https://github.com/CLDMV/node-android-tv-remote/tree/master/docs/changelog/)** — release notes for every version
429
+
430
+ [![CodeFactor]][codefactor_url] [![OpenSSF Scorecard]][ossf_scorecard_url] [![npms.io score]][npms_url] [![npm unpacked size]][npm_size_url] [![Repo size]][repo_size_url]
431
+
432
+ ---
433
+
434
+ ## 🤝 Contributing
435
+
436
+ Contributions are welcome — open an issue or a pull request on [GitHub](https://github.com/CLDMV/node-android-tv-remote).
437
+
438
+ ```bash
439
+ npm test # Vitest, then the CommonJS entry tests
440
+ npm run lint # ESLint
441
+ npm run format # Prettier
442
+ ```
443
+
444
+ [![Contributors]][contributors_url] [![Sponsor shinrai]][sponsor_url]
382
445
 
383
446
  ---
384
447
 
385
- ## License
448
+ ## 🔗 Links
449
+
450
+ - **npm**: [@cldmv/node-android-tv-remote](https://www.npmjs.com/package/@cldmv/node-android-tv-remote)
451
+ - **GitHub**: [CLDMV/node-android-tv-remote](https://github.com/CLDMV/node-android-tv-remote)
452
+ - **Issues**: [GitHub Issues](https://github.com/CLDMV/node-android-tv-remote/issues)
453
+ - **Changelog**: [docs/changelog/](https://github.com/CLDMV/node-android-tv-remote/tree/master/docs/changelog/)
454
+
455
+ ---
386
456
 
387
- MIT
457
+ ## 📄 License
458
+
459
+ [![npm license]][npm_license_url]
460
+
461
+ Apache-2.0 © Shinrai / CLDMV. See [LICENSE](https://github.com/CLDMV/node-android-tv-remote/blob/master/LICENSE) for the full text.
462
+
463
+ [npm version]: https://img.shields.io/npm/v/%40cldmv%2Fnode-android-tv-remote.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
464
+ [npm_version_url]: https://www.npmjs.com/package/@cldmv/node-android-tv-remote
465
+ [last commit]: https://img.shields.io/github/last-commit/CLDMV/node-android-tv-remote?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
466
+ [last_commit_url]: https://github.com/CLDMV/node-android-tv-remote/commits
467
+ [npm last update]: https://img.shields.io/npm/last-update/%40cldmv%2Fnode-android-tv-remote?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
468
+ [npm_last_update_url]: https://www.npmjs.com/package/@cldmv/node-android-tv-remote
469
+ [codefactor]: https://img.shields.io/codefactor/grade/github/CLDMV/node-android-tv-remote?style=for-the-badge&logo=codefactor&logoColor=white&labelColor=F44A6A
470
+ [codefactor_url]: https://www.codefactor.io/repository/github/cldmv/node-android-tv-remote
471
+ [openssf scorecard]: https://img.shields.io/ossf-scorecard/github.com/CLDMV/node-android-tv-remote?style=for-the-badge&label=OpenSSF%20Scorecard
472
+ [ossf_scorecard_url]: https://scorecard.dev/viewer/?uri=github.com/CLDMV/node-android-tv-remote
473
+ [npms.io score]: https://img.shields.io/npms-io/final-score/%40cldmv%2Fnode-android-tv-remote?style=for-the-badge&logo=npms&logoColor=white&labelColor=0B5D57
474
+ [npms_url]: https://npms.io/search?q=%40cldmv%2Fnode-android-tv-remote
475
+ [npm downloads]: https://img.shields.io/npm/dm/%40cldmv%2Fnode-android-tv-remote.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
476
+ [npm_downloads_url]: https://www.npmjs.com/package/@cldmv/node-android-tv-remote
477
+ [github downloads]: https://img.shields.io/github/downloads/CLDMV/node-android-tv-remote/total?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
478
+ [github_downloads_url]: https://github.com/CLDMV/node-android-tv-remote/releases
479
+ [npm unpacked size]: https://img.shields.io/npm/unpacked-size/%40cldmv%2Fnode-android-tv-remote.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
480
+ [npm_size_url]: https://www.npmjs.com/package/@cldmv/node-android-tv-remote
481
+ [repo size]: https://img.shields.io/github/repo-size/CLDMV/node-android-tv-remote?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
482
+ [repo_size_url]: https://github.com/CLDMV/node-android-tv-remote
483
+ [npm license]: https://img.shields.io/npm/l/%40cldmv%2Fnode-android-tv-remote.svg?style=for-the-badge&logo=npm&logoColor=white&labelColor=CB3837
484
+ [npm_license_url]: https://www.npmjs.com/package/@cldmv/node-android-tv-remote
485
+ [coverage]: https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2FCLDMV%2Fnode-android-tv-remote%2Fbadges%2Fcoverage.json&style=for-the-badge&logo=vitest&logoColor=white
486
+ [coverage_url]: https://github.com/CLDMV/node-android-tv-remote/blob/badges/coverage.json
487
+ [contributors]: https://img.shields.io/github/contributors/CLDMV/node-android-tv-remote.svg?style=for-the-badge&logo=github&logoColor=white&labelColor=181717
488
+ [contributors_url]: https://github.com/CLDMV/node-android-tv-remote/graphs/contributors
489
+ [sponsor shinrai]: https://img.shields.io/github/sponsors/shinrai?style=for-the-badge&logo=githubsponsors&logoColor=white&labelColor=EA4AAA&label=Sponsor
490
+ [sponsor_url]: https://github.com/sponsors/shinrai
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cldmv/node-android-tv-remote",
3
- "version": "2.1.7",
3
+ "version": "2.1.8",
4
4
  "description": "A Node.js library for controlling Android TV devices via ADB keycodes and text input.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -52,7 +52,7 @@
52
52
  "url": "https://github.com/CLDMV/node-android-tv-remote/issues"
53
53
  },
54
54
  "homepage": "https://github.com/CLDMV/node-android-tv-remote#readme",
55
- "license": "MIT",
55
+ "license": "Apache-2.0",
56
56
  "files": [
57
57
  "src/",
58
58
  "scripts/",
@@ -72,8 +72,8 @@
72
72
  "node": ">=20.9.0"
73
73
  },
74
74
  "devDependencies": {
75
- "@cldmv/configs": "^1.2.0",
76
- "@cldmv/fix-headers": "^2.1.1",
75
+ "@cldmv/configs": "^1.2.4",
76
+ "@cldmv/fix-headers": "^2.2.0",
77
77
  "@cldmv/vitest-runner": "^1.2.0",
78
78
  "@eslint/css": "^2.0.0",
79
79
  "@eslint/js": "^10.0.1",
@@ -18,6 +18,8 @@
18
18
  */
19
19
  import { execSync } from "child_process";
20
20
  import os from "os";
21
+ import { realpathSync } from "node:fs";
22
+ import { fileURLToPath } from "node:url";
21
23
 
22
24
  function hasAdb() {
23
25
  try {
@@ -28,36 +30,47 @@ function hasAdb() {
28
30
  }
29
31
  }
30
32
 
31
- if (hasAdb()) {
32
- console.log("ADB is installed and available in your PATH.");
33
- process.exit(0);
34
- }
33
+ /**
34
+ * Print whether adb is available, with install instructions when it isn't.
35
+ * @returns {void}
36
+ */
37
+ export function main() {
38
+ if (hasAdb()) {
39
+ console.log("ADB is installed and available in your PATH.");
40
+ return;
41
+ }
35
42
 
36
- console.log("\nADB is not installed or not in your PATH.");
37
- console.log("Follow these instructions to install ADB:");
43
+ console.log("\nADB is not installed or not in your PATH.");
44
+ console.log("Follow these instructions to install ADB:");
45
+
46
+ const platform = os.platform();
47
+ if (platform === "win32") {
48
+ console.log("\nWindows:");
49
+ console.log("1. Download the SDK Platform Tools for Windows: https://developer.android.com/studio/releases/platform-tools");
50
+ console.log("2. Extract the ZIP file.");
51
+ console.log("3. Add the extracted folder to your system PATH.");
52
+ console.log('4. Test by running "adb version" in Command Prompt.');
53
+ } else if (platform === "darwin") {
54
+ console.log("\nmacOS:");
55
+ console.log("1. Download the SDK Platform Tools for Mac: https://developer.android.com/studio/releases/platform-tools");
56
+ console.log("2. Extract the ZIP file.");
57
+ console.log("3. Move the extracted folder to /usr/local/bin or add it to your PATH.");
58
+ console.log('4. Test by running "adb version" in Terminal.');
59
+ } else if (platform === "linux") {
60
+ console.log("\nLinux:");
61
+ console.log("1. Download the SDK Platform Tools for Linux: https://developer.android.com/studio/releases/platform-tools");
62
+ console.log("2. Extract the ZIP file.");
63
+ console.log("3. Move the extracted folder to /usr/local/bin or add it to your PATH.");
64
+ console.log("4. Or install via your package manager:");
65
+ console.log(" - Ubuntu/Debian: sudo apt-get install android-tools-adb");
66
+ console.log(" - Fedora/Red Hat: sudo dnf install android-tools");
67
+ console.log(" - CentOS/yum: sudo yum install android-tools");
68
+ console.log('5. Test by running "adb version" in your shell.');
69
+ }
70
+ console.log("\nYou must accept the ADB authorization prompt on your Android TV device the first time you connect.");
71
+ }
38
72
 
39
- const platform = os.platform();
40
- if (platform === "win32") {
41
- console.log("\nWindows:");
42
- console.log("1. Download the SDK Platform Tools for Windows: https://developer.android.com/studio/releases/platform-tools");
43
- console.log("2. Extract the ZIP file.");
44
- console.log("3. Add the extracted folder to your system PATH.");
45
- console.log('4. Test by running "adb version" in Command Prompt.');
46
- } else if (platform === "darwin") {
47
- console.log("\nmacOS:");
48
- console.log("1. Download the SDK Platform Tools for Mac: https://developer.android.com/studio/releases/platform-tools");
49
- console.log("2. Extract the ZIP file.");
50
- console.log("3. Move the extracted folder to /usr/local/bin or add it to your PATH.");
51
- console.log('4. Test by running "adb version" in Terminal.');
52
- } else if (platform === "linux") {
53
- console.log("\nLinux:");
54
- console.log("1. Download the SDK Platform Tools for Linux: https://developer.android.com/studio/releases/platform-tools");
55
- console.log("2. Extract the ZIP file.");
56
- console.log("3. Move the extracted folder to /usr/local/bin or add it to your PATH.");
57
- console.log("4. Or install via your package manager:");
58
- console.log(" - Ubuntu/Debian: sudo apt-get install android-tools-adb");
59
- console.log(" - Fedora/Red Hat: sudo dnf install android-tools");
60
- console.log(" - CentOS/yum: sudo yum install android-tools");
61
- console.log('5. Test by running "adb version" in your shell.');
73
+ // Run only when executed directly (npm postinstall), not when imported.
74
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
75
+ main();
62
76
  }
63
- console.log("\nYou must accept the ADB authorization prompt on your Android TV device the first time you connect.");
@@ -13,12 +13,24 @@
13
13
  *
14
14
  */
15
15
 
16
- import readline from "readline";
17
- import AndroidTVSetup from "../src/lib/adb/setup.mjs";
16
+ import readline from "node:readline";
17
+ import { realpathSync } from "node:fs";
18
+ import { fileURLToPath } from "node:url";
19
+ import createRemote from "../src/lib/android-tv-remote.mjs";
18
20
 
19
21
  /**
20
22
  * Interactive CLI for setting up a new Android TV device.
21
- * Prompts for IP and port, then runs setup.
23
+ * Prompts for IP and port, then applies the keep-awake settings, wakes the
24
+ * device and returns it to the home screen, using the v2 remote API.
25
+ *
26
+ * Usage: npm run setup-device
27
+ */
28
+
29
+ /**
30
+ * Ask a question on the terminal.
31
+ * @param {string} question - Prompt text.
32
+ * @param {string} [defaultValue] - Value used when the answer is empty.
33
+ * @returns {Promise<string>} The answer, or the default.
22
34
  */
23
35
  async function prompt(question, defaultValue) {
24
36
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
@@ -30,20 +42,48 @@ async function prompt(question, defaultValue) {
30
42
  });
31
43
  }
32
44
 
33
- async function main() {
45
+ /**
46
+ * Connect to a device and prepare it for remote control: apply the keep-awake
47
+ * settings, make sure it is awake, return to the home screen, then disconnect.
48
+ * @param {object} options - Setup options.
49
+ * @param {string} options.ip - Device IP address.
50
+ * @param {number} [options.port=5555] - ADB port.
51
+ * @param {boolean} [options.quiet=false] - Suppress progress logs.
52
+ * @param {Function} [options.create=createRemote] - Remote factory (injectable for tests).
53
+ * @param {Function} [options.log=console.log] - Log sink for progress and error events.
54
+ * @returns {Promise<void>} Resolves once setup is complete; rejects on failure.
55
+ */
56
+ export async function setupDevice({ ip, port = 5555, quiet = false, create = createRemote, log = console.log }) {
57
+ const remote = await create({ ip, port, quiet, autoConnect: false, maintainConnection: false });
58
+ remote.on("log", (data) => log(`[${data.level}] ${data.message}`));
59
+ remote.on("error", (data) => log(`[error] ${data.message}`));
60
+
61
+ const result = await remote.connect();
62
+ if (!remote.isConnected) {
63
+ throw result instanceof Error ? result : new Error(`Could not connect to ${ip}:${port}`);
64
+ }
65
+ try {
66
+ await remote.setSettings();
67
+ await remote.ensureAwake();
68
+ await remote.press.home();
69
+ } finally {
70
+ await remote.disconnect();
71
+ }
72
+ }
73
+
74
+ /**
75
+ * CLI entry: prompt for the device address and run the setup.
76
+ * @returns {Promise<void>}
77
+ */
78
+ export async function main() {
34
79
  const ip = await prompt("Enter device IP address");
35
80
  if (!ip) {
36
81
  console.error("IP address is required.");
37
82
  process.exit(1);
38
83
  }
39
84
  const port = parseInt(await prompt("Enter device port", "5555"), 10) || 5555;
40
- const quiet = false;
41
- const setup = new AndroidTVSetup({ ip, port, quiet });
42
85
  try {
43
- await setup.connect();
44
- await setup.setSettings();
45
- await setup.ensureAwake();
46
- await setup.disconnect();
86
+ await setupDevice({ ip, port });
47
87
  console.log("\nSetup complete!");
48
88
  } catch (err) {
49
89
  console.error("Error:", err.message || err);
@@ -51,4 +91,7 @@ async function main() {
51
91
  }
52
92
  }
53
93
 
54
- main();
94
+ // Run only when executed directly (`npm run setup-device`), not when imported.
95
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
96
+ await main();
97
+ }
@@ -18,36 +18,50 @@
18
18
  * Usage: node wake-tv.mjs <ip_address>
19
19
  */
20
20
 
21
+ import { realpathSync } from "node:fs";
22
+ import { fileURLToPath } from "node:url";
21
23
  import createRemote from "../src/lib/android-tv-remote.mjs";
22
24
 
23
- // Get IP address from command line arguments
24
- const ip = process.argv[2];
25
+ /**
26
+ * CLI entry: wake the device whose IP is given on the command line.
27
+ * @param {string[]} [argv=process.argv.slice(2)] - CLI arguments.
28
+ * @returns {Promise<void>}
29
+ */
30
+ export async function main(argv = process.argv.slice(2)) {
31
+ // Get IP address from command line arguments
32
+ const ip = argv[0];
25
33
 
26
- if (!ip) {
27
- console.error("❌ Usage: node wake-tv.mjs <ip_address>");
28
- console.error(" Example: node wake-tv.mjs 10.6.0.133");
29
- process.exit(1);
30
- }
34
+ if (!ip) {
35
+ console.error("❌ Usage: node wake-tv.mjs <ip_address>");
36
+ console.error(" Example: node wake-tv.mjs 10.6.0.133");
37
+ process.exit(1);
38
+ }
31
39
 
32
- console.log(`🔌 Waking up TV at ${ip}...`);
40
+ console.log(`🔌 Waking up TV at ${ip}...`);
33
41
 
34
- try {
35
- const remote = await createRemote({
36
- ip: ip,
37
- autoConnect: true,
38
- quiet: false
39
- });
42
+ try {
43
+ const remote = await createRemote({
44
+ ip: ip,
45
+ autoConnect: true,
46
+ quiet: false
47
+ });
40
48
 
41
- console.log("✅ Connected to device");
49
+ console.log("✅ Connected to device");
42
50
 
43
- // Wake up the device
44
- await remote.ensureAwake();
45
- console.log("🎉 TV should now be awake and ready!");
51
+ // Wake up the device
52
+ await remote.ensureAwake();
53
+ console.log("🎉 TV should now be awake and ready!");
54
+
55
+ // Disconnect
56
+ await remote.disconnect();
57
+ console.log("✅ Disconnected from device");
58
+ } catch (error) {
59
+ console.error("❌ Failed to wake up TV:", error.message);
60
+ process.exit(1);
61
+ }
62
+ }
46
63
 
47
- // Disconnect
48
- await remote.disconnect();
49
- console.log("✅ Disconnected from device");
50
- } catch (error) {
51
- console.error("❌ Failed to wake up TV:", error.message);
52
- process.exit(1);
64
+ // Run only when executed directly, not when imported.
65
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
66
+ await main();
53
67
  }
@@ -142,6 +142,7 @@
142
142
 
143
143
  import adbkit from "@devicefarmer/adbkit";
144
144
  import { EventEmitter } from "events";
145
+ import { debuglog } from "node:util";
145
146
  import { createWriteStream } from "fs";
146
147
  import sharp from "sharp";
147
148
  // @devicefarmer/adbkit is plain CJS (`exports.default` / `exports.Adb` both
@@ -170,114 +171,141 @@ function wrapAsync(fn) {
170
171
  };
171
172
  }
172
173
 
173
- // Create event emitter for this instance
174
- const emitter = new EventEmitter();
175
-
176
174
  /**
177
- * Emit a log event with structured data.
175
+ * Debug channel for errors no "error" listener is attached to.
176
+ * Enable with NODE_DEBUG=android-tv-remote.
178
177
  * @private
179
- * @param {string} level - Log level (info, warn, error, debug).
180
- * @param {string} message - Log message.
181
- * @param {string} [source] - Source of the log message.
182
- * @param {any} [data] - Additional data to include.
183
178
  */
184
- function emitLog(level, message, source = "android-tv-remote", data = null) {
185
- emitter.emit("log", {
186
- level,
187
- message,
188
- source,
189
- timestamp: new Date().toISOString(),
190
- ...(data && { data })
191
- });
192
- }
179
+ const debug = debuglog("android-tv-remote");
193
180
 
194
181
  /**
195
- * Emit an error event with structured data.
182
+ * Create the event channel for one remote instance. Every remote gets its own
183
+ * EventEmitter, so listeners on one remote never see another remote's events.
196
184
  * @private
197
- * @param {Error} error - The error object.
198
- * @param {string} [source] - Source of the error.
199
- * @param {string} [message] - Additional error message.
185
+ * @returns {{ emitter: EventEmitter, emitLog: Function, emitError: Function, handleDisconnectError: Function }}
200
186
  */
201
- function emitError(error, source = "android-tv-remote", message = null) {
202
- // Filter out libspng/PNG processing errors that occur after disconnection
203
- // These are common when background operations try to process data after disconnect
204
- const errorMsg = error.message || "";
205
- if (errorMsg.includes("libspng") || errorMsg.includes("pngload_buffer") || errorMsg.includes("read error")) {
206
- // Log as debug instead of error to avoid noise
207
- emitLog("debug", `PNG processing error (likely post-disconnect): ${errorMsg}`, source);
208
- return;
209
- }
187
+ function createEventChannel() {
188
+ const emitter = new EventEmitter();
210
189
 
211
- emitter.emit("error", {
212
- error,
213
- source,
214
- message: message || error.message,
215
- timestamp: new Date().toISOString()
216
- });
217
- }
190
+ /**
191
+ * Emit a log event with structured data.
192
+ * @private
193
+ * @param {string} level - Log level (info, warn, error, debug).
194
+ * @param {string} message - Log message.
195
+ * @param {string} [source] - Source of the log message.
196
+ * @param {any} [data] - Additional data to include.
197
+ */
198
+ function emitLog(level, message, source = "android-tv-remote", data = null) {
199
+ emitter.emit("log", {
200
+ level,
201
+ message,
202
+ source,
203
+ timestamp: new Date().toISOString(),
204
+ ...(data && { data })
205
+ });
206
+ }
218
207
 
219
- /**
220
- * Handles disconnect and connection errors, emits helpful messages.
221
- * Also provides onboarding steps for common authentication and connection issues.
222
- * @private
223
- * @param {Error} err - The error object.
224
- * @example
225
- * try {
226
- * // ...code that may throw
227
- * } catch (err) {
228
- * handleDisconnectError(err);
229
- * }
230
- */
208
+ /**
209
+ * Emit an error event with structured data.
210
+ * @private
211
+ * @param {Error} error - The error object.
212
+ * @param {string} [source] - Source of the error.
213
+ * @param {string} [message] - Additional error message.
214
+ */
215
+ function emitError(error, source = "android-tv-remote", message = null) {
216
+ // Filter out libspng/PNG processing errors that occur after disconnection
217
+ // These are common when background operations try to process data after disconnect
218
+ const errorMsg = error.message || "";
219
+ if (errorMsg.includes("libspng") || errorMsg.includes("pngload_buffer") || errorMsg.includes("read error")) {
220
+ // Log as debug instead of error to avoid noise
221
+ emitLog("debug", `PNG processing error (likely post-disconnect): ${errorMsg}`, source);
222
+ return;
223
+ }
231
224
 
232
- function handleDisconnectError(err) {
233
- emitError(err, "handleDisconnectError");
234
-
235
- if (err.message && (err.message.includes("device unauthorized") || err.message.includes("failed to authenticate"))) {
236
- emitError(err, "handleDisconnectError", "Device unauthorized - authentication required");
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
- );
225
+ const payload = {
226
+ error,
227
+ source,
228
+ message: message || error.message,
229
+ timestamp: new Date().toISOString()
230
+ };
231
+
232
+ // EventEmitter throws when "error" is emitted with no listener, which would crash
233
+ // the consumer's process. Without a listener, route the error to the log channel
234
+ // (and NODE_DEBUG=android-tv-remote) instead; the failing operation still rejects
235
+ // or resolves with the error, so it is never silently lost.
236
+ if (emitter.listenerCount("error") > 0) {
237
+ emitter.emit("error", payload);
238
+ return;
239
+ }
240
+ debug("unhandled error from %s: %s", source, payload.message);
241
+ emitLog("error", payload.message, source, { error });
257
242
  }
258
243
 
259
- if (err.message && (err.message.includes("actively refused") || err.message.includes("No connection could be made"))) {
260
- emitError(err, "handleDisconnectError", "Connection refused - ADB not enabled");
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
- );
266
- emitLog("info", "1. Open Settings > Device Preferences > About (or My Fire TV > About)", "handleDisconnectError");
267
- emitLog("info", "2. Scroll to 'Build' and press OK 7 times to enable Developer Options", "handleDisconnectError");
268
- emitLog("info", "3. Go back to Settings > Device Preferences > Developer Options", "handleDisconnectError");
269
- emitLog(
270
- "info",
271
- "4. Enable 'Developer Options' if needed, then enable 'ADB Debugging' and 'Apps from Unknown Sources'",
272
- "handleDisconnectError"
273
- );
274
- emitLog("info", "5. Ensure your TV and computer are on the same network", "handleDisconnectError");
275
- emitLog("info", "6. On your computer, run: adb connect <device-ip>:5555", "handleDisconnectError");
276
- emitLog("info", "7. Accept the authorization prompt on your TV", "handleDisconnectError");
277
- emitLog("info", "If you do not see 'Developer Options', repeat step 2 until it appears.", "handleDisconnectError");
244
+ /**
245
+ * Handles disconnect and connection errors, emits helpful messages.
246
+ * Also provides onboarding steps for common authentication and connection issues.
247
+ * @private
248
+ * @param {Error} err - The error object.
249
+ * @example
250
+ * try {
251
+ * // ...code that may throw
252
+ * } catch (err) {
253
+ * handleDisconnectError(err);
254
+ * }
255
+ */
256
+
257
+ function handleDisconnectError(err) {
258
+ emitError(err, "handleDisconnectError");
259
+
260
+ if (err.message && (err.message.includes("device unauthorized") || err.message.includes("failed to authenticate"))) {
261
+ emitError(err, "handleDisconnectError", "Device unauthorized - authentication required");
262
+ emitLog(
263
+ "error",
264
+ "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.",
265
+ "handleDisconnectError"
266
+ );
267
+ emitLog(
268
+ "info",
269
+ "If you do not see a prompt, try disconnecting and reconnecting the device, or reboot your TV.",
270
+ "handleDisconnectError"
271
+ );
272
+ emitLog(
273
+ "info",
274
+ "If the problem persists, remove the device from the list of authorized ADB devices in Developer Options and try again.",
275
+ "handleDisconnectError"
276
+ );
277
+ emitLog(
278
+ "info",
279
+ "Tip: In Developer Options on your TV, try toggling 'ADB Debugging' off and then back on. This often resolves authentication issues.",
280
+ "handleDisconnectError"
281
+ );
282
+ }
283
+
284
+ if (err.message && (err.message.includes("actively refused") || err.message.includes("No connection could be made"))) {
285
+ emitError(err, "handleDisconnectError", "Connection refused - ADB not enabled");
286
+ emitLog(
287
+ "error",
288
+ "The device refused the connection. To enable ADB, follow these steps on your Android TV or Fire TV:",
289
+ "handleDisconnectError"
290
+ );
291
+ emitLog("info", "1. Open Settings > Device Preferences > About (or My Fire TV > About)", "handleDisconnectError");
292
+ emitLog("info", "2. Scroll to 'Build' and press OK 7 times to enable Developer Options", "handleDisconnectError");
293
+ emitLog("info", "3. Go back to Settings > Device Preferences > Developer Options", "handleDisconnectError");
294
+ emitLog(
295
+ "info",
296
+ "4. Enable 'Developer Options' if needed, then enable 'ADB Debugging' and 'Apps from Unknown Sources'",
297
+ "handleDisconnectError"
298
+ );
299
+ emitLog("info", "5. Ensure your TV and computer are on the same network", "handleDisconnectError");
300
+ emitLog("info", "6. On your computer, run: adb connect <device-ip>:5555", "handleDisconnectError");
301
+ emitLog("info", "7. Accept the authorization prompt on your TV", "handleDisconnectError");
302
+ emitLog("info", "If you do not see 'Developer Options', repeat step 2 until it appears.", "handleDisconnectError");
303
+ }
304
+
305
+ return err;
278
306
  }
279
307
 
280
- return err;
308
+ return { emitter, emitLog, emitError, handleDisconnectError };
281
309
  }
282
310
 
283
311
  /**
@@ -358,6 +386,8 @@ export default async function createRemote(config) {
358
386
  timeout: connectTimeout
359
387
  });
360
388
  const device = client.getDevice(host);
389
+ // Per-instance event channel: listeners are scoped to this remote.
390
+ const { emitter, emitLog, emitError, handleDisconnectError } = createEventChannel();
361
391
  let connected = false;
362
392
  let backgroundOperations = new Set();
363
393
 
@@ -454,6 +484,9 @@ export default async function createRemote(config) {
454
484
  }, INIT_TIMEOUT_MS);
455
485
  })
456
486
  ]);
487
+ // Callers who never look at initPromise must not get an unhandled rejection (which
488
+ // crashes Node.js) when auto-connect fails; awaiting it still rejects as before.
489
+ initPromise.catch(() => {});
457
490
 
458
491
  /**
459
492
  * Resets the disconnect timer if autoDisconnect is enabled.