CdpConnection.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.MapperCdpConnection = void 0;
  4. const log_js_1 = require("../utils/log.js");
  5. const CdpClient_js_1 = require("./CdpClient.js");
  6. /**
  7. * Represents a high-level CDP connection to the browser backend.
  8. *
  9. * Manages all CdpClients (each backed by a Session ID) instance for each active
  10. * CDP session.
  11. */
  12. class MapperCdpConnection {
  13. static LOGGER_PREFIX_RECV = `${log_js_1.LogType.cdp}:RECV ◂`;
  14. static LOGGER_PREFIX_SEND = `${log_js_1.LogType.cdp}:SEND ▸`;
  15. #mainBrowserCdpClient;
  16. #transport;
  17. /** Map from session ID to CdpClient.
  18. * `undefined` points to the main browser session. */
  19. #sessionCdpClients = new Map();
  20. #commandCallbacks = new Map();
  21. #logger;
  22. #nextId = 0;
  23. constructor(transport, logger) {
  24. this.#transport = transport;
  25. this.#logger = logger;
  26. this.#transport.setOnMessage(this.#onMessage);
  27. // Create default Browser CDP Session.
  28. this.#mainBrowserCdpClient = this.#createCdpClient(undefined);
  29. }
  30. /** Closes the connection to the browser. */
  31. close() {
  32. this.#transport.close();
  33. for (const [, { reject, error }] of this.#commandCallbacks) {
  34. reject(error);
  35. }
  36. this.#commandCallbacks.clear();
  37. this.#sessionCdpClients.clear();
  38. }
  39. async createBrowserSession() {
  40. const { sessionId } = await this.#mainBrowserCdpClient.sendCommand('Target.attachToBrowserTarget');
  41. return this.#createCdpClient(sessionId);
  42. }
  43. /**
  44. * Gets a CdpClient instance attached to the given session ID,
  45. * or null if the session is not attached.
  46. */
  47. getCdpClient(sessionId) {
  48. const cdpClient = this.#sessionCdpClients.get(sessionId);
  49. if (!cdpClient) {
  50. throw new Error(`Unknown CDP session ID: ${sessionId}`);
  51. }
  52. return cdpClient;
  53. }
  54. sendCommand(method, params, sessionId) {
  55. return new Promise((resolve, reject) => {
  56. const id = this.#nextId++;
  57. this.#commandCallbacks.set(id, {
  58. resolve,
  59. reject,
  60. error: new CdpClient_js_1.CloseError(`${method} ${JSON.stringify(params)} ${sessionId ?? ''} call rejected because the connection has been closed.`),
  61. });
  62. const cdpMessage = { id, method, params };
  63. if (sessionId) {
  64. cdpMessage.sessionId = sessionId;
  65. }
  66. void this.#transport
  67. .sendMessage(JSON.stringify(cdpMessage))
  68. ?.catch((error) => {
  69. this.#logger?.(log_js_1.LogType.debugError, error);
  70. this.#transport.close();
  71. });
  72. this.#logger?.(MapperCdpConnection.LOGGER_PREFIX_SEND, cdpMessage);
  73. });
  74. }
  75. #onMessage = (json) => {
  76. const message = JSON.parse(json);
  77. this.#logger?.(MapperCdpConnection.LOGGER_PREFIX_RECV, message);
  78. // Update client map if a session is attached
  79. // Listen for these events on every session.
  80. if (message.method === 'Target.attachedToTarget') {
  81. const { sessionId } = message.params;
  82. this.#createCdpClient(sessionId);
  83. }
  84. if (message.id !== undefined) {
  85. // Handle command response.
  86. const callbacks = this.#commandCallbacks.get(message.id);
  87. this.#commandCallbacks.delete(message.id);
  88. if (callbacks) {
  89. if (message.result) {
  90. callbacks.resolve(message.result);
  91. }
  92. else if (message.error) {
  93. callbacks.reject(message.error);
  94. }
  95. }
  96. }
  97. else if (message.method) {
  98. const client = this.#sessionCdpClients.get(message.sessionId ?? undefined);
  99. client?.emit(message.method, message.params || {});
  100. // Update client map if a session is detached
  101. // But emit on that session
  102. if (message.method === 'Target.detachedFromTarget') {
  103. const { sessionId } = message.params;
  104. const client = this.#sessionCdpClients.get(sessionId);
  105. if (client) {
  106. this.#sessionCdpClients.delete(sessionId);
  107. client.removeAllListeners();
  108. }
  109. }
  110. }
  111. };
  112. /**
  113. * Creates a new CdpClient instance for the given session ID.
  114. * @param sessionId either a string, or undefined for the main browser session.
  115. * The main browser session is used only to create new browser sessions.
  116. * @private
  117. */
  118. #createCdpClient(sessionId) {
  119. const cdpClient = new CdpClient_js_1.MapperCdpClient(this, sessionId);
  120. this.#sessionCdpClients.set(sessionId, cdpClient);
  121. return cdpClient;
  122. }
  123. }
  124. exports.MapperCdpConnection = MapperCdpConnection;
  125. //# sourceMappingURL=CdpConnection.js.map