summaryrefslogtreecommitdiffstats
path: root/devtools/server/actors/resources/console-messages.js
blob: a643546692399ae849acfaeee982bb7179a82930 (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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/* 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/. */

"use strict";

const {
  TYPES: { CONSOLE_MESSAGE },
} = require("devtools/server/actors/resources/index");
const Targets = require("devtools/server/actors/targets/index");

const consoleAPIListenerModule = isWorker
  ? "devtools/server/actors/webconsole/worker-listeners"
  : "devtools/server/actors/webconsole/listeners/console-api";
const { ConsoleAPIListener } = require(consoleAPIListenerModule);

const { isArray } = require("devtools/server/actors/object/utils");

const {
  makeDebuggeeValue,
  createValueGripForTarget,
} = require("devtools/server/actors/object/utils");

const {
  getActorIdForInternalSourceId,
} = require("devtools/server/actors/utils/dbg-source");

const {
  isSupportedByConsoleTable,
} = require("devtools/shared/webconsole/messages");

/**
 * Start watching for all console messages related to a given Target Actor.
 * This will notify about existing console messages, but also the one created in future.
 *
 * @param TargetActor targetActor
 *        The target actor from which we should observe console messages
 * @param Object options
 *        Dictionary object with following attributes:
 *        - onAvailable: mandatory function
 *          This will be called for each resource.
 */
class ConsoleMessageWatcher {
  async watch(targetActor, { onAvailable }) {
    this.targetActor = targetActor;
    this.onAvailable = onAvailable;

    // Bug 1642297: Maybe we could merge ConsoleAPI Listener into this module?
    const onConsoleAPICall = message => {
      onAvailable([
        {
          resourceType: CONSOLE_MESSAGE,
          message: prepareConsoleMessageForRemote(targetActor, message),
        },
      ]);
    };

    const isTargetActorContentProcess =
      targetActor.targetType === Targets.TYPES.PROCESS;

    // Only consider messages from a given window for all FRAME targets (this includes
    // WebExt and ParentProcess which inherits from WindowGlobalTargetActor)
    // But ParentProcess should be ignored as we want all messages emitted directly from
    // that process (window and window-less).
    // To do that we pass a null window and ConsoleAPIListener will catch everything.
    // And also ignore WebExtension as we will filter out only by addonId, which is
    // passed via consoleAPIListenerOptions. WebExtension may have multiple windows/documents
    // but all of them will be flagged with the same addon ID.
    const messagesShouldMatchWindow =
      targetActor.targetType === Targets.TYPES.FRAME &&
      targetActor.typeName != "parentProcessTarget" &&
      targetActor.typeName != "webExtensionTarget";
    const window = messagesShouldMatchWindow ? targetActor.window : null;

    // If we should match messages for a given window but for some reason, targetActor.window
    // did not return a window, bail out. Otherwise we wouldn't have anything to match against
    // and would consume all the messages, which could lead to issue (e.g. infinite loop,
    // see Bug 1828026).
    if (messagesShouldMatchWindow && !window) {
      return;
    }

    const listener = new ConsoleAPIListener(window, onConsoleAPICall, {
      excludeMessagesBoundToWindow: isTargetActorContentProcess,
      matchExactWindow: targetActor.ignoreSubFrames,
      ...(targetActor.consoleAPIListenerOptions || {}),
    });
    this.listener = listener;
    listener.init();

    // It can happen that the targetActor does not have a window reference (e.g. in worker
    // thread, targetActor exposes a workerGlobal property)
    const winStartTime =
      targetActor.window?.performance?.timing?.navigationStart || 0;

    const cachedMessages = listener.getCachedMessages(!targetActor.isRootActor);
    const messages = [];
    // Filter out messages that came from a ServiceWorker but happened
    // before the page was requested.
    for (const message of cachedMessages) {
      if (
        message.innerID === "ServiceWorker" &&
        winStartTime > message.timeStamp
      ) {
        continue;
      }
      messages.push({
        resourceType: CONSOLE_MESSAGE,
        message: prepareConsoleMessageForRemote(targetActor, message),
      });
    }
    onAvailable(messages);
  }

  /**
   * Stop watching for console messages.
   */
  destroy() {
    if (this.listener) {
      this.listener.destroy();
      this.listener = null;
    }
    this.targetActor = null;
    this.onAvailable = null;
  }

  /**
   * Spawn some custom console messages.
   * This is used for example for log points and JS tracing.
   *
   * @param Array<Object> messages
   *        A list of fake nsIConsoleMessage, which looks like the one being generated by
   *        the platform API.
   */
  emitMessages(messages) {
    if (!this.listener) {
      throw new Error("This target actor isn't listening to console messages");
    }
    this.onAvailable(
      messages.map(message => {
        if (!message.timeStamp) {
          throw new Error("timeStamp property is mandatory");
        }

        return {
          resourceType: CONSOLE_MESSAGE,
          message: prepareConsoleMessageForRemote(this.targetActor, message),
        };
      })
    );
  }
}

module.exports = ConsoleMessageWatcher;

/**
 * Return the properties needed to display the appropriate table for a given
 * console.table call.
 * This function does a little more than creating an ObjectActor for the first
 * parameter of the message. When layout out the console table in the output, we want
 * to be able to look into sub-properties so the table can have a different layout (
 * for arrays of arrays, objects with objects properties, arrays of objects, …).
 * So here we need to retrieve the properties of the first parameter, and also all the
 * sub-properties we might need.
 *
 * @param {TargetActor} targetActor: The Target Actor from which this object originates.
 * @param {Object} result: The console.table message.
 * @returns {Object} An object containing the properties of the first argument of the
 *                   console.table call.
 */
function getConsoleTableMessageItems(targetActor, result) {
  const [tableItemGrip] = result.arguments;
  const dataType = tableItemGrip.class;
  const needEntries = ["Map", "WeakMap", "Set", "WeakSet"].includes(dataType);
  const ignoreNonIndexedProperties = isArray(tableItemGrip);

  const tableItemActor = targetActor.getActorByID(tableItemGrip.actor);
  if (!tableItemActor) {
    return null;
  }

  // Retrieve the properties (or entries for Set/Map) of the console table first arg.
  const iterator = needEntries
    ? tableItemActor.enumEntries()
    : tableItemActor.enumProperties({
        ignoreNonIndexedProperties,
      });
  const { ownProperties } = iterator.all();

  // The iterator returns a descriptor for each property, wherein the value could be
  // in one of those sub-property.
  const descriptorKeys = ["safeGetterValues", "getterValue", "value"];

  Object.values(ownProperties).forEach(desc => {
    if (typeof desc !== "undefined") {
      descriptorKeys.forEach(key => {
        if (desc && desc.hasOwnProperty(key)) {
          const grip = desc[key];

          // We need to load sub-properties as well to render the table in a nice way.
          const actor = grip && targetActor.getActorByID(grip.actor);
          if (actor) {
            const res = actor
              .enumProperties({
                ignoreNonIndexedProperties: isArray(grip),
              })
              .all();
            if (res?.ownProperties) {
              desc[key].ownProperties = res.ownProperties;
            }
          }
        }
      });
    }
  });

  return ownProperties;
}

/**
 * Prepare a message from the console API to be sent to the remote Web Console
 * instance.
 *
 * @param TargetActor targetActor
 *        The related target actor
 * @param object message
 *        The original message received from the console storage listener.
 * @return object
 *         The object that can be sent to the remote client.
 */
function prepareConsoleMessageForRemote(targetActor, message) {
  const result = {
    arguments: message.arguments
      ? message.arguments.map(obj => {
          const dbgObj = makeDebuggeeValue(targetActor, obj);
          return createValueGripForTarget(targetActor, dbgObj);
        })
      : [],
    columnNumber: message.columnNumber,
    filename: message.filename,
    level: message.level,
    lineNumber: message.lineNumber,
    // messages emitted from Console.sys.mjs don't have a microSecondTimeStamp property
    timeStamp: message.microSecondTimeStamp
      ? message.microSecondTimeStamp / 1000
      : message.timeStamp || ChromeUtils.dateNow(),
    sourceId: getActorIdForInternalSourceId(targetActor, message.sourceId),
    innerWindowID: message.innerID,
  };

  // This can be a hot path when loading lots of messages, and it only make sense to
  // include the following properties in the message when they have a meaningful value.
  // Otherwise we simply don't include them so we save cycles in JSActor communication.
  if (message.chromeContext) {
    result.chromeContext = message.chromeContext;
  }

  if (message.counter) {
    result.counter = message.counter;
  }
  if (message.private) {
    result.private = message.private;
  }
  if (message.prefix) {
    result.prefix = message.prefix;
  }

  if (message.stacktrace) {
    result.stacktrace = message.stacktrace.map(frame => {
      return {
        ...frame,
        sourceId: getActorIdForInternalSourceId(targetActor, frame.sourceId),
      };
    });
  }

  if (message.styles && message.styles.length) {
    result.styles = message.styles.map(string => {
      return createValueGripForTarget(targetActor, string);
    });
  }

  if (message.timer) {
    result.timer = message.timer;
  }

  if (message.level === "table") {
    if (result && isSupportedByConsoleTable(result.arguments)) {
      const tableItems = getConsoleTableMessageItems(targetActor, result);
      if (tableItems) {
        result.arguments[0].ownProperties = tableItems;
        result.arguments[0].preview = null;

        // Only return the 2 first params.
        result.arguments = result.arguments.slice(0, 2);
      }
    }
    // NOTE: See transformConsoleAPICallResource for not-supported case.
  }

  return result;
}