summaryrefslogtreecommitdiffstats
path: root/remote/shared/messagehandler/WindowGlobalMessageHandler.sys.mjs
blob: 1e0164cf44fe2788ad96ac1e25d69c18ae8799ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import {
  ContextDescriptorType,
  MessageHandler,
} from "chrome://remote/content/shared/messagehandler/MessageHandler.sys.mjs";

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  error: "chrome://remote/content/shared/webdriver/Errors.sys.mjs",
  getMessageHandlerFrameChildActor:
    "chrome://remote/content/shared/messagehandler/transports/js-window-actors/MessageHandlerFrameChild.sys.mjs",
  RootMessageHandler:
    "chrome://remote/content/shared/messagehandler/RootMessageHandler.sys.mjs",
  WindowRealm: "chrome://remote/content/shared/Realm.sys.mjs",
});

/**
 * A WindowGlobalMessageHandler is dedicated to debugging a single window
 * global. It follows the lifecycle of the corresponding window global and will
 * therefore not survive any navigation. This MessageHandler cannot forward
 * commands further to other MessageHandlers and represents a leaf node in a
 * MessageHandler network.
 */
export class WindowGlobalMessageHandler extends MessageHandler {
  #innerWindowId;
  #realms;

  constructor() {
    super(...arguments);

    this.#innerWindowId = this.context.window.windowGlobalChild.innerWindowId;

    // Maps sandbox names to instances of window realms,
    // the default realm is mapped to an empty string sandbox name.
    this.#realms = new Map([["", new lazy.WindowRealm(this.context.window)]]);
  }

  destroy() {
    for (const realm of this.#realms.values()) {
      realm.destroy();
    }
    this.#realms = null;

    super.destroy();
  }

  /**
   * Returns the WindowGlobalMessageHandler module path.
   *
   * @returns {string}
   */
  static get modulePath() {
    return "windowglobal";
  }

  /**
   * Returns the WindowGlobalMessageHandler type.
   *
   * @returns {string}
   */
  static get type() {
    return "WINDOW_GLOBAL";
  }

  /**
   * For WINDOW_GLOBAL MessageHandlers, `context` is a BrowsingContext,
   * and BrowsingContext.id can be used as the context id.
   *
   * @param {BrowsingContext} context
   *     WindowGlobalMessageHandler contexts are expected to be
   *     BrowsingContexts.
   * @returns {string}
   *     The browsing context id.
   */
  static getIdFromContext(context) {
    return context.id;
  }

  get innerWindowId() {
    return this.#innerWindowId;
  }

  get realms() {
    return this.#realms;
  }

  get window() {
    return this.context.window;
  }

  #getRealmFromSandboxName(sandboxName = null) {
    if (sandboxName === null || sandboxName === "") {
      return this.#realms.get("");
    }

    if (this.#realms.has(sandboxName)) {
      return this.#realms.get(sandboxName);
    }

    const realm = new lazy.WindowRealm(this.context.window, {
      sandboxName,
    });

    this.#realms.set(sandboxName, realm);

    return realm;
  }

  async applyInitialSessionDataItems(sessionDataItems) {
    if (!Array.isArray(sessionDataItems)) {
      return;
    }

    const destination = {
      type: WindowGlobalMessageHandler.type,
    };

    // Create a Map with the structure moduleName -> category -> relevant session data items.
    const structuredUpdates = new Map();
    for (const sessionDataItem of sessionDataItems) {
      const { category, contextDescriptor, moduleName } = sessionDataItem;

      if (!this.matchesContext(contextDescriptor)) {
        continue;
      }
      if (!structuredUpdates.has(moduleName)) {
        // Skip session data item if the module is not present
        // for the destination.
        if (!this.moduleCache.hasModuleClass(moduleName, destination)) {
          continue;
        }
        structuredUpdates.set(moduleName, new Map());
      }

      if (!structuredUpdates.get(moduleName).has(category)) {
        structuredUpdates.get(moduleName).set(category, new Set());
      }

      structuredUpdates.get(moduleName).get(category).add(sessionDataItem);
    }

    const sessionDataPromises = [];

    for (const [moduleName, categories] of structuredUpdates.entries()) {
      for (const [category, relevantSessionData] of categories.entries()) {
        sessionDataPromises.push(
          this.handleCommand({
            moduleName,
            commandName: "_applySessionData",
            params: {
              category,
              initial: true,
              sessionData: Array.from(relevantSessionData),
            },
            destination,
          })
        );
      }
    }

    await Promise.all(sessionDataPromises);

    // With the session data applied the handler is now ready to be used.
    this.emitEvent("window-global-handler-created", {
      contextId: this.contextId,
      innerWindowId: this.#innerWindowId,
    });
  }

  forwardCommand(command) {
    switch (command.destination.type) {
      case lazy.RootMessageHandler.type:
        return lazy
          .getMessageHandlerFrameChildActor(this)
          .sendCommand(command, this.sessionId);
      default:
        throw new Error(
          `Cannot forward command to "${command.destination.type}" from "${this.constructor.type}".`
        );
    }
  }

  /**
   * If <var>realmId</var> is null or not provided get the realm for
   * a given <var>sandboxName</var>, otherwise find the realm
   * in the cache with the realm id equal given <var>realmId</var>.
   *
   * @param {object} options
   * @param {string|null=} options.realmId
   *     The realm id.
   * @param {string=} options.sandboxName
   *     The name of sandbox
   *
   * @returns {Realm}
   *     The realm object.
   */
  getRealm(options = {}) {
    const { realmId = null, sandboxName } = options;
    if (realmId === null) {
      return this.#getRealmFromSandboxName(sandboxName);
    }

    const realm = Array.from(this.#realms.values()).find(
      realm => realm.id === realmId
    );

    if (realm) {
      return realm;
    }

    throw new lazy.error.NoSuchFrameError(`Realm with id ${realmId} not found`);
  }

  matchesContext(contextDescriptor) {
    return (
      contextDescriptor.type === ContextDescriptorType.All ||
      (contextDescriptor.type === ContextDescriptorType.TopBrowsingContext &&
        contextDescriptor.id === this.context.browserId)
    );
  }

  /**
   * Send a command to the root MessageHandler.
   *
   * @param {Command} command
   *     The command to send to the root MessageHandler.
   * @returns {Promise}
   *     A promise which resolves with the return value of the command.
   */
  sendRootCommand(command) {
    return this.handleCommand({
      ...command,
      destination: {
        type: lazy.RootMessageHandler.type,
      },
    });
  }
}