Skip to content

feat!: native promises, package exports, ESLint 10 and Node 22 - #567

Merged
koral-- merged 8 commits into
masterfrom
feat/native-promises
Oct 24, 2026
Merged

koral-- merged 8 commits into
masterfrom
feat/native-promises

Conversation

@koral--

@koral-- koral-- commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

This is adbkit 4.0. It moves to the toolchain used in adbkit-logcat #325 and drops bluebird. Five commits, best reviewed one at a time:

  1. fix(sync): Stats no longer calls the deprecated fs.Stats constructor (DEP0180). instanceof fs.Stats, isFile(), isDirectory() and mtime still work.
  2. chore!: ESLint 10 flat config, TypeScript ~6.0.3, mocha 12, chai 6, sinon 22, engines >= 22, npm ci and Dependabot. ts-node and rimraf are removed. adbkit keeps its own Prettier style (semicolons, width 120). Tests are ESM .mts and run against the compiled dist/ (pretest compiles).
  3. feat!: native promises instead of bluebird. Each bluebird feature has a native replacement. Callbacks keep working where the API accepted them.
  4. feat!: an exports map. It covers the root, the internals stf imports (adb/parser, adb/sync/pushtransfer, adb/tcpusb/server, under both short and dist/src/...js paths) and package.json.
  5. chore(deps): commander 15 (ESM-only, loaded with a dynamic import() in the CLI) and node-forge 1.4. The CLI output matches 3.3.9.

Breaking changes

  • Every method returns a native Promise, so bluebird-only methods (.timeout, .delay, .return, .cancel, .catch(Class, fn) and so on) are gone.
  • Cancellation is explicit now:
    • Parser reads take an optional AbortSignal and cancel only that read, so a cancelled transfer or timeout never affects the next operation on the same connection. Parser.cancel() and Parser.CancellationError remain for tearing down a whole connection (trackers).
    • tracker.end() and jdwpTracker.end(); the latter now really ends its connection.
    • pushTransfer.cancel() and pullTransfer.cancel() end the sync connection.
    • New signal option on waitBootComplete() and waitForDevice().
  • Deep imports outside the exports map no longer resolve.
  • Node.js 22.12 or later is required (commander 15).
  • Promise chains nobody awaits (tracker loops, sync transfers, ProcStat) now end in a handler that prints a process warning instead of crashing, matching bluebird's warning-only behaviour.

The README has a "version 4.x" section and examples without bluebird.

Testing

  • npm run lint and tsc are clean.
  • Tests: 255 passing, 13 pending (the device tests). master had 213 passing, 13 pending.
  • 32 new tests cover parser cancel, the monkey timeout, tracker end between reads, sync push and pull including cancel, JdwpTracker, the promise helpers, ProcStat, the signal option and exports resolution. The cancel, monkey, jdwp and push tests were mutation-checked: each fails when the behaviour it covers is broken.
  • It also compiles and passes the tests with the upcoming adbkit-monkey (TypeError: v is not a function\n #92) and adbkit-logcat (Bump @typescript-eslint/eslint-plugin from 4.33.0 to 5.31.0 #325) majors installed. The ranges stay at the current majors until those are released.
  • stf needs a migration for this release (about 48 type errors from bluebird-only calls). That migration and an emulator end-to-end run come in a separate stf PR before stf picks up 4.0.

Existing bugs fixed along the way: JdwpTracker now keeps reading pid lists instead of stopping after the first, and no longer reports surviving pids as removed. Cleanup runs before 'error' is emitted, so a missing listener no longer leaks the connection.

One existing bug is left as it was:

  • The sync 'drain' branch never runs, because Connection.write() always returns this.

🤖 Generated with Claude Code

koral-- and others added 5 commits October 24, 2026 19:45
Node 22 warns with DEP0180 whenever `new fs.Stats()` runs, which Stats did
through `super()` on every stat, sta2 and readdir entry, and @types/node 22
marks the constructor private.

Stats no longer extends fs.Stats; its prototype chains to
fs.Stats.prototype instead, so `instanceof fs.Stats`, isFile(),
isDirectory() and the lazy mtime getter keep working, and it sets the same
own properties the constructor used to.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Karol Wrótniak <[email protected]>
- ESLint flat config with typescript-eslint 8; Prettier runs on its own
  instead of as an ESLint plugin, and the tests are linted too (the old
  .eslintignore skipped them). Fix what the new recommended rules flag.
- TypeScript 6 with module node20, targeting ES2023. The emitted
  declarations and the published files are unchanged.
- Tests converted to ESM .mts run by Node's type stripping, with mocha 12,
  chai 6, sinon 22 and sinon-chai 4. They import the compiled dist/, so
  `npm test` compiles first. ts-node and rimraf are gone.
- Drop the unused tsconfig-dist.json, compile2 and testJS.
- Regenerate the lockfile for the new dev dependencies.
- Weekly grouped Dependabot updates; hold TypeScript 7 until
  typescript-eslint supports it.

BREAKING CHANGE: requires Node.js 22 or newer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Karol Wrótniak <[email protected]>
Every public method now returns a native Promise.

Bluebird features replaced:
- .finally() and Promise.resolve/reject: the native ones.
- Filtered .catch(ErrorClass, fn) and .catch(predicate, fn): instanceof or
  predicate checks that rethrow anything else.
- .return(x): .then(() => x).
- .nodeify(callback): a nodeify() helper that returns the same promise and
  rethrows a throwing callback on the next tick. sync.stat(), sync.sta2(),
  sync.readdir(), util.readAll() and util.parsePublicKey() keep their
  callbacks.
- Promise.try: new Promise(resolve => resolve(fn())), which also runs fn
  synchronously; the tcpusb packet order depends on that.
- Promise.delay: timers/promises setTimeout.
- Promise.promisify(crypto.randomBytes): the callback form wrapped in a
  Promise.
- Promise.defer(): plain Promise executors in the sync writer.
- .timeout(1000) and TimeoutError in the monkey command: a timer that
  cancels the parser, so the search stops consuming the monkey's output.
- Cancellation (.cancel(), onCancel, CancellationError,
  Bluebird.config({ cancellation })): Parser.cancel(), which rejects the
  pending and every later read with Parser.CancellationError. It is
  sticky, so a cancel that lands between two reads still stops a loop.
  tracker.end(), jdwpTracker.end(), pushTransfer.cancel() and
  pullTransfer.cancel() use it.
- waitBootComplete() and waitForDevice() take { signal }: on abort they
  close the connection and reject with signal.reason, which replaces
  calling .timeout() or .cancel() on their promises.

Chains nobody awaits (tracker loops, sync transfers, ProcStat's timer,
tcpusb packet handling) end in a handler that turns a stray rejection
into a process warning, as bluebird did, instead of crashing the
process.

openMonkey() is typed as adbkit-monkey's connectStream() return type,
`any` with adbkit-monkey 1.x, so the typed monkey slots in without code
changes. SocketOptions.auth may return any PromiseLike.

BREAKING CHANGE: methods return native Promises, so bluebird-only methods
(.timeout(), .delay(), .return(), .tap(), .spread(), .cancel() ...) are
gone. jdwpTracker.end() now ends the connection and emits 'end', and
cancelling a push or pull transfer ends the sync connection as documented;
a cancelled pull transfer also ends.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Karol Wrótniak <[email protected]>
stf deep-imports Parser, PushTransfer and the TCP-USB bridge Server.
Export them under short subpaths (adb/parser, adb/sync/pushtransfer,
adb/tcpusb/server, as asked in #91) and, so that existing imports keep
working, under the dist/src/... paths stf uses today. Each entry lists its
declarations first, so the subpaths are typed under node16/nodenext
resolution.

BREAKING CHANGE: other internal modules can no longer be imported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Karol Wrótniak <[email protected]>
commander 15 is ESM-only, so the CLI loads it with a dynamic import,
which works on every Node.js 22 (require() of an ES module needs 22.12),
and parses with parseAsync() so a failing action exits with an error.

The @ts-ignore comments around node-forge's BigInteger are no longer
needed with the current @types/node-forge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Karol Wrótniak <[email protected]>

@koral-- koral-- left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review notes (npm test: 245 passing, 13 pending). I reproduced the first two inline findings (push cancel after completion, JdwpTracker.end() from a listener) against the built dist/.

Not in the diff, but related: JdwpTracker.read() (src/adb/jdwptracker.ts:83) reads a single pid list and never re-arms. Later lists from adb are never read, so add/remove/changeSet fire only for the first snapshot, and a closed connection is never noticed. This predates the PR, but the new reading/end() logic and the test should end the connection and emit end once a read has completed rely on this one-shot behaviour, so it may be worth fixing (or at least deciding on) here.

Comment thread src/adb/sync.ts Outdated
});
})
.catch(warnUnhandled);
transfer.on('cancel', () => {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: a cancel after a push finishes poisons the whole Sync. This 'cancel' listener is never removed, and Parser.cancel() stays set for the parser, which every operation on the Sync shares.

Repro: push completes and emits 'end', then the caller calls transfer.cancel() (for example, a timeout racing completion). stopWriter does nothing because the writer already resolved, but conn.parser.isCancelled() is now true. A second sync.push() on the same Sync then emits 'end' with no 'error' although the device never replied, because readReply treats CancellationError as success. Later pulls end empty, and stat/readdir reject with Parser was cancelled. On master, cancel() on a settled bluebird promise did nothing.

Suggest removing the listener when the transfer ends (like _readData does in readEnd), or keeping a cancelled flag per transfer.

Comment thread src/adb/jdwptracker.ts Outdated
*/
end(): JdwpTracker {
this.reader.cancel();
if (this.reading) {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: end() does nothing when called from a 'changeSet'/'add'/'remove' listener. Those events are emitted synchronously from inside the read's .then, so reading is still true but no read is pending. cancel() only sets the flag, and the one-shot read resolves normally.

Repro: tracker.on('changeSet', () => tracker.end()), then write one pid list. connection.end() is called 0 times, 'end' is emitted 0 times, and the socket stays open. The new test wraps the call in setImmediate, which avoids this path.

Comment thread src/adb/sync.ts
this.connection.end();
return;
}
transfer.emit('error', err);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error emitted before cleanup. If the transfer has no 'error' listener, emit('error') throws, so this.parser.cancel() (266) never runs. The same applies to stopWriter() after the emit at 274. The .catch(warnUnhandled) then turns the throw into a warning.

Example: pushFile() of a missing local file with no 'error' listener. The writer rejects with ENOENT, the parser is never cancelled, and readReply waits forever for OKAY/FAIL. 'end' never fires, and DeviceClient.push's sync.end() never runs, so the connection leaks. Doing the cleanup before the emit fixes it. The same ordering exists in master, but this is a good moment to fix it.

Comment thread src/adb/tcpusb/socket.ts
this.end();
return false;
}
this._error(err);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same ordering issue as in sync.ts: _error() (line 115) emits 'error' before this.end(). With no listener the emit throws, end() is skipped, and the warnUnhandled catch below hides it. The bridge socket and its services stay open. Calling end() first in _error() would fix it.

Comment thread src/adb/DeviceClient.ts Outdated
if (signal.aborted) {
return Promise.reject(signal.reason);
}
return connect().then((conn) => {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

abortable() doesn't race the signal against the operation. An abort during connect() (for example, while it spawns adb start-server) is only seen once connect settles. For waitBootComplete, the rejection also waits for parser.end() in searchLine's .finally, so it blocks until the remote side closes the socket. A stalled socket means the promise never rejects with signal.reason, even though the docs present this as the replacement for bluebird's .timeout(), which rejected immediately.

Consider racing an abort listener (or Promise.race with a rejection on the signal) and ending the connection in the background.

Comment thread package.json Outdated
},
"engines": {
"node": ">= 0.10.4"
"node": ">= 22"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

commander@^15 declares engines.node: >=22.12.0 (npm view commander@15 engines). Node 22.0–22.11 passes this check but gets EBADENGINE for commander (or a hard failure with engine-strict). Either use >= 22.12 here or pin a commander version that supports 22.0.

Comment thread src/adb/parser.ts
* (trackers, sync transfers, timeouts). It doesn't touch the stream; end
* or destroy it separately. `end()` keeps working after a cancel.
*/
public cancel(): void {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Design note: per-operation cancellation (push/pull cancel, the 1 s timeout in monkey.ts, abortable) is built on a sticky cancel flag for the whole connection, and callers treat CancellationError as a normal finish. A caller can't tell "my read was cancelled" from "someone cancelled this connection earlier". This is the root cause of the sync.ts:281 and JdwpTracker.end() issues. Per-read cancellation (an AbortSignal passed to _read, or a token per operation) would keep a cancel from poisoning the shared Sync or transport parser. This is probably a follow-up rather than a blocker.

Comment thread src/adb/parser.ts Outdated
readable: () => {
let chunk;
while ((chunk = this.stream.read())) {
all = Buffer.concat([all, chunk]);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Buffer.concat([all, chunk]) on every chunk copies the growing buffer each time, so the total copying grows with the square of the output size (for example, several MB of logcat/dumpsys in 64 KiB chunks). Collecting the chunks in an array and calling Buffer.concat(chunks) once on end fixes it.

Comment thread src/adb/tcpusb/socket.ts Outdated
}
// Runs the handler synchronously, like bluebird's Promise.try did; the
// order of the window, ack and open handling depends on it.
return new Promise<boolean>((resolve) => {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the hand-written Promise.try (new Promise((resolve) => resolve(fn()))) appears three times (here, line 232, and service.ts:76), each with its own ordering comment. A single promiseTry helper in the new src/adb/promise.ts would keep this in one place, ready to switch to native Promise.try later. _createToken could also use util.promisify(crypto.randomBytes).

koral-- and others added 3 commits October 25, 2026 00:42
- Cancellation is per operation. Parser reads take an optional
  AbortSignal that cancels just that read and rejects with signal.reason,
  so the caller can tell its own cancel apart. Push and pull transfers,
  the monkey command's 1 s timeout and the transfer readers use it.
  Parser.cancel() is left for tearing a whole connection down (the
  trackers, and abortable() for the connection it owns). A transfer
  removes its 'cancel' listener when it ends, so a late cancel() no
  longer poisons the shared Sync.
- JdwpTracker reads in a loop until end() or the connection closes, and
  emits 'end' (after 'error' for failures) when it stops. end() works
  when called from a 'changeSet', 'add' or 'remove' listener. update()
  now keeps every current pid in its map, so surviving pids are no longer
  reported as removed by the next list.
- Parser notices a stream that ended between two reads.
- Sync transfers and the tcpusb socket and service clean up before
  emitting 'error', so a missing listener no longer leaves a transfer or
  bridge connection hanging.
- abortable() races the signal: an abort rejects with signal.reason at
  once, also while connecting or on a stalled socket, and the connection
  is torn down in the background.
- engines.node >= 22.12, as commander 15 requires.
- Parser.readAll() concatenates once instead of per chunk.
- A single promiseTry() helper replaces the three hand-written copies;
  _createToken() uses util.promisify(crypto.randomBytes).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Karol Wrótniak <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Karol Wrótniak <[email protected]>
Master only bumped mocha to 12, which this branch already has, so
package.json and package-lock.json keep the branch's versions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Karol Wrótniak <[email protected]>
@koral--
koral-- merged commit b33b317 into master Oct 24, 2026
6 checks passed
@koral--
koral-- deleted the feat/native-promises branch October 24, 2026 23:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant