@lynx-js/devtool-connector 0.13.2 → 0.16.2

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.
Files changed (75) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +18 -134
  3. package/dist/2.js +2019 -0
  4. package/dist/{346.js → a.js} +102 -143
  5. package/dist/client-id.d.ts +0 -6
  6. package/dist/command/client.d.ts +8 -7
  7. package/dist/command/contract.d.ts +82 -24
  8. package/dist/command/core.d.ts +11 -10
  9. package/dist/command/in-process-client.d.ts +16 -0
  10. package/dist/command/index.d.ts +28 -20
  11. package/dist/command/index.js +177 -159
  12. package/dist/command/list-clients.d.ts +6 -0
  13. package/dist/command/list-sessions.d.ts +5 -0
  14. package/dist/command/open.d.ts +5 -0
  15. package/dist/command/query.d.ts +1 -1
  16. package/dist/command/reactlynx/controller.d.ts +3 -3
  17. package/dist/command/reactlynx/model.d.ts +7 -7
  18. package/dist/command/reactlynx/protocol.d.ts +0 -1
  19. package/dist/command/reactlynx/session.d.ts +3 -3
  20. package/dist/command/reactlynx/types.d.ts +7 -7
  21. package/dist/command/ref-actions.d.ts +4 -4
  22. package/dist/command/result.d.ts +0 -1
  23. package/dist/command/screenshot-annotation.d.ts +2 -2
  24. package/dist/command/screenshot.d.ts +2 -2
  25. package/dist/command/snapshot.d.ts +2 -2
  26. package/dist/command/source-info.d.ts +20 -0
  27. package/dist/command/targets.d.ts +8 -10
  28. package/dist/command/timeout.d.ts +3 -0
  29. package/dist/command/wait-for-client.d.ts +5 -0
  30. package/dist/daemon/device-connection.d.ts +4 -3
  31. package/dist/daemon/entry.js +18 -20
  32. package/dist/daemon/index.d.ts +7 -2
  33. package/dist/daemon/index.js +7 -3
  34. package/dist/daemon/inspector-assets.d.ts +11 -0
  35. package/dist/daemon/manager.d.ts +12 -4
  36. package/dist/daemon/protocol.d.ts +20 -16
  37. package/dist/daemon/server.d.ts +7 -1
  38. package/dist/daemon/static-server.d.ts +3 -1
  39. package/dist/f.js +5790 -0
  40. package/dist/f1.js +737 -0
  41. package/dist/{962.js → h.js} +841 -3259
  42. package/dist/{712.js → hb.js} +26 -19
  43. package/dist/i.js +2505 -0
  44. package/dist/index.d.ts +13 -18
  45. package/dist/index.js +3 -2
  46. package/dist/main.d.ts +2 -0
  47. package/dist/main.js +3 -0
  48. package/dist/request-id.d.ts +1 -0
  49. package/dist/streams/cdp.d.ts +3 -3
  50. package/dist/streams/customized.d.ts +5 -5
  51. package/dist/streams/index.d.ts +4 -3
  52. package/dist/streams/index.js +1 -1
  53. package/dist/streams/utils.d.ts +3 -3
  54. package/dist/{872.js → t.js} +364 -301
  55. package/dist/transport/adb-shell-types.d.ts +14 -0
  56. package/dist/transport/android-app-icon-helper.d.ts +1 -0
  57. package/dist/transport/android.d.ts +13 -3
  58. package/dist/transport/base.d.ts +2 -9
  59. package/dist/transport/daemon.d.ts +3 -2
  60. package/dist/transport/desktop.d.ts +1 -1
  61. package/dist/transport/hdt.d.ts +13 -0
  62. package/dist/transport/index.d.ts +9 -9
  63. package/dist/transport/index.js +2 -3
  64. package/dist/transport/ios.d.ts +2 -2
  65. package/dist/transport/peertalk.d.ts +4 -3
  66. package/dist/transport/stream-lifecycle.d.ts +4 -0
  67. package/dist/transport/transport.d.ts +4 -8
  68. package/dist/transport/usbmux.d.ts +5 -5
  69. package/dist/transport/ws-stream.d.ts +3 -10
  70. package/dist/types.d.ts +28 -24
  71. package/dist/{63.js → ws-stream.js} +23 -24
  72. package/package.json +32 -22
  73. package/dist/390.js +0 -329
  74. package/dist/556.js +0 -258
  75. package/dist/61.js +0 -3432
@@ -1,14 +1,14 @@
1
- import { Server, Socket } from "net";
2
- import { createDebug } from "obug";
1
+ import { AdbServerClient } from "@yume-chan/adb";
2
+ import node_net, { Server, Socket } from "node:net";
3
+ import node_os, { platform } from "node:os";
4
+ import { TransformStream as web_TransformStream, WritableStream as web_WritableStream } from "node:stream/web";
3
5
  import promises from "node:fs/promises";
4
- import node_os from "node:os";
5
6
  import node_path from "node:path";
6
- import { TransformStream as web_TransformStream } from "node:stream/web";
7
- import node_net from "node:net";
8
7
  import { Duplex } from "node:stream";
9
8
  import { on, once } from "node:events";
10
9
  import { __webpack_require__ } from "./rslib-runtime.js";
11
- import * as __rspack_external_node_net_0373943e from "node:net";
10
+ import { ansi_createDebug } from "./2.js";
11
+ import * as __rspack_external_node_net_5ed819e1 from "node:net";
12
12
  __webpack_require__.add({
13
13
  "../../../node_modules/.pnpm/@xmldom+xmldom@0.9.10/node_modules/@xmldom/xmldom/lib/conventions.js" (__unused_rspack_module, exports) {
14
14
  function find(list, predicate, ac) {
@@ -160,7 +160,7 @@ __webpack_require__.add({
160
160
  this.domHandler = options.domHandler || DOMHandler;
161
161
  this.onError = options.onError || options.errorHandler;
162
162
  if (options.errorHandler && 'function' != typeof options.errorHandler) throw new TypeError('errorHandler object is no longer supported, switch to onError!');
163
- if (options.errorHandler) options.errorHandler('warning', 'The `errorHandler` option has been deprecated, use `onError` instead!', this);
163
+ else if (options.errorHandler) options.errorHandler('warning', 'The `errorHandler` option has been deprecated, use `onError` instead!', this);
164
164
  this.normalizeLineEndings = options.normalizeLineEndings || normalizeLineEndings;
165
165
  this.locator = !!options.locator;
166
166
  this.xmlns = this.assign(Object.create(null), options.xmlns);
@@ -302,8 +302,10 @@ __webpack_require__.add({
302
302
  }
303
303
  function _toString(chars, start, length) {
304
304
  if ('string' == typeof chars) return chars.substr(start, length);
305
- if (chars.length >= start + length || start) return new java.lang.String(chars, start, length) + '';
306
- return chars;
305
+ else {
306
+ if (chars.length >= start + length || start) return new java.lang.String(chars, start, length) + '';
307
+ return chars;
308
+ }
307
309
  }
308
310
  'endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl'.replace(/\w+/g, function(key) {
309
311
  DOMHandler.prototype[key] = function() {
@@ -478,7 +480,7 @@ __webpack_require__.add({
478
480
  value: me[index++],
479
481
  done: false
480
482
  };
481
- return {
483
+ else return {
482
484
  done: true
483
485
  };
484
486
  },
@@ -603,7 +605,7 @@ __webpack_require__.add({
603
605
  value: me[index++],
604
606
  done: false
605
607
  };
606
- return {
608
+ else return {
607
609
  done: true
608
610
  };
609
611
  },
@@ -1515,7 +1517,7 @@ __webpack_require__.add({
1515
1517
  if (nodeFilter) {
1516
1518
  n = nodeFilter(n);
1517
1519
  if (!n) return null;
1518
- if ('string' == typeof n) {
1520
+ else if ('string' == typeof n) {
1519
1521
  buf.push(n);
1520
1522
  return null;
1521
1523
  }
@@ -4300,9 +4302,11 @@ __webpack_require__.add({
4300
4302
  if (source.indexOf(g.UNICODE_REPLACEMENT_CHARACTER) >= 0) errorHandler.warning('Unicode replacement character detected, source encoding issues?');
4301
4303
  function fixedFromCharCode(code) {
4302
4304
  if (!(code > 0xffff)) return String.fromCharCode(code);
4303
- code -= 0x10000;
4304
- var surrogate1 = 0xd800 + (code >> 10), surrogate2 = 0xdc00 + (0x3ff & code);
4305
- return String.fromCharCode(surrogate1, surrogate2);
4305
+ else {
4306
+ code -= 0x10000;
4307
+ var surrogate1 = 0xd800 + (code >> 10), surrogate2 = 0xdc00 + (0x3ff & code);
4308
+ return String.fromCharCode(surrogate1, surrogate2);
4309
+ }
4306
4310
  }
4307
4311
  function entityReplacer(a) {
4308
4312
  var complete = ';' === a[a.length - 1] ? a : a + ';';
@@ -4317,9 +4321,11 @@ __webpack_require__.add({
4317
4321
  }
4318
4322
  var k = complete.slice(1, -1);
4319
4323
  if (hasOwn(entityMap, k)) return entityMap[k];
4320
- if ('#' === k.charAt(0)) return fixedFromCharCode(parseInt(k.substring(1).replace('x', '0x')));
4321
- errorHandler.error('entity not found:' + a);
4322
- return a;
4324
+ else {
4325
+ if ('#' === k.charAt(0)) return fixedFromCharCode(parseInt(k.substring(1).replace('x', '0x')));
4326
+ errorHandler.error('entity not found:' + a);
4327
+ return a;
4328
+ }
4323
4329
  }
4324
4330
  function appendText(end) {
4325
4331
  if (end > start) {
@@ -4424,7 +4430,7 @@ __webpack_require__.add({
4424
4430
  }
4425
4431
  } catch (e) {
4426
4432
  if (e instanceof ParseError) throw e;
4427
- if (e instanceof DOMException) throw new ParseError(e.name + ': ' + e.message, domBuilder.locator, e);
4433
+ else if (e instanceof DOMException) throw new ParseError(e.name + ': ' + e.message, domBuilder.locator, e);
4428
4434
  errorHandler.error('element parse error: ' + e);
4429
4435
  end = -1;
4430
4436
  }
@@ -4752,16 +4758,20 @@ __webpack_require__.add({
4752
4758
  case '-':
4753
4759
  var comment = p.getMatch(g.Comment);
4754
4760
  if (!comment) return errorHandler.fatalError('comment is not well-formed at position ' + p.getIndex());
4755
- domBuilder.comment(comment, g.COMMENT_START.length, comment.length - g.COMMENT_START.length - g.COMMENT_END.length);
4756
- return p.getIndex();
4761
+ else {
4762
+ domBuilder.comment(comment, g.COMMENT_START.length, comment.length - g.COMMENT_START.length - g.COMMENT_END.length);
4763
+ return p.getIndex();
4764
+ }
4757
4765
  case '[':
4758
4766
  var cdata = p.getMatch(g.CDSect);
4759
4767
  if (!cdata) return errorHandler.fatalError('Invalid CDATA starting at position ' + start);
4760
- if (!isHTML && !domBuilder.currentElement) return errorHandler.fatalError('CDATA outside of element');
4761
- domBuilder.startCDATA();
4762
- domBuilder.characters(cdata, g.CDATA_START.length, cdata.length - g.CDATA_START.length - g.CDATA_END.length);
4763
- domBuilder.endCDATA();
4764
- return p.getIndex();
4768
+ else {
4769
+ if (!isHTML && !domBuilder.currentElement) return errorHandler.fatalError('CDATA outside of element');
4770
+ domBuilder.startCDATA();
4771
+ domBuilder.characters(cdata, g.CDATA_START.length, cdata.length - g.CDATA_START.length - g.CDATA_END.length);
4772
+ domBuilder.endCDATA();
4773
+ return p.getIndex();
4774
+ }
4765
4775
  case 'D':
4766
4776
  if (domBuilder.doc && domBuilder.doc.documentElement) return errorHandler.fatalError('Doctype not allowed inside or after documentElement at position ' + p.getIndex());
4767
4777
  if (isHTML ? !p.substringStartsWithCaseInsensitive(g.DOCTYPE_DECL_START) : !p.substringStartsWith(g.DOCTYPE_DECL_START)) return errorHandler.fatalError('Expected ' + g.DOCTYPE_DECL_START + ' at position ' + p.getIndex());
@@ -4913,13 +4923,15 @@ __webpack_require__.add({
4913
4923
  };
4914
4924
  isArray = function(val) {
4915
4925
  if (isFunction(Array.isArray)) return Array.isArray(val);
4916
- return '[object Array]' === Object.prototype.toString.call(val);
4926
+ else return '[object Array]' === Object.prototype.toString.call(val);
4917
4927
  };
4918
4928
  isEmpty = function(val) {
4919
4929
  var key;
4920
4930
  if (isArray(val)) return !val.length;
4921
- for(key in val)if (hasProp.call(val, key)) return false;
4922
- return true;
4931
+ else {
4932
+ for(key in val)if (hasProp.call(val, key)) return false;
4933
+ return true;
4934
+ }
4923
4935
  };
4924
4936
  isPlainObject = function(val) {
4925
4937
  var ctor, proto;
@@ -4927,7 +4939,7 @@ __webpack_require__.add({
4927
4939
  };
4928
4940
  getValue = function(obj) {
4929
4941
  if (isFunction(obj.valueOf)) return obj.valueOf();
4930
- return obj;
4942
+ else return obj;
4931
4943
  };
4932
4944
  module.exports.assign = assign;
4933
4945
  module.exports.isFunction = isFunction;
@@ -4977,7 +4989,7 @@ __webpack_require__.add({
4977
4989
  debugInfo(name) {
4978
4990
  name = name || this.name;
4979
4991
  if (null == name) return "parent: <" + this.parent.name + ">";
4980
- return "attribute: {" + name + "}, parent: <" + this.parent.name + ">";
4992
+ else return "attribute: {" + name + "}, parent: <" + this.parent.name + ">";
4981
4993
  }
4982
4994
  isEqualNode(node) {
4983
4995
  if (node.namespaceURI !== this.namespaceURI) return false;
@@ -5163,14 +5175,14 @@ __webpack_require__.add({
5163
5175
  }
5164
5176
  getParameter(name) {
5165
5177
  if (this.params.hasOwnProperty(name)) return this.params[name];
5166
- return null;
5178
+ else return null;
5167
5179
  }
5168
5180
  canSetParameter(name, value) {
5169
5181
  return true;
5170
5182
  }
5171
5183
  setParameter(name, value) {
5172
5184
  if (null != value) return this.params[name] = value;
5173
- return delete this.params[name];
5185
+ else return delete this.params[name];
5174
5186
  }
5175
5187
  }
5176
5188
  Object.defineProperty(XMLDOMConfiguration.prototype, 'parameterNames', {
@@ -5680,19 +5692,19 @@ __webpack_require__.add({
5680
5692
  Object.defineProperty(XMLDocument.prototype, 'xmlEncoding', {
5681
5693
  get: function() {
5682
5694
  if (0 !== this.children.length && this.children[0].type === NodeType.Declaration) return this.children[0].encoding;
5683
- return null;
5695
+ else return null;
5684
5696
  }
5685
5697
  });
5686
5698
  Object.defineProperty(XMLDocument.prototype, 'xmlStandalone', {
5687
5699
  get: function() {
5688
5700
  if (0 !== this.children.length && this.children[0].type === NodeType.Declaration) return 'yes' === this.children[0].standalone;
5689
- return false;
5701
+ else return false;
5690
5702
  }
5691
5703
  });
5692
5704
  Object.defineProperty(XMLDocument.prototype, 'xmlVersion', {
5693
5705
  get: function() {
5694
5706
  if (0 !== this.children.length && this.children[0].type === NodeType.Declaration) return this.children[0].version;
5695
- return "1.0";
5707
+ else return "1.0";
5696
5708
  }
5697
5709
  });
5698
5710
  Object.defineProperty(XMLDocument.prototype, 'URL', {
@@ -6046,7 +6058,7 @@ __webpack_require__.add({
6046
6058
  }
6047
6059
  debugInfo(name) {
6048
6060
  if (null == name) return "";
6049
- return "node: <" + name + ">";
6061
+ else return "node: <" + name + ">";
6050
6062
  }
6051
6063
  ele() {
6052
6064
  return this.element(...arguments);
@@ -6095,11 +6107,11 @@ __webpack_require__.add({
6095
6107
  }
6096
6108
  att() {
6097
6109
  if (this.currentNode && this.currentNode.type === NodeType.DocType) return this.attList(...arguments);
6098
- return this.attribute(...arguments);
6110
+ else return this.attribute(...arguments);
6099
6111
  }
6100
6112
  a() {
6101
6113
  if (this.currentNode && this.currentNode.type === NodeType.DocType) return this.attList(...arguments);
6102
- return this.attribute(...arguments);
6114
+ else return this.attribute(...arguments);
6103
6115
  }
6104
6116
  ent(name, value) {
6105
6117
  return this.entity(name, value);
@@ -6223,14 +6235,14 @@ __webpack_require__.add({
6223
6235
  }
6224
6236
  getAttribute(name) {
6225
6237
  if (this.attribs.hasOwnProperty(name)) return this.attribs[name].value;
6226
- return null;
6238
+ else return null;
6227
6239
  }
6228
6240
  setAttribute(name, value) {
6229
6241
  throw new Error("This DOM method is not implemented." + this.debugInfo());
6230
6242
  }
6231
6243
  getAttributeNode(name) {
6232
6244
  if (this.attribs.hasOwnProperty(name)) return this.attribs[name];
6233
- return null;
6245
+ else return null;
6234
6246
  }
6235
6247
  setAttributeNode(newAttr) {
6236
6248
  throw new Error("This DOM method is not implemented." + this.debugInfo());
@@ -6267,7 +6279,7 @@ __webpack_require__.add({
6267
6279
  }
6268
6280
  setIdAttribute(name, isId) {
6269
6281
  if (this.attribs.hasOwnProperty(name)) return this.attribs[name].isId;
6270
- return isId;
6282
+ else return isId;
6271
6283
  }
6272
6284
  setIdAttributeNS(namespaceURI, localName, isId) {
6273
6285
  throw new Error("This DOM method is not implemented." + this.debugInfo());
@@ -6502,13 +6514,14 @@ __webpack_require__.add({
6502
6514
  Array.prototype.push.apply(children, removed);
6503
6515
  } else children.push(newChild);
6504
6516
  return newChild;
6517
+ } else {
6518
+ if (this.isRoot) throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
6519
+ i = this.parent.children.indexOf(this);
6520
+ removed = this.parent.children.splice(i);
6521
+ child = this.parent.element(name, attributes, text);
6522
+ Array.prototype.push.apply(this.parent.children, removed);
6523
+ return child;
6505
6524
  }
6506
- if (this.isRoot) throw new Error("Cannot insert elements at root level. " + this.debugInfo(name));
6507
- i = this.parent.children.indexOf(this);
6508
- removed = this.parent.children.splice(i);
6509
- child = this.parent.element(name, attributes, text);
6510
- Array.prototype.push.apply(this.parent.children, removed);
6511
- return child;
6512
6525
  }
6513
6526
  insertAfter(name, attributes, text) {
6514
6527
  var child, i, removed;
@@ -6718,9 +6731,9 @@ __webpack_require__.add({
6718
6731
  var ref1, ref2;
6719
6732
  name = name || this.name;
6720
6733
  if (null == name && !(null != (ref1 = this.parent) ? ref1.name : void 0)) return "";
6721
- if (null == name) return "parent: <" + this.parent.name + ">";
6722
- if (!(null != (ref2 = this.parent) ? ref2.name : void 0)) return "node: <" + name + ">";
6723
- return "node: <" + name + ">, parent: <" + this.parent.name + ">";
6734
+ else if (null == name) return "parent: <" + this.parent.name + ">";
6735
+ else if (!(null != (ref2 = this.parent) ? ref2.name : void 0)) return "node: <" + name + ">";
6736
+ else return "node: <" + name + ">, parent: <" + this.parent.name + ">";
6724
6737
  }
6725
6738
  ele(name, attributes, text) {
6726
6739
  return this.element(name, attributes, text);
@@ -6813,15 +6826,14 @@ __webpack_require__.add({
6813
6826
  var ref, res;
6814
6827
  ref = this;
6815
6828
  if (ref === other) return 0;
6816
- if (this.document() !== other.document()) {
6829
+ else if (this.document() !== other.document()) {
6817
6830
  res = DocumentPosition.Disconnected | DocumentPosition.ImplementationSpecific;
6818
6831
  if (Math.random() < 0.5) res |= DocumentPosition.Preceding;
6819
6832
  else res |= DocumentPosition.Following;
6820
6833
  return res;
6821
- }
6822
- if (ref.isAncestor(other)) return DocumentPosition.Contains | DocumentPosition.Preceding;
6823
- if (ref.isDescendant(other)) return DocumentPosition.Contains | DocumentPosition.Following;
6824
- if (ref.isPreceding(other)) return DocumentPosition.Preceding;
6834
+ } else if (ref.isAncestor(other)) return DocumentPosition.Contains | DocumentPosition.Preceding;
6835
+ else if (ref.isDescendant(other)) return DocumentPosition.Contains | DocumentPosition.Following;
6836
+ else if (ref.isPreceding(other)) return DocumentPosition.Preceding;
6825
6837
  else return DocumentPosition.Following;
6826
6838
  }
6827
6839
  isSameNode(other) {
@@ -6875,14 +6887,14 @@ __webpack_require__.add({
6875
6887
  nodePos = this.treePosition(node);
6876
6888
  thisPos = this.treePosition(this);
6877
6889
  if (-1 === nodePos || -1 === thisPos) return false;
6878
- return nodePos < thisPos;
6890
+ else return nodePos < thisPos;
6879
6891
  }
6880
6892
  isFollowing(node) {
6881
6893
  var nodePos, thisPos;
6882
6894
  nodePos = this.treePosition(node);
6883
6895
  thisPos = this.treePosition(this);
6884
6896
  if (-1 === nodePos || -1 === thisPos) return false;
6885
- return nodePos > thisPos;
6897
+ else return nodePos > thisPos;
6886
6898
  }
6887
6899
  treePosition(node) {
6888
6900
  var found, pos;
@@ -6893,7 +6905,7 @@ __webpack_require__.add({
6893
6905
  if (!found && childNode === node) return found = true;
6894
6906
  });
6895
6907
  if (found) return pos;
6896
- return -1;
6908
+ else return -1;
6897
6909
  }
6898
6910
  foreachTreeNode(node, func) {
6899
6911
  var child, j, len, ref1, res;
@@ -6902,8 +6914,10 @@ __webpack_require__.add({
6902
6914
  for(j = 0, len = ref1.length; j < len; j++){
6903
6915
  child = ref1[j];
6904
6916
  if (res = func(child)) return res;
6905
- res = this.foreachTreeNode(child, func);
6906
- if (res) return res;
6917
+ else {
6918
+ res = this.foreachTreeNode(child, func);
6919
+ if (res) return res;
6920
+ }
6907
6921
  }
6908
6922
  }
6909
6923
  }
@@ -6966,13 +6980,15 @@ __webpack_require__.add({
6966
6980
  get: function() {
6967
6981
  var child, j, len, ref1, str;
6968
6982
  if (this.nodeType !== NodeType.Element && this.nodeType !== NodeType.DocumentFragment) return null;
6969
- str = '';
6970
- ref1 = this.children;
6971
- for(j = 0, len = ref1.length; j < len; j++){
6972
- child = ref1[j];
6973
- if (child.textContent) str += child.textContent;
6983
+ else {
6984
+ str = '';
6985
+ ref1 = this.children;
6986
+ for(j = 0, len = ref1.length; j < len; j++){
6987
+ child = ref1[j];
6988
+ if (child.textContent) str += child.textContent;
6989
+ }
6990
+ return str;
6974
6991
  }
6975
- return str;
6976
6992
  },
6977
6993
  set: function(value) {
6978
6994
  throw new Error("This DOM method is not implemented." + this.debugInfo());
@@ -7067,7 +7083,7 @@ __webpack_require__.add({
7067
7083
  }
7068
7084
  endline(node, options, level) {
7069
7085
  if (node.isLastRootNode && options.state === WriterState.CloseTag) return '';
7070
- return super.endline(node, options, level);
7086
+ else return super.endline(node, options, level);
7071
7087
  }
7072
7088
  document(doc, options) {
7073
7089
  var child, i, j, k, len1, len2, ref, ref1, results;
@@ -7305,7 +7321,7 @@ __webpack_require__.add({
7305
7321
  xmlStandalone(val) {
7306
7322
  if (this.options.noValidation) return val;
7307
7323
  if (val) return "yes";
7308
- return "no";
7324
+ else return "no";
7309
7325
  }
7310
7326
  dtdPubID(val) {
7311
7327
  if (this.options.noValidation) return val;
@@ -7497,7 +7513,7 @@ __webpack_require__.add({
7497
7513
  }
7498
7514
  endline(node, options, level) {
7499
7515
  if (!options.pretty || options.suppressPrettyCount) return '';
7500
- return options.newline;
7516
+ else return options.newline;
7501
7517
  }
7502
7518
  attribute(att, options, level) {
7503
7519
  var r;
@@ -7833,7 +7849,7 @@ __webpack_require__.add({
7833
7849
  options = {};
7834
7850
  }
7835
7851
  if (onData) return new XMLDocumentCB(options, onData, onEnd);
7836
- return new XMLDocument(options);
7852
+ else return new XMLDocument(options);
7837
7853
  };
7838
7854
  module.exports.stringWriter = function(options) {
7839
7855
  return new XMLStringWriter(options);
@@ -7873,36 +7889,31 @@ class PromiseResolver {
7873
7889
  this.#state = 'rejected';
7874
7890
  };
7875
7891
  }
7876
- function getUint64LittleEndian(buffer, offset) {
7877
- return BigInt(buffer[offset]) | BigInt(buffer[offset + 1]) << 8n | BigInt(buffer[offset + 2]) << 16n | BigInt(buffer[offset + 3]) << 24n | BigInt(buffer[offset + 4]) << 32n | BigInt(buffer[offset + 5]) << 40n | BigInt(buffer[offset + 6]) << 48n | BigInt(buffer[offset + 7]) << 56n;
7892
+ function isPromiseLike(value) {
7893
+ return "object" == typeof value && null !== value && "then" in value;
7878
7894
  }
7879
- function getUint64(buffer, offset, littleEndian) {
7880
- return littleEndian ? BigInt(buffer[offset]) | BigInt(buffer[offset + 1]) << 8n | BigInt(buffer[offset + 2]) << 16n | BigInt(buffer[offset + 3]) << 24n | BigInt(buffer[offset + 4]) << 32n | BigInt(buffer[offset + 5]) << 40n | BigInt(buffer[offset + 6]) << 48n | BigInt(buffer[offset + 7]) << 56n : BigInt(buffer[offset]) << 56n | BigInt(buffer[offset + 1]) << 48n | BigInt(buffer[offset + 2]) << 40n | BigInt(buffer[offset + 3]) << 32n | BigInt(buffer[offset + 4]) << 24n | BigInt(buffer[offset + 5]) << 16n | BigInt(buffer[offset + 6]) << 8n | BigInt(buffer[offset + 7]);
7895
+ function tryClose(value) {
7896
+ try {
7897
+ const result = value.close();
7898
+ if (isPromiseLike(result)) return result.then(()=>true, ()=>false);
7899
+ return true;
7900
+ } catch {
7901
+ return false;
7902
+ }
7881
7903
  }
7882
- function setUint64(buffer, offset, value, littleEndian) {
7883
- if (littleEndian) {
7884
- buffer[offset] = Number(0xffn & value);
7885
- buffer[offset + 1] = Number(value >> 8n & 0xffn);
7886
- buffer[offset + 2] = Number(value >> 16n & 0xffn);
7887
- buffer[offset + 3] = Number(value >> 24n & 0xffn);
7888
- buffer[offset + 4] = Number(value >> 32n & 0xffn);
7889
- buffer[offset + 5] = Number(value >> 40n & 0xffn);
7890
- buffer[offset + 6] = Number(value >> 48n & 0xffn);
7891
- buffer[offset + 7] = Number(value >> 56n & 0xffn);
7892
- } else {
7893
- buffer[offset] = Number(value >> 56n & 0xffn);
7894
- buffer[offset + 1] = Number(value >> 48n & 0xffn);
7895
- buffer[offset + 2] = Number(value >> 40n & 0xffn);
7896
- buffer[offset + 3] = Number(value >> 32n & 0xffn);
7897
- buffer[offset + 4] = Number(value >> 24n & 0xffn);
7898
- buffer[offset + 5] = Number(value >> 16n & 0xffn);
7899
- buffer[offset + 6] = Number(value >> 8n & 0xffn);
7900
- buffer[offset + 7] = Number(0xffn & value);
7904
+ async function tryCancel(stream) {
7905
+ try {
7906
+ await stream.cancel();
7907
+ return true;
7908
+ } catch {
7909
+ return false;
7901
7910
  }
7902
7911
  }
7903
- const { AbortController: stream_AbortController } = globalThis;
7904
- const stream_ReadableStream = /* #__PURE__ */ (()=>{
7905
- const { ReadableStream } = globalThis;
7912
+ function utils_getGlobalValue(key) {
7913
+ return globalThis[key];
7914
+ }
7915
+ const streams_ReadableStream = /* #__PURE__ */ (()=>{
7916
+ const ReadableStream = utils_getGlobalValue("ReadableStream");
7906
7917
  if (!ReadableStream.from) ReadableStream.from = function(iterable) {
7907
7918
  const iterator = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
7908
7919
  return new ReadableStream({
@@ -7926,7 +7937,7 @@ const stream_ReadableStream = /* #__PURE__ */ (()=>{
7926
7937
  yield value;
7927
7938
  }
7928
7939
  } finally{
7929
- if (!options?.preventCancel) await reader.cancel();
7940
+ if (!options?.preventCancel) await tryCancel(reader);
7930
7941
  reader.releaseLock();
7931
7942
  }
7932
7943
  };
@@ -7934,715 +7945,67 @@ const stream_ReadableStream = /* #__PURE__ */ (()=>{
7934
7945
  }
7935
7946
  return ReadableStream;
7936
7947
  })();
7937
- const { WritableStream: WritableStream, TransformStream: TransformStream } = globalThis;
7938
- const Global = globalThis;
7939
- const TextDecoderStream = Global.TextDecoderStream;
7940
- Global.TextEncoderStream;
7941
- function isPromiseLike(value) {
7942
- return "object" == typeof value && null !== value && "then" in value;
7943
- }
7944
- function advance(iterator, next) {
7945
- while(true){
7946
- const { done, value } = iterator.next(next);
7947
- if (done) return value;
7948
- if (isPromiseLike(value)) return value.then((value)=>advance(iterator, {
7949
- resolved: value
7950
- }), (error)=>advance(iterator, {
7951
- error
7952
- }));
7953
- next = value;
7954
- }
7955
- }
7956
- function bipedal(fn, bindThis) {
7957
- function result(...args) {
7958
- const iterator = fn.call(this, function*(value) {
7959
- if (isPromiseLike(value)) {
7960
- const result = yield value;
7961
- if ("resolved" in result) return result.resolved;
7962
- throw result.error;
7963
- }
7964
- return value;
7965
- }, ...args);
7966
- return advance(iterator, void 0);
7967
- }
7968
- if (bindThis) return result.bind(bindThis);
7969
- return result;
7970
- }
7971
- function defaultFieldSerializer(serializer) {
7972
- return (source, context)=>{
7973
- if (!("buffer" in context)) return serializer(source, context);
7974
- {
7975
- const buffer = serializer(source, context);
7976
- context.buffer.set(buffer, context.index);
7977
- return buffer.length;
7978
- }
7979
- };
7980
- }
7981
- function byobFieldSerializer(size, serializer) {
7982
- return (source, context)=>{
7983
- if ("buffer" in context) {
7984
- context.index ??= 0;
7985
- serializer(source, context);
7986
- return size;
7987
- }
7988
- {
7989
- const buffer = new Uint8Array(size);
7990
- serializer(source, {
7991
- buffer,
7992
- index: 0,
7993
- littleEndian: context.littleEndian
7948
+ const WritableStream = utils_getGlobalValue("WritableStream");
7949
+ const abort_signal_AbortController = utils_getGlobalValue("AbortController");
7950
+ class TaskQueue {
7951
+ #ready;
7952
+ #disposed = false;
7953
+ enqueue(task, bail = false) {
7954
+ if (this.#disposed) throw new Error("TaskQueue is disposed");
7955
+ if (!this.#ready) try {
7956
+ const result = task();
7957
+ if (isPromiseLike(result)) this.#ready = result.then(()=>{}, (e)=>{
7958
+ if (bail) throw e;
7994
7959
  });
7995
- return buffer;
7996
- }
7997
- };
7998
- }
7999
- function _field(size, type, serialize, deserialize, options) {
8000
- const field = {
8001
- size,
8002
- type: type,
8003
- serialize: "default" === type ? defaultFieldSerializer(serialize) : byobFieldSerializer(size, serialize),
8004
- deserialize: bipedal(deserialize),
8005
- omitInit: options?.omitInit
8006
- };
8007
- if (options?.init) field.init = options.init;
8008
- return field;
8009
- }
8010
- const factory_field = _field;
8011
- const EmptyUint8Array = new Uint8Array(0);
8012
- function copyMaybeDifferentLength(dest, source, index, length) {
8013
- if (source.length < length) {
8014
- dest.set(source, index);
8015
- dest.fill(0, index + source.length, index + length);
8016
- } else if (source.length === length) dest.set(source, index);
8017
- else dest.set(source.subarray(0, length), index);
8018
- }
8019
- function buffer_buffer(lengthOrField, converter) {
8020
- if ("number" == typeof lengthOrField) {
8021
- let serialize;
8022
- let deserialize;
8023
- let init;
8024
- if (0 === lengthOrField) {
8025
- serialize = ()=>{};
8026
- deserialize = converter ? function*() {
8027
- return converter.convert(EmptyUint8Array);
8028
- } : function*() {
8029
- return EmptyUint8Array;
8030
- };
8031
- } else {
8032
- serialize = (value, { buffer, index })=>copyMaybeDifferentLength(buffer, value, index, lengthOrField);
8033
- if (converter) {
8034
- deserialize = function*(then, reader) {
8035
- const array = reader.readExactly(lengthOrField);
8036
- return converter.convert((yield* then(array)));
8037
- };
8038
- init = (value)=>converter.back(value);
8039
- } else deserialize = function*(_then, reader) {
8040
- const array = reader.readExactly(lengthOrField);
8041
- return array;
8042
- };
8043
- }
8044
- return factory_field(lengthOrField, "byob", serialize, deserialize, {
8045
- init
8046
- });
8047
- }
8048
- if (("object" == typeof lengthOrField || "function" == typeof lengthOrField) && "serialize" in lengthOrField) {
8049
- let deserialize;
8050
- let init;
8051
- if (converter) {
8052
- deserialize = function*(then, reader, context) {
8053
- const length = yield* then(lengthOrField.deserialize(reader, context));
8054
- const array = 0 !== length ? reader.readExactly(length) : EmptyUint8Array;
8055
- return converter.convert((yield* then(array)));
8056
- };
8057
- init = (value)=>converter.back(value);
8058
- } else deserialize = function*(then, reader, context) {
8059
- const length = yield* then(lengthOrField.deserialize(reader, context));
8060
- const array = 0 !== length ? reader.readExactly(length) : EmptyUint8Array;
8061
- return array;
8062
- };
8063
- return factory_field(lengthOrField.size, "default", (value, { littleEndian })=>{
8064
- if ("default" === lengthOrField.type) {
8065
- const lengthBuffer = lengthOrField.serialize(value.length, {
8066
- littleEndian
8067
- });
8068
- if (0 === value.length) return lengthBuffer;
8069
- const result = new Uint8Array(lengthBuffer.length + value.length);
8070
- result.set(lengthBuffer, 0);
8071
- result.set(value, lengthBuffer.length);
8072
- return result;
8073
- }
8074
- {
8075
- const result = new Uint8Array(lengthOrField.size + value.length);
8076
- lengthOrField.serialize(value.length, {
8077
- buffer: result,
8078
- index: 0,
8079
- littleEndian
8080
- });
8081
- result.set(value, lengthOrField.size);
8082
- return result;
7960
+ return result;
7961
+ } catch (e) {
7962
+ if (bail) {
7963
+ const promise = Promise.reject(e);
7964
+ promise.catch(()=>{});
7965
+ this.#ready = promise;
8083
7966
  }
8084
- }, deserialize, {
8085
- init
8086
- });
8087
- }
8088
- if ("string" == typeof lengthOrField) {
8089
- let deserialize;
8090
- let init;
8091
- if (converter) {
8092
- deserialize = function*(then, reader, { dependencies }) {
8093
- const length = dependencies[lengthOrField];
8094
- const array = 0 !== length ? reader.readExactly(length) : EmptyUint8Array;
8095
- return converter.convert((yield* then(array)));
8096
- };
8097
- init = (value, dependencies)=>{
8098
- const array = converter.back(value);
8099
- dependencies[lengthOrField] = array.length;
8100
- return array;
8101
- };
8102
- } else {
8103
- deserialize = function*(_then, reader, { dependencies }) {
8104
- const length = dependencies[lengthOrField];
8105
- const array = 0 !== length ? reader.readExactly(length) : EmptyUint8Array;
8106
- return array;
8107
- };
8108
- init = (value, dependencies)=>{
8109
- const array = value;
8110
- dependencies[lengthOrField] = array.length;
8111
- return array;
8112
- };
7967
+ throw e;
8113
7968
  }
8114
- return factory_field(0, "default", (source)=>source, deserialize, {
8115
- init
7969
+ const result = this.#ready.then(()=>{
7970
+ if (this.#disposed) throw new Error("TaskQueue is disposed");
7971
+ return task();
8116
7972
  });
8117
- }
8118
- let deserialize;
8119
- let init;
8120
- if (converter) {
8121
- deserialize = function*(then, reader, { dependencies }) {
8122
- const rawLength = dependencies[lengthOrField.field];
8123
- const length = lengthOrField.convert(rawLength);
8124
- const array = 0 !== length ? reader.readExactly(length) : EmptyUint8Array;
8125
- return converter.convert((yield* then(array)));
8126
- };
8127
- init = (value, dependencies)=>{
8128
- const array = converter.back(value);
8129
- dependencies[lengthOrField.field] = lengthOrField.back(array.length);
8130
- return array;
8131
- };
8132
- } else {
8133
- deserialize = function*(_then, reader, { dependencies }) {
8134
- const rawLength = dependencies[lengthOrField.field];
8135
- const length = lengthOrField.convert(rawLength);
8136
- const array = 0 !== length ? reader.readExactly(length) : EmptyUint8Array;
8137
- return array;
8138
- };
8139
- init = (value, dependencies)=>{
8140
- const array = value;
8141
- dependencies[lengthOrField.field] = lengthOrField.back(array.length);
8142
- return array;
8143
- };
8144
- }
8145
- return factory_field(0, "default", (source)=>source, deserialize, {
8146
- init
8147
- });
8148
- }
8149
- class ConcatStringStream {
8150
- #result = "";
8151
- #resolver = new PromiseResolver();
8152
- #writable = new WritableStream({
8153
- write: (chunk)=>{
8154
- this.#result += chunk;
8155
- },
8156
- close: ()=>{
8157
- this.#resolver.resolve(this.#result);
8158
- this.#readableController.enqueue(this.#result);
8159
- this.#readableController.close();
8160
- },
8161
- abort: (reason)=>{
8162
- this.#resolver.reject(reason);
8163
- this.#readableController.error(reason);
8164
- }
8165
- });
8166
- get writable() {
8167
- return this.#writable;
8168
- }
8169
- #readableController;
8170
- #readable = new stream_ReadableStream({
8171
- start: (controller)=>{
8172
- this.#readableController = controller;
8173
- }
8174
- });
8175
- get readable() {
8176
- return this.#readable;
8177
- }
8178
- constructor(){
8179
- Object.defineProperties(this.#readable, {
8180
- then: {
8181
- get: ()=>this.#resolver.promise.then.bind(this.#resolver.promise)
8182
- },
8183
- catch: {
8184
- get: ()=>this.#resolver.promise.catch.bind(this.#resolver.promise)
8185
- },
8186
- finally: {
8187
- get: ()=>this.#resolver.promise.finally.bind(this.#resolver.promise)
8188
- }
7973
+ this.#ready = result.then(()=>{}, (e)=>{
7974
+ if (bail || this.#disposed) throw e;
8189
7975
  });
7976
+ return result;
8190
7977
  }
8191
- }
8192
- class ConcatBufferStream {
8193
- #segments = [];
8194
- #resolver = new PromiseResolver();
8195
- #writable = new WritableStream({
8196
- write: (chunk)=>{
8197
- this.#segments.push(chunk);
8198
- },
8199
- close: ()=>{
8200
- let result;
8201
- let offset = 0;
8202
- switch(this.#segments.length){
8203
- case 0:
8204
- result = EmptyUint8Array;
8205
- break;
8206
- case 1:
8207
- result = this.#segments[0];
8208
- break;
8209
- default:
8210
- result = new Uint8Array(this.#segments.reduce((prev, item)=>prev + item.length, 0));
8211
- for (const segment of this.#segments){
8212
- result.set(segment, offset);
8213
- offset += segment.length;
8214
- }
8215
- break;
8216
- }
8217
- this.#resolver.resolve(result);
8218
- this.#readableController.enqueue(result);
8219
- this.#readableController.close();
8220
- },
8221
- abort: (reason)=>{
8222
- this.#resolver.reject(reason);
8223
- this.#readableController.error(reason);
8224
- }
8225
- });
8226
- get writable() {
8227
- return this.#writable;
8228
- }
8229
- #readableController;
8230
- #readable = new stream_ReadableStream({
8231
- start: (controller)=>{
8232
- this.#readableController = controller;
8233
- }
8234
- });
8235
- get readable() {
8236
- return this.#readable;
8237
- }
8238
- constructor(){
8239
- Object.defineProperties(this.#readable, {
8240
- then: {
8241
- get: ()=>this.#resolver.promise.then.bind(this.#resolver.promise)
8242
- },
8243
- catch: {
8244
- get: ()=>this.#resolver.promise.catch.bind(this.#resolver.promise)
8245
- },
8246
- finally: {
8247
- get: ()=>this.#resolver.promise.finally.bind(this.#resolver.promise)
8248
- }
8249
- });
7978
+ dispose() {
7979
+ this.#disposed = true;
8250
7980
  }
8251
7981
  }
8252
- const AdbFeature = {
8253
- ShellV2: "shell_v2",
8254
- Cmd: "cmd",
8255
- StatV2: "stat_v2",
8256
- ListV2: "ls_v2",
8257
- FixedPushMkdir: "fixed_push_mkdir",
8258
- Abb: "abb",
8259
- AbbExec: "abb_exec",
8260
- SendReceiveV2: "sendrecv_v2",
8261
- DelayedAck: "delayed_ack"
8262
- };
8263
- class AdbNoneProtocolProcessImpl {
8264
- #socket;
8265
- get stdin() {
8266
- return this.#socket.writable;
8267
- }
8268
- get output() {
8269
- return this.#socket.readable;
8270
- }
8271
- #exited;
8272
- get exited() {
8273
- return this.#exited;
8274
- }
8275
- constructor(socket, signal){
8276
- this.#socket = socket;
8277
- if (signal) {
8278
- const exited = new PromiseResolver();
8279
- this.#socket.closed.then(()=>exited.resolve(void 0), (e)=>exited.reject(e));
8280
- signal.addEventListener("abort", ()=>{
8281
- exited.reject(signal.reason);
8282
- this.#socket.close();
7982
+ class PushReadableStream extends streams_ReadableStream {
7983
+ constructor(source, strategy, logger){
7984
+ let controller;
7985
+ const tasks = new TaskQueue();
7986
+ let zeroHighWaterMarkAllowEnqueue = false;
7987
+ let waterMarkLow;
7988
+ const abortController = new abort_signal_AbortController();
7989
+ let stopped = false;
7990
+ const enqueue = (chunk)=>{
7991
+ logger?.({
7992
+ source: "producer",
7993
+ operation: "enqueue",
7994
+ value: chunk,
7995
+ phase: "start"
8283
7996
  });
8284
- this.#exited = exited.promise;
8285
- } else this.#exited = this.#socket.closed;
8286
- }
8287
- kill() {
8288
- return this.#socket.close();
8289
- }
8290
- }
8291
- class ConsumableWritableStream extends WritableStream {
8292
- static async write(writer, value) {
8293
- const consumable = new consumable_Consumable(value);
8294
- await writer.write(consumable);
8295
- await consumable.consumed;
8296
- }
8297
- constructor(sink, strategy){
8298
- let wrappedStrategy;
8299
- if (strategy) {
8300
- wrappedStrategy = {};
8301
- if ("highWaterMark" in strategy) wrappedStrategy.highWaterMark = strategy.highWaterMark;
8302
- if ("size" in strategy) wrappedStrategy.size = (chunk)=>strategy.size(chunk instanceof consumable_Consumable ? chunk.value : chunk);
8303
- }
8304
- super({
8305
- start (controller) {
8306
- return sink.start?.(controller);
8307
- },
8308
- write (chunk, controller) {
8309
- return chunk.tryConsume((chunk)=>sink.write?.(chunk, controller));
8310
- },
8311
- abort (reason) {
8312
- return sink.abort?.(reason);
8313
- },
8314
- close () {
8315
- return sink.close?.();
7997
+ if (abortController.signal.aborted) {
7998
+ logger?.({
7999
+ source: "producer",
8000
+ operation: "enqueue",
8001
+ value: chunk,
8002
+ phase: "ignored"
8003
+ });
8004
+ return false;
8316
8005
  }
8317
- }, wrappedStrategy);
8318
- }
8319
- }
8320
- class ConsumableWrapWritableStream extends WritableStream {
8321
- constructor(stream){
8322
- const writer = stream.getWriter();
8323
- super({
8324
- write (chunk) {
8325
- return chunk.tryConsume((chunk)=>writer.write(chunk));
8326
- },
8327
- abort (reason) {
8328
- return writer.abort(reason);
8329
- },
8330
- close () {
8331
- return writer.close();
8332
- }
8333
- });
8334
- }
8335
- }
8336
- class ConsumableReadableStream extends stream_ReadableStream {
8337
- static async enqueue(controller, chunk) {
8338
- const output = new consumable_Consumable(chunk);
8339
- controller.enqueue(output);
8340
- await output.consumed;
8341
- }
8342
- constructor(source, strategy){
8343
- let wrappedController;
8344
- let wrappedStrategy;
8345
- if (strategy) {
8346
- wrappedStrategy = {};
8347
- if ("highWaterMark" in strategy) wrappedStrategy.highWaterMark = strategy.highWaterMark;
8348
- if ("size" in strategy) wrappedStrategy.size = (chunk)=>strategy.size(chunk.value);
8349
- }
8350
- super({
8351
- start (controller) {
8352
- wrappedController = {
8353
- enqueue (chunk) {
8354
- return ConsumableReadableStream.enqueue(controller, chunk);
8355
- },
8356
- close () {
8357
- controller.close();
8358
- },
8359
- error (reason) {
8360
- controller.error(reason);
8361
- }
8362
- };
8363
- return source.start?.(wrappedController);
8364
- },
8365
- pull () {
8366
- return source.pull?.(wrappedController);
8367
- },
8368
- cancel (reason) {
8369
- return source.cancel?.(reason);
8370
- }
8371
- }, wrappedStrategy);
8372
- }
8373
- }
8374
- class ConsumableWrapByteReadableStream extends stream_ReadableStream {
8375
- constructor(stream, chunkSize, min){
8376
- const reader = stream.getReader({
8377
- mode: "byob"
8378
- });
8379
- let array = new Uint8Array(chunkSize);
8380
- super({
8381
- async pull (controller) {
8382
- const { done, value } = await reader.read(array, {
8383
- min
8384
- });
8385
- if (done) return void controller.close();
8386
- await ConsumableReadableStream.enqueue(controller, value);
8387
- array = new Uint8Array(value.buffer);
8388
- },
8389
- cancel (reason) {
8390
- return reader.cancel(reason);
8391
- }
8392
- });
8393
- }
8394
- }
8395
- const { console: console } = globalThis;
8396
- const createTask = /* #__PURE__ */ (()=>console?.createTask?.bind(console) ?? (()=>({
8397
- run (callback) {
8398
- return callback();
8399
- }
8400
- })))();
8401
- class consumable_Consumable {
8402
- static WritableStream = ConsumableWritableStream;
8403
- static WrapWritableStream = ConsumableWrapWritableStream;
8404
- static ReadableStream = ConsumableReadableStream;
8405
- static WrapByteReadableStream = ConsumableWrapByteReadableStream;
8406
- #task;
8407
- #resolver;
8408
- value;
8409
- consumed;
8410
- constructor(value){
8411
- this.#task = createTask("Consumable");
8412
- this.value = value;
8413
- this.#resolver = new PromiseResolver();
8414
- this.consumed = this.#resolver.promise;
8415
- }
8416
- consume() {
8417
- this.#resolver.resolve();
8418
- }
8419
- error(error) {
8420
- this.#resolver.reject(error);
8421
- }
8422
- tryConsume(callback) {
8423
- try {
8424
- let result = this.#task.run(()=>callback(this.value));
8425
- if (isPromiseLike(result)) result = result.then((value)=>{
8426
- this.#resolver.resolve();
8427
- return value;
8428
- }, (e)=>{
8429
- this.#resolver.reject(e);
8430
- throw e;
8431
- });
8432
- else this.#resolver.resolve();
8433
- return result;
8434
- } catch (e) {
8435
- this.#resolver.reject(e);
8436
- throw e;
8437
- }
8438
- }
8439
- }
8440
- function tryConsume(value, callback) {
8441
- if (value instanceof consumable_Consumable) return value.tryConsume(callback);
8442
- return callback(value);
8443
- }
8444
- class MaybeConsumableWritableStream extends WritableStream {
8445
- constructor(sink, strategy){
8446
- let wrappedStrategy;
8447
- if (strategy) {
8448
- wrappedStrategy = {};
8449
- if ("highWaterMark" in strategy) wrappedStrategy.highWaterMark = strategy.highWaterMark;
8450
- if ("size" in strategy) wrappedStrategy.size = (chunk)=>strategy.size(chunk instanceof consumable_Consumable ? chunk.value : chunk);
8451
- }
8452
- super({
8453
- start (controller) {
8454
- return sink.start?.(controller);
8455
- },
8456
- write (chunk, controller) {
8457
- return tryConsume(chunk, (chunk)=>sink.write?.(chunk, controller));
8458
- },
8459
- abort (reason) {
8460
- return sink.abort?.(reason);
8461
- },
8462
- close () {
8463
- return sink.close?.();
8464
- }
8465
- }, wrappedStrategy);
8466
- }
8467
- }
8468
- class AdbNoneProtocolPtyProcess {
8469
- #socket;
8470
- #writer;
8471
- #input;
8472
- get input() {
8473
- return this.#input;
8474
- }
8475
- get output() {
8476
- return this.#socket.readable;
8477
- }
8478
- get exited() {
8479
- return this.#socket.closed;
8480
- }
8481
- constructor(socket){
8482
- this.#socket = socket;
8483
- this.#writer = this.#socket.writable.getWriter();
8484
- this.#input = new MaybeConsumableWritableStream({
8485
- write: (chunk)=>this.#writer.write(chunk)
8486
- });
8487
- }
8488
- sigint() {
8489
- return this.#writer.write(new Uint8Array([
8490
- 0x03
8491
- ]));
8492
- }
8493
- kill() {
8494
- return this.#socket.close();
8495
- }
8496
- }
8497
- function escapeArg(s) {
8498
- let result = "";
8499
- result += "'";
8500
- let base = 0;
8501
- while(true){
8502
- const found = s.indexOf("'", base);
8503
- if (-1 === found) {
8504
- result += s.substring(base);
8505
- break;
8506
- }
8507
- result += s.substring(base, found);
8508
- result += String.raw`'\''`;
8509
- base = found + 1;
8510
- }
8511
- result += "'";
8512
- return result;
8513
- }
8514
- function splitCommand(command) {
8515
- const result = [];
8516
- let quote;
8517
- let isEscaped = false;
8518
- let start = 0;
8519
- for(let i = 0, len = command.length; i < len; i += 1){
8520
- if (isEscaped) {
8521
- isEscaped = false;
8522
- continue;
8523
- }
8524
- const char = command.charAt(i);
8525
- switch(char){
8526
- case " ":
8527
- if (!quote && i !== start) {
8528
- result.push(command.substring(start, i));
8529
- start = i + 1;
8530
- }
8531
- break;
8532
- case "'":
8533
- case '"':
8534
- if (quote) {
8535
- if (char === quote) quote = void 0;
8536
- } else quote = char;
8537
- break;
8538
- case "\\":
8539
- isEscaped = true;
8540
- break;
8541
- }
8542
- }
8543
- if (start < command.length) result.push(command.substring(start));
8544
- return result;
8545
- }
8546
- class AdbNoneProtocolSpawner {
8547
- #spawn;
8548
- constructor(spawn){
8549
- this.#spawn = spawn;
8550
- }
8551
- spawn(command, signal) {
8552
- signal?.throwIfAborted();
8553
- if ("string" == typeof command) command = splitCommand(command);
8554
- return this.#spawn(command, signal);
8555
- }
8556
- async spawnWait(command) {
8557
- const process1 = await this.spawn(command);
8558
- return await process1.output.pipeThrough(new ConcatBufferStream());
8559
- }
8560
- async spawnWaitText(command) {
8561
- const process1 = await this.spawn(command);
8562
- return await process1.output.pipeThrough(new TextDecoderStream()).pipeThrough(new ConcatStringStream());
8563
- }
8564
- }
8565
- class AdbNoneProtocolSubprocessService extends AdbNoneProtocolSpawner {
8566
- #adb;
8567
- get adb() {
8568
- return this.#adb;
8569
- }
8570
- constructor(adb){
8571
- super(async (command, signal)=>{
8572
- const socket = await this.#adb.createSocket(`exec:${command.join(" ")}`);
8573
- if (signal?.aborted) {
8574
- await socket.close();
8575
- throw signal.reason;
8576
- }
8577
- return new AdbNoneProtocolProcessImpl(socket, signal);
8578
- });
8579
- this.#adb = adb;
8580
- }
8581
- async pty(command) {
8582
- if (void 0 === command) command = "";
8583
- else if (Array.isArray(command)) command = command.join(" ");
8584
- return new AdbNoneProtocolPtyProcess(await this.#adb.createSocket(`shell:${command}`));
8585
- }
8586
- }
8587
- class TaskQueue {
8588
- #ready;
8589
- #disposed = false;
8590
- enqueue(task, bail = false) {
8591
- if (this.#disposed) throw new Error("TaskQueue is disposed");
8592
- if (!this.#ready) try {
8593
- const result = task();
8594
- if (isPromiseLike(result)) this.#ready = result.then(()=>{}, (e)=>{
8595
- if (bail) throw e;
8596
- });
8597
- return result;
8598
- } catch (e) {
8599
- if (bail) {
8600
- const promise = Promise.reject(e);
8601
- promise.catch(()=>{});
8602
- this.#ready = promise;
8603
- }
8604
- throw e;
8605
- }
8606
- const result = this.#ready.then(()=>{
8607
- if (this.#disposed) throw new Error("TaskQueue is disposed");
8608
- return task();
8609
- });
8610
- this.#ready = result.then(()=>{}, (e)=>{
8611
- if (bail || this.#disposed) throw e;
8612
- });
8613
- return result;
8614
- }
8615
- dispose() {
8616
- this.#disposed = true;
8617
- }
8618
- }
8619
- class PushReadableStream extends stream_ReadableStream {
8620
- constructor(source, strategy, logger){
8621
- let controller;
8622
- const tasks = new TaskQueue();
8623
- let zeroHighWaterMarkAllowEnqueue = false;
8624
- let waterMarkLow;
8625
- const abortController = new stream_AbortController();
8626
- let stopped = false;
8627
- const enqueue = (chunk)=>{
8628
- logger?.({
8629
- source: "producer",
8630
- operation: "enqueue",
8631
- value: chunk,
8632
- phase: "start"
8633
- });
8634
- if (abortController.signal.aborted) {
8635
- logger?.({
8636
- source: "producer",
8637
- operation: "enqueue",
8638
- value: chunk,
8639
- phase: "ignored"
8640
- });
8641
- return false;
8642
- }
8643
- if (null === controller.desiredSize) {
8644
- controller.enqueue(chunk);
8645
- throw new Error("unreachable");
8006
+ if (null === controller.desiredSize) {
8007
+ controller.enqueue(chunk);
8008
+ throw new Error("unreachable");
8646
8009
  }
8647
8010
  if (zeroHighWaterMarkAllowEnqueue) {
8648
8011
  zeroHighWaterMarkAllowEnqueue = false;
@@ -8780,2319 +8143,259 @@ class PushReadableStream extends stream_ReadableStream {
8780
8143
  }, strategy);
8781
8144
  }
8782
8145
  }
8783
- class ExactReadableEndedError extends Error {
8784
- constructor(){
8785
- super("ExactReadable ended");
8786
- }
8787
- }
8788
- class StructDeserializeError extends Error {
8789
- constructor(message){
8790
- super(message);
8146
+ class ConsumableWritableStream extends WritableStream {
8147
+ static async write(writer, value) {
8148
+ const consumable = new consumable_Consumable(value);
8149
+ await writer.write(consumable);
8150
+ await consumable.consumed;
8791
8151
  }
8792
- }
8793
- class StructNotEnoughDataError extends StructDeserializeError {
8794
- constructor(){
8795
- super("The underlying readable was ended before the struct was fully deserialized");
8152
+ constructor(sink, strategy){
8153
+ let wrappedStrategy;
8154
+ if (strategy) {
8155
+ wrappedStrategy = {};
8156
+ if ("highWaterMark" in strategy) wrappedStrategy.highWaterMark = strategy.highWaterMark;
8157
+ if ("size" in strategy) wrappedStrategy.size = (chunk)=>strategy.size(chunk instanceof consumable_Consumable ? chunk.value : chunk);
8158
+ }
8159
+ super({
8160
+ start (controller) {
8161
+ return sink.start?.(controller);
8162
+ },
8163
+ write (chunk, controller) {
8164
+ return chunk.tryConsume((chunk)=>sink.write?.(chunk, controller));
8165
+ },
8166
+ abort (reason) {
8167
+ return sink.abort?.(reason);
8168
+ },
8169
+ close () {
8170
+ return sink.close?.();
8171
+ }
8172
+ }, wrappedStrategy);
8796
8173
  }
8797
8174
  }
8798
- class StructEmptyError extends StructDeserializeError {
8799
- constructor(){
8800
- super("The underlying readable doesn't contain any more struct");
8175
+ class ConsumableWrapWritableStream extends WritableStream {
8176
+ constructor(stream, hooks){
8177
+ const writer = stream.getWriter();
8178
+ super({
8179
+ write (chunk) {
8180
+ return chunk.tryConsume(async (chunk)=>{
8181
+ if (hooks?.write) await hooks.write(chunk);
8182
+ await writer.write(chunk);
8183
+ });
8184
+ },
8185
+ async abort (reason) {
8186
+ if (hooks?.abort) await hooks.abort(reason);
8187
+ await writer.abort(reason);
8188
+ },
8189
+ async close () {
8190
+ if (hooks?.close) await hooks.close();
8191
+ await writer.close();
8192
+ }
8193
+ });
8801
8194
  }
8802
8195
  }
8803
- function struct_struct(fields, options) {
8804
- const fieldList = Object.entries(fields);
8805
- let size = 0;
8806
- let byob = true;
8807
- for (const [, field] of fieldList){
8808
- size += field.size;
8809
- if (byob && "byob" !== field.type) byob = false;
8196
+ class ConsumableReadableStream extends streams_ReadableStream {
8197
+ static async enqueue(controller, chunk) {
8198
+ const output = new consumable_Consumable(chunk);
8199
+ controller.enqueue(output);
8200
+ await output.consumed;
8810
8201
  }
8811
- const littleEndian = options.littleEndian;
8812
- const extra = options.extra ? Object.getOwnPropertyDescriptors(options.extra) : void 0;
8813
- return {
8814
- littleEndian,
8815
- fields,
8816
- extra: options.extra,
8817
- type: byob ? "byob" : "default",
8818
- size,
8819
- serialize (source, bufferOrContext) {
8820
- const temp = {
8821
- ...source
8822
- };
8823
- for (const [key, field] of fieldList)if (key in temp && "init" in field) {
8824
- const result = field.init?.(temp[key], temp);
8825
- temp[key] = result;
8826
- }
8827
- const sizes = new Array(fieldList.length);
8828
- const buffers = new Array(fieldList.length);
8829
- {
8830
- const context = {
8831
- littleEndian
8202
+ constructor(source, strategy){
8203
+ let wrappedController;
8204
+ let wrappedStrategy;
8205
+ if (strategy) {
8206
+ wrappedStrategy = {};
8207
+ if ("highWaterMark" in strategy) wrappedStrategy.highWaterMark = strategy.highWaterMark;
8208
+ if ("size" in strategy) wrappedStrategy.size = (chunk)=>strategy.size(chunk.value);
8209
+ }
8210
+ super({
8211
+ start (controller) {
8212
+ wrappedController = {
8213
+ enqueue (chunk) {
8214
+ return ConsumableReadableStream.enqueue(controller, chunk);
8215
+ },
8216
+ close () {
8217
+ controller.close();
8218
+ },
8219
+ error (reason) {
8220
+ controller.error(reason);
8221
+ }
8832
8222
  };
8833
- for (const [index, [key, field]] of fieldList.entries())if ("byob" === field.type) sizes[index] = field.size;
8834
- else {
8835
- buffers[index] = field.serialize(temp[key], context);
8836
- sizes[index] = buffers[index].length;
8837
- }
8838
- }
8839
- const size = sizes.reduce((sum, size)=>sum + size, 0);
8840
- let externalBuffer;
8841
- let buffer;
8842
- let index;
8843
- if (bufferOrContext instanceof Uint8Array) {
8844
- if (bufferOrContext.length < size) throw new Error("Buffer too small");
8845
- externalBuffer = true;
8846
- buffer = bufferOrContext;
8847
- index = 0;
8848
- } else if ("object" == typeof bufferOrContext && "buffer" in bufferOrContext) {
8849
- externalBuffer = true;
8850
- buffer = bufferOrContext.buffer;
8851
- index = bufferOrContext.index ?? 0;
8852
- if (buffer.length - index < size) throw new Error("Buffer too small");
8853
- } else {
8854
- externalBuffer = false;
8855
- buffer = new Uint8Array(size);
8856
- index = 0;
8857
- }
8858
- const context = {
8859
- buffer,
8860
- index,
8861
- littleEndian
8862
- };
8863
- for (const [index, [key, field]] of fieldList.entries()){
8864
- if (buffers[index]) buffer.set(buffers[index], context.index);
8865
- else field.serialize(temp[key], context);
8866
- context.index += sizes[index];
8867
- }
8868
- if (externalBuffer) return size;
8869
- return buffer;
8870
- },
8871
- deserialize: bipedal(function*(then, reader) {
8872
- const startPosition = reader.position;
8873
- const result = {};
8874
- const context = {
8875
- dependencies: result,
8876
- littleEndian: littleEndian
8877
- };
8878
- try {
8879
- for (const [key, field] of fieldList)result[key] = yield* then(field.deserialize(reader, context));
8880
- } catch (e) {
8881
- if (!(e instanceof ExactReadableEndedError)) throw e;
8882
- if (reader.position === startPosition) throw new StructEmptyError();
8883
- throw new StructNotEnoughDataError();
8884
- }
8885
- if (extra) Object.defineProperties(result, extra);
8886
- if (options.postDeserialize) return options.postDeserialize.call(result, result);
8887
- return result;
8888
- })
8889
- };
8890
- }
8891
- function tryClose(value) {
8892
- try {
8893
- const result = value.close();
8894
- if (isPromiseLike(result)) return result.then(()=>true, ()=>false);
8895
- return true;
8896
- } catch {
8897
- return false;
8898
- }
8899
- }
8900
- async function tryCancel(stream) {
8901
- try {
8902
- await stream.cancel();
8903
- return true;
8904
- } catch {
8905
- return false;
8906
- }
8907
- }
8908
- class BufferedReadableStream {
8909
- #buffered;
8910
- #bufferedOffset = 0;
8911
- #bufferedLength = 0;
8912
- #position = 0;
8913
- get position() {
8914
- return this.#position;
8915
- }
8916
- stream;
8917
- reader;
8918
- constructor(stream){
8919
- this.stream = stream;
8920
- this.reader = stream.getReader();
8921
- }
8922
- #readBuffered(length) {
8923
- if (!this.#buffered) return;
8924
- const value = this.#buffered.subarray(this.#bufferedOffset, this.#bufferedOffset + length);
8925
- if (this.#bufferedLength > length) {
8926
- this.#position += length;
8927
- this.#bufferedOffset += length;
8928
- this.#bufferedLength -= length;
8929
- return value;
8930
- }
8931
- this.#position += this.#bufferedLength;
8932
- this.#buffered = void 0;
8933
- this.#bufferedOffset = 0;
8934
- this.#bufferedLength = 0;
8935
- return value;
8936
- }
8937
- async #readSource(length) {
8938
- const { done, value } = await this.reader.read();
8939
- if (done) throw new ExactReadableEndedError();
8940
- if (value.length > length) {
8941
- this.#buffered = value;
8942
- this.#bufferedOffset = length;
8943
- this.#bufferedLength = value.length - length;
8944
- this.#position += length;
8945
- return value.subarray(0, length);
8946
- }
8947
- this.#position += value.length;
8948
- return value;
8949
- }
8950
- iterateExactly(length) {
8951
- let state = this.#buffered ? 0 : 1;
8952
- return {
8953
- next: ()=>{
8954
- switch(state){
8955
- case 0:
8956
- {
8957
- const value = this.#readBuffered(length);
8958
- if (value.length === length) state = 2;
8959
- else {
8960
- length -= value.length;
8961
- state = 1;
8962
- }
8963
- return {
8964
- done: false,
8965
- value
8966
- };
8967
- }
8968
- case 1:
8969
- state = 3;
8970
- return {
8971
- done: false,
8972
- value: this.#readSource(length).then((value)=>{
8973
- if (value.length === length) state = 2;
8974
- else {
8975
- length -= value.length;
8976
- state = 1;
8977
- }
8978
- return value;
8979
- })
8980
- };
8981
- case 2:
8982
- return {
8983
- done: true,
8984
- value: void 0
8985
- };
8986
- case 3:
8987
- throw new Error("Can't call `next` before previous Promise resolves");
8988
- default:
8989
- throw new Error("unreachable");
8990
- }
8991
- }
8992
- };
8993
- }
8994
- readExactly = bipedal(function*(then, length) {
8995
- let result;
8996
- let index = 0;
8997
- const initial = this.#readBuffered(length);
8998
- if (initial) {
8999
- if (initial.length === length) return initial;
9000
- result = new Uint8Array(length);
9001
- result.set(initial, index);
9002
- index += initial.length;
9003
- length -= initial.length;
9004
- } else result = new Uint8Array(length);
9005
- while(length > 0){
9006
- const value = yield* then(this.#readSource(length));
9007
- result.set(value, index);
9008
- index += value.length;
9009
- length -= value.length;
9010
- }
9011
- return result;
9012
- });
9013
- release() {
9014
- if (this.#bufferedLength > 0) return new PushReadableStream(async (controller)=>{
9015
- const buffered = this.#buffered.subarray(this.#bufferedOffset);
9016
- await controller.enqueue(buffered);
9017
- controller.abortSignal.addEventListener("abort", ()=>{
9018
- tryCancel(this.reader);
9019
- });
9020
- while(true){
9021
- const { done, value } = await this.reader.read();
9022
- if (done) return;
9023
- await controller.enqueue(value);
9024
- }
9025
- });
9026
- this.reader.releaseLock();
9027
- return this.stream;
9028
- }
9029
- async cancel(reason) {
9030
- await this.reader.cancel(reason);
9031
- }
9032
- }
9033
- class BufferedTransformStream {
9034
- #readable;
9035
- get readable() {
9036
- return this.#readable;
9037
- }
9038
- #writable;
9039
- get writable() {
9040
- return this.#writable;
9041
- }
9042
- constructor(transform){
9043
- let bufferedStreamController;
9044
- let writableStreamController;
9045
- const buffered = new BufferedReadableStream(new PushReadableStream((controller)=>{
9046
- bufferedStreamController = controller;
9047
- }));
9048
- this.#readable = new stream_ReadableStream({
9049
- async pull (controller) {
9050
- try {
9051
- const value = await transform(buffered);
9052
- controller.enqueue(value);
9053
- } catch (e) {
9054
- if (e instanceof StructEmptyError) return void controller.close();
9055
- throw e;
9056
- }
9057
- },
9058
- cancel: (reason)=>writableStreamController.error(reason)
9059
- });
9060
- this.#writable = new WritableStream({
9061
- start (controller) {
9062
- writableStreamController = controller;
9063
- },
9064
- async write (chunk) {
9065
- await bufferedStreamController.enqueue(chunk);
9066
- },
9067
- abort () {
9068
- bufferedStreamController.close();
9069
- },
9070
- close () {
9071
- bufferedStreamController.close();
9072
- }
9073
- });
9074
- }
9075
- }
9076
- class StructDeserializeStream extends BufferedTransformStream {
9077
- constructor(struct){
9078
- super((stream)=>struct.deserialize(stream));
9079
- }
9080
- }
9081
- function getUint32LittleEndian(buffer, offset) {
9082
- return (buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24) >>> 0;
9083
- }
9084
- function getUint32(buffer, offset, littleEndian) {
9085
- return littleEndian ? (buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24) >>> 0 : (buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3]) >>> 0;
9086
- }
9087
- function setUint32(buffer, offset, value, littleEndian) {
9088
- if (littleEndian) {
9089
- buffer[offset] = value;
9090
- buffer[offset + 1] = value >> 8;
9091
- buffer[offset + 2] = value >> 16;
9092
- buffer[offset + 3] = value >> 24;
9093
- } else {
9094
- buffer[offset] = value >> 24;
9095
- buffer[offset + 1] = value >> 16;
9096
- buffer[offset + 2] = value >> 8;
9097
- buffer[offset + 3] = value;
9098
- }
9099
- }
9100
- function number(size, serialize, deserialize) {
9101
- const fn = ()=>fn;
9102
- Object.assign(fn, factory_field(size, "byob", serialize, deserialize));
9103
- return fn;
9104
- }
9105
- const u8 = number(1, (value, { buffer, index })=>{
9106
- buffer[index] = value;
9107
- }, function*(then, reader) {
9108
- const data = yield* then(reader.readExactly(1));
9109
- return data[0];
9110
- });
9111
- const u32 = number(4, (value, { buffer, index, littleEndian })=>{
9112
- setUint32(buffer, index, value, littleEndian);
9113
- }, function*(then, reader, { littleEndian }) {
9114
- const data = yield* then(reader.readExactly(4));
9115
- return getUint32(data, 0, littleEndian);
9116
- });
9117
- const u64 = number(8, (value, { buffer, index, littleEndian })=>{
9118
- setUint64(buffer, index, value, littleEndian);
9119
- }, function*(then, reader, { littleEndian }) {
9120
- const data = yield* then(reader.readExactly(8));
9121
- return getUint64(data, 0, littleEndian);
9122
- });
9123
- const AdbShellProtocolId = {
9124
- Stdin: 0,
9125
- Stdout: 1,
9126
- Stderr: 2,
9127
- Exit: 3,
9128
- CloseStdin: 4,
9129
- WindowSizeChange: 5
9130
- };
9131
- const AdbShellProtocolPacket = struct_struct({
9132
- id: u8(),
9133
- data: buffer_buffer(u32)
9134
- }, {
9135
- littleEndian: true
9136
- });
9137
- class AdbShellProtocolProcessImpl {
9138
- #socket;
9139
- #writer;
9140
- #stdin;
9141
- get stdin() {
9142
- return this.#stdin;
9143
- }
9144
- #stdout;
9145
- get stdout() {
9146
- return this.#stdout;
9147
- }
9148
- #stderr;
9149
- get stderr() {
9150
- return this.#stderr;
9151
- }
9152
- #exited;
9153
- get exited() {
9154
- return this.#exited;
9155
- }
9156
- constructor(socket, signal){
9157
- this.#socket = socket;
9158
- let stdoutController;
9159
- let stderrController;
9160
- this.#stdout = new PushReadableStream((controller)=>{
9161
- stdoutController = controller;
9162
- });
9163
- this.#stderr = new PushReadableStream((controller)=>{
9164
- stderrController = controller;
9165
- });
9166
- const exited = new PromiseResolver();
9167
- this.#exited = exited.promise;
9168
- socket.readable.pipeThrough(new StructDeserializeStream(AdbShellProtocolPacket)).pipeTo(new WritableStream({
9169
- write: async (chunk)=>{
9170
- switch(chunk.id){
9171
- case AdbShellProtocolId.Exit:
9172
- exited.resolve(chunk.data[0]);
9173
- break;
9174
- case AdbShellProtocolId.Stdout:
9175
- await stdoutController.enqueue(chunk.data);
9176
- break;
9177
- case AdbShellProtocolId.Stderr:
9178
- await stderrController.enqueue(chunk.data);
9179
- break;
9180
- default:
9181
- break;
9182
- }
9183
- }
9184
- })).then(()=>{
9185
- stdoutController.close();
9186
- stderrController.close();
9187
- exited.reject(new Error("Socket ended without exit message"));
9188
- }, (e)=>{
9189
- stdoutController.error(e);
9190
- stderrController.error(e);
9191
- exited.reject(e);
9192
- });
9193
- if (signal) signal.addEventListener("abort", ()=>{
9194
- exited.reject(signal.reason);
9195
- this.#socket.close();
9196
- });
9197
- this.#writer = this.#socket.writable.getWriter();
9198
- this.#stdin = new MaybeConsumableWritableStream({
9199
- write: async (chunk)=>{
9200
- await this.#writer.write(AdbShellProtocolPacket.serialize({
9201
- id: AdbShellProtocolId.Stdin,
9202
- data: chunk
9203
- }));
9204
- },
9205
- close: ()=>this.#writer.write(AdbShellProtocolPacket.serialize({
9206
- id: AdbShellProtocolId.CloseStdin,
9207
- data: EmptyUint8Array
9208
- }))
9209
- });
9210
- }
9211
- kill() {
9212
- return this.#socket.close();
9213
- }
9214
- }
9215
- const { TextEncoder: utils_TextEncoder, TextDecoder: utils_TextDecoder } = globalThis;
9216
- const SharedEncoder = /* #__PURE__ */ new utils_TextEncoder();
9217
- const SharedDecoder = /* #__PURE__ */ new utils_TextDecoder();
9218
- function encodeUtf8(input) {
9219
- return SharedEncoder.encode(input);
9220
- }
9221
- function decodeUtf8(buffer) {
9222
- return SharedDecoder.decode(buffer);
9223
- }
9224
- class AdbShellProtocolPtyProcess {
9225
- #socket;
9226
- #writer;
9227
- #input;
9228
- get input() {
9229
- return this.#input;
9230
- }
9231
- #stdout;
9232
- get output() {
9233
- return this.#stdout;
9234
- }
9235
- #exited = new PromiseResolver();
9236
- get exited() {
9237
- return this.#exited.promise;
9238
- }
9239
- constructor(socket){
9240
- this.#socket = socket;
9241
- let stdoutController;
9242
- this.#stdout = new PushReadableStream((controller)=>{
9243
- stdoutController = controller;
9244
- });
9245
- socket.readable.pipeThrough(new StructDeserializeStream(AdbShellProtocolPacket)).pipeTo(new WritableStream({
9246
- write: async (chunk)=>{
9247
- switch(chunk.id){
9248
- case AdbShellProtocolId.Exit:
9249
- this.#exited.resolve(chunk.data[0]);
9250
- break;
9251
- case AdbShellProtocolId.Stdout:
9252
- await stdoutController.enqueue(chunk.data);
9253
- break;
9254
- }
9255
- }
9256
- })).then(()=>{
9257
- stdoutController.close();
9258
- this.#exited.reject(new Error("Socket ended without exit message"));
9259
- }, (e)=>{
9260
- stdoutController.error(e);
9261
- this.#exited.reject(e);
9262
- });
9263
- this.#writer = this.#socket.writable.getWriter();
9264
- this.#input = new MaybeConsumableWritableStream({
9265
- write: (chunk)=>this.#writeStdin(chunk)
9266
- });
9267
- }
9268
- #writeStdin(chunk) {
9269
- return this.#writer.write(AdbShellProtocolPacket.serialize({
9270
- id: AdbShellProtocolId.Stdin,
9271
- data: chunk
9272
- }));
9273
- }
9274
- async resize(rows, cols) {
9275
- await this.#writer.write(AdbShellProtocolPacket.serialize({
9276
- id: AdbShellProtocolId.WindowSizeChange,
9277
- data: encodeUtf8(`${rows}x${cols},0x0\0`)
9278
- }));
9279
- }
9280
- sigint() {
9281
- return this.#writeStdin(new Uint8Array([
9282
- 0x03
9283
- ]));
9284
- }
9285
- kill() {
9286
- return this.#socket.close();
9287
- }
9288
- }
9289
- class AdbShellProtocolSpawner {
9290
- #spawn;
9291
- constructor(spawn){
9292
- this.#spawn = spawn;
9293
- }
9294
- spawn(command, signal) {
9295
- signal?.throwIfAborted();
9296
- if ("string" == typeof command) command = splitCommand(command);
9297
- return this.#spawn(command, signal);
9298
- }
9299
- async spawnWait(command) {
9300
- const process1 = await this.spawn(command);
9301
- const [stdout, stderr, exitCode] = await Promise.all([
9302
- process1.stdout.pipeThrough(new ConcatBufferStream()),
9303
- process1.stderr.pipeThrough(new ConcatBufferStream()),
9304
- process1.exited
9305
- ]);
9306
- return {
9307
- stdout,
9308
- stderr,
9309
- exitCode
9310
- };
9311
- }
9312
- async spawnWaitText(command) {
9313
- const process1 = await this.spawn(command);
9314
- const [stdout, stderr, exitCode] = await Promise.all([
9315
- process1.stdout.pipeThrough(new TextDecoderStream()).pipeThrough(new ConcatStringStream()),
9316
- process1.stderr.pipeThrough(new TextDecoderStream()).pipeThrough(new ConcatStringStream()),
9317
- process1.exited
9318
- ]);
9319
- return {
9320
- stdout,
9321
- stderr,
9322
- exitCode
9323
- };
9324
- }
9325
- }
9326
- class AdbShellProtocolSubprocessService extends AdbShellProtocolSpawner {
9327
- #adb;
9328
- get adb() {
9329
- return this.#adb;
9330
- }
9331
- get isSupported() {
9332
- return this.#adb.canUseFeature(AdbFeature.ShellV2);
9333
- }
9334
- constructor(adb){
9335
- super(async (command, signal)=>{
9336
- const socket = await this.#adb.createSocket(`shell,v2,raw:${command.join(" ")}`);
9337
- if (signal?.aborted) {
9338
- await socket.close();
9339
- throw signal.reason;
9340
- }
9341
- return new AdbShellProtocolProcessImpl(socket, signal);
9342
- });
9343
- this.#adb = adb;
9344
- }
9345
- async pty(options) {
9346
- let service = "shell,v2,pty";
9347
- if (options?.terminalType) service += ",TERM=" + options.terminalType;
9348
- service += ":";
9349
- if (options) {
9350
- if ("string" == typeof options.command) service += options.command;
9351
- else if (Array.isArray(options.command)) service += options.command.join(" ");
9352
- }
9353
- return new AdbShellProtocolPtyProcess(await this.#adb.createSocket(service));
9354
- }
9355
- }
9356
- class AdbSubprocessService {
9357
- #adb;
9358
- get adb() {
9359
- return this.#adb;
9360
- }
9361
- #noneProtocol;
9362
- get noneProtocol() {
9363
- return this.#noneProtocol;
9364
- }
9365
- #shellProtocol;
9366
- get shellProtocol() {
9367
- return this.#shellProtocol;
9368
- }
9369
- constructor(adb){
9370
- this.#adb = adb;
9371
- this.#noneProtocol = new AdbNoneProtocolSubprocessService(adb);
9372
- if (adb.canUseFeature(AdbFeature.ShellV2)) this.#shellProtocol = new AdbShellProtocolSubprocessService(adb);
9373
- }
9374
- }
9375
- class AutoDisposable {
9376
- #disposables = [];
9377
- constructor(){
9378
- this.dispose = this.dispose.bind(this);
9379
- }
9380
- addDisposable(disposable) {
9381
- this.#disposables.push(disposable);
9382
- return disposable;
9383
- }
9384
- dispose() {
9385
- for (const disposable of this.#disposables)disposable.dispose();
9386
- this.#disposables = [];
9387
- }
9388
- }
9389
- class AdbServiceBase extends AutoDisposable {
9390
- #adb;
9391
- get adb() {
9392
- return this.#adb;
9393
- }
9394
- constructor(adb){
9395
- super();
9396
- this.#adb = adb;
9397
- }
9398
- }
9399
- class AdbPower extends AdbServiceBase {
9400
- reboot(mode = "") {
9401
- return this.adb.createSocketAndWait(`reboot:${mode}`);
9402
- }
9403
- bootloader() {
9404
- return this.reboot("bootloader");
9405
- }
9406
- fastboot() {
9407
- return this.reboot("fastboot");
9408
- }
9409
- recovery() {
9410
- return this.reboot("recovery");
9411
- }
9412
- sideload() {
9413
- return this.reboot("sideload");
9414
- }
9415
- qualcommEdlMode() {
9416
- return this.reboot("edl");
9417
- }
9418
- powerOff() {
9419
- return this.adb.subprocess.noneProtocol.spawnWaitText([
9420
- "reboot",
9421
- "-p"
9422
- ]);
9423
- }
9424
- powerButton(longPress = false) {
9425
- const args = [
9426
- "input",
9427
- "keyevent"
9428
- ];
9429
- if (longPress) args.push("--longpress");
9430
- args.push("POWER");
9431
- return this.adb.subprocess.noneProtocol.spawnWaitText(args);
9432
- }
9433
- samsungOdin() {
9434
- return this.reboot("download");
9435
- }
9436
- }
9437
- const string = (lengthOrField)=>{
9438
- const field = buffer_buffer(lengthOrField, {
9439
- convert: decodeUtf8,
9440
- back: encodeUtf8
9441
- });
9442
- field.as = ()=>field;
9443
- return field;
9444
- };
9445
- function extend(base, fields, options) {
9446
- return struct_struct(Object.assign({}, base.fields, fields), {
9447
- littleEndian: options?.littleEndian ?? base.littleEndian,
9448
- extra: base.extra,
9449
- postDeserialize: options?.postDeserialize
9450
- });
9451
- }
9452
- function sequenceEqual(a, b) {
9453
- if (a.length !== b.length) return false;
9454
- for(let i = 0; i < a.length; i += 1)if (a[i] !== b[i]) return false;
9455
- return true;
9456
- }
9457
- function hexCharToNumber(char) {
9458
- if (char < 48) throw new TypeError(`Invalid hex char ${char}`);
9459
- if (char < 58) return char - 48;
9460
- if (char < 65) throw new TypeError(`Invalid hex char ${char}`);
9461
- if (char < 71) return char - 55;
9462
- if (char < 97) throw new TypeError(`Invalid hex char ${char}`);
9463
- if (char < 103) return char - 87;
9464
- throw new TypeError(`Invalid hex char ${char}`);
9465
- }
9466
- function hexToNumber(data) {
9467
- let result = 0;
9468
- for(let i = 0; i < data.length; i += 1)result = result << 4 | hexCharToNumber(data[i]);
9469
- return result;
9470
- }
9471
- function write4HexDigits(buffer, index, value) {
9472
- const start = index;
9473
- index += 3;
9474
- while(index >= start && value > 0){
9475
- const digit = 0xf & value;
9476
- value >>= 4;
9477
- if (digit < 10) buffer[index] = digit + 48;
9478
- else buffer[index] = digit + 87;
9479
- index -= 1;
9480
- }
9481
- while(index >= start){
9482
- buffer[index] = 48;
9483
- index -= 1;
9484
- }
9485
- }
9486
- const AdbReverseStringResponse = struct_struct({
9487
- length: string(4),
9488
- content: string({
9489
- field: "length",
9490
- convert (value) {
9491
- return Number.parseInt(value, 16);
9492
- },
9493
- back (value) {
9494
- return value.toString(16).padStart(4, "0");
9495
- }
9496
- })
9497
- }, {
9498
- littleEndian: true
9499
- });
9500
- class AdbReverseError extends Error {
9501
- constructor(message){
9502
- super(message);
9503
- }
9504
- }
9505
- class AdbReverseNotSupportedError extends AdbReverseError {
9506
- constructor(){
9507
- super("ADB reverse tunnel is not supported on this device when connected wirelessly.");
9508
- }
9509
- }
9510
- const AdbReverseErrorResponse = extend(AdbReverseStringResponse, {}, {
9511
- postDeserialize (value) {
9512
- if ("more than one device/emulator" === value.content) throw new AdbReverseNotSupportedError();
9513
- throw new AdbReverseError(value.content);
9514
- }
9515
- });
9516
- function decimalToNumber(buffer) {
9517
- let value = 0;
9518
- for (const byte of buffer){
9519
- if (byte < 48 || byte > 57) break;
9520
- value = 10 * value + byte - 48;
9521
- }
9522
- return value;
9523
- }
9524
- const OKAY = encodeUtf8("OKAY");
9525
- class AdbReverseService extends AdbServiceBase {
9526
- #deviceAddressToLocalAddress = new Map();
9527
- async createBufferedStream(service) {
9528
- const socket = await this.adb.createSocket(service);
9529
- return new BufferedReadableStream(socket.readable);
9530
- }
9531
- async sendRequest(service) {
9532
- const stream = await this.createBufferedStream(service);
9533
- const response = await stream.readExactly(4);
9534
- if (!sequenceEqual(response, OKAY)) await AdbReverseErrorResponse.deserialize(stream);
9535
- return stream;
9536
- }
9537
- async list() {
9538
- const stream = await this.createBufferedStream("reverse:list-forward");
9539
- const response = await AdbReverseStringResponse.deserialize(stream);
9540
- return response.content.split("\n").filter((line)=>!!line).map((line)=>{
9541
- const [deviceSerial, localName, remoteName] = line.split(" ");
9542
- return {
9543
- deviceSerial,
9544
- localName,
9545
- remoteName
9546
- };
9547
- });
9548
- }
9549
- async addExternal(deviceAddress, localAddress) {
9550
- const stream = await this.sendRequest(`reverse:forward:${deviceAddress};${localAddress}`);
9551
- if (deviceAddress.startsWith("tcp:")) {
9552
- const position = stream.position;
9553
- try {
9554
- const length = hexToNumber(await stream.readExactly(4));
9555
- const port = decimalToNumber(await stream.readExactly(length));
9556
- deviceAddress = `tcp:${port}`;
9557
- } catch (e) {
9558
- if (e instanceof ExactReadableEndedError && stream.position === position) ;
9559
- else throw e;
9560
- }
9561
- }
9562
- return deviceAddress;
9563
- }
9564
- async add(deviceAddress, handler, localAddress) {
9565
- localAddress = await this.adb.transport.addReverseTunnel(handler, localAddress);
9566
- try {
9567
- deviceAddress = await this.addExternal(deviceAddress, localAddress);
9568
- this.#deviceAddressToLocalAddress.set(deviceAddress, localAddress);
9569
- return deviceAddress;
9570
- } catch (e) {
9571
- await this.adb.transport.removeReverseTunnel(localAddress);
9572
- throw e;
9573
- }
9574
- }
9575
- async remove(deviceAddress) {
9576
- const localAddress = this.#deviceAddressToLocalAddress.get(deviceAddress);
9577
- if (localAddress) await this.adb.transport.removeReverseTunnel(localAddress);
9578
- await this.sendRequest(`reverse:killforward:${deviceAddress}`);
9579
- }
9580
- async removeAll() {
9581
- await this.adb.transport.clearReverseTunnels();
9582
- this.#deviceAddressToLocalAddress.clear();
9583
- await this.sendRequest("reverse:killforward-all");
9584
- }
9585
- }
9586
- function parsePort(value) {
9587
- if (!value || "0" === value) return;
9588
- return Number.parseInt(value, 10);
9589
- }
9590
- class AdbTcpIpService extends AdbServiceBase {
9591
- async getListenAddresses() {
9592
- const serviceListenAddresses = await this.adb.getProp("service.adb.listen_addrs");
9593
- const servicePort = await this.adb.getProp("service.adb.tcp.port");
9594
- const persistPort = await this.adb.getProp("persist.adb.tcp.port");
9595
- return {
9596
- serviceListenAddresses: "" != serviceListenAddresses ? serviceListenAddresses.split(",") : [],
9597
- servicePort: parsePort(servicePort),
9598
- persistPort: parsePort(persistPort)
9599
- };
9600
- }
9601
- async setPort(port) {
9602
- if (port <= 0) throw new TypeError(`Invalid port ${port}`);
9603
- const output = await this.adb.createSocketAndWait(`tcpip:${port}`);
9604
- if (output !== `restarting in TCP mode port: ${port}\n`) throw new Error(output);
9605
- return output;
9606
- }
9607
- async disable() {
9608
- const output = await this.adb.createSocketAndWait("usb:");
9609
- if ("restarting in USB mode\n" !== output) throw new Error(output);
9610
- return output;
9611
- }
9612
- }
9613
- const NOOP = ()=>{};
9614
- function unreachable(...args) {
9615
- throw new Error("Unreachable. Arguments:\n" + args.join("\n"));
9616
- }
9617
- function encodeAsciiUnchecked(value) {
9618
- const result = new Uint8Array(value.length);
9619
- for(let i = 0; i < value.length; i += 1)result[i] = value.charCodeAt(i);
9620
- return result;
9621
- }
9622
- function adbSyncEncodeId(value) {
9623
- const buffer = encodeAsciiUnchecked(value);
9624
- return getUint32LittleEndian(buffer, 0);
9625
- }
9626
- const AdbSyncResponseId = {
9627
- Entry: adbSyncEncodeId("DENT"),
9628
- Entry2: adbSyncEncodeId("DNT2"),
9629
- Lstat: adbSyncEncodeId("STAT"),
9630
- Stat: adbSyncEncodeId("STA2"),
9631
- Lstat2: adbSyncEncodeId("LST2"),
9632
- Done: adbSyncEncodeId("DONE"),
9633
- Data: adbSyncEncodeId("DATA"),
9634
- Ok: adbSyncEncodeId("OKAY"),
9635
- Fail: adbSyncEncodeId("FAIL")
9636
- };
9637
- class AdbSyncError extends Error {
9638
- }
9639
- const AdbSyncFailResponse = struct_struct({
9640
- message: string(u32)
9641
- }, {
9642
- littleEndian: true,
9643
- postDeserialize (value) {
9644
- throw new AdbSyncError(value.message);
9645
- }
9646
- });
9647
- async function adbSyncReadResponse(stream, id, type) {
9648
- if ("string" == typeof id) id = adbSyncEncodeId(id);
9649
- const buffer = await stream.readExactly(4);
9650
- switch(getUint32LittleEndian(buffer, 0)){
9651
- case AdbSyncResponseId.Fail:
9652
- await AdbSyncFailResponse.deserialize(stream);
9653
- throw new Error("Unreachable");
9654
- case id:
9655
- return await type.deserialize(stream);
9656
- default:
9657
- throw new Error(`Expected '${id}', but got '${decodeUtf8(buffer)}'`);
9658
- }
9659
- }
9660
- async function* adbSyncReadResponses(stream, id, type) {
9661
- if ("string" == typeof id) id = adbSyncEncodeId(id);
9662
- while(true){
9663
- const buffer = await stream.readExactly(4);
9664
- switch(getUint32LittleEndian(buffer, 0)){
9665
- case AdbSyncResponseId.Fail:
9666
- await AdbSyncFailResponse.deserialize(stream);
9667
- unreachable();
9668
- case AdbSyncResponseId.Done:
9669
- await stream.readExactly(type.size);
9670
- return;
9671
- case id:
9672
- yield await type.deserialize(stream);
9673
- break;
9674
- default:
9675
- throw new Error(`Expected '${id}' or '${AdbSyncResponseId.Done}', but got '${decodeUtf8(buffer)}'`);
9676
- }
9677
- }
9678
- }
9679
- const AdbSyncRequestId = {
9680
- List: adbSyncEncodeId("LIST"),
9681
- ListV2: adbSyncEncodeId("LIS2"),
9682
- Send: adbSyncEncodeId("SEND"),
9683
- SendV2: adbSyncEncodeId("SND2"),
9684
- Lstat: adbSyncEncodeId("STAT"),
9685
- Stat: adbSyncEncodeId("STA2"),
9686
- LstatV2: adbSyncEncodeId("LST2"),
9687
- Data: adbSyncEncodeId("DATA"),
9688
- Done: adbSyncEncodeId("DONE"),
9689
- Receive: adbSyncEncodeId("RECV")
9690
- };
9691
- const AdbSyncNumberRequest = struct_struct({
9692
- id: u32,
9693
- arg: u32
9694
- }, {
9695
- littleEndian: true
9696
- });
9697
- async function adbSyncWriteRequest(writable, id, value) {
9698
- if ("string" == typeof id) id = adbSyncEncodeId(id);
9699
- if ("number" == typeof value) return void await writable.write(AdbSyncNumberRequest.serialize({
9700
- id,
9701
- arg: value
9702
- }));
9703
- if ("string" == typeof value) value = encodeUtf8(value);
9704
- await writable.write(AdbSyncNumberRequest.serialize({
9705
- id,
9706
- arg: value.length
9707
- }));
9708
- await writable.write(value);
9709
- }
9710
- const LinuxFileType = {
9711
- Directory: 4,
9712
- File: 8,
9713
- Link: 10
9714
- };
9715
- const AdbSyncLstatResponse = struct_struct({
9716
- mode: u32,
9717
- size: u32,
9718
- mtime: u32
9719
- }, {
9720
- littleEndian: true,
9721
- extra: {
9722
- get type () {
9723
- return this.mode >> 12;
9724
- },
9725
- get permission () {
9726
- return 4095 & this.mode;
9727
- }
9728
- },
9729
- postDeserialize (value) {
9730
- if (0 === value.mode && 0 === value.size && 0 === value.mtime) throw new Error("lstat error");
9731
- return value;
9732
- }
9733
- });
9734
- const AdbSyncStatErrorCode = {
9735
- SUCCESS: 0,
9736
- EACCES: 13,
9737
- EEXIST: 17,
9738
- EFAULT: 14,
9739
- EFBIG: 27,
9740
- EINTR: 4,
9741
- EINVAL: 22,
9742
- EIO: 5,
9743
- EISDIR: 21,
9744
- ELOOP: 40,
9745
- EMFILE: 24,
9746
- ENAMETOOLONG: 36,
9747
- ENFILE: 23,
9748
- ENOENT: 2,
9749
- ENOMEM: 12,
9750
- ENOSPC: 28,
9751
- ENOTDIR: 20,
9752
- EOVERFLOW: 75,
9753
- EPERM: 1,
9754
- EROFS: 30,
9755
- ETXTBSY: 26
9756
- };
9757
- const AdbSyncStatErrorName = /* #__PURE__ */ (()=>Object.fromEntries(Object.entries(AdbSyncStatErrorCode).map(([key, value])=>[
9758
- value,
9759
- key
9760
- ])))();
9761
- const AdbSyncStatResponse = struct_struct({
9762
- error: u32(),
9763
- dev: u64,
9764
- ino: u64,
9765
- mode: u32,
9766
- nlink: u32,
9767
- uid: u32,
9768
- gid: u32,
9769
- size: u64,
9770
- atime: u64,
9771
- mtime: u64,
9772
- ctime: u64
9773
- }, {
9774
- littleEndian: true,
9775
- extra: {
9776
- get type () {
9777
- return this.mode >> 12;
9778
- },
9779
- get permission () {
9780
- return 4095 & this.mode;
9781
- }
9782
- },
9783
- postDeserialize (value) {
9784
- if (value.error) throw new Error(AdbSyncStatErrorName[value.error]);
9785
- return value;
9786
- }
9787
- });
9788
- async function adbSyncLstat(socket, path, v2) {
9789
- const locked = await socket.lock();
9790
- try {
9791
- if (v2) {
9792
- await adbSyncWriteRequest(locked, AdbSyncRequestId.LstatV2, path);
9793
- return await adbSyncReadResponse(locked, AdbSyncResponseId.Lstat2, AdbSyncStatResponse);
9794
- }
9795
- {
9796
- await adbSyncWriteRequest(locked, AdbSyncRequestId.Lstat, path);
9797
- const response = await adbSyncReadResponse(locked, AdbSyncResponseId.Lstat, AdbSyncLstatResponse);
9798
- return {
9799
- mode: response.mode,
9800
- size: BigInt(response.size),
9801
- mtime: BigInt(response.mtime),
9802
- get type () {
9803
- return response.type;
9804
- },
9805
- get permission () {
9806
- return response.permission;
9807
- }
9808
- };
9809
- }
9810
- } finally{
9811
- locked.release();
9812
- }
9813
- }
9814
- async function adbSyncStat(socket, path) {
9815
- const locked = await socket.lock();
9816
- try {
9817
- await adbSyncWriteRequest(locked, AdbSyncRequestId.Stat, path);
9818
- return await adbSyncReadResponse(locked, AdbSyncResponseId.Stat, AdbSyncStatResponse);
9819
- } finally{
9820
- locked.release();
9821
- }
9822
- }
9823
- const AdbSyncEntryResponse = extend(AdbSyncLstatResponse, {
9824
- name: string(u32)
9825
- });
9826
- const AdbSyncEntry2Response = extend(AdbSyncStatResponse, {
9827
- name: string(u32)
9828
- });
9829
- async function* adbSyncOpenDirV2(socket, path) {
9830
- const locked = await socket.lock();
9831
- try {
9832
- await adbSyncWriteRequest(locked, AdbSyncRequestId.ListV2, path);
9833
- for await (const item of adbSyncReadResponses(locked, AdbSyncResponseId.Entry2, AdbSyncEntry2Response))if (item.error === AdbSyncStatErrorCode.SUCCESS) yield item;
9834
- } finally{
9835
- locked.release();
9836
- }
9837
- }
9838
- async function* adbSyncOpenDirV1(socket, path) {
9839
- const locked = await socket.lock();
9840
- try {
9841
- await adbSyncWriteRequest(locked, AdbSyncRequestId.List, path);
9842
- for await (const item of adbSyncReadResponses(locked, AdbSyncResponseId.Entry, AdbSyncEntryResponse))yield item;
9843
- } finally{
9844
- locked.release();
9845
- }
9846
- }
9847
- async function* adbSyncOpenDir(socket, path, v2) {
9848
- if (v2) yield* adbSyncOpenDirV2(socket, path);
9849
- else for await (const item of adbSyncOpenDirV1(socket, path))yield {
9850
- mode: item.mode,
9851
- size: BigInt(item.size),
9852
- mtime: BigInt(item.mtime),
9853
- get type () {
9854
- return item.type;
9855
- },
9856
- get permission () {
9857
- return item.permission;
9858
- },
9859
- name: item.name
9860
- };
9861
- }
9862
- const AdbSyncDataResponse = struct_struct({
9863
- data: buffer_buffer(u32)
9864
- }, {
9865
- littleEndian: true
9866
- });
9867
- async function* adbSyncPullGenerator(socket, path) {
9868
- const locked = await socket.lock();
9869
- let done = false;
9870
- try {
9871
- await adbSyncWriteRequest(locked, AdbSyncRequestId.Receive, path);
9872
- for await (const packet of adbSyncReadResponses(locked, AdbSyncResponseId.Data, AdbSyncDataResponse))yield packet.data;
9873
- done = true;
9874
- } catch (e) {
9875
- done = true;
9876
- throw e;
9877
- } finally{
9878
- if (!done) for await (const packet of adbSyncReadResponses(locked, AdbSyncResponseId.Data, AdbSyncDataResponse));
9879
- locked.release();
9880
- }
9881
- }
9882
- function adbSyncPull(socket, path) {
9883
- return stream_ReadableStream.from(adbSyncPullGenerator(socket, path));
9884
- }
9885
- class BufferCombiner {
9886
- #capacity;
9887
- #buffer;
9888
- #offset;
9889
- #available;
9890
- constructor(size){
9891
- this.#capacity = size;
9892
- this.#buffer = new Uint8Array(size);
9893
- this.#offset = 0;
9894
- this.#available = size;
9895
- }
9896
- *push(data) {
9897
- let offset = 0;
9898
- let available = data.length;
9899
- if (0 !== this.#offset) if (available >= this.#available) {
9900
- this.#buffer.set(data.subarray(0, this.#available), this.#offset);
9901
- offset += this.#available;
9902
- available -= this.#available;
9903
- yield this.#buffer;
9904
- this.#offset = 0;
9905
- this.#available = this.#capacity;
9906
- if (0 === available) return;
9907
- } else {
9908
- this.#buffer.set(data, this.#offset);
9909
- this.#offset += available;
9910
- this.#available -= available;
9911
- return;
9912
- }
9913
- while(available >= this.#capacity){
9914
- const end = offset + this.#capacity;
9915
- yield data.subarray(offset, end);
9916
- offset = end;
9917
- available -= this.#capacity;
9918
- }
9919
- if (available > 0) {
9920
- this.#buffer.set(data.subarray(offset), this.#offset);
9921
- this.#offset += available;
9922
- this.#available -= available;
9923
- }
9924
- }
9925
- flush() {
9926
- if (0 === this.#offset) return;
9927
- const output = this.#buffer.subarray(0, this.#offset);
9928
- this.#offset = 0;
9929
- this.#available = this.#capacity;
9930
- return output;
9931
- }
9932
- }
9933
- class DistributionStream extends TransformStream {
9934
- constructor(size, combine = false){
9935
- const combiner = combine ? new BufferCombiner(size) : void 0;
9936
- super({
9937
- async transform (chunk, controller) {
9938
- await tryConsume(chunk, async (chunk)=>{
9939
- if (combiner) for (const buffer of combiner.push(chunk))await consumable_Consumable.ReadableStream.enqueue(controller, buffer);
9940
- else {
9941
- let offset = 0;
9942
- let available = chunk.length;
9943
- while(available > 0){
9944
- const end = offset + size;
9945
- await consumable_Consumable.ReadableStream.enqueue(controller, chunk.subarray(offset, end));
9946
- offset = end;
9947
- available -= size;
9948
- }
9949
- }
9950
- });
8223
+ return source.start?.(wrappedController);
9951
8224
  },
9952
- flush (controller) {
9953
- if (combiner) {
9954
- const data = combiner.flush();
9955
- if (data) controller.enqueue(data);
9956
- }
9957
- }
9958
- });
9959
- }
9960
- }
9961
- const ADB_SYNC_MAX_PACKET_SIZE = 65536;
9962
- const AdbSyncOkResponse = struct_struct({
9963
- unused: u32
9964
- }, {
9965
- littleEndian: true
9966
- });
9967
- async function pipeFileData(locked, file, packetSize, mtime) {
9968
- const abortController = new stream_AbortController();
9969
- file.pipeThrough(new DistributionStream(packetSize, true)).pipeTo(new MaybeConsumableWritableStream({
9970
- write (chunk) {
9971
- return adbSyncWriteRequest(locked, AdbSyncRequestId.Data, chunk);
9972
- }
9973
- }), {
9974
- signal: abortController.signal
9975
- }).then(async ()=>{
9976
- await adbSyncWriteRequest(locked, AdbSyncRequestId.Done, mtime);
9977
- await locked.flush();
9978
- }, NOOP);
9979
- await adbSyncReadResponse(locked, AdbSyncResponseId.Ok, AdbSyncOkResponse).catch((e)=>{
9980
- abortController.abort();
9981
- throw e;
9982
- });
9983
- }
9984
- async function adbSyncPushV1({ socket, filename, file, type = LinuxFileType.File, permission = 438, mtime = Date.now() / 1000 | 0, packetSize = ADB_SYNC_MAX_PACKET_SIZE }) {
9985
- const locked = await socket.lock();
9986
- try {
9987
- const mode = type << 12 | permission;
9988
- const pathAndMode = `${filename},${mode.toString()}`;
9989
- await adbSyncWriteRequest(locked, AdbSyncRequestId.Send, pathAndMode);
9990
- await pipeFileData(locked, file, packetSize, mtime);
9991
- } finally{
9992
- locked.release();
9993
- }
9994
- }
9995
- const AdbSyncSendV2Flags = {
9996
- None: 0,
9997
- Brotli: 1,
9998
- Lz4: 2,
9999
- Zstd: 4,
10000
- DryRun: 0x80000000
10001
- };
10002
- const AdbSyncSendV2Request = struct_struct({
10003
- id: u32,
10004
- mode: u32,
10005
- flags: u32()
10006
- }, {
10007
- littleEndian: true
10008
- });
10009
- async function adbSyncPushV2({ socket, filename, file, type = LinuxFileType.File, permission = 438, mtime = Date.now() / 1000 | 0, packetSize = ADB_SYNC_MAX_PACKET_SIZE, dryRun = false }) {
10010
- const locked = await socket.lock();
10011
- try {
10012
- await adbSyncWriteRequest(locked, AdbSyncRequestId.SendV2, filename);
10013
- const mode = type << 12 | permission;
10014
- let flags = AdbSyncSendV2Flags.None;
10015
- if (dryRun) flags |= AdbSyncSendV2Flags.DryRun;
10016
- await locked.write(AdbSyncSendV2Request.serialize({
10017
- id: AdbSyncRequestId.SendV2,
10018
- mode,
10019
- flags
10020
- }));
10021
- await pipeFileData(locked, file, packetSize, mtime);
10022
- } finally{
10023
- locked.release();
10024
- }
10025
- }
10026
- function adbSyncPush(options) {
10027
- if (options.v2) return adbSyncPushV2(options);
10028
- if (options.dryRun) throw new Error("dryRun is not supported in v1");
10029
- return adbSyncPushV1(options);
10030
- }
10031
- class AutoResetEvent {
10032
- #set;
10033
- #queue = [];
10034
- constructor(initialSet = false){
10035
- this.#set = initialSet;
10036
- }
10037
- wait() {
10038
- if (!this.#set) {
10039
- this.#set = true;
10040
- if (0 === this.#queue.length) return Promise.resolve();
10041
- }
10042
- const resolver = new PromiseResolver();
10043
- this.#queue.push(resolver);
10044
- return resolver.promise;
10045
- }
10046
- notifyOne() {
10047
- if (0 !== this.#queue.length) this.#queue.pop().resolve();
10048
- else this.#set = false;
10049
- }
10050
- dispose() {
10051
- for (const item of this.#queue)item.reject(new Error("The AutoResetEvent has been disposed"));
10052
- this.#queue.length = 0;
10053
- }
10054
- }
10055
- class AdbSyncSocketLocked {
10056
- #writer;
10057
- #readable;
10058
- #socketLock;
10059
- #writeLock = new AutoResetEvent();
10060
- #combiner;
10061
- get position() {
10062
- return this.#readable.position;
10063
- }
10064
- constructor(writer, readable, bufferSize, lock){
10065
- this.#writer = writer;
10066
- this.#readable = readable;
10067
- this.#socketLock = lock;
10068
- this.#combiner = new BufferCombiner(bufferSize);
10069
- }
10070
- #write(buffer) {
10071
- return consumable_Consumable.WritableStream.write(this.#writer, buffer);
10072
- }
10073
- async flush() {
10074
- try {
10075
- await this.#writeLock.wait();
10076
- const buffer = this.#combiner.flush();
10077
- if (buffer) await this.#write(buffer);
10078
- } finally{
10079
- this.#writeLock.notifyOne();
10080
- }
10081
- }
10082
- async write(data) {
10083
- try {
10084
- await this.#writeLock.wait();
10085
- for (const buffer of this.#combiner.push(data))await this.#write(buffer);
10086
- } finally{
10087
- this.#writeLock.notifyOne();
10088
- }
10089
- }
10090
- async readExactly(length) {
10091
- await this.flush();
10092
- return await this.#readable.readExactly(length);
10093
- }
10094
- release() {
10095
- this.#combiner.flush();
10096
- this.#socketLock.notifyOne();
10097
- }
10098
- async close() {
10099
- await this.#readable.cancel();
10100
- }
10101
- }
10102
- class AdbSyncSocket {
10103
- #lock = new AutoResetEvent();
10104
- #socket;
10105
- #locked;
10106
- constructor(socket, bufferSize){
10107
- this.#socket = socket;
10108
- this.#locked = new AdbSyncSocketLocked(socket.writable.getWriter(), new BufferedReadableStream(socket.readable), bufferSize, this.#lock);
10109
- }
10110
- async lock() {
10111
- await this.#lock.wait();
10112
- return this.#locked;
10113
- }
10114
- async close() {
10115
- await this.#locked.close();
10116
- await this.#socket.close();
10117
- }
10118
- }
10119
- function dirname(path) {
10120
- const end = path.lastIndexOf("/");
10121
- if (-1 === end) throw new Error("Invalid path");
10122
- if (0 === end) return "/";
10123
- return path.substring(0, end);
10124
- }
10125
- class AdbSync {
10126
- _adb;
10127
- _socket;
10128
- #supportsStat;
10129
- #supportsListV2;
10130
- #fixedPushMkdir;
10131
- #supportsSendReceiveV2;
10132
- #needPushMkdirWorkaround;
10133
- get supportsStat() {
10134
- return this.#supportsStat;
10135
- }
10136
- get supportsListV2() {
10137
- return this.#supportsListV2;
10138
- }
10139
- get fixedPushMkdir() {
10140
- return this.#fixedPushMkdir;
10141
- }
10142
- get supportsSendReceiveV2() {
10143
- return this.#supportsSendReceiveV2;
10144
- }
10145
- get needPushMkdirWorkaround() {
10146
- return this.#needPushMkdirWorkaround;
10147
- }
10148
- constructor(adb, socket){
10149
- this._adb = adb;
10150
- this._socket = new AdbSyncSocket(socket, adb.maxPayloadSize);
10151
- this.#supportsStat = adb.canUseFeature(AdbFeature.StatV2);
10152
- this.#supportsListV2 = adb.canUseFeature(AdbFeature.ListV2);
10153
- this.#fixedPushMkdir = adb.canUseFeature(AdbFeature.FixedPushMkdir);
10154
- this.#supportsSendReceiveV2 = adb.canUseFeature(AdbFeature.SendReceiveV2);
10155
- this.#needPushMkdirWorkaround = this._adb.canUseFeature(AdbFeature.ShellV2) && !this.fixedPushMkdir;
10156
- }
10157
- async lstat(path) {
10158
- return await adbSyncLstat(this._socket, path, this.#supportsStat);
10159
- }
10160
- async stat(path) {
10161
- if (!this.#supportsStat) throw new Error("Not supported");
10162
- return await adbSyncStat(this._socket, path);
10163
- }
10164
- async isDirectory(path) {
10165
- try {
10166
- await this.lstat(path + "/");
10167
- return true;
10168
- } catch {
10169
- return false;
10170
- }
10171
- }
10172
- opendir(path) {
10173
- return adbSyncOpenDir(this._socket, path, this.supportsListV2);
10174
- }
10175
- async readdir(path) {
10176
- const results = [];
10177
- for await (const entry of this.opendir(path))results.push(entry);
10178
- return results;
10179
- }
10180
- read(filename) {
10181
- return adbSyncPull(this._socket, filename);
10182
- }
10183
- async write(options) {
10184
- if (this.needPushMkdirWorkaround) await this._adb.subprocess.noneProtocol.spawnWait([
10185
- "mkdir",
10186
- "-p",
10187
- escapeArg(dirname(options.filename))
10188
- ]);
10189
- await adbSyncPush({
10190
- v2: this.supportsSendReceiveV2,
10191
- socket: this._socket,
10192
- ...options
10193
- });
10194
- }
10195
- lockSocket() {
10196
- return this._socket.lock();
10197
- }
10198
- dispose() {
10199
- return this._socket.close();
10200
- }
10201
- }
10202
- const Version = struct_struct({
10203
- version: u32
10204
- }, {
10205
- littleEndian: true
10206
- });
10207
- const AdbFrameBufferV1 = struct_struct({
10208
- bpp: u32,
10209
- size: u32,
10210
- width: u32,
10211
- height: u32,
10212
- red_offset: u32,
10213
- red_length: u32,
10214
- blue_offset: u32,
10215
- blue_length: u32,
10216
- green_offset: u32,
10217
- green_length: u32,
10218
- alpha_offset: u32,
10219
- alpha_length: u32,
10220
- data: buffer_buffer("size")
10221
- }, {
10222
- littleEndian: true
10223
- });
10224
- const AdbFrameBufferV2 = struct_struct({
10225
- bpp: u32,
10226
- colorSpace: u32,
10227
- size: u32,
10228
- width: u32,
10229
- height: u32,
10230
- red_offset: u32,
10231
- red_length: u32,
10232
- blue_offset: u32,
10233
- blue_length: u32,
10234
- green_offset: u32,
10235
- green_length: u32,
10236
- alpha_offset: u32,
10237
- alpha_length: u32,
10238
- data: buffer_buffer("size")
10239
- }, {
10240
- littleEndian: true
10241
- });
10242
- class AdbFrameBufferError extends Error {
10243
- constructor(message, options){
10244
- super(message, options);
10245
- }
10246
- }
10247
- class AdbFrameBufferUnsupportedVersionError extends AdbFrameBufferError {
10248
- constructor(version){
10249
- super(`Unsupported FrameBuffer version ${version}`);
10250
- }
10251
- }
10252
- class AdbFrameBufferForbiddenError extends AdbFrameBufferError {
10253
- constructor(){
10254
- super("FrameBuffer is disabled by current app");
10255
- }
10256
- }
10257
- async function framebuffer(adb) {
10258
- const socket = await adb.createSocket("framebuffer:");
10259
- const stream = new BufferedReadableStream(socket.readable);
10260
- let version;
10261
- try {
10262
- ({ version } = await Version.deserialize(stream));
10263
- } catch (e) {
10264
- if (e instanceof StructEmptyError) throw new AdbFrameBufferForbiddenError();
10265
- throw e;
10266
- }
10267
- switch(version){
10268
- case 1:
10269
- return await AdbFrameBufferV1.deserialize(stream);
10270
- case 2:
10271
- return await AdbFrameBufferV2.deserialize(stream);
10272
- default:
10273
- throw new AdbFrameBufferUnsupportedVersionError(version);
10274
- }
10275
- }
10276
- class Adb {
10277
- #transport;
10278
- get transport() {
10279
- return this.#transport;
10280
- }
10281
- get serial() {
10282
- return this.#transport.serial;
10283
- }
10284
- get maxPayloadSize() {
10285
- return this.#transport.maxPayloadSize;
10286
- }
10287
- get banner() {
10288
- return this.#transport.banner;
10289
- }
10290
- get disconnected() {
10291
- return this.#transport.disconnected;
10292
- }
10293
- get clientFeatures() {
10294
- return this.#transport.clientFeatures;
10295
- }
10296
- get deviceFeatures() {
10297
- return this.banner.features;
10298
- }
10299
- subprocess;
10300
- power;
10301
- reverse;
10302
- tcpip;
10303
- constructor(transport){
10304
- this.#transport = transport;
10305
- this.subprocess = new AdbSubprocessService(this);
10306
- this.power = new AdbPower(this);
10307
- this.reverse = new AdbReverseService(this);
10308
- this.tcpip = new AdbTcpIpService(this);
10309
- }
10310
- canUseFeature(feature) {
10311
- return this.clientFeatures.includes(feature) && this.deviceFeatures.includes(feature);
10312
- }
10313
- async createSocket(service) {
10314
- return this.#transport.connect(service);
10315
- }
10316
- async createSocketAndWait(service) {
10317
- const socket = await this.createSocket(service);
10318
- return await socket.readable.pipeThrough(new TextDecoderStream()).pipeThrough(new ConcatStringStream());
10319
- }
10320
- getProp(key) {
10321
- return this.subprocess.noneProtocol.spawnWaitText([
10322
- "getprop",
10323
- key
10324
- ]).then((output)=>output.trim());
10325
- }
10326
- rm(filenames, options) {
10327
- const args = [
10328
- "rm"
10329
- ];
10330
- if (options?.recursive) args.push("-r");
10331
- if (options?.force) args.push("-f");
10332
- if (Array.isArray(filenames)) for (const filename of filenames)args.push(escapeArg(filename));
10333
- else args.push(escapeArg(filenames));
10334
- args.push("</dev/null");
10335
- return this.subprocess.noneProtocol.spawnWaitText(args);
10336
- }
10337
- async sync() {
10338
- const socket = await this.createSocket("sync:");
10339
- return new AdbSync(this, socket);
10340
- }
10341
- async framebuffer() {
10342
- return framebuffer(this);
10343
- }
10344
- async close() {
10345
- await this.#transport.close();
10346
- }
10347
- }
10348
- const AdbBannerKey = {
10349
- Product: "ro.product.name",
10350
- Model: "ro.product.model",
10351
- Device: "ro.product.device",
10352
- Features: "features"
10353
- };
10354
- class AdbBanner {
10355
- static parse(banner) {
10356
- let state;
10357
- let product;
10358
- let model;
10359
- let device;
10360
- let features = [];
10361
- const pieces = banner.split("::");
10362
- if (pieces.length > 1) {
10363
- state = pieces[0].trim() || void 0;
10364
- const props = pieces[1];
10365
- for (const prop of props.split(";")){
10366
- if (!prop) continue;
10367
- const keyValue = prop.split("=");
10368
- if (2 !== keyValue.length) continue;
10369
- const [key, value] = keyValue;
10370
- switch(key){
10371
- case AdbBannerKey.Product:
10372
- product = value;
10373
- break;
10374
- case AdbBannerKey.Model:
10375
- model = value;
10376
- break;
10377
- case AdbBannerKey.Device:
10378
- device = value;
10379
- break;
10380
- case AdbBannerKey.Features:
10381
- features = value.split(",");
10382
- break;
10383
- }
10384
- }
10385
- }
10386
- return new AdbBanner(state, product, model, device, features);
10387
- }
10388
- #state;
10389
- get state() {
10390
- return this.#state;
10391
- }
10392
- #product;
10393
- get product() {
10394
- return this.#product;
10395
- }
10396
- #model;
10397
- get model() {
10398
- return this.#model;
10399
- }
10400
- #device;
10401
- get device() {
10402
- return this.#device;
10403
- }
10404
- #features = [];
10405
- get features() {
10406
- return this.#features;
10407
- }
10408
- constructor(state, product, model, device, features){
10409
- this.#state = state;
10410
- this.#product = product;
10411
- this.#model = model;
10412
- this.#device = device;
10413
- this.#features = features;
10414
- }
10415
- }
10416
- const stream_OKAY = encodeUtf8("OKAY");
10417
- const FAIL = encodeUtf8("FAIL");
10418
- class AdbServerStream {
10419
- #connection;
10420
- #buffered;
10421
- #writer;
10422
- constructor(connection){
10423
- this.#connection = connection;
10424
- this.#buffered = new BufferedReadableStream(connection.readable);
10425
- this.#writer = connection.writable.getWriter();
10426
- }
10427
- readExactly(length) {
10428
- return this.#buffered.readExactly(length);
10429
- }
10430
- readString = bipedal(function*(then) {
10431
- const data = yield* then(this.readExactly(4));
10432
- const length = hexToNumber(data);
10433
- if (0 === length) return "";
10434
- {
10435
- const decoder = new utils_TextDecoder();
10436
- let result = "";
10437
- const iterator = this.#buffered.iterateExactly(length);
10438
- while(true){
10439
- const { done, value } = iterator.next();
10440
- if (done) break;
10441
- result += decoder.decode((yield* then(value)), {
10442
- stream: true
10443
- });
10444
- }
10445
- result += decoder.decode();
10446
- return result;
10447
- }
10448
- });
10449
- async readOkay() {
10450
- const response = await this.readExactly(4);
10451
- if (sequenceEqual(response, stream_OKAY)) return;
10452
- if (sequenceEqual(response, FAIL)) {
10453
- const reason = await this.readString();
10454
- throw new Error(reason);
10455
- }
10456
- throw new Error(`Unexpected response: ${decodeUtf8(response)}`);
10457
- }
10458
- async writeString(value) {
10459
- const encoded = encodeUtf8(value);
10460
- const buffer = new Uint8Array(4 + encoded.length);
10461
- write4HexDigits(buffer, 0, encoded.length);
10462
- buffer.set(encoded, 4);
10463
- await this.#writer.write(buffer);
10464
- }
10465
- release() {
10466
- this.#writer.releaseLock();
10467
- return {
10468
- readable: this.#buffered.release(),
10469
- writable: this.#connection.writable,
10470
- closed: this.#connection.closed,
10471
- close: ()=>this.#connection.close()
10472
- };
10473
- }
10474
- async dispose() {
10475
- tryCancel(this.#buffered);
10476
- tryClose(this.#writer);
10477
- await this.#connection.close();
10478
- }
10479
- }
10480
- class NetworkError extends Error {
10481
- constructor(message){
10482
- super(message);
10483
- this.name = "NetworkError";
10484
- }
10485
- }
10486
- class UnauthorizedError extends Error {
10487
- constructor(message){
10488
- super(message);
10489
- this.name = "UnauthorizedError";
10490
- }
10491
- }
10492
- class AlreadyConnectedError extends Error {
10493
- constructor(message){
10494
- super(message);
10495
- this.name = "AlreadyConnectedError";
10496
- }
10497
- }
10498
- class WirelessCommands {
10499
- #client;
10500
- constructor(client){
10501
- this.#client = client;
10502
- }
10503
- async pair(address, password) {
10504
- const connection = await this.#client.createConnection(`host:pair:${password}:${address}`);
10505
- try {
10506
- const response = await connection.readExactly(4);
10507
- if (sequenceEqual(response, FAIL)) throw new Error(await connection.readString());
10508
- const length = hexToNumber(response);
10509
- await connection.readExactly(length);
10510
- } finally{
10511
- await connection.dispose();
10512
- }
10513
- }
10514
- async connect(address) {
10515
- const connection = await this.#client.createConnection(`host:connect:${address}`);
10516
- try {
10517
- const response = await connection.readString();
10518
- switch(response){
10519
- case `already connected to ${address}`:
10520
- throw new AlreadyConnectedError(response);
10521
- case `failed to connect to ${address}`:
10522
- case `failed to authenticate to ${address}`:
10523
- throw new UnauthorizedError(response);
10524
- case `connected to ${address}`:
10525
- return;
10526
- default:
10527
- throw new NetworkError(response);
10528
- }
10529
- } finally{
10530
- await connection.dispose();
10531
- }
10532
- }
10533
- async disconnect(address) {
10534
- const connection = await this.#client.createConnection(`host:disconnect:${address}`);
10535
- try {
10536
- await connection.readString();
10537
- } finally{
10538
- await connection.dispose();
10539
- }
10540
- }
10541
- }
10542
- class MDnsCommands {
10543
- #client;
10544
- constructor(client){
10545
- this.#client = client;
10546
- }
10547
- async check() {
10548
- const connection = await this.#client.createConnection("host:mdns:check");
10549
- try {
10550
- const response = await connection.readString();
10551
- return !response.startsWith("ERROR:");
10552
- } finally{
10553
- await connection.dispose();
10554
- }
10555
- }
10556
- async getServices() {
10557
- const connection = await this.#client.createConnection("host:mdns:services");
10558
- try {
10559
- const response = await connection.readString();
10560
- return response.split("\n").filter(Boolean).map((line)=>{
10561
- const parts = line.split("\t");
10562
- return {
10563
- name: parts[0],
10564
- service: parts[1],
10565
- address: parts[2]
10566
- };
10567
- });
10568
- } finally{
10569
- await connection.dispose();
10570
- }
10571
- }
10572
- }
10573
- class EventEmitter {
10574
- listeners = [];
10575
- constructor(){
10576
- this.event = this.event.bind(this);
10577
- }
10578
- addEventListener(info) {
10579
- this.listeners.push(info);
10580
- const remove = ()=>{
10581
- const index = this.listeners.indexOf(info);
10582
- if (-1 !== index) this.listeners.splice(index, 1);
10583
- };
10584
- remove.dispose = remove;
10585
- return remove;
10586
- }
10587
- event = (listener, thisArg, ...args)=>{
10588
- const info = {
10589
- listener: listener,
10590
- thisArg,
10591
- args
10592
- };
10593
- return this.addEventListener(info);
10594
- };
10595
- fire(e) {
10596
- for (const info of this.listeners.slice())info.listener.call(info.thisArg, e, ...info.args);
10597
- }
10598
- dispose() {
10599
- this.listeners.length = 0;
10600
- }
10601
- }
10602
- const Undefined = Symbol("undefined");
10603
- class StickyEventEmitter extends EventEmitter {
10604
- #value = Undefined;
10605
- addEventListener(info) {
10606
- if (this.#value !== Undefined) info.listener.call(info.thisArg, this.#value, ...info.args);
10607
- return super.addEventListener(info);
10608
- }
10609
- fire(e) {
10610
- this.#value = e;
10611
- super.fire(e);
10612
- }
10613
- }
10614
- const { setInterval: ref_setInterval, clearInterval: ref_clearInterval } = globalThis;
10615
- class Ref {
10616
- #intervalId;
10617
- constructor(options){
10618
- if (!options?.unref) this.ref();
10619
- }
10620
- ref() {
10621
- this.#intervalId = ref_setInterval(()=>{}, 60000);
10622
- }
10623
- unref() {
10624
- if (this.#intervalId) {
10625
- ref_clearInterval(this.#intervalId);
10626
- this.#intervalId = void 0;
10627
- }
10628
- }
10629
- }
10630
- function unorderedRemove(array, index) {
10631
- if (index < 0 || index >= array.length) return;
10632
- array[index] = array[array.length - 1];
10633
- array.length -= 1;
10634
- }
10635
- function filterDeviceStates(devices, states) {
10636
- return devices.filter((device)=>states.includes(device.state));
10637
- }
10638
- class AdbServerDeviceObserverOwner {
10639
- current = [];
10640
- #client;
10641
- #stream;
10642
- #observers = [];
10643
- constructor(client){
10644
- this.#client = client;
10645
- }
10646
- async #receive(stream) {
10647
- const response = await stream.readString();
10648
- const next = AdbServerClient.parseDeviceList(response);
10649
- const removed = this.current.slice();
10650
- const added = [];
10651
- for (const nextDevice of next){
10652
- const index = removed.findIndex((device)=>device.transportId === nextDevice.transportId);
10653
- if (-1 === index) {
10654
- added.push(nextDevice);
10655
- continue;
10656
- }
10657
- unorderedRemove(removed, index);
10658
- }
10659
- this.current = next;
10660
- if (added.length) for (const observer of this.#observers){
10661
- const filtered = filterDeviceStates(added, observer.includeStates);
10662
- if (filtered.length) observer.onDeviceAdd.fire(filtered);
10663
- }
10664
- if (removed.length) for (const observer of this.#observers){
10665
- const filtered = filterDeviceStates(removed, observer.includeStates);
10666
- if (filtered.length) observer.onDeviceRemove.fire(removed);
10667
- }
10668
- for (const observer of this.#observers){
10669
- const filtered = filterDeviceStates(this.current, observer.includeStates);
10670
- observer.onListChange.fire(filtered);
10671
- }
10672
- }
10673
- async #receiveLoop(stream) {
10674
- try {
10675
- while(true)await this.#receive(stream);
10676
- } catch (e) {
10677
- this.#stream = void 0;
10678
- for (const observer of this.#observers)observer.onError.fire(e);
10679
- }
10680
- }
10681
- async #connect() {
10682
- const stream = await this.#client.createConnection("host:track-devices-l", {
10683
- unref: true
10684
- });
10685
- await this.#receive(stream);
10686
- this.#receiveLoop(stream);
10687
- return stream;
10688
- }
10689
- async #handleObserverStop(stream) {
10690
- if (0 === this.#observers.length) {
10691
- this.#stream = void 0;
10692
- await stream.dispose();
10693
- }
10694
- }
10695
- async createObserver(options) {
10696
- options?.signal?.throwIfAborted();
10697
- let current = [];
10698
- const onDeviceAdd = new EventEmitter();
10699
- const onDeviceRemove = new EventEmitter();
10700
- const onListChange = new StickyEventEmitter();
10701
- const onError = new StickyEventEmitter();
10702
- const includeStates = options?.includeStates ?? [
10703
- "device",
10704
- "unauthorized"
10705
- ];
10706
- const observer = {
10707
- includeStates,
10708
- onDeviceAdd,
10709
- onDeviceRemove,
10710
- onListChange,
10711
- onError
10712
- };
10713
- this.#observers.push(observer);
10714
- onListChange.event((value)=>current = value);
10715
- let stream;
10716
- if (this.#stream) {
10717
- stream = await this.#stream;
10718
- onListChange.fire(filterDeviceStates(this.current, includeStates));
10719
- } else {
10720
- this.#stream = this.#connect();
10721
- try {
10722
- stream = await this.#stream;
10723
- } catch (e) {
10724
- this.#stream = void 0;
10725
- throw e;
10726
- }
10727
- }
10728
- const ref = new Ref(options);
10729
- const stop = async ()=>{
10730
- unorderedRemove(this.#observers, this.#observers.indexOf(observer));
10731
- await this.#handleObserverStop(stream);
10732
- ref.unref();
10733
- };
10734
- if (options?.signal) {
10735
- if (options.signal.aborted) {
10736
- await stop();
10737
- throw options.signal.reason;
10738
- }
10739
- options.signal.addEventListener("abort", ()=>void stop());
10740
- }
10741
- return {
10742
- onDeviceAdd: onDeviceAdd.event,
10743
- onDeviceRemove: onDeviceRemove.event,
10744
- onListChange: onListChange.event,
10745
- onError: onError.event,
10746
- get current () {
10747
- return current;
8225
+ pull () {
8226
+ return source.pull?.(wrappedController);
10748
8227
  },
10749
- stop
10750
- };
10751
- }
10752
- }
10753
- const ADB_SERVER_DEFAULT_FEATURES = /* #__PURE__ */ (()=>[
10754
- AdbFeature.ShellV2,
10755
- AdbFeature.Cmd,
10756
- AdbFeature.StatV2,
10757
- AdbFeature.ListV2,
10758
- AdbFeature.FixedPushMkdir,
10759
- "apex",
10760
- AdbFeature.Abb,
10761
- "fixed_push_symlink_timestamp",
10762
- AdbFeature.AbbExec,
10763
- "remount_shell",
10764
- "track_app",
10765
- AdbFeature.SendReceiveV2,
10766
- "sendrecv_v2_brotli",
10767
- "sendrecv_v2_lz4",
10768
- "sendrecv_v2_zstd",
10769
- "sendrecv_v2_dry_run_send"
10770
- ])();
10771
- class AdbServerTransport {
10772
- #client;
10773
- serial;
10774
- transportId;
10775
- maxPayloadSize = 1048576;
10776
- banner;
10777
- #sockets = [];
10778
- #closed = new PromiseResolver();
10779
- #disconnected;
10780
- get disconnected() {
10781
- return this.#disconnected;
10782
- }
10783
- get clientFeatures() {
10784
- return ADB_SERVER_DEFAULT_FEATURES;
10785
- }
10786
- constructor(client, serial, banner, transportId, disconnected){
10787
- this.#client = client;
10788
- this.serial = serial;
10789
- this.banner = banner;
10790
- this.transportId = transportId;
10791
- this.#disconnected = Promise.race([
10792
- this.#closed.promise,
10793
- disconnected
10794
- ]);
10795
- }
10796
- async connect(service) {
10797
- const socket = await this.#client.createDeviceConnection({
10798
- transportId: this.transportId
10799
- }, service);
10800
- this.#sockets.push(socket);
10801
- return socket;
10802
- }
10803
- async addReverseTunnel(handler, address) {
10804
- return await this.#client.connector.addReverseTunnel(handler, address);
10805
- }
10806
- async removeReverseTunnel(address) {
10807
- await this.#client.connector.removeReverseTunnel(address);
10808
- }
10809
- async clearReverseTunnels() {
10810
- await this.#client.connector.clearReverseTunnels();
10811
- }
10812
- async close() {
10813
- for (const socket of this.#sockets)await socket.close();
10814
- this.#sockets.length = 0;
10815
- this.#closed.resolve();
8228
+ cancel (reason) {
8229
+ return source.cancel?.(reason);
8230
+ }
8231
+ }, wrappedStrategy);
10816
8232
  }
10817
8233
  }
10818
- class AdbServerClient {
10819
- static NetworkError = NetworkError;
10820
- static UnauthorizedError = UnauthorizedError;
10821
- static AlreadyConnectedError = AlreadyConnectedError;
10822
- static parseDeviceList(value, includeStates = [
10823
- "device",
10824
- "unauthorized"
10825
- ]) {
10826
- const devices = [];
10827
- for (const line of value.split("\n")){
10828
- if (!line) continue;
10829
- const parts = line.split(" ").filter(Boolean);
10830
- const serial = parts[0];
10831
- const state = parts[1];
10832
- if (!includeStates.includes(state)) continue;
10833
- let product;
10834
- let model;
10835
- let device;
10836
- let transportId;
10837
- for(let i = 2; i < parts.length; i += 1){
10838
- const [key, value] = parts[i].split(":");
10839
- switch(key){
10840
- case "product":
10841
- product = value;
10842
- break;
10843
- case "model":
10844
- model = value;
10845
- break;
10846
- case "device":
10847
- device = value;
10848
- break;
10849
- case "transport_id":
10850
- transportId = BigInt(value);
10851
- break;
8234
+ class ConsumableWrapByteReadableStream extends streams_ReadableStream {
8235
+ constructor(stream, chunkSize, options){
8236
+ const reader = stream.getReader({
8237
+ mode: "byob"
8238
+ });
8239
+ let buffer = new ArrayBuffer(chunkSize);
8240
+ super({
8241
+ async pull (controller) {
8242
+ const { done, value } = await reader.read(new Uint8Array(buffer), {
8243
+ min: options?.min
8244
+ });
8245
+ if (value) {
8246
+ await ConsumableReadableStream.enqueue(controller, value);
8247
+ options?.onRead?.(value.byteLength);
10852
8248
  }
8249
+ if (done) return void controller.close();
8250
+ buffer = value.buffer;
8251
+ },
8252
+ cancel (reason) {
8253
+ return reader.cancel(reason);
10853
8254
  }
10854
- if (!transportId) throw new Error(`No transport id for device ${serial}`);
10855
- devices.push({
10856
- serial,
10857
- state,
10858
- authenticating: "unauthorized" === state,
10859
- product,
10860
- model,
10861
- device,
10862
- transportId
10863
- });
10864
- }
10865
- return devices;
10866
- }
10867
- static formatDeviceService(device, command) {
10868
- if (!device) return `host:${command}`;
10869
- if ("transportId" in device) return `host-transport-id:${device.transportId}:${command}`;
10870
- if ("serial" in device) return `host-serial:${device.serial}:${command}`;
10871
- if ("usb" in device) return `host-usb:${command}`;
10872
- if ("tcp" in device) return `host-local:${command}`;
10873
- throw new TypeError("Invalid device selector");
10874
- }
10875
- connector;
10876
- wireless = new WirelessCommands(this);
10877
- mDns = new MDnsCommands(this);
10878
- #observerOwner = new AdbServerDeviceObserverOwner(this);
10879
- constructor(connector){
10880
- this.connector = connector;
10881
- }
10882
- async createConnection(request, options) {
10883
- const connection = await this.connector.connect(options);
10884
- const stream = new AdbServerStream(connection);
10885
- try {
10886
- await stream.writeString(request);
10887
- } catch (e) {
10888
- await stream.dispose();
10889
- throw e;
10890
- }
10891
- try {
10892
- await raceSignal(()=>stream.readOkay(), options?.signal);
10893
- return stream;
10894
- } catch (e) {
10895
- await stream.dispose();
10896
- throw e;
10897
- }
10898
- }
10899
- async getVersion() {
10900
- const connection = await this.createConnection("host:version");
10901
- try {
10902
- const length = hexToNumber(await connection.readExactly(4));
10903
- const version = hexToNumber(await connection.readExactly(length));
10904
- return version;
10905
- } finally{
10906
- await connection.dispose();
10907
- }
10908
- }
10909
- async validateVersion(minimalVersion) {
10910
- const version = await this.getVersion();
10911
- if (version < minimalVersion) throw new Error(`adb server version (${version}) doesn't match this client (${minimalVersion})`);
10912
- }
10913
- async killServer() {
10914
- const connection = await this.createConnection("host:kill");
10915
- await connection.dispose();
10916
- }
10917
- async getServerFeatures() {
10918
- const connection = await this.createConnection("host:host-features");
10919
- try {
10920
- const response = await connection.readString();
10921
- return response.split(",");
10922
- } finally{
10923
- await connection.dispose();
10924
- }
8255
+ });
10925
8256
  }
10926
- async getDevices(includeStates = [
10927
- "device",
10928
- "unauthorized"
10929
- ]) {
10930
- const connection = await this.createConnection("host:devices-l");
10931
- try {
10932
- const response = await connection.readString();
10933
- return AdbServerClient.parseDeviceList(response, includeStates);
10934
- } finally{
10935
- await connection.dispose();
10936
- }
8257
+ }
8258
+ const { console: console } = globalThis;
8259
+ const createTask = /* #__PURE__ */ (()=>console?.createTask?.bind(console) ?? (()=>({
8260
+ run (callback) {
8261
+ return callback();
8262
+ }
8263
+ })))();
8264
+ const Brand = Symbol.for("Consumable.brand");
8265
+ class consumable_Consumable {
8266
+ static WritableStream = ConsumableWritableStream;
8267
+ static WrapWritableStream = ConsumableWrapWritableStream;
8268
+ static ReadableStream = ConsumableReadableStream;
8269
+ static WrapByteReadableStream = ConsumableWrapByteReadableStream;
8270
+ [Brand] = true;
8271
+ static [Symbol.hasInstance](value) {
8272
+ return !!value?.[Brand];
10937
8273
  }
10938
- async trackDevices(options) {
10939
- return this.#observerOwner.createObserver(options);
8274
+ #task;
8275
+ #resolver;
8276
+ value;
8277
+ consumed;
8278
+ constructor(value){
8279
+ this.#task = createTask("Consumable");
8280
+ this.value = value;
8281
+ this.#resolver = new PromiseResolver();
8282
+ this.consumed = this.#resolver.promise;
10940
8283
  }
10941
- async reconnectDevice(device) {
10942
- const connection = await this.createConnection("offline" === device ? "host:reconnect-offline" : AdbServerClient.formatDeviceService(device, "reconnect"));
10943
- try {
10944
- await connection.readString();
10945
- } finally{
10946
- await connection.dispose();
10947
- }
8284
+ consume() {
8285
+ this.#resolver.resolve();
10948
8286
  }
10949
- async getDeviceFeatures(device) {
10950
- const connection = await this.createDeviceConnection(device, "host:features");
10951
- const stream = new AdbServerStream(connection);
10952
- try {
10953
- const featuresString = await stream.readString();
10954
- const features = featuresString.split(",");
10955
- return {
10956
- transportId: connection.transportId,
10957
- features
10958
- };
10959
- } finally{
10960
- await stream.dispose();
10961
- }
8287
+ error(error) {
8288
+ this.#resolver.reject(error);
10962
8289
  }
10963
- async createDeviceConnection(device, service) {
10964
- let switchService;
10965
- let transportId;
10966
- if (device) if ("transportId" in device) {
10967
- switchService = `host:transport-id:${device.transportId}`;
10968
- transportId = device.transportId;
10969
- } else if ("serial" in device) {
10970
- await this.validateVersion(41);
10971
- switchService = `host:tport:serial:${device.serial}`;
10972
- } else if ("usb" in device) {
10973
- await this.validateVersion(41);
10974
- switchService = "host:tport:usb";
10975
- } else if ("tcp" in device) {
10976
- await this.validateVersion(41);
10977
- switchService = "host:tport:local";
10978
- } else throw new TypeError("Invalid device selector");
10979
- else {
10980
- await this.validateVersion(41);
10981
- switchService = "host:tport:any";
10982
- }
10983
- const connection = await this.createConnection(switchService);
10984
- try {
10985
- await connection.writeString(service);
10986
- } catch (e) {
10987
- await connection.dispose();
10988
- throw e;
10989
- }
8290
+ tryConsume(callback) {
10990
8291
  try {
10991
- if (void 0 === transportId) {
10992
- const array = await connection.readExactly(8);
10993
- transportId = getUint64LittleEndian(array, 0);
10994
- }
10995
- await connection.readOkay();
10996
- const socket = connection.release();
10997
- return {
10998
- transportId,
10999
- service,
11000
- readable: socket.readable,
11001
- writable: socket.writable,
11002
- get closed () {
11003
- return socket.closed;
11004
- },
11005
- async close () {
11006
- await socket.close();
11007
- }
11008
- };
8292
+ let result = this.#task.run(()=>callback(this.value));
8293
+ if (isPromiseLike(result)) result = result.then((value)=>{
8294
+ this.#resolver.resolve();
8295
+ return value;
8296
+ }, (e)=>{
8297
+ this.#resolver.reject(e);
8298
+ throw e;
8299
+ });
8300
+ else this.#resolver.resolve();
8301
+ return result;
11009
8302
  } catch (e) {
11010
- await connection.dispose();
8303
+ this.#resolver.reject(e);
11011
8304
  throw e;
11012
8305
  }
11013
8306
  }
11014
- async #waitForUnchecked(device, state, options) {
11015
- let type;
11016
- if (device) if ("transportId" in device) type = "any";
11017
- else if ("serial" in device) type = "any";
11018
- else if ("usb" in device) type = "usb";
11019
- else if ("tcp" in device) type = "local";
11020
- else throw new TypeError("Invalid device selector");
11021
- else type = "any";
11022
- const service = AdbServerClient.formatDeviceService(device, `wait-for-${type}-${state}`);
11023
- const connection = await this.createConnection(service, options);
11024
- try {
11025
- await connection.readOkay();
11026
- } finally{
11027
- await connection.dispose();
11028
- }
11029
- }
11030
- async waitFor(device, state, options) {
11031
- if ("disconnect" === state) await this.validateVersion(41);
11032
- return this.#waitForUnchecked(device, state, options);
11033
- }
11034
- async waitForDisconnect(transportId, options) {
11035
- const serverVersion = await this.getVersion();
11036
- if (serverVersion >= 41) return this.#waitForUnchecked({
11037
- transportId
11038
- }, "disconnect", options);
11039
- {
11040
- const observer = await this.trackDevices(options);
11041
- return new Promise((resolve, reject)=>{
11042
- observer.onDeviceRemove((devices)=>{
11043
- if (devices.some((device)=>device.transportId === transportId)) {
11044
- observer.stop();
11045
- resolve();
11046
- }
11047
- });
11048
- observer.onError((e)=>{
11049
- observer.stop();
11050
- reject(e);
11051
- });
11052
- });
8307
+ }
8308
+ function tryConsume(value, callback) {
8309
+ if (value instanceof consumable_Consumable) return value.tryConsume(callback);
8310
+ else return callback(value);
8311
+ }
8312
+ class MaybeConsumableWritableStream extends WritableStream {
8313
+ constructor(sink, strategy){
8314
+ let wrappedStrategy;
8315
+ if (strategy) {
8316
+ wrappedStrategy = {};
8317
+ if ("highWaterMark" in strategy) wrappedStrategy.highWaterMark = strategy.highWaterMark;
8318
+ if ("size" in strategy) wrappedStrategy.size = (chunk)=>strategy.size(chunk instanceof consumable_Consumable ? chunk.value : chunk);
11053
8319
  }
8320
+ super({
8321
+ start (controller) {
8322
+ return sink.start?.(controller);
8323
+ },
8324
+ write (chunk, controller) {
8325
+ return tryConsume(chunk, (chunk)=>sink.write?.(chunk, controller));
8326
+ },
8327
+ abort (reason) {
8328
+ return sink.abort?.(reason);
8329
+ },
8330
+ close () {
8331
+ return sink.close?.();
8332
+ }
8333
+ }, wrappedStrategy);
11054
8334
  }
11055
- async createTransport(device) {
11056
- const { transportId, features } = await this.getDeviceFeatures(device);
11057
- const devices = await this.getDevices();
11058
- const info = devices.find((device)=>device.transportId === transportId);
11059
- const banner = new AdbBanner(info?.state, info?.product, info?.model, info?.device, features);
11060
- const waitAbortController = new stream_AbortController();
11061
- const disconnected = this.waitForDisconnect(transportId, {
11062
- unref: true,
11063
- signal: waitAbortController.signal
11064
- });
11065
- const transport = new AdbServerTransport(this, info?.serial ?? "", banner, transportId, disconnected);
11066
- transport.disconnected.finally(()=>waitAbortController.abort());
11067
- return transport;
8335
+ }
8336
+ function findIndices(str, char) {
8337
+ const indices = [];
8338
+ let index = -1;
8339
+ while(-1 !== (index = str.indexOf(char, index + 1)))indices.push(index);
8340
+ return indices;
8341
+ }
8342
+ function decimalToNumber(input, start = 0, end = input.length) {
8343
+ if (start >= end) return;
8344
+ const negative = "-" === input.charAt(start);
8345
+ if (negative) {
8346
+ start += 1;
8347
+ if (start === end) return;
11068
8348
  }
11069
- async createAdb(device) {
11070
- const transport = await this.createTransport(device);
11071
- return new Adb(transport);
8349
+ let value = 0;
8350
+ for(; start < end; start += 1){
8351
+ const char = input.charCodeAt(start);
8352
+ if (char < 48 || char > 57) return;
8353
+ value = 10 * value + char - 48;
11072
8354
  }
8355
+ return negative ? -value : value;
11073
8356
  }
11074
- async function raceSignal(callback, ...signals) {
11075
- const abortPromise = new PromiseResolver();
11076
- function abort() {
11077
- abortPromise.reject(this.reason);
8357
+ function parseTcpSocketSpec(spec) {
8358
+ let port = decimalToNumber(spec);
8359
+ if (void 0 !== port) {
8360
+ if (port <= 0 || port > 65535) throw new Error(`bad port number ${port}`);
8361
+ return {
8362
+ port
8363
+ };
11078
8364
  }
11079
- try {
11080
- for (const signal of signals)if (signal) {
11081
- if (signal.aborted) throw signal.reason;
11082
- signal.addEventListener("abort", abort);
11083
- }
11084
- return await Promise.race([
11085
- callback(),
11086
- abortPromise.promise
11087
- ]);
11088
- } finally{
11089
- for (const signal of signals)if (signal) signal.removeEventListener("abort", abort);
8365
+ if (spec.startsWith("[")) {
8366
+ const end = spec.indexOf("]");
8367
+ if (end < 0) throw new Error(`bad IPv6 address ${spec}`);
8368
+ const host = spec.substring(1, end);
8369
+ const port = decimalToNumber(spec, end + 2);
8370
+ if (void 0 === port || port <= 0 || port > 65535) throw new Error(`bad port number ${port} in ${spec}`);
8371
+ return {
8372
+ host,
8373
+ port
8374
+ };
11090
8375
  }
8376
+ let host;
8377
+ port = void 0;
8378
+ const colons = findIndices(spec, ":");
8379
+ if (!spec.includes(".") && colons.length >= 2 && colons.length <= 7) host = spec;
8380
+ else if (0 === colons.length) host = spec;
8381
+ else if (1 === colons.length) {
8382
+ host = spec.substring(0, colons[0]);
8383
+ port = decimalToNumber(spec, colons[0] + 1);
8384
+ if (void 0 === port || port <= 0 || port > 65535) throw new Error(`bad port number ${port} in ${spec}`);
8385
+ }
8386
+ if (!host) throw new Error(`no host in ${spec}`);
8387
+ if (void 0 !== port) return {
8388
+ host,
8389
+ port
8390
+ };
8391
+ else return {
8392
+ host
8393
+ };
11091
8394
  }
11092
8395
  function nodeSocketToConnection(socket) {
11093
8396
  socket.setNoDelay(true);
11094
8397
  const closed = new Promise((resolve)=>{
11095
- socket.on("close", resolve);
8398
+ socket.once("close", resolve);
11096
8399
  });
11097
8400
  return {
11098
8401
  readable: new PushReadableStream((controller)=>{
@@ -11102,11 +8405,19 @@ function nodeSocketToConnection(socket) {
11102
8405
  await controller.enqueue(data);
11103
8406
  socket.resume();
11104
8407
  });
8408
+ socket.on("error", (e)=>{
8409
+ controller.error(e);
8410
+ });
11105
8411
  socket.on("end", ()=>{
11106
8412
  tryClose(controller);
11107
8413
  });
11108
8414
  }),
11109
8415
  writable: new MaybeConsumableWritableStream({
8416
+ start (controller) {
8417
+ socket.on("error", (e)=>{
8418
+ controller.error(e);
8419
+ });
8420
+ },
11110
8421
  write: (chunk)=>new Promise((resolve, reject)=>{
11111
8422
  socket.write(chunk, (err)=>{
11112
8423
  if (err) reject(err);
@@ -11122,17 +8433,99 @@ function nodeSocketToConnection(socket) {
11122
8433
  }
11123
8434
  };
11124
8435
  }
8436
+ const DefaultServerPort = 5037;
8437
+ const SocketTypes = {
8438
+ tcp: (spec)=>{
8439
+ const parsed = parseTcpSocketSpec(spec);
8440
+ return {
8441
+ host: parsed.host ?? "localhost",
8442
+ port: parsed.port ?? DefaultServerPort
8443
+ };
8444
+ },
8445
+ vsock: ()=>{
8446
+ throw new Error("vsock is not supported in Node.js");
8447
+ },
8448
+ local: (spec)=>{
8449
+ if ("win32" === platform()) throw new Error("socket type local is unavailable on this platform");
8450
+ return {
8451
+ path: spec
8452
+ };
8453
+ },
8454
+ localabstract: ()=>{
8455
+ throw new Error("localabstract is not supported in Node.js");
8456
+ },
8457
+ localfilesystem: (spec)=>{
8458
+ if ("win32" === platform()) throw new Error("socket type localfilesystem is unavailable on this platform");
8459
+ return {
8460
+ path: spec
8461
+ };
8462
+ }
8463
+ };
8464
+ function parseSocketSpec(spec) {
8465
+ for (const [type, parser] of Object.entries(SocketTypes))if (spec.startsWith(type + ":")) return parser(spec.substring(type.length + 1));
8466
+ throw new Error(`unknown socket specification: ${spec}`);
8467
+ }
8468
+ function getServerSocketSpec() {
8469
+ const value = process.env["ADB_SERVER_SOCKET"];
8470
+ if (value) return parseSocketSpec(value);
8471
+ }
8472
+ function getServerAddress() {
8473
+ return process.env["ANDROID_ADB_SERVER_ADDRESS"] ?? "localhost";
8474
+ }
8475
+ function getServerPort() {
8476
+ const value = process.env["ANDROID_ADB_SERVER_PORT"];
8477
+ if (!value) return DefaultServerPort;
8478
+ const port = decimalToNumber(value);
8479
+ if (void 0 === port || port <= 0 || port > 65535) throw new Error(`$ANDROID_ADB_SERVER_PORT must be a positive number less than 65535: got "${value}"`);
8480
+ return port;
8481
+ }
11125
8482
  class AdbServerNodeTcpConnector {
11126
8483
  spec;
11127
8484
  #listeners = new Map();
11128
8485
  constructor(spec){
11129
- this.spec = spec;
8486
+ if (!spec) {
8487
+ const value = getServerSocketSpec();
8488
+ if (value) {
8489
+ this.spec = value;
8490
+ return;
8491
+ }
8492
+ this.spec = {
8493
+ host: getServerAddress(),
8494
+ port: getServerPort()
8495
+ };
8496
+ return;
8497
+ }
8498
+ if ("string" == typeof spec) {
8499
+ this.spec = parseSocketSpec(spec);
8500
+ return;
8501
+ }
8502
+ if ("path" in spec) {
8503
+ if ("win32" === platform()) throw new Error("socket type local is unavailable on this platform");
8504
+ this.spec = spec;
8505
+ return;
8506
+ }
8507
+ if (!spec.host && !spec.port) {
8508
+ const value = getServerSocketSpec();
8509
+ if (value) {
8510
+ if ("path" in value) this.spec = value;
8511
+ else this.spec = {
8512
+ ...spec,
8513
+ ...value
8514
+ };
8515
+ return;
8516
+ }
8517
+ }
8518
+ this.spec = {
8519
+ ...spec,
8520
+ host: spec.host ?? getServerAddress(),
8521
+ port: spec.port ?? getServerPort()
8522
+ };
11130
8523
  }
11131
8524
  async connect({ unref, signal } = {
11132
8525
  unref: false
11133
8526
  }) {
11134
8527
  const socket = new Socket({
11135
- signal: signal
8528
+ signal
11136
8529
  });
11137
8530
  if (unref) socket.unref();
11138
8531
  socket.connect(this.spec);
@@ -11161,12 +8554,13 @@ class AdbServerNodeTcpConnector {
11161
8554
  socket.end();
11162
8555
  }
11163
8556
  });
11164
- if (address) {
11165
- const url = new URL(address);
11166
- if ("tcp:" === url.protocol) server.listen(Number.parseInt(url.port, 10), url.hostname);
11167
- else if ("unix:" === url.protocol) server.listen(url.pathname);
11168
- else throw new TypeError(`Unsupported protocol ${url.protocol}`);
11169
- } else server.listen();
8557
+ if (address) if (address.startsWith("tcp:")) {
8558
+ const spec = parseTcpSocketSpec(address.substring(4));
8559
+ if (!spec.port) throw new Error(`Invalid destination port: '${address.substring(4)}'`);
8560
+ server.listen(spec.port, spec.host);
8561
+ } else if (address.startsWith("unix:")) server.listen(address.substring(5));
8562
+ else throw new TypeError(`Unsupported protocol ${address}`);
8563
+ else server.listen();
11170
8564
  await new Promise((resolve, reject)=>{
11171
8565
  server.on("listening", ()=>resolve());
11172
8566
  server.on("error", (e)=>reject(e));
@@ -11189,10 +8583,12 @@ class AdbServerNodeTcpConnector {
11189
8583
  this.#listeners.clear();
11190
8584
  }
11191
8585
  }
11192
- const debug = createDebug('devtool-mcp-server:takeover');
11193
- const DEBUG_ROUTER_DIR = node_path.join(node_os.homedir(), '.DebugRouterConnector');
11194
- const DEBUG_ROUTER_LOCK_DIR = node_path.join(DEBUG_ROUTER_DIR, 'lockfile');
11195
- const DEBUG_ROUTER_LATEST_FILE = node_path.join(DEBUG_ROUTER_DIR, 'LatestDriverProcess');
8586
+ const APP_ICON_HELPER_JAR_BASE64 = "UEsDBBQACAgIAAAAIQAAAAAAAAAAAAAAAAALAAkAY2xhc3Nlcy5kZXhVVAUAAQAAAAB9lkFsG8cVht+SS1KkKYmkYtlmnWZFqbGTSKIsS5YsKk1k2Q4IULYbF0KgBAiGuyNq4+Xsencp0zAaBAXqtL24aFAgl+bk9py6OTin+lIgBQqkhx6coIccCvTSUxugRZFD/pkdKZQVlMTHefvmzcyb994sx+H9wtzZRTImt/7xecP+66cP7n/8af0FXnjwxdJPn/7lZyePEAVE1N9cqJD+tApEL1Gi/w7wDKIS2sdoTbTvp4ieQvsQLVT0Wprofg5zoB3JEI2DCbAEtkAf3AF3wc/APfAeeB/8HjwGqSzRFHgJbIF3wK/A78CfwBfg36CAdebAddABd8A98CH4M/gX+A/4HzCGiDIgD4qgAp4FDXANeOAn4B74NXgAHoI/gE/A38CXIJcnqoIaOA0WwQrYAG+ADhAA2yCEk4pgGIyAUUpiVwYywGOUxO4oGAfHwHFwAlR1vE+Cp8F3wTNgAnwPnAKnwXMA26OUzhdcVGvfR3Lyuu9DLRe1XNB+PNR6KT/SsvTpE20jffuLmaw5ruevafkx9JNa/vuA/M8BWa41peUvB/RfQX5W79eEs2l8LSnja6jYHKHzOi5Is9Itqj2maF7tb5SmVWvQjLIpKN9yGFdXbZ5WVSyGaEXlYYjm1P7TdEa1WTqr2hwtqNwU1fhR3ZZUFGUsMrSs4mDSOdUOU0P5lfQfxcgl7WdZx5F0Lhbg0jFwqiD9N9Qe7prJmQlKI2rVIWhlrn4OZSRzG1TKZ0su3VRZq9LzdLOU5K2SElYBMSqmhTWKOBbTVfMF1WtS0Zw8epwq2Q3KZKs0S2LuCKJaJGGV4dFk+QRtpI2smCuRZRRRQwYJ5WiRLudyWWEZONvFXBv6MeMR3ZxLYy9FquEQBpaJvYgfZKkzLqwMaq4Nx8YMh9op6F9OUTBRyC3nhqDHc2kIfo9QLTcK302MHsbzqVwtN4LnNJ6L6nkYNiWDRq6s9t91P1r97W/e3Vp98Y/bKXFXepXWMTR13ss6niWcCkOfDUOfk5TqP65s9z6Grn9joHaO6baq55cUKLvqCjf+PuXXXn3lwpvL+NBTa0HQtH3xKhcOD3k4+xbbZTRxqR9wO+aO5QturQkn9F3HCph9g3W4JViX08nLzPVgEPsWF7bvcMvFNBaLrGtXXiGjSfnm+tUrb15vbl0io0Vmq9lsUarVonQLPydaLJm0jkExF3F9Xbb9uEGTh7qCbv1asvQGE/gNG3R636gTsmDHtaP6BTfusmBq3e8GIY+iy37YZZjO+j+WYtvtNAZ8ecLiW7vWmdhlUYOmDnc5IbvF2h6vX9RCg8b2rfyo3vL9QDpfbTnM23Vv1JkQfsxi1xf1H+6E/i1MO96SCai7fv1qLw568fU45KzboKP7+muhK/bV5UTtMdGpr3ssivYtlepS3+aBnF/6+4266Xm8w7y1sNPrIsADVhOHra7DQz5gUhkwudp+C2VyUAfXXNF5Qnc7ijncfWZAF/JtD4Nl4qM47Nmxr0Jz2GCDxzu+I3fgh526d1v0ZWUILkfUnyjfBqVV+W1SZrOJD6U2UXWbW2RskbnVQglWXj8csrHXv2VPB5R7m6rqdM6yIJhds2N3141vI3ecOXRssE+Xc7MbeDRk65qkog3LmCflRWPJUxIcPYBMWUWU2fZ60Q7ltv3wijxtlQ6PsVXPtVW5yC3TOHQXue2xkDsDQaTygD6JnVIdPEKUdcWuf4OT2WWuoCOC32piCiZsTmm/F1MZHgeYYgPdSeHScAQnbBsbcVHclMfjBb8nnIgyu8zrcfrAePvti8t3am0shYTUVmoO79ema3L/rqc8n+niVYGOkHucRRydOyyasXe4fSPqdaPayjbzIj5d67pihgVubWX+zHQt2mEzZzCItRlrL5w7317kbWfBcebb7fNn2myOO+e2Fxbnl5a2GeMLNsOsuzyMsBwGLc+em52fcfhu7UeUyhsvnjSODxt4kaarlR+/Y/43a+R/kTOmHiXvy9HCwfcq6fvBdCF5Lw/qZbt3T5Tv5b27YpoO3hf37owZ+ubeuPeelndHw0rGy/tjWsvyf9MoJfcXea9JWcla8n5pWgO+aln+72a0LP9/06VEln5ntX5BX4KkLO+4XwNQSwcIXW7w3TMGAAAcCwAAUEsBAhQAFAAICAgAAAAhAF1u8N0zBgAAHAsAAAsACQAAAAAAAAAAAAAAAAAAAGNsYXNzZXMuZGV4VVQFAAEAAAAAUEsFBgAAAAABAAEAQgAAAHUGAAAAAA==";
8587
+ const ANDROID_APP_ICON_HELPER_JAR = Buffer.from(APP_ICON_HELPER_JAR_BASE64, "base64");
8588
+ const debug = ansi_createDebug("devtool-mcp-server:takeover");
8589
+ const DEBUG_ROUTER_DIR = node_path.join(node_os.homedir(), ".DebugRouterConnector");
8590
+ const DEBUG_ROUTER_LOCK_DIR = node_path.join(DEBUG_ROUTER_DIR, "lockfile");
8591
+ const DEBUG_ROUTER_LATEST_FILE = node_path.join(DEBUG_ROUTER_DIR, "LatestDriverProcess");
11196
8592
  async function takeoverDebugRouterLock() {
11197
8593
  try {
11198
8594
  await promises.mkdir(DEBUG_ROUTER_DIR, {
@@ -11205,10 +8601,10 @@ async function takeoverDebugRouterLock() {
11205
8601
  await promises.mkdir(DEBUG_ROUTER_LOCK_DIR, {
11206
8602
  recursive: true
11207
8603
  });
11208
- await promises.writeFile(DEBUG_ROUTER_LATEST_FILE, `${process.pid}`, 'utf-8');
8604
+ await promises.writeFile(DEBUG_ROUTER_LATEST_FILE, `${process.pid}`, "utf-8");
11209
8605
  debug(`wrote PID=${process.pid}`);
11210
8606
  } catch (err) {
11211
- debug('skipped due to filesystem error %O', err);
8607
+ debug("skipped due to filesystem error %O", err);
11212
8608
  } finally{
11213
8609
  try {
11214
8610
  await promises.rm(DEBUG_ROUTER_LOCK_DIR, {
@@ -11216,30 +8612,46 @@ async function takeoverDebugRouterLock() {
11216
8612
  force: true
11217
8613
  });
11218
8614
  } catch (_cleanupError) {
11219
- debug('failed to remove lock directory %O', _cleanupError);
8615
+ debug("failed to remove lock directory %O", _cleanupError);
11220
8616
  }
11221
8617
  }
11222
8618
  }
11223
8619
  class PeertalkToMessageTransformStream extends web_TransformStream {
11224
8620
  constructor(){
11225
8621
  let buffer = new Uint8Array(0);
8622
+ let start = 0;
8623
+ let end = 0;
11226
8624
  const decoder = new TextDecoder();
11227
8625
  super({
11228
8626
  transform: (chunk, c)=>{
11229
- const n = new Uint8Array(buffer.length + chunk.length);
11230
- n.set(buffer);
11231
- n.set(chunk, buffer.length);
11232
- buffer = n;
11233
- while(buffer.length >= 20){
11234
- const v = new DataView(buffer.buffer, buffer.byteOffset);
8627
+ const buffered = end - start;
8628
+ if (buffer.length - end < chunk.length) if (buffered + chunk.length <= buffer.length) {
8629
+ buffer.copyWithin(0, start, end);
8630
+ start = 0;
8631
+ end = buffered;
8632
+ } else {
8633
+ const next = new Uint8Array(Math.max(buffered + chunk.length, Math.max(20, 2 * buffer.length)));
8634
+ next.set(buffer.subarray(start, end));
8635
+ buffer = next;
8636
+ start = 0;
8637
+ end = buffered;
8638
+ }
8639
+ buffer.set(chunk, end);
8640
+ end += chunk.length;
8641
+ while(end - start >= 20){
8642
+ const v = new DataView(buffer.buffer, buffer.byteOffset + start, 20);
11235
8643
  const len = v.getUint32(16);
11236
- if (buffer.length < 20 + len) break;
8644
+ if (end - start < 20 + len) break;
11237
8645
  try {
11238
- c.enqueue(JSON.parse(decoder.decode(buffer.subarray(20, 20 + len))));
8646
+ c.enqueue(JSON.parse(decoder.decode(buffer.subarray(start + 20, start + 20 + len))));
11239
8647
  } catch (e) {
11240
8648
  c.error(e);
11241
8649
  }
11242
- buffer = buffer.subarray(20 + len);
8650
+ start += 20 + len;
8651
+ if (start === end) {
8652
+ start = 0;
8653
+ end = 0;
8654
+ }
11243
8655
  }
11244
8656
  }
11245
8657
  });
@@ -11247,58 +8659,81 @@ class PeertalkToMessageTransformStream extends web_TransformStream {
11247
8659
  }
11248
8660
  class MessageToPeertalkTransformStream extends web_TransformStream {
11249
8661
  constructor(){
11250
- const encoder = new TextEncoder();
11251
8662
  super({
11252
8663
  transform (chunk, controller) {
11253
- const body = encoder.encode(JSON.stringify(chunk));
11254
- const len = body.length;
11255
- const data = new Uint8Array(20 + len);
11256
- const view = new DataView(data.buffer);
11257
- view.setUint32(0, 1);
11258
- view.setUint32(4, 101);
11259
- view.setUint32(8, 0);
11260
- view.setUint32(12, len + 4);
11261
- view.setUint32(16, len);
11262
- data.set(body, 20);
11263
- controller.enqueue(data);
8664
+ controller.enqueue(encodePeertalkMessage(chunk));
11264
8665
  }
11265
8666
  });
11266
8667
  }
11267
8668
  }
11268
- const peertalkCodecFactory = {
11269
- createEncodeTransformStream () {
11270
- return new MessageToPeertalkTransformStream();
11271
- },
11272
- createDecodeTransformStream () {
11273
- return new PeertalkToMessageTransformStream();
11274
- }
11275
- };
11276
- async function createMessageConnection(connectRaw, codecFactory, options) {
8669
+ const peertalk_encoder = new TextEncoder();
8670
+ function encodePeertalkMessage(message) {
8671
+ const body = peertalk_encoder.encode(JSON.stringify(message));
8672
+ const len = body.length;
8673
+ const data = new Uint8Array(20 + len);
8674
+ const view = new DataView(data.buffer);
8675
+ view.setUint32(0, 1);
8676
+ view.setUint32(4, 101);
8677
+ view.setUint32(8, 0);
8678
+ view.setUint32(12, len + 4);
8679
+ view.setUint32(16, len);
8680
+ data.set(body, 20);
8681
+ return data;
8682
+ }
8683
+ async function connectWithPeertalk(connectRaw, options, takeoverHDT = true) {
8684
+ if (takeoverHDT) await takeoverDebugRouterLock();
11277
8685
  const conn = await connectRaw(options);
11278
- const encoder = codecFactory.createEncodeTransformStream();
11279
- const pipeAbortController = new AbortController();
11280
- encoder.readable.pipeTo(conn.writable, {
11281
- preventClose: true,
11282
- signal: pipeAbortController.signal
11283
- }).catch((err)=>{
11284
- if (err?.name !== 'AbortError') conn[Symbol.asyncDispose]();
8686
+ const rawWriter = conn.writable.getWriter();
8687
+ const disposeReason = new Error("Peertalk connection disposed");
8688
+ let terminationPromise;
8689
+ let writerReleased = false;
8690
+ const releaseWriter = ()=>{
8691
+ if (!writerReleased) {
8692
+ writerReleased = true;
8693
+ rawWriter.releaseLock();
8694
+ }
8695
+ };
8696
+ const terminateConnection = (reason)=>{
8697
+ if (!terminationPromise) {
8698
+ const rawAbort = writerReleased ? Promise.resolve() : rawWriter.abort(reason);
8699
+ const dispose = Promise.resolve().then(()=>conn[Symbol.asyncDispose]());
8700
+ terminationPromise = rawAbort.then(()=>dispose, async (error)=>{
8701
+ await dispose.catch(()=>{});
8702
+ throw error;
8703
+ }).finally(releaseWriter);
8704
+ terminationPromise.catch(()=>{});
8705
+ }
8706
+ return terminationPromise;
8707
+ };
8708
+ const writable = new web_WritableStream({
8709
+ write (message, controller) {
8710
+ const signal = controller.signal;
8711
+ const abort = ()=>void terminateConnection(signal.reason).catch(()=>{});
8712
+ signal.addEventListener("abort", abort, {
8713
+ once: true
8714
+ });
8715
+ const write = Promise.resolve().then(()=>rawWriter.write(encodePeertalkMessage(message))).catch((error)=>{
8716
+ terminateConnection(error).catch(()=>{});
8717
+ throw error;
8718
+ });
8719
+ return write.finally(()=>{
8720
+ signal.removeEventListener("abort", abort);
8721
+ });
8722
+ },
8723
+ close: releaseWriter,
8724
+ abort: terminateConnection
11285
8725
  });
11286
- const readable = conn.readable.pipeThrough(codecFactory.createDecodeTransformStream());
8726
+ const readable = conn.readable.pipeThrough(new PeertalkToMessageTransformStream());
11287
8727
  return {
11288
8728
  readable,
11289
- writable: encoder.writable,
11290
- async [Symbol.asyncDispose] () {
11291
- pipeAbortController.abort();
11292
- await conn[Symbol.asyncDispose]();
8729
+ writable,
8730
+ [Symbol.asyncDispose] () {
8731
+ return terminateConnection(disposeReason);
11293
8732
  }
11294
8733
  };
11295
8734
  }
11296
- async function connectWithPeertalk(connectRaw, options) {
11297
- await takeoverDebugRouterLock();
11298
- return createMessageConnection(connectRaw, peertalkCodecFactory, options);
11299
- }
11300
8735
  function requireNumericPort(port) {
11301
- if ('number' == typeof port) return port;
8736
+ if ("number" == typeof port) return port;
11302
8737
  if (/^\d+$/.test(port)) return Number(port);
11303
8738
  throw new TypeError(`Transport requires a numeric port, received target: ${port}`);
11304
8739
  }
@@ -11333,43 +8768,91 @@ function _ts_add_disposable_resource(env, value, async) {
11333
8768
  });
11334
8769
  return value;
11335
8770
  }
11336
- function android_ts_dispose_resources(env) {
11337
- var _SuppressedError = "function" == typeof SuppressedError ? SuppressedError : function(error, suppressed, message) {
11338
- var e = new Error(message);
11339
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
11340
- };
11341
- return (android_ts_dispose_resources = function(env) {
11342
- function fail(e) {
11343
- env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
11344
- env.hasError = true;
11345
- }
11346
- var r, s = 0;
11347
- function next() {
11348
- while(r = env.stack.pop())try {
11349
- if (!r.async && 1 === s) return s = 0, env.stack.push(r), Promise.resolve().then(next);
11350
- if (r.dispose) {
11351
- var result = r.dispose.call(r.value);
11352
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
11353
- fail(e);
11354
- return next();
11355
- });
11356
- } else s |= 1;
11357
- } catch (e) {
11358
- fail(e);
11359
- }
11360
- if (1 === s) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
11361
- if (env.hasError) throw env.error;
11362
- }
11363
- return next();
11364
- })(env);
8771
+ function _ts_dispose_resources(env) {
8772
+ function fail(e) {
8773
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
8774
+ env.hasError = true;
8775
+ }
8776
+ var r, s = 0;
8777
+ function next() {
8778
+ while(r = env.stack.pop())try {
8779
+ if (!r.async && 1 === s) return s = 0, env.stack.push(r), Promise.resolve().then(next);
8780
+ if (r.dispose) {
8781
+ var result = r.dispose.call(r.value);
8782
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
8783
+ fail(e);
8784
+ return next();
8785
+ });
8786
+ } else s |= 1;
8787
+ } catch (e) {
8788
+ fail(e);
8789
+ }
8790
+ if (1 === s) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
8791
+ if (env.hasError) throw env.error;
8792
+ }
8793
+ return next();
8794
+ }
8795
+ const android_debug = ansi_createDebug("devtool-mcp-server:connector:android");
8796
+ const APP_ICON_HELPER_REMOTE_PATH = "/data/local/tmp/lynx-connector-app-icon-v1.jar";
8797
+ const PNG_SIGNATURE = [
8798
+ 0x89,
8799
+ 0x50,
8800
+ 0x4e,
8801
+ 0x47,
8802
+ 0x0d,
8803
+ 0x0a,
8804
+ 0x1a,
8805
+ 0x0a
8806
+ ];
8807
+ function createQueryLauncherActivitiesCommandArgs(packageName) {
8808
+ return [
8809
+ "cmd",
8810
+ "package",
8811
+ "query-activities",
8812
+ "--components",
8813
+ "-a",
8814
+ "android.intent.action.MAIN",
8815
+ "-c",
8816
+ "android.intent.category.LAUNCHER",
8817
+ "-p",
8818
+ packageName
8819
+ ];
8820
+ }
8821
+ function parseLauncherActivityComponents(output) {
8822
+ return output.split("\n").map((line)=>line.trim()).filter((line)=>{
8823
+ const separatorIndex = line.indexOf("/");
8824
+ return !/\s/u.test(line) && separatorIndex > 0 && separatorIndex === line.lastIndexOf("/") && separatorIndex < line.length - 1;
8825
+ });
8826
+ }
8827
+ function createOpenAppCommandArgs(componentName) {
8828
+ return [
8829
+ "am",
8830
+ "start",
8831
+ "-W",
8832
+ "-S",
8833
+ "-a",
8834
+ "android.intent.action.MAIN",
8835
+ "-c",
8836
+ "android.intent.category.LAUNCHER",
8837
+ "-n",
8838
+ componentName
8839
+ ];
8840
+ }
8841
+ function spawnWaitText(adb, command) {
8842
+ return adb.subprocess.noneProtocol.spawn(command).wait().toString();
11365
8843
  }
11366
- const android_debug = createDebug('devtool-mcp-server:connector:android');
11367
8844
  class AndroidTransport {
11368
8845
  client;
8846
+ #appIconHelperDeployments = new Map();
11369
8847
  constructor(spec = {
11370
8848
  port: 5037
11371
8849
  }){
11372
- this.client = new AdbServerClient(new AdbServerNodeTcpConnector(spec));
8850
+ const resolvedSpec = "port" in spec ? {
8851
+ ...spec,
8852
+ host: spec.host ?? "127.0.0.1"
8853
+ } : spec;
8854
+ const connector = "path" in resolvedSpec ? new AdbServerNodeTcpConnector(resolvedSpec) : new AdbServerNodeTcpConnector(resolvedSpec);
8855
+ this.client = new AdbServerClient(connector);
11373
8856
  }
11374
8857
  async connect(options) {
11375
8858
  return connectWithPeertalk((opts)=>this.#connectRaw(opts), options);
@@ -11385,62 +8868,103 @@ class AndroidTransport {
11385
8868
  });
11386
8869
  }
11387
8870
  async close() {
11388
- android_debug('Android transport closed');
8871
+ android_debug("Android transport closed");
11389
8872
  }
11390
8873
  async #connectRaw({ deviceId, port, signal }) {
11391
8874
  const numericPort = requireNumericPort(port);
11392
- const adb = await this.client.createAdb({
11393
- serial: deviceId
11394
- });
11395
8875
  android_debug(`connect: create connection to deviceId: ${deviceId}, port: ${numericPort}`);
11396
8876
  signal?.throwIfAborted();
11397
8877
  const service = `tcp:${numericPort}`;
8878
+ const closeController = new AbortController();
8879
+ const socketSignal = signal ? AbortSignal.any([
8880
+ signal,
8881
+ closeController.signal
8882
+ ]) : closeController.signal;
11398
8883
  let socket;
11399
8884
  try {
11400
- socket = await adb.createSocket(service);
8885
+ socket = await this.client.createDeviceConnection({
8886
+ serial: deviceId
8887
+ }, service, {
8888
+ signal: socketSignal
8889
+ });
11401
8890
  } catch (err) {
11402
- await adb.close();
11403
8891
  android_debug(`connect: create socket to ${service} failed with err: %o`, err);
11404
8892
  throw err;
11405
8893
  }
8894
+ const socketClosed = Promise.resolve(socket.closed);
8895
+ let socketClosedSettled = false;
8896
+ socketClosed.then(()=>{
8897
+ socketClosedSettled = true;
8898
+ }, ()=>{
8899
+ socketClosedSettled = true;
8900
+ });
8901
+ let closePromise;
8902
+ const closeSocket = ()=>{
8903
+ if (!closePromise) {
8904
+ let closeResult;
8905
+ try {
8906
+ closeResult = Promise.resolve(socket.close());
8907
+ } catch (err) {
8908
+ closeResult = Promise.reject(err);
8909
+ }
8910
+ const hardCloseCheck = new Promise((resolve)=>{
8911
+ setImmediate(()=>{
8912
+ if (!socketClosedSettled) {
8913
+ android_debug(`connect: force close socket ${service} after graceful close stalled`);
8914
+ closeController.abort();
8915
+ }
8916
+ resolve();
8917
+ });
8918
+ });
8919
+ closePromise = Promise.allSettled([
8920
+ closeResult,
8921
+ socketClosed,
8922
+ hardCloseCheck
8923
+ ]).then(([closeResultOutcome, socketClosedOutcome])=>{
8924
+ if ("rejected" === closeResultOutcome.status) throw closeResultOutcome.reason;
8925
+ if ("rejected" === socketClosedOutcome.status) throw socketClosedOutcome.reason;
8926
+ });
8927
+ }
8928
+ return closePromise;
8929
+ };
11406
8930
  if (signal?.aborted) {
11407
- await socket.close();
11408
- await adb.close();
8931
+ try {
8932
+ await closeSocket();
8933
+ } catch (err) {
8934
+ android_debug(`connect: close canceled socket ${service} err: %o`, err);
8935
+ }
11409
8936
  signal.throwIfAborted();
11410
8937
  }
11411
8938
  const abortHandler = ()=>{
11412
- Promise.resolve(socket.close()).catch((err)=>{
8939
+ closeSocket().catch((err)=>{
11413
8940
  android_debug(`connect: socket ${service} close on abort err: %o`, err);
11414
8941
  });
11415
8942
  };
11416
- signal?.addEventListener('abort', abortHandler, {
8943
+ signal?.addEventListener("abort", abortHandler, {
11417
8944
  once: true
11418
8945
  });
11419
- Promise.resolve(socket.closed).catch((err)=>{
8946
+ socketClosed.catch((err)=>{
11420
8947
  android_debug(`connect: socket ${service} closed with err: %o`, err);
11421
8948
  });
11422
8949
  return {
11423
8950
  readable: socket.readable,
11424
8951
  writable: socket.writable,
11425
8952
  async [Symbol.asyncDispose] () {
11426
- signal?.removeEventListener('abort', abortHandler);
8953
+ signal?.removeEventListener("abort", abortHandler);
11427
8954
  android_debug(`connect: close connection to deviceId: ${deviceId}, port: ${numericPort}`);
11428
- try {
11429
- await socket.close();
11430
- } finally{
11431
- await adb.close();
11432
- }
8955
+ await closeSocket();
11433
8956
  }
11434
8957
  };
11435
8958
  }
11436
8959
  async listDevices() {
11437
8960
  const devices = await this.client.getDevices();
11438
- android_debug('listDevices: devices %o', devices);
8961
+ android_debug("listDevices: devices %o", devices);
11439
8962
  return devices.map(({ serial })=>({
11440
- os: 'Android',
8963
+ os: "Android",
11441
8964
  id: serial
11442
8965
  }));
11443
8966
  }
8967
+ getKnownApp(_packageName) {}
11444
8968
  async listAvailableApps(deviceId) {
11445
8969
  const env = {
11446
8970
  stack: [],
@@ -11449,26 +8973,78 @@ class AndroidTransport {
11449
8973
  };
11450
8974
  try {
11451
8975
  const adb = _ts_add_disposable_resource(env, await this.#createAdb(deviceId), true);
11452
- const output = await adb.subprocess.noneProtocol.spawnWaitText([
11453
- 'pm',
11454
- 'list',
11455
- 'packages',
11456
- '-3'
8976
+ const output = await spawnWaitText(adb, [
8977
+ "pm",
8978
+ "list",
8979
+ "packages",
8980
+ "-3"
11457
8981
  ]);
11458
- const packages = output.split('\n').map((line)=>line.replace('package:', '').trim()).filter((i)=>'' !== i);
8982
+ const packages = output.split("\n").map((line)=>line.replace("package:", "").trim()).filter((i)=>"" !== i);
11459
8983
  android_debug("listAvailableApps all packages: %o", packages);
11460
8984
  return packages.map((packageName)=>({
11461
8985
  packageName,
11462
- name: packageName
8986
+ name: this.getKnownApp(packageName)?.name ?? packageName
11463
8987
  }));
11464
8988
  } catch (e) {
11465
8989
  env.error = e;
11466
8990
  env.hasError = true;
11467
8991
  } finally{
11468
- const result = android_ts_dispose_resources(env);
8992
+ const result = _ts_dispose_resources(env);
8993
+ if (result) await result;
8994
+ }
8995
+ }
8996
+ async getAppIcon(deviceId, packageName) {
8997
+ const env = {
8998
+ stack: [],
8999
+ error: void 0,
9000
+ hasError: false
9001
+ };
9002
+ try {
9003
+ if (!/^[A-Za-z][\w.]*$/u.test(packageName)) throw new TypeError(`Invalid Android package name: ${packageName}`);
9004
+ const adb = _ts_add_disposable_resource(env, await this.#createAdb(deviceId), true);
9005
+ await this.#ensureAppIconHelper(adb, deviceId);
9006
+ const data = await adb.subprocess.noneProtocol.spawn([
9007
+ `CLASSPATH=${APP_ICON_HELPER_REMOTE_PATH}`,
9008
+ "app_process",
9009
+ "/system/bin",
9010
+ "org.lynx.connector.AppIconRenderer",
9011
+ packageName
9012
+ ]).wait();
9013
+ if (PNG_SIGNATURE.some((byte, index)=>data[index] !== byte)) throw new Error(`Device returned an invalid App icon for package ${packageName}`);
9014
+ return {
9015
+ data,
9016
+ mimeType: "image/png"
9017
+ };
9018
+ } catch (e) {
9019
+ env.error = e;
9020
+ env.hasError = true;
9021
+ } finally{
9022
+ const result = _ts_dispose_resources(env);
11469
9023
  if (result) await result;
11470
9024
  }
11471
9025
  }
9026
+ async #ensureAppIconHelper(adb, deviceId) {
9027
+ let deployment = this.#appIconHelperDeployments.get(deviceId);
9028
+ if (!deployment) {
9029
+ deployment = adb.sync.write({
9030
+ path: APP_ICON_HELPER_REMOTE_PATH,
9031
+ permission: 420,
9032
+ readable: new streams_ReadableStream({
9033
+ start (controller) {
9034
+ controller.enqueue(ANDROID_APP_ICON_HELPER_JAR);
9035
+ controller.close();
9036
+ }
9037
+ })
9038
+ }).then(()=>void 0);
9039
+ this.#appIconHelperDeployments.set(deviceId, deployment);
9040
+ }
9041
+ try {
9042
+ await deployment;
9043
+ } catch (error) {
9044
+ this.#appIconHelperDeployments.delete(deviceId);
9045
+ throw error;
9046
+ }
9047
+ }
11472
9048
  async openApp(deviceId, packageName, { withDataCleared } = {}) {
11473
9049
  const env = {
11474
9050
  stack: [],
@@ -11477,55 +9053,55 @@ class AndroidTransport {
11477
9053
  };
11478
9054
  try {
11479
9055
  const adb = _ts_add_disposable_resource(env, await this.#createAdb(deviceId), true);
11480
- const pmOutput = await adb.subprocess.noneProtocol.spawnWaitText([
11481
- 'pm',
11482
- 'list',
11483
- 'packages',
9056
+ const pmOutput = await spawnWaitText(adb, [
9057
+ "pm",
9058
+ "list",
9059
+ "packages",
11484
9060
  packageName
11485
9061
  ]);
11486
- const installed = pmOutput.split('\n').some((line)=>line.trim() === `package:${packageName}`);
9062
+ const installed = pmOutput.split("\n").some((line)=>line.trim() === `package:${packageName}`);
11487
9063
  if (!installed) throw new Error(`package ${packageName} not found`);
11488
9064
  if (withDataCleared) {
11489
- const output = await adb.subprocess.noneProtocol.spawnWaitText([
11490
- 'pm',
11491
- 'clear',
9065
+ const output = await spawnWaitText(adb, [
9066
+ "pm",
9067
+ "clear",
11492
9068
  packageName
11493
9069
  ]);
11494
9070
  android_debug(`openApp clear data output ${output}`);
11495
9071
  }
11496
- const output = await adb.subprocess.noneProtocol.spawnWaitText([
11497
- 'monkey',
11498
- '-p',
11499
- packageName,
11500
- '-c',
11501
- 'android.intent.category.LAUNCHER',
11502
- '1'
11503
- ]);
9072
+ const knownActivity = this.getKnownApp(packageName)?.activityName;
9073
+ let componentName = knownActivity ? `${packageName}/${knownActivity}` : void 0;
9074
+ if (!componentName) {
9075
+ const queryOutput = await spawnWaitText(adb, createQueryLauncherActivitiesCommandArgs(packageName));
9076
+ android_debug(`openApp launcher activities output ${queryOutput}`);
9077
+ [componentName] = parseLauncherActivityComponents(queryOutput);
9078
+ }
9079
+ if (!componentName) throw new Error(`No launchable activity found for package ${packageName}.`);
9080
+ const output = await spawnWaitText(adb, createOpenAppCommandArgs(componentName));
11504
9081
  android_debug(`openApp LAUNCHER output ${output}`);
11505
- if (output.includes('No activities found')) throw new Error(`No launchable activity found for package ${packageName}.`);
11506
- if (output.includes('monkey aborted')) throw new Error(`Failed to open app ${packageName}.`);
9082
+ if (output.includes("Error: Activity not started") || output.includes("unable to resolve Intent") || /Error type \d+/u.test(output)) throw new Error(`Failed to open app ${packageName}: ${output.trim()}`);
11507
9083
  } catch (e) {
11508
9084
  env.error = e;
11509
9085
  env.hasError = true;
11510
9086
  } finally{
11511
- const result = android_ts_dispose_resources(env);
9087
+ const result = _ts_dispose_resources(env);
11512
9088
  if (result) await result;
11513
9089
  }
11514
9090
  }
11515
9091
  }
11516
- const desktop_debug = createDebug('devtool-mcp-server:connector:desktop');
9092
+ const desktop_debug = ansi_createDebug("devtool-mcp-server:connector:desktop");
11517
9093
  class DesktopTransport {
11518
9094
  async connect(options) {
11519
9095
  return connectWithPeertalk((opts)=>this.#connectRaw(opts), options);
11520
9096
  }
11521
9097
  async close() {
11522
- desktop_debug('Desktop transport closed');
9098
+ desktop_debug("Desktop transport closed");
11523
9099
  }
11524
9100
  async listDevices() {
11525
9101
  return [
11526
9102
  {
11527
- id: 'localhost',
11528
- os: 'Desktop'
9103
+ id: "localhost",
9104
+ os: "Desktop"
11529
9105
  }
11530
9106
  ];
11531
9107
  }
@@ -11533,21 +9109,30 @@ class DesktopTransport {
11533
9109
  return [];
11534
9110
  }
11535
9111
  async openApp(deviceId, packageName) {
11536
- throw new Error('openApp is not supported on DesktopTransport');
9112
+ throw new Error("openApp is not supported on DesktopTransport");
11537
9113
  }
11538
9114
  async #connectRaw({ deviceId, port, signal }) {
11539
- if ('localhost' !== deviceId) throw new Error(`DesktopTransport only supports 'localhost' deviceId, got: ${deviceId}`);
11540
9115
  const numericPort = requireNumericPort(port);
9116
+ if ("localhost" !== deviceId) throw new Error(`DesktopTransport only supports 'localhost' deviceId, got: ${deviceId}`);
11541
9117
  desktop_debug(`connect: connecting to 127.0.0.1:${numericPort}`);
11542
9118
  const socket = node_net.createConnection({
11543
- host: '127.0.0.1',
9119
+ host: "127.0.0.1",
11544
9120
  port: numericPort,
11545
9121
  signal
11546
9122
  });
9123
+ const socketClosed = socket.closed ? Promise.resolve() : new Promise((resolve)=>socket.once("close", resolve));
9124
+ let disposePromise;
9125
+ const dispose = ()=>{
9126
+ disposePromise ??= (async ()=>{
9127
+ socket.destroy();
9128
+ await socketClosed;
9129
+ })();
9130
+ return disposePromise;
9131
+ };
11547
9132
  try {
11548
9133
  if (socket.connecting) await new Promise((resolve, reject)=>{
11549
- socket.once('connect', resolve);
11550
- socket.once('error', reject);
9134
+ socket.once("connect", resolve);
9135
+ socket.once("error", reject);
11551
9136
  });
11552
9137
  desktop_debug(`connect: connected to 127.0.0.1:${numericPort}`);
11553
9138
  const { readable, writable } = Duplex.toWeb(socket);
@@ -11556,12 +9141,12 @@ class DesktopTransport {
11556
9141
  writable,
11557
9142
  async [Symbol.asyncDispose] () {
11558
9143
  desktop_debug(`connect: closing connection to 127.0.0.1:${numericPort}`);
11559
- socket.destroy();
9144
+ await dispose();
11560
9145
  }
11561
9146
  };
11562
9147
  } catch (err) {
11563
9148
  desktop_debug(`connect: error connecting to 127.0.0.1:${numericPort} %O`, err);
11564
- socket.destroy();
9149
+ await dispose();
11565
9150
  throw err;
11566
9151
  }
11567
9152
  }
@@ -11862,7 +9447,7 @@ function shouldIgnoreNode(node) {
11862
9447
  }
11863
9448
  function isEmptyNode(node) {
11864
9449
  if (!node.childNodes || 0 === node.childNodes.length) return true;
11865
- return false;
9450
+ else return false;
11866
9451
  }
11867
9452
  function invariant(test, message) {
11868
9453
  if (!test) throw new Error(message);
@@ -11892,8 +9477,7 @@ function parsePlistXML(node) {
11892
9477
  if (isEmptyNode(node)) return new_arr;
11893
9478
  for(let i = 0; i < node.childNodes.length; i++)if (!shouldIgnoreNode(node.childNodes[i])) new_arr.push(parsePlistXML(node.childNodes[i]));
11894
9479
  return new_arr;
11895
- }
11896
- if ("dict" === node.nodeName) {
9480
+ } else if ("dict" === node.nodeName) {
11897
9481
  const new_obj = {};
11898
9482
  let key = null;
11899
9483
  let counter = 0;
@@ -11910,8 +9494,7 @@ function parsePlistXML(node) {
11910
9494
  }
11911
9495
  if (counter % 2 === 1) new_obj[key] = "";
11912
9496
  return new_obj;
11913
- }
11914
- if ("array" === node.nodeName) {
9497
+ } else if ("array" === node.nodeName) {
11915
9498
  const new_arr = [];
11916
9499
  if (isEmptyNode(node)) return new_arr;
11917
9500
  for(let i = 0; i < node.childNodes.length; i++)if (!shouldIgnoreNode(node.childNodes[i])) {
@@ -11919,8 +9502,7 @@ function parsePlistXML(node) {
11919
9502
  if (null != res) new_arr.push(res);
11920
9503
  }
11921
9504
  return new_arr;
11922
- }
11923
- if ("#text" === node.nodeName) ;
9505
+ } else if ("#text" === node.nodeName) ;
11924
9506
  else if ("key" === node.nodeName) {
11925
9507
  if (isEmptyNode(node)) return "";
11926
9508
  invariant("__proto__" !== node.childNodes[0].nodeValue, "__proto__ keys can lead to prototype pollution. More details on CVE-2022-22912");
@@ -11981,7 +9563,7 @@ function build(obj, opts) {
11981
9563
  }
11982
9564
  function walk_obj(next, next_child) {
11983
9565
  if (void 0 === next) return;
11984
- if (Array.isArray(next)) {
9566
+ else if (Array.isArray(next)) {
11985
9567
  next_child = next_child.ele('array');
11986
9568
  for(let i = 0; i < next.length; i++)walk_obj(next[i], next_child);
11987
9569
  } else if (next instanceof ArrayBuffer) next_child.ele('data').raw(uint8ArrayToBase64(new Uint8Array(next)));
@@ -12013,33 +9595,33 @@ const TAG = 1;
12013
9595
  class Usbmux {
12014
9596
  connectOptions;
12015
9597
  constructor(connectOptions){
12016
- if ('string' == typeof connectOptions) this.connectOptions = {
9598
+ if ("string" == typeof connectOptions) this.connectOptions = {
12017
9599
  path: connectOptions
12018
9600
  };
12019
9601
  else if (connectOptions) this.connectOptions = connectOptions;
12020
9602
  else this.connectOptions = {
12021
- path: '/var/run/usbmuxd'
9603
+ path: "/var/run/usbmuxd"
12022
9604
  };
12023
9605
  }
12024
9606
  async listDevices(signal) {
12025
9607
  const { socket, response } = await this.#sendAndReceive({
12026
- MessageType: 'ListDevices',
12027
- ClientVersionString: 'usbmux-driver',
12028
- ProgName: 'usbmux-driver'
9608
+ MessageType: "ListDevices",
9609
+ ClientVersionString: "usbmux-driver",
9610
+ ProgName: "usbmux-driver"
12029
9611
  }, signal);
12030
9612
  socket.destroy();
12031
9613
  return response.DeviceList;
12032
9614
  }
12033
9615
  async connect(deviceId, port, signal) {
12034
- const networkPort = port >> 8 & 0xff | port << 8 & 0xff00;
9616
+ const networkPort = port >> 8 & 0xFF | port << 8 & 0xFF00;
12035
9617
  const { socket, response, tail } = await this.#sendAndReceive({
12036
- MessageType: 'Connect',
12037
- ClientVersionString: 'usbmux-driver',
12038
- ProgName: 'usbmux-driver',
9618
+ MessageType: "Connect",
9619
+ ClientVersionString: "usbmux-driver",
9620
+ ProgName: "usbmux-driver",
12039
9621
  DeviceID: Number(deviceId),
12040
9622
  PortNumber: networkPort
12041
9623
  }, signal);
12042
- if ('Result' === response.MessageType && 0 === response.Number) {
9624
+ if ("Result" === response.MessageType && 0 === response.Number) {
12043
9625
  if (tail.length > 0) socket.unshift(tail);
12044
9626
  const { readable, writable } = Duplex.toWeb(socket);
12045
9627
  return {
@@ -12052,21 +9634,21 @@ class Usbmux {
12052
9634
  throw new Error(`Invalid response for Connect: ${JSON.stringify(response)}`);
12053
9635
  }
12054
9636
  async #sendAndReceive(payload, signal) {
12055
- const socket = __rspack_external_node_net_0373943e.createConnection(this.connectOptions);
9637
+ const socket = __rspack_external_node_net_5ed819e1.createConnection(this.connectOptions);
12056
9638
  if (signal) {
12057
9639
  const abortHandler = ()=>socket.destroy();
12058
- signal.addEventListener('abort', abortHandler, {
9640
+ signal.addEventListener("abort", abortHandler, {
12059
9641
  once: true
12060
9642
  });
12061
- socket.once('close', ()=>signal.removeEventListener('abort', abortHandler));
9643
+ socket.once("close", ()=>signal.removeEventListener("abort", abortHandler));
12062
9644
  }
12063
9645
  try {
12064
- await once(socket, 'connect', {
9646
+ await once(socket, "connect", {
12065
9647
  signal
12066
9648
  });
12067
9649
  socket.write(encodeRequest());
12068
9650
  let buffer = Buffer.alloc(0);
12069
- for await (const [chunk] of on(socket, 'data', {
9651
+ for await (const [chunk] of on(socket, "data", {
12070
9652
  signal
12071
9653
  })){
12072
9654
  buffer = Buffer.concat([
@@ -12078,21 +9660,21 @@ class Usbmux {
12078
9660
  if (buffer.length < length) continue;
12079
9661
  const responseBuffer = buffer.subarray(HEADER_SIZE, length);
12080
9662
  const tail = buffer.subarray(length);
12081
- const response = parse(responseBuffer.toString('utf8'));
9663
+ const response = parse(responseBuffer.toString("utf8"));
12082
9664
  return {
12083
9665
  socket,
12084
9666
  response,
12085
9667
  tail
12086
9668
  };
12087
9669
  }
12088
- throw new Error('Connection closed before response received');
9670
+ throw new Error("Connection closed before response received");
12089
9671
  } catch (error) {
12090
9672
  socket.destroy();
12091
9673
  throw error;
12092
9674
  }
12093
9675
  function encodeRequest() {
12094
9676
  const xml = build(payload);
12095
- const body = Buffer.from(xml, 'utf8');
9677
+ const body = Buffer.from(xml, "utf8");
12096
9678
  const length = HEADER_SIZE + body.length;
12097
9679
  const header = Buffer.alloc(HEADER_SIZE);
12098
9680
  header.writeUInt32LE(length, 0);
@@ -12106,7 +9688,7 @@ class Usbmux {
12106
9688
  }
12107
9689
  }
12108
9690
  }
12109
- const ios_debug = createDebug('devtool-mcp-server:connector:ios');
9691
+ const ios_debug = ansi_createDebug("devtool-mcp-server:connector:ios");
12110
9692
  class iOSTransport {
12111
9693
  #client;
12112
9694
  constructor(options){
@@ -12116,7 +9698,7 @@ class iOSTransport {
12116
9698
  return connectWithPeertalk((opts)=>this.#connectRaw(opts), options);
12117
9699
  }
12118
9700
  async close() {
12119
- ios_debug('iOS transport closed');
9701
+ ios_debug("iOS transport closed");
12120
9702
  }
12121
9703
  async #connectRaw({ deviceId, port, signal }) {
12122
9704
  const numericPort = requireNumericPort(port);
@@ -12142,17 +9724,17 @@ class iOSTransport {
12142
9724
  }
12143
9725
  async listDevices() {
12144
9726
  const devices = await this.#client.listDevices(AbortSignal.timeout(1000));
12145
- ios_debug('listDevices: devices %o', devices);
9727
+ ios_debug("listDevices: devices %o", devices);
12146
9728
  return devices.map(({ Properties })=>({
12147
- os: 'iOS',
9729
+ os: "iOS",
12148
9730
  id: Properties.SerialNumber
12149
9731
  }));
12150
9732
  }
12151
9733
  async listAvailableApps() {
12152
- throw new Error('Not implemented');
9734
+ throw new Error("Not implemented");
12153
9735
  }
12154
9736
  async openApp(_, __, ___) {
12155
- throw new Error('Not implemented');
9737
+ throw new Error("Not implemented");
12156
9738
  }
12157
9739
  }
12158
- export { AndroidTransport, DesktopTransport, MessageToPeertalkTransformStream, PeertalkToMessageTransformStream, Usbmux, connectWithPeertalk, createMessageConnection, iOSTransport, peertalkCodecFactory, requireNumericPort };
9740
+ export { AndroidTransport, DesktopTransport, MessageToPeertalkTransformStream, PeertalkToMessageTransformStream, Usbmux, connectWithPeertalk, encodePeertalkMessage, iOSTransport, requireNumericPort };