Repository navigation
feat!: native promises, package exports, ESLint 10 and Node 22 - #567
Conversation
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--
left a comment
There was a problem hiding this comment.
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.
| }); | ||
| }) | ||
| .catch(warnUnhandled); | ||
| transfer.on('cancel', () => { |
There was a problem hiding this comment.
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.
| */ | ||
| end(): JdwpTracker { | ||
| this.reader.cancel(); | ||
| if (this.reading) { |
There was a problem hiding this comment.
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.
| this.connection.end(); | ||
| return; | ||
| } | ||
| transfer.emit('error', err); |
There was a problem hiding this comment.
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.
| this.end(); | ||
| return false; | ||
| } | ||
| this._error(err); |
There was a problem hiding this comment.
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.
| if (signal.aborted) { | ||
| return Promise.reject(signal.reason); | ||
| } | ||
| return connect().then((conn) => { |
There was a problem hiding this comment.
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.
| }, | ||
| "engines": { | ||
| "node": ">= 0.10.4" | ||
| "node": ">= 22" |
There was a problem hiding this comment.
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.
| * (trackers, sync transfers, timeouts). It doesn't touch the stream; end | ||
| * or destroy it separately. `end()` keeps working after a cancel. | ||
| */ | ||
| public cancel(): void { |
There was a problem hiding this comment.
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.
| readable: () => { | ||
| let chunk; | ||
| while ((chunk = this.stream.read())) { | ||
| all = Buffer.concat([all, chunk]); |
There was a problem hiding this comment.
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.
| } | ||
| // 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) => { |
There was a problem hiding this comment.
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).
- 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]>
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:
fix(sync):Statsno longer calls the deprecatedfs.Statsconstructor (DEP0180).instanceof fs.Stats,isFile(),isDirectory()andmtimestill work.chore!: ESLint 10 flat config, TypeScript ~6.0.3, mocha 12, chai 6, sinon 22,engines>= 22,npm ciand Dependabot. ts-node and rimraf are removed. adbkit keeps its own Prettier style (semicolons, width 120). Tests are ESM.mtsand run against the compileddist/(pretestcompiles).feat!: native promises instead of bluebird. Each bluebird feature has a native replacement. Callbacks keep working where the API accepted them.feat!: anexportsmap. It covers the root, the internals stf imports (adb/parser,adb/sync/pushtransfer,adb/tcpusb/server, under both short anddist/src/...jspaths) andpackage.json.chore(deps): commander 15 (ESM-only, loaded with a dynamicimport()in the CLI) and node-forge 1.4. The CLI output matches 3.3.9.Breaking changes
.timeout,.delay,.return,.cancel,.catch(Class, fn)and so on) are gone.AbortSignaland cancel only that read, so a cancelled transfer or timeout never affects the next operation on the same connection.Parser.cancel()andParser.CancellationErrorremain for tearing down a whole connection (trackers).tracker.end()andjdwpTracker.end(); the latter now really ends its connection.pushTransfer.cancel()andpullTransfer.cancel()end the sync connection.signaloption onwaitBootComplete()andwaitForDevice().exportsmap no longer resolve.The README has a "version 4.x" section and examples without bluebird.
Testing
npm run lintandtscare clean.signaloption andexportsresolution. The cancel, monkey, jdwp and push tests were mutation-checked: each fails when the behaviour it covers is broken.Existing bugs fixed along the way:
JdwpTrackernow 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:
'drain'branch never runs, becauseConnection.write()always returnsthis.🤖 Generated with Claude Code