summaryrefslogtreecommitdiffstats
path: root/devtools/client/netmonitor/src/components/messages
diff options
context:
space:
mode:
Diffstat (limited to 'devtools/client/netmonitor/src/components/messages')
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnData.js60
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnEventName.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnFinBit.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnLastEventId.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnMaskBit.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnOpCode.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnRetry.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnSize.js43
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnTime.js56
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageFilterMenu.js122
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageListContent.js398
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js62
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageListHeader.js121
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageListHeaderContextMenu.js61
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageListItem.js127
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessagePayload.js403
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessagesView.js173
-rw-r--r--devtools/client/netmonitor/src/components/messages/RawData.js34
-rw-r--r--devtools/client/netmonitor/src/components/messages/StatusBar.js130
-rw-r--r--devtools/client/netmonitor/src/components/messages/Toolbar.js152
-rw-r--r--devtools/client/netmonitor/src/components/messages/cbor.js270
-rw-r--r--devtools/client/netmonitor/src/components/messages/moz.build32
-rw-r--r--devtools/client/netmonitor/src/components/messages/msgpack.js365
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/moz.build11
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js82
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js33
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js120
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js33
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js25
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js13
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build12
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js48
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js84
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js292
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build10
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js56
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build7
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js25
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js204
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build10
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js230
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js274
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build8
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js73
46 files changed, 4579 insertions, 0 deletions
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnData.js b/devtools/client/netmonitor/src/components/messages/ColumnData.js
new file mode 100644
index 0000000000..2c4b7c1b60
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnData.js
@@ -0,0 +1,60 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ limitTooltipLength,
+} = require("resource://devtools/client/netmonitor/src/utils/tooltips.js");
+
+/**
+ * Renders the "Data" column of a message.
+ */
+class ColumnData extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ connector: PropTypes.object.isRequired,
+ };
+ }
+
+ render() {
+ const { type, payload } = this.props.item;
+ // type could be undefined for sse channel.
+ const typeLabel = type ? L10N.getStr(`netmonitor.ws.type.${type}`) : null;
+
+ // If payload is a LongStringActor object, we show the first 1000 characters
+ const displayedPayload = payload.initial ? payload.initial : payload;
+
+ const frameTypeImg = type
+ ? dom.img({
+ alt: typeLabel,
+ className: `message-list-type-icon message-list-type-icon-${type}`,
+ src: `chrome://devtools/content/netmonitor/src/assets/icons/arrow-up.svg`,
+ })
+ : null;
+
+ let title = limitTooltipLength(displayedPayload);
+ title = type ? typeLabel + " " + title : title;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-payload",
+ title,
+ },
+ frameTypeImg,
+ " " + displayedPayload
+ );
+ }
+}
+
+module.exports = ColumnData;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnEventName.js b/devtools/client/netmonitor/src/components/messages/ColumnEventName.js
new file mode 100644
index 0000000000..812de4d40c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnEventName.js
@@ -0,0 +1,40 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+/**
+ * Renders the "EventName" column of a message.
+ */
+class ColumnEventName extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.eventName !== nextProps.item.eventName;
+ }
+
+ render() {
+ const { eventName } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-eventName",
+ title: eventName,
+ },
+ eventName
+ );
+ }
+}
+
+module.exports = ColumnEventName;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnFinBit.js b/devtools/client/netmonitor/src/components/messages/ColumnFinBit.js
new file mode 100644
index 0000000000..8f9a1d9e0b
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnFinBit.js
@@ -0,0 +1,40 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+/**
+ * Renders the "FinBit" column of a message.
+ */
+class ColumnFinBit extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.finBit !== nextProps.item.finBit;
+ }
+
+ render() {
+ const { finBit } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-finBit",
+ title: finBit.toString(),
+ },
+ finBit.toString()
+ );
+ }
+}
+
+module.exports = ColumnFinBit;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnLastEventId.js b/devtools/client/netmonitor/src/components/messages/ColumnLastEventId.js
new file mode 100644
index 0000000000..2c5a65313a
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnLastEventId.js
@@ -0,0 +1,40 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+/**
+ * Renders the "LastEventId" column of a message.
+ */
+class ColumnLastEventId extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.lastEventId !== nextProps.item.lastEventId;
+ }
+
+ render() {
+ const { lastEventId } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-lastEventId",
+ title: lastEventId,
+ },
+ lastEventId
+ );
+ }
+}
+
+module.exports = ColumnLastEventId;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnMaskBit.js b/devtools/client/netmonitor/src/components/messages/ColumnMaskBit.js
new file mode 100644
index 0000000000..20330ebc92
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnMaskBit.js
@@ -0,0 +1,40 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+/**
+ * Renders the "MaskBit" column of a message.
+ */
+class ColumnMaskBit extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.maskBit !== nextProps.item.maskBit;
+ }
+
+ render() {
+ const { maskBit } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-maskBit",
+ title: maskBit.toString(),
+ },
+ maskBit.toString()
+ );
+ }
+}
+
+module.exports = ColumnMaskBit;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnOpCode.js b/devtools/client/netmonitor/src/components/messages/ColumnOpCode.js
new file mode 100644
index 0000000000..2fcdc85ed0
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnOpCode.js
@@ -0,0 +1,40 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+/**
+ * Renders the "OpCode" column of a message.
+ */
+class ColumnOpCode extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.opCode !== nextProps.item.opCode;
+ }
+
+ render() {
+ const { opCode } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-opCode",
+ title: opCode,
+ },
+ opCode
+ );
+ }
+}
+
+module.exports = ColumnOpCode;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnRetry.js b/devtools/client/netmonitor/src/components/messages/ColumnRetry.js
new file mode 100644
index 0000000000..e1fb63d706
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnRetry.js
@@ -0,0 +1,40 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+/**
+ * Renders the "Retry" column of a message.
+ */
+class ColumnRetry extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.retry !== nextProps.item.retry;
+ }
+
+ render() {
+ const { retry } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-retry",
+ title: retry,
+ },
+ retry
+ );
+ }
+}
+
+module.exports = ColumnRetry;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnSize.js b/devtools/client/netmonitor/src/components/messages/ColumnSize.js
new file mode 100644
index 0000000000..4f00e1a521
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnSize.js
@@ -0,0 +1,43 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ getFormattedSize,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+/**
+ * Renders the "Size" column of a message.
+ */
+class ColumnSize extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.payload !== nextProps.item.payload;
+ }
+
+ render() {
+ const { payload } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-size",
+ title: getFormattedSize(payload.length),
+ },
+ getFormattedSize(payload.length)
+ );
+ }
+}
+
+module.exports = ColumnSize;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnTime.js b/devtools/client/netmonitor/src/components/messages/ColumnTime.js
new file mode 100644
index 0000000000..594a6b705b
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnTime.js
@@ -0,0 +1,56 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+/**
+ * Renders the "Time" column of a message.
+ */
+class ColumnTime extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ this.props.item.type !== nextProps.item.type ||
+ this.props.item.timeStamp !== nextProps.item.timeStamp
+ );
+ }
+
+ /**
+ * Format a DOMHighResTimeStamp (in microseconds) as HH:mm:ss.SSS
+ * @param {number} highResTimeStamp
+ */
+ formatTime(highResTimeStamp) {
+ const date = new Date(highResTimeStamp / 1000);
+ const hh = date.getHours().toString().padStart(2, "0");
+ const mm = date.getMinutes().toString().padStart(2, "0");
+ const ss = date.getSeconds().toString().padStart(2, "0");
+ const mmm = date.getMilliseconds().toString().padStart(3, "0");
+ return `${hh}:${mm}:${ss}.${mmm}`;
+ }
+
+ render() {
+ const label = this.formatTime(this.props.item.timeStamp);
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-time",
+ title: label,
+ },
+ label
+ );
+ }
+}
+
+module.exports = ColumnTime;
diff --git a/devtools/client/netmonitor/src/components/messages/MessageFilterMenu.js b/devtools/client/netmonitor/src/components/messages/MessageFilterMenu.js
new file mode 100644
index 0000000000..b2cd2d346d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageFilterMenu.js
@@ -0,0 +1,122 @@
+/* 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 {
+ PureComponent,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+// Menu
+loader.lazyRequireGetter(
+ this,
+ "showMenu",
+ "resource://devtools/client/shared/components/menu/utils.js",
+ true
+);
+
+class MessageFilterMenu extends PureComponent {
+ static get propTypes() {
+ return {
+ messageFilterType: PropTypes.string.isRequired,
+ toggleMessageFilterType: PropTypes.func.isRequired,
+ // showControlFrames decides if control frames
+ // will be shown in messages panel
+ showControlFrames: PropTypes.bool.isRequired,
+ // toggleControlFrames toggles the value for showControlFrames
+ toggleControlFrames: PropTypes.func.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.onShowFilterMenu = this.onShowFilterMenu.bind(this);
+ }
+
+ onShowFilterMenu(event) {
+ const {
+ messageFilterType,
+ toggleMessageFilterType,
+ showControlFrames,
+ toggleControlFrames,
+ } = this.props;
+
+ const menuItems = [
+ {
+ id: "message-list-context-filter-all",
+ label: L10N.getStr("netmonitor.ws.context.all"),
+ accesskey: L10N.getStr("netmonitor.ws.context.all.accesskey"),
+ type: "checkbox",
+ checked: messageFilterType === "all",
+ click: () => {
+ toggleMessageFilterType("all");
+ },
+ },
+ {
+ id: "message-list-context-filter-sent",
+ label: L10N.getStr("netmonitor.ws.context.sent"),
+ accesskey: L10N.getStr("netmonitor.ws.context.sent.accesskey"),
+ type: "checkbox",
+ checked: messageFilterType === "sent",
+ click: () => {
+ toggleMessageFilterType("sent");
+ },
+ },
+ {
+ id: "message-list-context-filter-received",
+ label: L10N.getStr("netmonitor.ws.context.received"),
+ accesskey: L10N.getStr("netmonitor.ws.context.received.accesskey"),
+ type: "checkbox",
+ checked: messageFilterType === "received",
+ click: () => {
+ toggleMessageFilterType("received");
+ },
+ },
+ {
+ type: "separator",
+ },
+ {
+ id: "message-list-context-filter-controlFrames",
+ label: L10N.getStr("netmonitor.ws.context.controlFrames"),
+ accesskey: L10N.getStr("netmonitor.ws.context.controlFrames.accesskey"),
+ type: "checkbox",
+ checked: showControlFrames,
+ click: () => {
+ toggleControlFrames();
+ },
+ },
+ ];
+
+ showMenu(menuItems, { button: event.target });
+ }
+
+ render() {
+ const { messageFilterType, showControlFrames } = this.props;
+ const messageFilterTypeTitle = L10N.getStr(
+ `netmonitor.ws.context.${messageFilterType}`
+ );
+ const title =
+ messageFilterTypeTitle +
+ (showControlFrames
+ ? " (" + L10N.getStr(`netmonitor.ws.context.controlFrames`) + ")"
+ : "");
+
+ return dom.button(
+ {
+ id: "frame-filter-menu",
+ className: "devtools-button devtools-dropdown-button",
+ title,
+ onClick: this.onShowFilterMenu,
+ },
+ dom.span({ className: "title" }, title)
+ );
+ }
+}
+
+module.exports = MessageFilterMenu;
diff --git a/devtools/client/netmonitor/src/components/messages/MessageListContent.js b/devtools/client/netmonitor/src/components/messages/MessageListContent.js
new file mode 100644
index 0000000000..f4377911af
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageListContent.js
@@ -0,0 +1,398 @@
+/* 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 {
+ Component,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const { PluralForm } = require("resource://devtools/shared/plural-form.js");
+const {
+ getDisplayedMessages,
+ isCurrentChannelClosed,
+ getClosedConnectionDetails,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const { table, tbody, tr, td, div, input, label, hr, p } = dom;
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const MESSAGES_EMPTY_TEXT = L10N.getStr("messagesEmptyText");
+const TOGGLE_MESSAGES_TRUNCATION = L10N.getStr("toggleMessagesTruncation");
+const TOGGLE_MESSAGES_TRUNCATION_TITLE = L10N.getStr(
+ "toggleMessagesTruncation.title"
+);
+const CONNECTION_CLOSED_TEXT = L10N.getStr("netmonitor.ws.connection.closed");
+const {
+ MESSAGE_HEADERS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+
+const {
+ getSelectedMessage,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+// Components
+const MessageListContextMenu = require("resource://devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js");
+loader.lazyGetter(this, "MessageListHeader", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessageListHeader.js")
+ );
+});
+loader.lazyGetter(this, "MessageListItem", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessageListItem.js")
+ );
+});
+
+const LEFT_MOUSE_BUTTON = 0;
+
+/**
+ * Renders the actual contents of the message list.
+ */
+class MessageListContent extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ startPanelContainer: PropTypes.object,
+ messages: PropTypes.array,
+ selectedMessage: PropTypes.object,
+ selectMessage: PropTypes.func.isRequired,
+ columns: PropTypes.object.isRequired,
+ isClosed: PropTypes.bool.isRequired,
+ closedConnectionDetails: PropTypes.object,
+ channelId: PropTypes.number,
+ onSelectMessageDelta: PropTypes.func.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.onContextMenu = this.onContextMenu.bind(this);
+ this.onKeyDown = this.onKeyDown.bind(this);
+ this.messagesLimit = Services.prefs.getIntPref(
+ "devtools.netmonitor.msg.displayed-messages.limit"
+ );
+ this.currentTruncatedNum = 0;
+ this.state = {
+ checked: false,
+ };
+ this.pinnedToBottom = false;
+ this.initIntersectionObserver = false;
+ this.intersectionObserver = null;
+ this.toggleTruncationCheckBox = this.toggleTruncationCheckBox.bind(this);
+ }
+
+ componentDidMount() {
+ const { startPanelContainer } = this.props;
+ const { scrollAnchor } = this.refs;
+
+ if (scrollAnchor) {
+ // Always scroll to anchor when MessageListContent component first mounts.
+ scrollAnchor.scrollIntoView();
+ }
+ this.setupScrollToBottom(startPanelContainer, scrollAnchor);
+ }
+
+ componentDidUpdate(prevProps) {
+ const { startPanelContainer, channelId } = this.props;
+ const { scrollAnchor } = this.refs;
+
+ // When messages are cleared, the previous scrollAnchor would be destroyed, so we need to reset this boolean.
+ if (!scrollAnchor) {
+ this.initIntersectionObserver = false;
+ }
+
+ // In addition to that, we need to reset currentTruncatedNum
+ if (prevProps.messages.length && this.props.messages.length === 0) {
+ this.currentTruncatedNum = 0;
+ }
+
+ // If a new connection is selected, scroll to anchor.
+ if (channelId !== prevProps.channelId && scrollAnchor) {
+ scrollAnchor.scrollIntoView();
+ }
+
+ // Do not autoscroll if the selection changed. This would cause
+ // the newly selected message to jump just after clicking in.
+ // (not user friendly)
+ //
+ // If the selection changed, we need to ensure that the newly
+ // selected message is properly scrolled into the visible area.
+ if (prevProps.selectedMessage === this.props.selectedMessage) {
+ this.setupScrollToBottom(startPanelContainer, scrollAnchor);
+ } else {
+ const head = document.querySelector("thead.message-list-headers-group");
+ const selectedRow = document.querySelector(
+ "tr.message-list-item.selected"
+ );
+
+ if (selectedRow) {
+ const rowRect = selectedRow.getBoundingClientRect();
+ const scrollableRect = startPanelContainer.getBoundingClientRect();
+ const headRect = head.getBoundingClientRect();
+
+ if (rowRect.top <= scrollableRect.top) {
+ selectedRow.scrollIntoView(true);
+
+ // We need to scroll a bit more to get the row out
+ // of the header. The header is sticky and overlaps
+ // part of the scrollable area.
+ startPanelContainer.scrollTop -= headRect.height;
+ } else if (rowRect.bottom > scrollableRect.bottom) {
+ selectedRow.scrollIntoView(false);
+ }
+ }
+ }
+ }
+
+ componentWillUnmount() {
+ // Reset observables and boolean values.
+ const { scrollAnchor } = this.refs;
+
+ if (this.intersectionObserver) {
+ if (scrollAnchor) {
+ this.intersectionObserver.unobserve(scrollAnchor);
+ }
+ this.initIntersectionObserver = false;
+ this.pinnedToBottom = false;
+ }
+ }
+
+ setupScrollToBottom(startPanelContainer, scrollAnchor) {
+ if (startPanelContainer && scrollAnchor) {
+ // Initialize intersection observer.
+ if (!this.initIntersectionObserver) {
+ this.intersectionObserver = new IntersectionObserver(
+ () => {
+ // When scrollAnchor first comes into view, this.pinnedToBottom is set to true.
+ // When the anchor goes out of view, this callback function triggers again and toggles this.pinnedToBottom.
+ // Subsequent scroll into/out of view will toggle this.pinnedToBottom.
+ this.pinnedToBottom = !this.pinnedToBottom;
+ },
+ {
+ root: startPanelContainer,
+ threshold: 0.1,
+ }
+ );
+ if (this.intersectionObserver) {
+ this.intersectionObserver.observe(scrollAnchor);
+ this.initIntersectionObserver = true;
+ }
+ }
+
+ if (this.pinnedToBottom) {
+ scrollAnchor.scrollIntoView();
+ }
+ }
+ }
+
+ toggleTruncationCheckBox() {
+ this.setState({
+ checked: !this.state.checked,
+ });
+ }
+
+ onMouseDown(evt, item) {
+ if (evt.button === LEFT_MOUSE_BUTTON) {
+ this.props.selectMessage(item);
+ }
+ }
+
+ onContextMenu(evt, item) {
+ evt.preventDefault();
+ const { connector } = this.props;
+ this.contextMenu = new MessageListContextMenu({
+ connector,
+ });
+ this.contextMenu.open(evt, item);
+ }
+
+ /**
+ * Handler for keyboard events. For arrow up/down, page up/down, home/end,
+ * move the selection up or down.
+ */
+ onKeyDown(evt) {
+ evt.preventDefault();
+ evt.stopPropagation();
+ let delta;
+
+ switch (evt.key) {
+ case "ArrowUp":
+ delta = -1;
+ break;
+ case "ArrowDown":
+ delta = +1;
+ break;
+ case "PageUp":
+ delta = "PAGE_UP";
+ break;
+ case "PageDown":
+ delta = "PAGE_DOWN";
+ break;
+ case "Home":
+ delta = -Infinity;
+ break;
+ case "End":
+ delta = +Infinity;
+ break;
+ }
+
+ if (delta) {
+ this.props.onSelectMessageDelta(delta);
+ }
+ }
+
+ render() {
+ const {
+ messages,
+ selectedMessage,
+ connector,
+ columns,
+ isClosed,
+ closedConnectionDetails,
+ } = this.props;
+
+ if (messages.length === 0) {
+ return div(
+ { className: "empty-notice message-list-empty-notice" },
+ MESSAGES_EMPTY_TEXT
+ );
+ }
+
+ const visibleColumns = MESSAGE_HEADERS.filter(
+ header => columns[header.name]
+ ).map(col => col.name);
+
+ let displayedMessages;
+ let MESSAGES_TRUNCATED;
+ const shouldTruncate = messages.length > this.messagesLimit;
+ if (shouldTruncate) {
+ // If the checkbox is checked, we display all messages after the currentTruncatedNum limit.
+ // If the checkbox is unchecked, we display all messages after the messagesLimit.
+ this.currentTruncatedNum = this.state.checked
+ ? this.currentTruncatedNum
+ : messages.length - this.messagesLimit;
+ displayedMessages = messages.slice(this.currentTruncatedNum);
+
+ MESSAGES_TRUNCATED = PluralForm.get(
+ this.currentTruncatedNum,
+ L10N.getStr("netmonitor.ws.truncated-messages.warning")
+ ).replace("#1", this.currentTruncatedNum);
+ } else {
+ displayedMessages = messages;
+ }
+
+ let connectionClosedMsg = CONNECTION_CLOSED_TEXT;
+ if (
+ closedConnectionDetails &&
+ closedConnectionDetails.code !== undefined &&
+ closedConnectionDetails.reason !== undefined
+ ) {
+ connectionClosedMsg += `: ${closedConnectionDetails.code} ${closedConnectionDetails.reason}`;
+ }
+ return div(
+ {},
+ table(
+ { className: "message-list-table" },
+ MessageListHeader(),
+ tbody(
+ {
+ className: "message-list-body",
+ onKeyDown: this.onKeyDown,
+ },
+ tr(
+ {
+ tabIndex: 0,
+ },
+ td(
+ {
+ className: "truncated-messages-cell",
+ colSpan: visibleColumns.length,
+ },
+ shouldTruncate &&
+ div(
+ {
+ className: "truncated-messages-header",
+ },
+ div(
+ {
+ className: "truncated-messages-container",
+ },
+ div({
+ className: "truncated-messages-warning-icon",
+ }),
+ div(
+ {
+ className: "truncated-message",
+ title: MESSAGES_TRUNCATED,
+ },
+ MESSAGES_TRUNCATED
+ )
+ ),
+ label(
+ {
+ className: "truncated-messages-checkbox-label",
+ title: TOGGLE_MESSAGES_TRUNCATION_TITLE,
+ },
+ input({
+ type: "checkbox",
+ className: "truncation-checkbox",
+ title: TOGGLE_MESSAGES_TRUNCATION_TITLE,
+ checked: this.state.checked,
+ onChange: this.toggleTruncationCheckBox,
+ }),
+ TOGGLE_MESSAGES_TRUNCATION
+ )
+ )
+ )
+ ),
+ displayedMessages.map((item, index) =>
+ MessageListItem({
+ key: "message-list-item-" + index,
+ item,
+ index,
+ isSelected: item === selectedMessage,
+ onMouseDown: evt => this.onMouseDown(evt, item),
+ onContextMenu: evt => this.onContextMenu(evt, item),
+ connector,
+ visibleColumns,
+ })
+ )
+ )
+ ),
+ isClosed &&
+ p(
+ {
+ className: "msg-connection-closed-message",
+ },
+ connectionClosedMsg
+ ),
+ hr({
+ ref: "scrollAnchor",
+ className: "message-list-scroll-anchor",
+ })
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ selectedMessage: getSelectedMessage(state),
+ messages: getDisplayedMessages(state),
+ columns: state.messages.columns,
+ isClosed: isCurrentChannelClosed(state),
+ closedConnectionDetails: getClosedConnectionDetails(state),
+ }),
+ dispatch => ({
+ selectMessage: item => dispatch(Actions.selectMessage(item)),
+ onSelectMessageDelta: delta => dispatch(Actions.selectMessageDelta(delta)),
+ })
+)(MessageListContent);
diff --git a/devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js b/devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js
new file mode 100644
index 0000000000..a3169ab12c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js
@@ -0,0 +1,62 @@
+/* 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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+loader.lazyRequireGetter(
+ this,
+ "showMenu",
+ "resource://devtools/client/shared/components/menu/utils.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "copyString",
+ "resource://devtools/shared/platform/clipboard.js",
+ true
+);
+const {
+ getMessagePayload,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+class MessageListContextMenu {
+ constructor(props) {
+ this.props = props;
+ }
+
+ /**
+ * Handle the context menu opening.
+ */
+ open(event = {}, item) {
+ const menuItems = [
+ {
+ id: `message-list-context-copy-message`,
+ label: L10N.getStr("netmonitor.ws.context.copyFrame"),
+ accesskey: L10N.getStr("netmonitor.ws.context.copyFrame.accesskey"),
+ click: () => this.copyMessagePayload(item),
+ },
+ ];
+
+ showMenu(menuItems, {
+ screenX: event.screenX,
+ screenY: event.screenY,
+ });
+ }
+
+ /**
+ * Copy the full payload from the selected message.
+ */
+ copyMessagePayload(item) {
+ getMessagePayload(item.payload, this.props.connector.getLongString).then(
+ payload => {
+ copyString(payload);
+ }
+ );
+ }
+}
+
+module.exports = MessageListContextMenu;
diff --git a/devtools/client/netmonitor/src/components/messages/MessageListHeader.js b/devtools/client/netmonitor/src/components/messages/MessageListHeader.js
new file mode 100644
index 0000000000..b3c49ac0eb
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageListHeader.js
@@ -0,0 +1,121 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ MESSAGE_HEADERS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+
+// Components
+const MessageListHeaderContextMenu = require("resource://devtools/client/netmonitor/src/components/messages/MessageListHeaderContextMenu.js");
+
+/**
+ * Renders the message list header.
+ */
+class MessageListHeader extends Component {
+ static get propTypes() {
+ return {
+ columns: PropTypes.object.isRequired,
+ toggleColumn: PropTypes.func.isRequired,
+ resetColumns: PropTypes.func.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.onContextMenu = this.onContextMenu.bind(this);
+ }
+
+ onContextMenu(evt) {
+ evt.preventDefault();
+ const { resetColumns, toggleColumn, columns } = this.props;
+
+ if (!this.contextMenu) {
+ this.contextMenu = new MessageListHeaderContextMenu({
+ toggleColumn,
+ resetColumns,
+ });
+ }
+ this.contextMenu.open(evt, columns);
+ }
+
+ /**
+ * Helper method to get visibleColumns.
+ */
+ getVisibleColumns() {
+ const { columns } = this.props;
+ return MESSAGE_HEADERS.filter(header => columns[header.name]);
+ }
+
+ /**
+ * Render one column header from the table headers.
+ */
+ renderColumn({ name, width = "10%" }) {
+ const label = L10N.getStr(`netmonitor.ws.toolbar.${name}`);
+
+ return dom.th(
+ {
+ key: name,
+ id: `message-list-${name}-header-box`,
+ className: `message-list-column message-list-${name}`,
+ scope: "col",
+ style: { width },
+ },
+ dom.button(
+ {
+ id: `message-list-${name}-button`,
+ className: `message-list-header-button`,
+ title: label,
+ },
+ dom.div({ className: "button-text" }, label),
+ dom.div({ className: "button-icon" })
+ )
+ );
+ }
+
+ /**
+ * Render all columns in the table header.
+ */
+ renderColumns() {
+ const visibleColumns = this.getVisibleColumns();
+ return visibleColumns.map(header => this.renderColumn(header));
+ }
+
+ render() {
+ return dom.thead(
+ { className: "message-list-headers-group" },
+ dom.tr(
+ {
+ className: "message-list-headers",
+ onContextMenu: this.onContextMenu,
+ },
+ this.renderColumns()
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ columns: state.messages.columns,
+ }),
+ dispatch => ({
+ toggleColumn: column => dispatch(Actions.toggleMessageColumn(column)),
+ resetColumns: () => dispatch(Actions.resetMessageColumns()),
+ })
+)(MessageListHeader);
diff --git a/devtools/client/netmonitor/src/components/messages/MessageListHeaderContextMenu.js b/devtools/client/netmonitor/src/components/messages/MessageListHeaderContextMenu.js
new file mode 100644
index 0000000000..edf99bd5ac
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageListHeaderContextMenu.js
@@ -0,0 +1,61 @@
+/* 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 {
+ showMenu,
+} = require("resource://devtools/client/shared/components/menu/utils.js");
+const {
+ MESSAGE_HEADERS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+class MessageListHeaderContextMenu {
+ constructor(props) {
+ this.props = props;
+ }
+
+ /**
+ * Handle the context menu opening.
+ */
+ open(event = {}, columns) {
+ const visibleColumns = Object.values(columns).filter(state => state);
+ const onlyOneColumn = visibleColumns.length === 1;
+
+ const columnsToShow = Object.keys(columns);
+ const menuItems = MESSAGE_HEADERS.filter(({ name }) =>
+ columnsToShow.includes(name)
+ ).map(({ name: column }) => {
+ const shown = columns[column];
+ const label = L10N.getStr(`netmonitor.ws.toolbar.${column}`);
+ return {
+ id: `message-list-header-${column}-toggle`,
+ label,
+ type: "checkbox",
+ checked: shown,
+ click: () => this.props.toggleColumn(column),
+ // We don't want to allow hiding the last visible column
+ disabled: onlyOneColumn && shown,
+ };
+ });
+ menuItems.push(
+ { type: "separator" },
+ {
+ id: "message-list-header-reset-columns",
+ label: L10N.getStr("netmonitor.ws.toolbar.resetColumns"),
+ click: () => this.props.resetColumns(),
+ }
+ );
+
+ showMenu(menuItems, {
+ screenX: event.screenX,
+ screenY: event.screenY,
+ });
+ }
+}
+
+module.exports = MessageListHeaderContextMenu;
diff --git a/devtools/client/netmonitor/src/components/messages/MessageListItem.js b/devtools/client/netmonitor/src/components/messages/MessageListItem.js
new file mode 100644
index 0000000000..a5d837a31b
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageListItem.js
@@ -0,0 +1,127 @@
+/* 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 {
+ Component,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+loader.lazyGetter(this, "ColumnData", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnData.js")
+ );
+});
+loader.lazyGetter(this, "ColumnEventName", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnEventName.js")
+ );
+});
+loader.lazyGetter(this, "ColumnFinBit", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnFinBit.js")
+ );
+});
+loader.lazyGetter(this, "ColumnLastEventId", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnLastEventId.js")
+ );
+});
+loader.lazyGetter(this, "ColumnMaskBit", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnMaskBit.js")
+ );
+});
+loader.lazyGetter(this, "ColumnOpCode", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnOpCode.js")
+ );
+});
+loader.lazyGetter(this, "ColumnRetry", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnRetry.js")
+ );
+});
+loader.lazyGetter(this, "ColumnSize", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnSize.js")
+ );
+});
+loader.lazyGetter(this, "ColumnTime", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnTime.js")
+ );
+});
+
+const COLUMN_COMPONENT_MAP = {
+ data: ColumnData,
+ eventName: ColumnEventName,
+ finBit: ColumnFinBit,
+ lastEventId: ColumnLastEventId,
+ maskBit: ColumnMaskBit,
+ opCode: ColumnOpCode,
+ retry: ColumnRetry,
+ size: ColumnSize,
+ time: ColumnTime,
+};
+
+/**
+ * Renders one row in the list.
+ */
+class MessageListItem extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ index: PropTypes.number.isRequired,
+ isSelected: PropTypes.bool.isRequired,
+ onMouseDown: PropTypes.func.isRequired,
+ onContextMenu: PropTypes.func.isRequired,
+ connector: PropTypes.object.isRequired,
+ visibleColumns: PropTypes.array.isRequired,
+ };
+ }
+
+ render() {
+ const {
+ item,
+ index,
+ isSelected,
+ onMouseDown,
+ onContextMenu,
+ connector,
+ visibleColumns,
+ } = this.props;
+
+ const classList = [
+ "message-list-item",
+ index % 2 ? "odd" : "even",
+ item.type,
+ ];
+ if (isSelected) {
+ classList.push("selected");
+ }
+
+ return dom.tr(
+ {
+ className: classList.join(" "),
+ tabIndex: 0,
+ onMouseDown,
+ onContextMenu,
+ },
+ visibleColumns.map(name => {
+ const ColumnComponent = COLUMN_COMPONENT_MAP[name];
+ return ColumnComponent({
+ key: `message-list-column-${name}-${index}`,
+ connector,
+ item,
+ });
+ })
+ );
+ }
+}
+
+module.exports = MessageListItem;
diff --git a/devtools/client/netmonitor/src/components/messages/MessagePayload.js b/devtools/client/netmonitor/src/components/messages/MessagePayload.js
new file mode 100644
index 0000000000..b8d3f7ae33
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessagePayload.js
@@ -0,0 +1,403 @@
+/* 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 {
+ Component,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const { div, input, label, span, h2 } = dom;
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ getMessagePayload,
+ getResponseHeader,
+ parseJSON,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getFormattedSize,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const MESSAGE_DATA_LIMIT = Services.prefs.getIntPref(
+ "devtools.netmonitor.msg.messageDataLimit"
+);
+const MESSAGE_DATA_TRUNCATED = L10N.getStr("messageDataTruncated");
+const SocketIODecoder = require("resource://devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js");
+const {
+ JsonHubProtocol,
+ HandshakeProtocol,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js");
+const {
+ parseSockJS,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js");
+const {
+ parseStompJs,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js");
+const {
+ wampSerializers,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js");
+const {
+ getRequestByChannelId,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+// Components
+const RawData = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/RawData.js")
+);
+loader.lazyGetter(this, "PropertiesView", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+ );
+});
+
+const RAW_DATA = L10N.getStr("netmonitor.response.raw");
+
+/**
+ * Shows the full payload of a message.
+ * The payload is unwrapped from the LongStringActor object.
+ */
+class MessagePayload extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ selectedMessage: PropTypes.object,
+ request: PropTypes.object.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ payload: "",
+ isFormattedData: false,
+ formattedData: {},
+ formattedDataTitle: "",
+ rawDataDisplayed: false,
+ };
+
+ this.toggleRawData = this.toggleRawData.bind(this);
+ this.renderRawDataBtn = this.renderRawDataBtn.bind(this);
+ }
+
+ componentDidMount() {
+ this.updateMessagePayload();
+ }
+
+ componentDidUpdate(prevProps) {
+ if (this.props.selectedMessage !== prevProps.selectedMessage) {
+ this.updateMessagePayload();
+ }
+ }
+
+ updateMessagePayload() {
+ const { selectedMessage, connector } = this.props;
+
+ getMessagePayload(selectedMessage.payload, connector.getLongString).then(
+ async payload => {
+ const { formattedData, formattedDataTitle } = await this.parsePayload(
+ payload
+ );
+ this.setState({
+ payload,
+ isFormattedData: !!formattedData,
+ formattedData,
+ formattedDataTitle,
+ });
+ }
+ );
+ }
+
+ async parsePayload(payload) {
+ const { connector, selectedMessage, request } = this.props;
+
+ // Don't apply formatting to control frames
+ // Control frame check can be done using opCode as specified here:
+ // https://tools.ietf.org/html/rfc6455
+ const controlFrames = [0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf];
+ const isControlFrame = controlFrames.includes(selectedMessage.opCode);
+ if (isControlFrame) {
+ return {
+ formattedData: null,
+ formattedDataTitle: "",
+ };
+ }
+
+ // Make sure that request headers are fetched from the backend before
+ // looking for `Sec-WebSocket-Protocol` header.
+ const responseHeaders = await connector.requestData(
+ request.id,
+ "responseHeaders"
+ );
+
+ const wsProtocol = getResponseHeader(
+ { responseHeaders },
+ "Sec-WebSocket-Protocol"
+ );
+
+ const wampSerializer = wampSerializers[wsProtocol];
+ if (wampSerializer) {
+ const wampPayload = wampSerializer.deserializeMessage(payload);
+
+ return {
+ formattedData: wampPayload,
+ formattedDataTitle: wampSerializer.description,
+ };
+ }
+
+ // socket.io payload
+ const socketIOPayload = this.parseSocketIOPayload(payload);
+
+ if (socketIOPayload) {
+ return {
+ formattedData: socketIOPayload,
+ formattedDataTitle: "Socket.IO",
+ };
+ }
+ // sockjs payload
+ const sockJSPayload = parseSockJS(payload);
+ if (sockJSPayload) {
+ let formattedData = sockJSPayload.data;
+
+ if (sockJSPayload.type === "message") {
+ if (Array.isArray(formattedData)) {
+ formattedData = formattedData.map(
+ message => parseStompJs(message) || message
+ );
+ } else {
+ formattedData = parseStompJs(formattedData) || formattedData;
+ }
+ }
+
+ return {
+ formattedData,
+ formattedDataTitle: "SockJS",
+ };
+ }
+ // signalr payload
+ const signalRPayload = this.parseSignalR(payload);
+ if (signalRPayload) {
+ return {
+ formattedData: signalRPayload,
+ formattedDataTitle: "SignalR",
+ };
+ }
+ // STOMP
+ const stompPayload = parseStompJs(payload);
+ if (stompPayload) {
+ return {
+ formattedData: stompPayload,
+ formattedDataTitle: "STOMP",
+ };
+ }
+
+ // json payload
+ let { json } = parseJSON(payload);
+ if (json) {
+ const { data, identifier } = json;
+ // A json payload MAY be an "Action cable" if it
+ // contains either a `data` or an `identifier` property
+ // which are also json strings and would need to be parsed.
+ // See https://medium.com/codequest/actioncable-in-rails-api-f087b65c860d
+ if (
+ (data && typeof data == "string") ||
+ (identifier && typeof identifier == "string")
+ ) {
+ const actionCablePayload = this.parseActionCable(json);
+ return {
+ formattedData: actionCablePayload,
+ formattedDataTitle: "Action Cable",
+ };
+ }
+
+ if (Array.isArray(json)) {
+ json = json.map(message => parseStompJs(message) || message);
+ }
+
+ return {
+ formattedData: json,
+ formattedDataTitle: "JSON",
+ };
+ }
+ return {
+ formattedData: null,
+ formattedDataTitle: "",
+ };
+ }
+
+ parseSocketIOPayload(payload) {
+ let result;
+ // Try decoding socket.io frames
+ try {
+ const decoder = new SocketIODecoder();
+ decoder.on("decoded", decodedPacket => {
+ if (
+ decodedPacket &&
+ !decodedPacket.data.includes("parser error") &&
+ decodedPacket.type
+ ) {
+ result = decodedPacket;
+ }
+ });
+ decoder.add(payload);
+ return result;
+ } catch (err) {
+ // Ignore errors
+ }
+ return null;
+ }
+
+ parseSignalR(payload) {
+ // attempt to parse as HandshakeResponseMessage
+ let decoder;
+ try {
+ decoder = new HandshakeProtocol();
+ const [remainingData, responseMessage] =
+ decoder.parseHandshakeResponse(payload);
+
+ if (responseMessage) {
+ return {
+ handshakeResponse: responseMessage,
+ remainingData: this.parseSignalR(remainingData),
+ };
+ }
+ } catch (err) {
+ // ignore errors;
+ }
+
+ // attempt to parse as JsonHubProtocolMessage
+ try {
+ decoder = new JsonHubProtocol();
+ const msgs = decoder.parseMessages(payload, null);
+ if (msgs?.length) {
+ return msgs;
+ }
+ } catch (err) {
+ // ignore errors;
+ }
+
+ // MVP Signalr
+ if (payload.endsWith("\u001e")) {
+ const { json } = parseJSON(payload.slice(0, -1));
+ if (json) {
+ return json;
+ }
+ }
+
+ return null;
+ }
+
+ parseActionCable(payload) {
+ const identifier = payload.identifier && parseJSON(payload.identifier).json;
+ const data = payload.data && parseJSON(payload.data).json;
+
+ if (identifier) {
+ payload.identifier = identifier;
+ }
+ if (data) {
+ payload.data = data;
+ }
+ return payload;
+ }
+
+ toggleRawData() {
+ this.setState({
+ rawDataDisplayed: !this.state.rawDataDisplayed,
+ });
+ }
+
+ renderRawDataBtn(key, checked, onChange) {
+ return [
+ label(
+ {
+ key: `${key}RawDataBtn`,
+ className: "raw-data-toggle",
+ htmlFor: `raw-${key}-checkbox`,
+ onClick: event => {
+ // stop the header click event
+ event.stopPropagation();
+ },
+ },
+ span({ className: "raw-data-toggle-label" }, RAW_DATA),
+ span(
+ { className: "raw-data-toggle-input" },
+ input({
+ id: `raw-${key}-checkbox`,
+ checked,
+ className: "devtools-checkbox-toggle",
+ onChange,
+ type: "checkbox",
+ })
+ )
+ ),
+ ];
+ }
+
+ renderData(component, componentProps) {
+ return component(componentProps);
+ }
+
+ render() {
+ let component;
+ let componentProps;
+ let dataLabel;
+ let { payload, rawDataDisplayed } = this.state;
+ let isTruncated = false;
+ if (this.state.payload.length >= MESSAGE_DATA_LIMIT) {
+ payload = payload.substring(0, MESSAGE_DATA_LIMIT);
+ isTruncated = true;
+ }
+
+ if (
+ !isTruncated &&
+ this.state.isFormattedData &&
+ !this.state.rawDataDisplayed
+ ) {
+ component = PropertiesView;
+ componentProps = {
+ object: this.state.formattedData,
+ };
+ dataLabel = this.state.formattedDataTitle;
+ } else {
+ component = RawData;
+ componentProps = { payload };
+ dataLabel = L10N.getFormatStrWithNumbers(
+ "netmonitor.ws.rawData.header",
+ getFormattedSize(this.state.payload.length)
+ );
+ }
+
+ return div(
+ {
+ className: "message-payload",
+ },
+ isTruncated &&
+ div(
+ {
+ className: "truncated-data-message",
+ },
+ MESSAGE_DATA_TRUNCATED
+ ),
+ h2({ className: "data-header", role: "heading" }, [
+ span({ key: "data-label", className: "data-label" }, dataLabel),
+ !isTruncated &&
+ this.state.isFormattedData &&
+ this.renderRawDataBtn("data", rawDataDisplayed, this.toggleRawData),
+ ]),
+ this.renderData(component, componentProps)
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ request: getRequestByChannelId(state, state.messages.currentChannelId),
+}))(MessagePayload);
diff --git a/devtools/client/netmonitor/src/components/messages/MessagesView.js b/devtools/client/netmonitor/src/components/messages/MessagesView.js
new file mode 100644
index 0000000000..898e28289d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessagesView.js
@@ -0,0 +1,173 @@
+/* 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 {
+ Component,
+ createRef,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const { div } = dom;
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ findDOMNode,
+} = require("resource://devtools/client/shared/vendor/react-dom.js");
+const {
+ getSelectedMessage,
+ isSelectedMessageVisible,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+// Components
+const SplitBox = createFactory(
+ require("resource://devtools/client/shared/components/splitter/SplitBox.js")
+);
+const MessageListContent = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessageListContent.js")
+);
+const Toolbar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/Toolbar.js")
+);
+const StatusBar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/StatusBar.js")
+);
+
+loader.lazyGetter(this, "MessagePayload", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessagePayload.js")
+ );
+});
+
+/**
+ * Renders a list of messages in table view.
+ * Full payload is separated using a SplitBox.
+ */
+class MessagesView extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ selectedMessage: PropTypes.object,
+ messageDetailsOpen: PropTypes.bool.isRequired,
+ openMessageDetailsTab: PropTypes.func.isRequired,
+ selectedMessageVisible: PropTypes.bool.isRequired,
+ channelId: PropTypes.number,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.searchboxRef = createRef();
+ this.clearFilterText = this.clearFilterText.bind(this);
+ this.handleContainerElement = this.handleContainerElement.bind(this);
+ this.state = {
+ startPanelContainer: null,
+ };
+ }
+
+ componentDidUpdate(prevProps) {
+ const { channelId, openMessageDetailsTab, selectedMessageVisible } =
+ this.props;
+
+ // If a new connection is selected, clear the filter text
+ if (channelId !== prevProps.channelId) {
+ this.clearFilterText();
+ }
+
+ if (!selectedMessageVisible) {
+ openMessageDetailsTab(false);
+ }
+ }
+
+ componentWillUnmount() {
+ const { openMessageDetailsTab } = this.props;
+ openMessageDetailsTab(false);
+
+ const { clientHeight } = findDOMNode(this.refs.endPanel) || {};
+
+ if (clientHeight) {
+ Services.prefs.setIntPref(
+ "devtools.netmonitor.msg.payload-preview-height",
+ clientHeight
+ );
+ }
+ }
+
+ /* Store the parent DOM element of the SplitBox startPanel's element.
+ We need this element for as an option for the IntersectionObserver */
+ handleContainerElement(element) {
+ if (!this.state.startPanelContainer) {
+ this.setState({
+ startPanelContainer: element,
+ });
+ }
+ }
+
+ // Reset the filter text
+ clearFilterText() {
+ if (this.searchboxRef) {
+ this.searchboxRef.current.onClearButtonClick();
+ }
+ }
+
+ render() {
+ const { messageDetailsOpen, connector, selectedMessage, channelId } =
+ this.props;
+
+ const { searchboxRef } = this;
+ const { startPanelContainer } = this.state;
+
+ const initialHeight = Services.prefs.getIntPref(
+ "devtools.netmonitor.msg.payload-preview-height"
+ );
+
+ return div(
+ { id: "messages-view", className: "monitor-panel" },
+ Toolbar({
+ searchboxRef,
+ }),
+ SplitBox({
+ className: "devtools-responsive-container",
+ initialHeight,
+ minSize: "50px",
+ maxSize: "80%",
+ splitterSize: messageDetailsOpen ? 1 : 0,
+ onSelectContainerElement: this.handleContainerElement,
+ startPanel: MessageListContent({
+ connector,
+ startPanelContainer,
+ channelId,
+ }),
+ endPanel:
+ messageDetailsOpen &&
+ MessagePayload({
+ ref: "endPanel",
+ connector,
+ selectedMessage,
+ }),
+ endPanelCollapsed: !messageDetailsOpen,
+ endPanelControl: true,
+ vert: false,
+ }),
+ StatusBar()
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ channelId: state.messages.currentChannelId,
+ messageDetailsOpen: state.messages.messageDetailsOpen,
+ selectedMessage: getSelectedMessage(state),
+ selectedMessageVisible: isSelectedMessageVisible(state),
+ }),
+ dispatch => ({
+ openMessageDetailsTab: open => dispatch(Actions.openMessageDetails(open)),
+ })
+)(MessagesView);
diff --git a/devtools/client/netmonitor/src/components/messages/RawData.js b/devtools/client/netmonitor/src/components/messages/RawData.js
new file mode 100644
index 0000000000..e0b49759c9
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/RawData.js
@@ -0,0 +1,34 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+
+/**
+ * Shows raw data of a message.
+ */
+class RawData extends Component {
+ static get propTypes() {
+ return {
+ payload: PropTypes.string.isRequired,
+ };
+ }
+
+ render() {
+ const { payload } = this.props;
+ return dom.textarea({
+ className: "message-rawData-payload",
+ rows: payload.split(/\n/g).length + 1,
+ value: payload,
+ readOnly: true,
+ });
+ }
+}
+
+module.exports = RawData;
diff --git a/devtools/client/netmonitor/src/components/messages/StatusBar.js b/devtools/client/netmonitor/src/components/messages/StatusBar.js
new file mode 100644
index 0000000000..61bfc75e31
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/StatusBar.js
@@ -0,0 +1,130 @@
+/* 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 {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const { PluralForm } = require("resource://devtools/shared/plural-form.js");
+const {
+ getDisplayedMessagesSummary,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ getFormattedSize,
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const {
+ CHANNEL_TYPE,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const { div, footer } = dom;
+
+const MESSAGE_COUNT_EMPTY = L10N.getStr(
+ "networkMenu.ws.summary.framesCountEmpty"
+);
+const TOOLTIP_MESSAGE_COUNT = L10N.getStr(
+ "networkMenu.ws.summary.tooltip.framesCount"
+);
+const TOOLTIP_MESSAGE_TOTAL_SIZE = L10N.getStr(
+ "networkMenu.ws.summary.tooltip.framesTotalSize"
+);
+const TOOLTIP_MESSAGE_TOTAL_TIME = L10N.getStr(
+ "networkMenu.ws.summary.tooltip.framesTotalTime"
+);
+
+const UPDATED_MSG_SUMMARY_PROPS = ["count", "totalMs", "totalSize"];
+
+/**
+ * Displays the summary of message count, total size and total time since the first message.
+ */
+class StatusBar extends Component {
+ static get propTypes() {
+ return {
+ channelType: PropTypes.string,
+ summary: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ const { summary, channelType } = this.props;
+ return (
+ channelType !== nextProps.channelType ||
+ !propertiesEqual(UPDATED_MSG_SUMMARY_PROPS, summary, nextProps.summary)
+ );
+ }
+
+ render() {
+ const { summary, channelType } = this.props;
+ const { count, totalMs, sentSize, receivedSize, totalSize } = summary;
+
+ const countText =
+ count === 0
+ ? MESSAGE_COUNT_EMPTY
+ : PluralForm.get(
+ count,
+ L10N.getStr("networkMenu.ws.summary.framesCount2")
+ ).replace("#1", count);
+ const totalSizeText = getFormattedSize(totalSize);
+ const sentSizeText = getFormattedSize(sentSize);
+ const receivedText = getFormattedSize(receivedSize);
+ const totalMillisText = getFormattedTime(totalMs);
+
+ // channelType might be null in which case it's better to just show
+ // total size than showing all three sizes.
+ const summaryText =
+ channelType === CHANNEL_TYPE.WEB_SOCKET
+ ? L10N.getFormatStr(
+ "networkMenu.ws.summary.label.framesTranferredSize",
+ totalSizeText,
+ sentSizeText,
+ receivedText
+ )
+ : `${totalSizeText} total`;
+
+ return footer(
+ { className: "devtools-toolbar devtools-toolbar-bottom" },
+ div(
+ {
+ className: "status-bar-label message-network-summary-count",
+ title: TOOLTIP_MESSAGE_COUNT,
+ },
+ countText
+ ),
+ count !== 0 &&
+ div(
+ {
+ className: "status-bar-label message-network-summary-total-size",
+ title: TOOLTIP_MESSAGE_TOTAL_SIZE,
+ },
+ summaryText
+ ),
+ count !== 0 &&
+ div(
+ {
+ className: "status-bar-label message-network-summary-total-millis",
+ title: TOOLTIP_MESSAGE_TOTAL_TIME,
+ },
+ totalMillisText
+ )
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ channelType: state.messages.currentChannelType,
+ summary: getDisplayedMessagesSummary(state),
+}))(StatusBar);
diff --git a/devtools/client/netmonitor/src/components/messages/Toolbar.js b/devtools/client/netmonitor/src/components/messages/Toolbar.js
new file mode 100644
index 0000000000..7b71c9aa06
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/Toolbar.js
@@ -0,0 +1,152 @@
+/* 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 {
+ Component,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ CHANNEL_TYPE,
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const { button, span, div } = dom;
+
+// Components
+const MessageFilterMenu = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessageFilterMenu.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+
+// Localization
+const MSG_TOOLBAR_CLEAR = L10N.getStr("netmonitor.ws.toolbar.clear");
+const MSG_SEARCH_KEY_SHORTCUT = L10N.getStr(
+ "netmonitor.ws.toolbar.filterFreetext.key"
+);
+const MSG_SEARCH_PLACE_HOLDER = L10N.getStr(
+ "netmonitor.ws.toolbar.filterFreetext.label"
+);
+
+/**
+ * MessagesPanel toolbar component.
+ *
+ * Toolbar contains a set of useful tools that clear the list of
+ * existing messages as well as filter content.
+ */
+class Toolbar extends Component {
+ static get propTypes() {
+ return {
+ searchboxRef: PropTypes.object.isRequired,
+ toggleMessageFilterType: PropTypes.func.isRequired,
+ toggleControlFrames: PropTypes.func.isRequired,
+ clearMessages: PropTypes.func.isRequired,
+ setMessageFilterText: PropTypes.func.isRequired,
+ messageFilterType: PropTypes.string.isRequired,
+ showControlFrames: PropTypes.bool.isRequired,
+ channelType: PropTypes.string,
+ };
+ }
+
+ componentWillUnmount() {
+ const { setMessageFilterText } = this.props;
+ setMessageFilterText("");
+ }
+
+ /**
+ * Render a separator.
+ */
+ renderSeparator() {
+ return span({ className: "devtools-separator" });
+ }
+
+ /**
+ * Render a clear button.
+ */
+ renderClearButton(clearMessages) {
+ return button({
+ className:
+ "devtools-button devtools-clear-icon message-list-clear-button",
+ title: MSG_TOOLBAR_CLEAR,
+ onClick: () => {
+ clearMessages();
+ },
+ });
+ }
+
+ /**
+ * Render the message filter menu button.
+ */
+ renderMessageFilterMenu() {
+ const {
+ messageFilterType,
+ toggleMessageFilterType,
+ showControlFrames,
+ toggleControlFrames,
+ } = this.props;
+
+ return MessageFilterMenu({
+ messageFilterType,
+ toggleMessageFilterType,
+ showControlFrames,
+ toggleControlFrames,
+ });
+ }
+
+ /**
+ * Render filter Searchbox.
+ */
+ renderFilterBox(setMessageFilterText) {
+ return SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ keyShortcut: MSG_SEARCH_KEY_SHORTCUT,
+ placeholder: MSG_SEARCH_PLACE_HOLDER,
+ type: "filter",
+ ref: this.props.searchboxRef,
+ onChange: setMessageFilterText,
+ });
+ }
+
+ render() {
+ const { clearMessages, setMessageFilterText, channelType } = this.props;
+ const isWs = channelType === CHANNEL_TYPE.WEB_SOCKET;
+ return div(
+ {
+ id: "netmonitor-toolbar-container",
+ className: "devtools-toolbar devtools-input-toolbar",
+ },
+ this.renderClearButton(clearMessages),
+ isWs ? this.renderSeparator() : null,
+ isWs ? this.renderMessageFilterMenu() : null,
+ this.renderSeparator(),
+ this.renderFilterBox(setMessageFilterText)
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ messageFilterType: state.messages.messageFilterType,
+ showControlFrames: state.messages.showControlFrames,
+ channelType: state.messages.currentChannelType,
+ }),
+ dispatch => ({
+ clearMessages: () => dispatch(Actions.clearMessages()),
+ toggleMessageFilterType: filter =>
+ dispatch(Actions.toggleMessageFilterType(filter)),
+ toggleControlFrames: () => dispatch(Actions.toggleControlFrames()),
+ setMessageFilterText: text => dispatch(Actions.setMessageFilterText(text)),
+ })
+)(Toolbar);
diff --git a/devtools/client/netmonitor/src/components/messages/cbor.js b/devtools/client/netmonitor/src/components/messages/cbor.js
new file mode 100644
index 0000000000..8b8b249391
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/cbor.js
@@ -0,0 +1,270 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2016 Patrick Gansterer <paroga@paroga.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+"use strict";
+const POW_2_24 = 5.960464477539063e-8;
+const POW_2_32 = 4294967296;
+
+function decode(data, tagger, simpleValue) {
+ const dataView = new DataView(data);
+ let offset = 0;
+
+ if (typeof tagger !== "function") {
+ tagger = function (value) {
+ return value;
+ };
+ }
+ if (typeof simpleValue !== "function") {
+ simpleValue = function () {
+ return undefined;
+ };
+ }
+
+ function commitRead(length, value) {
+ offset += length;
+ return value;
+ }
+ function readArrayBuffer(length) {
+ return commitRead(length, new Uint8Array(data, offset, length));
+ }
+ function readFloat16() {
+ const tempArrayBuffer = new ArrayBuffer(4);
+ const tempDataView = new DataView(tempArrayBuffer);
+ const value = readUint16();
+
+ const sign = value & 0x8000;
+ let exponent = value & 0x7c00;
+ const fraction = value & 0x03ff;
+
+ if (exponent === 0x7c00) {
+ exponent = 0xff << 10;
+ } else if (exponent !== 0) {
+ exponent += (127 - 15) << 10;
+ } else if (fraction !== 0) {
+ return (sign ? -1 : 1) * fraction * POW_2_24;
+ }
+
+ tempDataView.setUint32(
+ 0,
+ (sign << 16) | (exponent << 13) | (fraction << 13)
+ );
+ return tempDataView.getFloat32(0);
+ }
+ function readFloat32() {
+ return commitRead(4, dataView.getFloat32(offset));
+ }
+ function readFloat64() {
+ return commitRead(8, dataView.getFloat64(offset));
+ }
+ function readUint8() {
+ return commitRead(1, dataView.getUint8(offset));
+ }
+ function readUint16() {
+ return commitRead(2, dataView.getUint16(offset));
+ }
+ function readUint32() {
+ return commitRead(4, dataView.getUint32(offset));
+ }
+ function readUint64() {
+ return readUint32() * POW_2_32 + readUint32();
+ }
+ function readBreak() {
+ if (dataView.getUint8(offset) !== 0xff) {
+ return false;
+ }
+ offset += 1;
+ return true;
+ }
+ function readLength(additionalInformation) {
+ if (additionalInformation < 24) {
+ return additionalInformation;
+ }
+ if (additionalInformation === 24) {
+ return readUint8();
+ }
+ if (additionalInformation === 25) {
+ return readUint16();
+ }
+ if (additionalInformation === 26) {
+ return readUint32();
+ }
+ if (additionalInformation === 27) {
+ return readUint64();
+ }
+ if (additionalInformation === 31) {
+ return -1;
+ }
+ throw new Error("Invalid length encoding");
+ }
+ function readIndefiniteStringLength(majorType) {
+ const initialByte = readUint8();
+ if (initialByte === 0xff) {
+ return -1;
+ }
+ const length = readLength(initialByte & 0x1f);
+ if (length < 0 || initialByte >> 5 !== majorType) {
+ throw new Error("Invalid indefinite length element");
+ }
+ return length;
+ }
+
+ function appendUtf16Data(utf16data, length) {
+ for (let i = 0; i < length; ++i) {
+ let value = readUint8();
+ if (value & 0x80) {
+ if (value < 0xe0) {
+ value = ((value & 0x1f) << 6) | (readUint8() & 0x3f);
+ length -= 1;
+ } else if (value < 0xf0) {
+ value =
+ ((value & 0x0f) << 12) |
+ ((readUint8() & 0x3f) << 6) |
+ (readUint8() & 0x3f);
+ length -= 2;
+ } else {
+ value =
+ ((value & 0x0f) << 18) |
+ ((readUint8() & 0x3f) << 12) |
+ ((readUint8() & 0x3f) << 6) |
+ (readUint8() & 0x3f);
+ length -= 3;
+ }
+ }
+
+ if (value < 0x10000) {
+ utf16data.push(value);
+ } else {
+ value -= 0x10000;
+ utf16data.push(0xd800 | (value >> 10));
+ utf16data.push(0xdc00 | (value & 0x3ff));
+ }
+ }
+ }
+
+ // eslint-disable-next-line complexity
+ function decodeItem() {
+ const initialByte = readUint8();
+ const majorType = initialByte >> 5;
+ const additionalInformation = initialByte & 0x1f;
+ let i;
+ let length;
+
+ if (majorType === 7) {
+ switch (additionalInformation) {
+ case 25:
+ return readFloat16();
+ case 26:
+ return readFloat32();
+ case 27:
+ return readFloat64();
+ }
+ }
+
+ length = readLength(additionalInformation);
+ if (length < 0 && (majorType < 2 || majorType > 6)) {
+ throw new Error("Invalid length");
+ }
+
+ switch (majorType) {
+ case 0:
+ return length;
+ case 1:
+ return -1 - length;
+ case 2:
+ if (length < 0) {
+ const elements = [];
+ let fullArrayLength = 0;
+ while ((length = readIndefiniteStringLength(majorType)) >= 0) {
+ fullArrayLength += length;
+ elements.push(readArrayBuffer(length));
+ }
+ const fullArray = new Uint8Array(fullArrayLength);
+ let fullArrayOffset = 0;
+ for (i = 0; i < elements.length; ++i) {
+ fullArray.set(elements[i], fullArrayOffset);
+ fullArrayOffset += elements[i].length;
+ }
+ return fullArray;
+ }
+ return readArrayBuffer(length);
+ case 3:
+ const utf16data = [];
+ if (length < 0) {
+ while ((length = readIndefiniteStringLength(majorType)) >= 0) {
+ appendUtf16Data(utf16data, length);
+ }
+ } else {
+ appendUtf16Data(utf16data, length);
+ }
+ return String.fromCharCode.apply(null, utf16data);
+ case 4:
+ let retArray;
+ if (length < 0) {
+ retArray = [];
+ while (!readBreak()) {
+ retArray.push(decodeItem());
+ }
+ } else {
+ retArray = new Array(length);
+ for (i = 0; i < length; ++i) {
+ retArray[i] = decodeItem();
+ }
+ }
+ return retArray;
+ case 5:
+ const retObject = {};
+ for (i = 0; i < length || (length < 0 && !readBreak()); ++i) {
+ const key = decodeItem();
+ retObject[key] = decodeItem();
+ }
+ return retObject;
+ case 6:
+ return tagger(decodeItem(), length);
+ case 7:
+ switch (length) {
+ case 20:
+ return false;
+ case 21:
+ return true;
+ case 22:
+ return null;
+ case 23:
+ return undefined;
+ default:
+ return simpleValue(length);
+ }
+ }
+
+ throw new Error("Invalid major byte");
+ }
+
+ const ret = decodeItem();
+ if (offset !== data.byteLength) {
+ throw new Error("Remaining bytes");
+ }
+
+ return ret;
+}
+
+module.exports = { decode };
diff --git a/devtools/client/netmonitor/src/components/messages/moz.build b/devtools/client/netmonitor/src/components/messages/moz.build
new file mode 100644
index 0000000000..b5b8751d30
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/moz.build
@@ -0,0 +1,32 @@
+# 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/.
+
+DIRS += [
+ "parsers",
+]
+
+DevToolsModules(
+ "cbor.js",
+ "ColumnData.js",
+ "ColumnEventName.js",
+ "ColumnFinBit.js",
+ "ColumnLastEventId.js",
+ "ColumnMaskBit.js",
+ "ColumnOpCode.js",
+ "ColumnRetry.js",
+ "ColumnSize.js",
+ "ColumnTime.js",
+ "MessageFilterMenu.js",
+ "MessageListContent.js",
+ "MessageListContextMenu.js",
+ "MessageListHeader.js",
+ "MessageListHeaderContextMenu.js",
+ "MessageListItem.js",
+ "MessagePayload.js",
+ "MessagesView.js",
+ "msgpack.js",
+ "RawData.js",
+ "StatusBar.js",
+ "Toolbar.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/msgpack.js b/devtools/client/netmonitor/src/components/messages/msgpack.js
new file mode 100644
index 0000000000..e54e2707e9
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/msgpack.js
@@ -0,0 +1,365 @@
+// Copyright © 2019, Yves Goergen, https://unclassified.software/source/msgpack-js
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+// associated documentation files (the “Software”), to deal in the Software without restriction,
+// including without limitation the rights to use, copy, modify, merge, publish, distribute,
+// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+"use strict";
+
+// Deserializes a MessagePack byte array to a value.
+//
+// array: The MessagePack byte array to deserialize. This must be an Array or Uint8Array containing bytes, not a string.
+function deserialize(array) {
+ const pow32 = 0x100000000; // 2^32
+ let pos = 0;
+ if (array instanceof ArrayBuffer) {
+ array = new Uint8Array(array);
+ }
+ if (typeof array !== "object" || typeof array.length === "undefined") {
+ throw new Error(
+ "Invalid argument type: Expected a byte array (Array or Uint8Array) to deserialize."
+ );
+ }
+ if (!array.length) {
+ throw new Error(
+ "Invalid argument: The byte array to deserialize is empty."
+ );
+ }
+ if (!(array instanceof Uint8Array)) {
+ array = new Uint8Array(array);
+ }
+ const data = read();
+ if (pos < array.length) {
+ // Junk data at the end
+ }
+ return data;
+
+ // eslint-disable-next-line complexity
+ function read() {
+ const byte = array[pos++];
+ if (byte >= 0x00 && byte <= 0x7f) {
+ return byte;
+ } // positive fixint
+ if (byte >= 0x80 && byte <= 0x8f) {
+ return readMap(byte - 0x80);
+ } // fixmap
+ if (byte >= 0x90 && byte <= 0x9f) {
+ return readArray(byte - 0x90);
+ } // fixarray
+ if (byte >= 0xa0 && byte <= 0xbf) {
+ return readStr(byte - 0xa0);
+ } // fixstr
+ if (byte === 0xc0) {
+ return null;
+ } // nil
+ if (byte === 0xc1) {
+ throw new Error("Invalid byte code 0xc1 found.");
+ } // never used
+ if (byte === 0xc2) {
+ return false;
+ } // false
+ if (byte === 0xc3) {
+ return true;
+ } // true
+ if (byte === 0xc4) {
+ return readBin(-1, 1);
+ } // bin 8
+ if (byte === 0xc5) {
+ return readBin(-1, 2);
+ } // bin 16
+ if (byte === 0xc6) {
+ return readBin(-1, 4);
+ } // bin 32
+ if (byte === 0xc7) {
+ return readExt(-1, 1);
+ } // ext 8
+ if (byte === 0xc8) {
+ return readExt(-1, 2);
+ } // ext 16
+ if (byte === 0xc9) {
+ return readExt(-1, 4);
+ } // ext 32
+ if (byte === 0xca) {
+ return readFloat(4);
+ } // float 32
+ if (byte === 0xcb) {
+ return readFloat(8);
+ } // float 64
+ if (byte === 0xcc) {
+ return readUInt(1);
+ } // uint 8
+ if (byte === 0xcd) {
+ return readUInt(2);
+ } // uint 16
+ if (byte === 0xce) {
+ return readUInt(4);
+ } // uint 32
+ if (byte === 0xcf) {
+ return readUInt(8);
+ } // uint 64
+ if (byte === 0xd0) {
+ return readInt(1);
+ } // int 8
+ if (byte === 0xd1) {
+ return readInt(2);
+ } // int 16
+ if (byte === 0xd2) {
+ return readInt(4);
+ } // int 32
+ if (byte === 0xd3) {
+ return readInt(8);
+ } // int 64
+ if (byte === 0xd4) {
+ return readExt(1);
+ } // fixext 1
+ if (byte === 0xd5) {
+ return readExt(2);
+ } // fixext 2
+ if (byte === 0xd6) {
+ return readExt(4);
+ } // fixext 4
+ if (byte === 0xd7) {
+ return readExt(8);
+ } // fixext 8
+ if (byte === 0xd8) {
+ return readExt(16);
+ } // fixext 16
+ if (byte === 0xd9) {
+ return readStr(-1, 1);
+ } // str 8
+ if (byte === 0xda) {
+ return readStr(-1, 2);
+ } // str 16
+ if (byte === 0xdb) {
+ return readStr(-1, 4);
+ } // str 32
+ if (byte === 0xdc) {
+ return readArray(-1, 2);
+ } // array 16
+ if (byte === 0xdd) {
+ return readArray(-1, 4);
+ } // array 32
+ if (byte === 0xde) {
+ return readMap(-1, 2);
+ } // map 16
+ if (byte === 0xdf) {
+ return readMap(-1, 4);
+ } // map 32
+ if (byte >= 0xe0 && byte <= 0xff) {
+ return byte - 256;
+ } // negative fixint
+ console.debug("msgpack array:", array);
+ throw new Error(
+ "Invalid byte value '" +
+ byte +
+ "' at index " +
+ (pos - 1) +
+ " in the MessagePack binary data (length " +
+ array.length +
+ "): Expecting a range of 0 to 255. This is not a byte array."
+ );
+ }
+
+ function readInt(size) {
+ let value = 0;
+ let first = true;
+ while (size-- > 0) {
+ if (first) {
+ const byte = array[pos++];
+ value += byte & 0x7f;
+ if (byte & 0x80) {
+ value -= 0x80; // Treat most-significant bit as -2^i instead of 2^i
+ }
+ first = false;
+ } else {
+ value *= 256;
+ value += array[pos++];
+ }
+ }
+ return value;
+ }
+
+ function readUInt(size) {
+ let value = 0;
+ while (size-- > 0) {
+ value *= 256;
+ value += array[pos++];
+ }
+ return value;
+ }
+
+ function readFloat(size) {
+ const view = new DataView(array.buffer, pos, size);
+ pos += size;
+ if (size === 4) {
+ return view.getFloat32(0, false);
+ }
+ if (size === 8) {
+ return view.getFloat64(0, false);
+ }
+ throw new Error("Invalid size for readFloat.");
+ }
+
+ function readBin(size, lengthSize) {
+ if (size < 0) {
+ size = readUInt(lengthSize);
+ }
+ const readData = array.subarray(pos, pos + size);
+ pos += size;
+ return readData;
+ }
+
+ function readMap(size, lengthSize) {
+ if (size < 0) {
+ size = readUInt(lengthSize);
+ }
+ const readData = {};
+ while (size-- > 0) {
+ const key = read();
+ readData[key] = read();
+ }
+ return readData;
+ }
+
+ function readArray(size, lengthSize) {
+ if (size < 0) {
+ size = readUInt(lengthSize);
+ }
+ const readData = [];
+ while (size-- > 0) {
+ readData.push(read());
+ }
+ return readData;
+ }
+
+ function readStr(size, lengthSize) {
+ if (size < 0) {
+ size = readUInt(lengthSize);
+ }
+ const start = pos;
+ pos += size;
+ return decodeUtf8(array, start, size);
+ }
+
+ function readExt(size, lengthSize) {
+ if (size < 0) {
+ size = readUInt(lengthSize);
+ }
+ const type = readUInt(1);
+ const readData = readBin(size);
+ switch (type) {
+ case 255:
+ return readExtDate(readData);
+ }
+ return { type, data: readData };
+ }
+
+ function readExtDate(givenData) {
+ if (givenData.length === 4) {
+ const sec =
+ ((givenData[0] << 24) >>> 0) +
+ ((givenData[1] << 16) >>> 0) +
+ ((givenData[2] << 8) >>> 0) +
+ givenData[3];
+ return new Date(sec * 1000);
+ }
+ if (givenData.length === 8) {
+ const ns =
+ ((givenData[0] << 22) >>> 0) +
+ ((givenData[1] << 14) >>> 0) +
+ ((givenData[2] << 6) >>> 0) +
+ (givenData[3] >>> 2);
+ const sec =
+ (givenData[3] & 0x3) * pow32 +
+ ((givenData[4] << 24) >>> 0) +
+ ((givenData[5] << 16) >>> 0) +
+ ((givenData[6] << 8) >>> 0) +
+ givenData[7];
+ return new Date(sec * 1000 + ns / 1000000);
+ }
+ if (givenData.length === 12) {
+ const ns =
+ ((givenData[0] << 24) >>> 0) +
+ ((givenData[1] << 16) >>> 0) +
+ ((givenData[2] << 8) >>> 0) +
+ givenData[3];
+ pos -= 8;
+ const sec = readInt(8);
+ return new Date(sec * 1000 + ns / 1000000);
+ }
+ throw new Error("Invalid givenData length for a date value.");
+ }
+}
+
+// Decodes a string from UTF-8 bytes.
+function decodeUtf8(bytes, start, length) {
+ // Based on: https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330
+ let i = start,
+ str = "";
+ length += start;
+ while (i < length) {
+ let c = bytes[i++];
+ if (c > 127) {
+ if (c > 191 && c < 224) {
+ if (i >= length) {
+ throw new Error("UTF-8 decode: incomplete 2-byte sequence");
+ }
+ c = ((c & 31) << 6) | (bytes[i++] & 63);
+ } else if (c > 223 && c < 240) {
+ if (i + 1 >= length) {
+ throw new Error("UTF-8 decode: incomplete 3-byte sequence");
+ }
+ c = ((c & 15) << 12) | ((bytes[i++] & 63) << 6) | (bytes[i++] & 63);
+ } else if (c > 239 && c < 248) {
+ if (i + 2 >= length) {
+ throw new Error("UTF-8 decode: incomplete 4-byte sequence");
+ }
+ c =
+ ((c & 7) << 18) |
+ ((bytes[i++] & 63) << 12) |
+ ((bytes[i++] & 63) << 6) |
+ (bytes[i++] & 63);
+ } else {
+ throw new Error(
+ "UTF-8 decode: unknown multibyte start 0x" +
+ c.toString(16) +
+ " at index " +
+ (i - 1)
+ );
+ }
+ }
+ if (c <= 0xffff) {
+ str += String.fromCharCode(c);
+ } else if (c <= 0x10ffff) {
+ c -= 0x10000;
+ str += String.fromCharCode((c >> 10) | 0xd800);
+ str += String.fromCharCode((c & 0x3ff) | 0xdc00);
+ } else {
+ throw new Error(
+ "UTF-8 decode: code point 0x" + c.toString(16) + " exceeds UTF-16 reach"
+ );
+ }
+ }
+ return str;
+}
+
+// The exported functions
+const msgpack = {
+ deserialize,
+
+ // Compatibility with other libraries
+ decode: deserialize,
+};
+
+module.exports = msgpack;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/moz.build
new file mode 100644
index 0000000000..6b1947e4a1
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/moz.build
@@ -0,0 +1,11 @@
+# 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/.
+
+DIRS += [
+ "socket-io",
+ "sockjs",
+ "stomp",
+ "signalr",
+ "wamp",
+]
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js
new file mode 100644
index 0000000000..c1c64d6717
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js
@@ -0,0 +1,82 @@
+/*
+ * A helper class for working with SignalR handshakes.
+ *
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+const TextMessageFormat = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js");
+const Utils = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js");
+/** @private */
+class HandshakeProtocol {
+ // Handshake request is always JSON
+ writeHandshakeRequest(handshakeRequest) {
+ return TextMessageFormat.TextMessageFormat.write(
+ JSON.stringify(handshakeRequest)
+ );
+ }
+ parseHandshakeResponse(data) {
+ let messageData;
+ let remainingData;
+ if (
+ Utils.isArrayBuffer(data) ||
+ // eslint-disable-next-line no-undef
+ (typeof Buffer !== "undefined" && data instanceof Buffer)
+ ) {
+ // Format is binary but still need to read JSON text from handshake response
+ const binaryData = new Uint8Array(data);
+ const separatorIndex = binaryData.indexOf(
+ TextMessageFormat.TextMessageFormat.RecordSeparatorCode
+ );
+ if (separatorIndex === -1) {
+ throw new Error("Message is incomplete.");
+ }
+ // content before separator is handshake response
+ // optional content after is additional messages
+ const responseLength = separatorIndex + 1;
+ messageData = String.fromCharCode.apply(
+ null,
+ binaryData.slice(0, responseLength)
+ );
+ remainingData =
+ binaryData.byteLength > responseLength
+ ? binaryData.slice(responseLength).buffer
+ : null;
+ } else {
+ const textData = data;
+ const separatorIndex = textData.indexOf(
+ TextMessageFormat.TextMessageFormat.RecordSeparator
+ );
+ if (separatorIndex === -1) {
+ throw new Error("Message is incomplete.");
+ }
+ // content before separator is handshake response
+ // optional content after is additional messages
+ const responseLength = separatorIndex + 1;
+ messageData = textData.substring(0, responseLength);
+ remainingData =
+ textData.length > responseLength
+ ? textData.substring(responseLength)
+ : null;
+ }
+ // At this point we should have just the single handshake message
+ const messages = TextMessageFormat.TextMessageFormat.parse(messageData);
+ const response = JSON.parse(messages[0]);
+ if (response.type) {
+ throw new Error("Expected a handshake response from the server.");
+ }
+ const responseMessage = response;
+ // multiple messages could have arrived with handshake
+ // return additional data to be parsed as usual, or null if all parsed
+ return [remainingData, responseMessage];
+ }
+}
+exports.HandshakeProtocol = HandshakeProtocol;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js
new file mode 100644
index 0000000000..fec2cdbff4
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js
@@ -0,0 +1,33 @@
+/*
+ * A protocol abstraction for communicating with SignalR hubs.
+ *
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+/** Defines the type of a Hub Message. */
+var MessageType;
+(function (_MessageType) {
+ /** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */
+ MessageType[(MessageType.Invocation = 1)] = "Invocation";
+ /** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */
+ MessageType[(MessageType.StreamItem = 2)] = "StreamItem";
+ /** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */
+ MessageType[(MessageType.Completion = 3)] = "Completion";
+ /** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */
+ MessageType[(MessageType.StreamInvocation = 4)] = "StreamInvocation";
+ /** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */
+ MessageType[(MessageType.CancelInvocation = 5)] = "CancelInvocation";
+ /** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */
+ MessageType[(MessageType.Ping = 6)] = "Ping";
+ /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */
+ MessageType[(MessageType.Close = 7)] = "Close";
+})((MessageType = exports.MessageType || (exports.MessageType = {})));
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js
new file mode 100644
index 0000000000..c3648e940f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js
@@ -0,0 +1,120 @@
+/*
+ * Implements the SignalR Hub Protocol.
+ *
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+const IHubProtocol = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js");
+const TextMessageFormat = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js");
+/** Implements the JSON Hub Protocol. */
+class JsonHubProtocol {
+ /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.
+ *
+ * @param {string} input A string containing the serialized representation.
+ */
+ parseMessages(input) {
+ // The interface does allow "ArrayBuffer" to be passed in, but this implementation does not. So let's throw a useful error.
+ if (typeof input !== "string") {
+ throw new Error(
+ "Invalid input for JSON hub protocol. Expected a string."
+ );
+ }
+ if (!input) {
+ return [];
+ }
+ // Parse the messages
+ const messages = TextMessageFormat.TextMessageFormat.parse(input);
+ const hubMessages = [];
+ for (const message of messages) {
+ const parsedMessage = JSON.parse(message);
+ if (typeof parsedMessage.type !== "number") {
+ throw new Error("Invalid payload.");
+ }
+ switch (parsedMessage.type) {
+ case IHubProtocol.MessageType.Invocation:
+ this.isInvocationMessage(parsedMessage);
+ break;
+ case IHubProtocol.MessageType.StreamItem:
+ this.isStreamItemMessage(parsedMessage);
+ break;
+ case IHubProtocol.MessageType.Completion:
+ this.isCompletionMessage(parsedMessage);
+ break;
+ case IHubProtocol.MessageType.Ping:
+ // Single value, no need to validate
+ break;
+ case IHubProtocol.MessageType.Close:
+ // All optional values, no need to validate
+ break;
+ default:
+ // Future protocol changes can add message types, new kinds of messages
+ // will show up without having to update Firefox.
+ break;
+ }
+ // Map numeric message type to their textual name if it exists
+ parsedMessage.type =
+ IHubProtocol.MessageType[parsedMessage.type] || parsedMessage.type;
+ hubMessages.push(parsedMessage);
+ }
+ return hubMessages;
+ }
+ /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.
+ *
+ * @param {HubMessage} message The message to write.
+ * @returns {string} A string containing the serialized representation of the message.
+ */
+ writeMessage(message) {
+ return TextMessageFormat.TextMessageFormat.write(JSON.stringify(message));
+ }
+ isInvocationMessage(message) {
+ this.assertNotEmptyString(
+ message.target,
+ "Invalid payload for Invocation message."
+ );
+ if (message.invocationId !== undefined) {
+ this.assertNotEmptyString(
+ message.invocationId,
+ "Invalid payload for Invocation message."
+ );
+ }
+ }
+ isStreamItemMessage(message) {
+ this.assertNotEmptyString(
+ message.invocationId,
+ "Invalid payload for StreamItem message."
+ );
+ if (message.item === undefined) {
+ throw new Error("Invalid payload for StreamItem message.");
+ }
+ }
+ isCompletionMessage(message) {
+ if (message.result && message.error) {
+ throw new Error("Invalid payload for Completion message.");
+ }
+ if (!message.result && message.error) {
+ this.assertNotEmptyString(
+ message.error,
+ "Invalid payload for Completion message."
+ );
+ }
+ this.assertNotEmptyString(
+ message.invocationId,
+ "Invalid payload for Completion message."
+ );
+ }
+ assertNotEmptyString(value, errorMessage) {
+ if (typeof value !== "string" || value === "") {
+ throw new Error(errorMessage);
+ }
+ }
+}
+exports.JsonHubProtocol = JsonHubProtocol;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js
new file mode 100644
index 0000000000..a9ec58ee36
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+// Not exported from index
+/** @private */
+class TextMessageFormat {
+ static write(output) {
+ return `${output}${TextMessageFormat.RecordSeparator}`;
+ }
+ static parse(input) {
+ if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {
+ throw new Error("Message is incomplete.");
+ }
+ const messages = input.split(TextMessageFormat.RecordSeparator);
+ messages.pop();
+ return messages;
+ }
+}
+exports.TextMessageFormat = TextMessageFormat;
+TextMessageFormat.RecordSeparatorCode = 0x1e;
+TextMessageFormat.RecordSeparator = String.fromCharCode(
+ TextMessageFormat.RecordSeparatorCode
+);
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js
new file mode 100644
index 0000000000..77b00daf45
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+// Also in signalr-protocol-msgpack/Utils.ts
+/** @private */
+function isArrayBuffer(val) {
+ return (
+ val &&
+ typeof ArrayBuffer !== "undefined" &&
+ (val instanceof ArrayBuffer ||
+ // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof
+ (val.constructor && val.constructor.name === "ArrayBuffer"))
+ );
+}
+exports.isArrayBuffer = isArrayBuffer;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js
new file mode 100644
index 0000000000..927b0a0922
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js
@@ -0,0 +1,13 @@
+/* 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 JsonHubProtocol = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js");
+const HandshakeProtocol = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js");
+
+module.exports = {
+ JsonHubProtocol: JsonHubProtocol.JsonHubProtocol,
+ HandshakeProtocol: HandshakeProtocol.HandshakeProtocol,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build
new file mode 100644
index 0000000000..48329513f2
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build
@@ -0,0 +1,12 @@
+# 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/.
+
+DevToolsModules(
+ "HandshakeProtocol.js",
+ "IHubProtocol.js",
+ "index.js",
+ "JSONHubProtocol.js",
+ "TextMessageFormat.js",
+ "Utils.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js
new file mode 100644
index 0000000000..340791199f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js
@@ -0,0 +1,48 @@
+/*
+ * A socket.io encoder and decoder written in JavaScript complying with version 4
+ * of socket.io-protocol. Used by socket.io and socket.io-client.
+ *
+ * Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/socketio/socket.io-parser
+ */
+
+"use strict";
+
+/**
+ * Reconstructs a binary packet from its placeholder packet and buffers
+ *
+ * @param {Object} packet - event packet with placeholders
+ * @param {Array} buffers - binary buffers to put in placeholder positions
+ * @return {Object} reconstructed packet
+ * @api public
+ */
+
+exports.reconstructPacket = function (packet, buffers) {
+ packet.data = _reconstructPacket(packet.data, buffers);
+ packet.attachments = undefined; // no longer useful
+ return packet;
+};
+
+function _reconstructPacket(data, buffers) {
+ if (!data) {
+ return data;
+ }
+
+ if (data && data._placeholder) {
+ return buffers[data.num]; // appropriate buffer (should be natural order anyway)
+ } else if (Array.isArray(data)) {
+ for (let i = 0; i < data.length; i++) {
+ data[i] = _reconstructPacket(data[i], buffers);
+ }
+ } else if (typeof data === "object") {
+ for (const key in data) {
+ data[key] = _reconstructPacket(data[key], buffers);
+ }
+ }
+
+ return data;
+}
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js
new file mode 100644
index 0000000000..5874778f75
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js
@@ -0,0 +1,84 @@
+/*
+ * Event emitter component.
+ *
+ * Copyright (c) 2014 Component contributors <dev@component.io>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/component/emitter
+ */
+
+"use strict";
+
+/**
+ * Initialize a new `Emitter`.
+ *
+ * @api public
+ */
+
+function Emitter(obj) {
+ if (obj) {
+ return mixin(obj);
+ }
+}
+
+/**
+ * Mixin the emitter properties.
+ *
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
+
+function mixin(obj) {
+ for (const key in Emitter.prototype) {
+ obj[key] = Emitter.prototype[key];
+ }
+ return obj;
+}
+
+/**
+ * Listen on the given `event` with `fn`.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.on = function (event, fn) {
+ this._callbacks = this._callbacks || {};
+ (this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
+ return this;
+};
+
+/**
+ * Emit `event` with the given args.
+ *
+ * @param {String} event
+ * @param {Mixed} ...
+ * @return {Emitter}
+ */
+
+Emitter.prototype.emit = function (event) {
+ this._callbacks = this._callbacks || {};
+
+ const args = new Array(arguments.length - 1);
+ let callbacks = this._callbacks["$" + event];
+
+ for (let i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+
+ if (callbacks) {
+ callbacks = callbacks.slice(0);
+ for (let i = 0, len = callbacks.length; i < len; ++i) {
+ callbacks[i].apply(this, args);
+ }
+ }
+
+ return this;
+};
+
+module.exports = Emitter;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js
new file mode 100644
index 0000000000..9d631d014b
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js
@@ -0,0 +1,292 @@
+/*
+ * A socket.io encoder and decoder written in JavaScript complying with version 4
+ * of socket.io-protocol. Used by socket.io and socket.io-client.
+ *
+ * Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/socketio/socket.io-parser
+ */
+
+/* eslint-disable no-unused-vars */
+
+"use strict";
+
+const Emitter = require("resource://devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js");
+const binary = require("resource://devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js");
+const isBuf = require("resource://devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js");
+
+/**
+ * Packet types
+ */
+
+const TYPES = [
+ "CONNECT",
+ "DISCONNECT",
+ "EVENT",
+ "ACK",
+ "ERROR",
+ "BINARY_EVENT",
+ "BINARY_ACK",
+];
+
+/**
+ * Packet type `connect`
+ */
+
+const CONNECT = 0;
+
+/**
+ * Packet type `disconnect`
+ */
+
+const DISCONNECT = 1;
+
+/**
+ * Packet type `event`
+ */
+
+const EVENT = 2;
+
+/**
+ * Packet type `ack`
+ */
+
+const ACK = 3;
+
+/**
+ * Packet type `error`
+ */
+
+const ERROR = 4;
+
+/**
+ * Packet type 'binary event'
+ */
+const BINARY_EVENT = 5;
+
+/**
+ * Packet type `binary ack`. For acks with binary arguments
+ */
+
+const BINARY_ACK = 6;
+
+/**
+ * A socket.io Decoder instance
+ *
+ * @return {Object} decoder
+ * @api public
+ */
+
+function Decoder() {
+ this.reconstructor = null;
+}
+
+/**
+ * Mix in `Emitter` with Decoder.
+ */
+
+Emitter(Decoder.prototype);
+
+/**
+ * A manager of a binary event's 'buffer sequence'. Should
+ * be constructed whenever a packet of type BINARY_EVENT is
+ * decoded.
+ *
+ * @param {Object} packet
+ * @return {BinaryReconstructor} initialized reconstructor
+ * @api private
+ */
+
+function BinaryReconstructor(packet) {
+ this.reconPack = packet;
+ this.buffers = [];
+}
+
+/**
+ * Method to be called when binary data received from connection
+ * after a BINARY_EVENT packet.
+ *
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
+ * @return {null | Object} returns null if more binary data is expected or
+ * a reconstructed packet object if all buffers have been received.
+ * @api private
+ */
+
+BinaryReconstructor.prototype.takeBinaryData = function (binData) {
+ this.buffers.push(binData);
+ if (this.buffers.length === this.reconPack.attachments) {
+ // done with buffer list
+ const packet = binary.reconstructPacket(this.reconPack, this.buffers);
+ this.finishedReconstruction();
+ return packet;
+ }
+ return null;
+};
+
+/**
+ * Cleans up binary packet reconstruction variables.
+ *
+ * @api private
+ */
+
+BinaryReconstructor.prototype.finishedReconstruction = function () {
+ this.reconPack = null;
+ this.buffers = [];
+};
+
+/**
+ * Decodes an encoded packet string into packet JSON.
+ *
+ * @param {String} obj - encoded packet
+ * @return {Object} packet
+ * @api public
+ */
+
+Decoder.prototype.add = function (obj) {
+ let packet;
+ if (typeof obj === "string") {
+ packet = decodeString(obj);
+ if (BINARY_EVENT === packet.type || BINARY_ACK === packet.type) {
+ // binary packet's json
+ this.reconstructor = new BinaryReconstructor(packet);
+
+ // no attachments, labeled binary but no binary data to follow
+ if (this.reconstructor.reconPack.attachments === 0) {
+ this.emit("decoded", packet);
+ }
+ } else {
+ // non-binary full packet
+ this.emit("decoded", packet);
+ }
+ } else if (isBuf(obj) || obj.base64) {
+ // raw binary data
+ if (!this.reconstructor) {
+ throw new Error("got binary data when not reconstructing a packet");
+ } else {
+ packet = this.reconstructor.takeBinaryData(obj);
+ if (packet) {
+ // received final buffer
+ this.reconstructor = null;
+ this.emit("decoded", packet);
+ }
+ }
+ } else {
+ throw new Error("Unknown type: " + obj);
+ }
+};
+
+/**
+ * Decode a packet String (JSON data)
+ *
+ * @param {String} str
+ * @return {Object} packet
+ * @api private
+ */
+// eslint-disable-next-line complexity
+function decodeString(str) {
+ let i = 0;
+ // look up type
+ const p = {
+ type: Number(str.charAt(0)),
+ };
+
+ if (TYPES[p.type] == null) {
+ return error("unknown packet type " + p.type);
+ }
+
+ // look up attachments if type binary
+ if (BINARY_EVENT === p.type || BINARY_ACK === p.type) {
+ let buf = "";
+ while (str.charAt(++i) !== "-") {
+ buf += str.charAt(i);
+ if (i === str.length) {
+ break;
+ }
+ }
+ if (buf != Number(buf) || str.charAt(i) !== "-") {
+ throw new Error("Illegal attachments");
+ }
+ p.attachments = Number(buf);
+ }
+
+ // look up namespace (if any)
+ if (str.charAt(i + 1) === "/") {
+ p.nsp = "";
+ while (++i) {
+ const c = str.charAt(i);
+ if (c === ",") {
+ break;
+ }
+ p.nsp += c;
+ if (i === str.length) {
+ break;
+ }
+ }
+ } else {
+ p.nsp = "/";
+ }
+
+ // look up id
+ const next = str.charAt(i + 1);
+ if (next !== "" && Number(next) == next) {
+ p.id = "";
+ while (++i) {
+ const c = str.charAt(i);
+ if (c == null || Number(c) != c) {
+ --i;
+ break;
+ }
+ p.id += str.charAt(i);
+ if (i === str.length) {
+ break;
+ }
+ }
+ p.id = Number(p.id);
+ }
+
+ // look up json data
+ if (str.charAt(++i)) {
+ const payload = tryParse(str.substr(i));
+ const isPayloadValid =
+ payload !== false && (p.type === ERROR || Array.isArray(payload));
+ if (isPayloadValid) {
+ p.data = payload;
+ } else {
+ return error("invalid payload");
+ }
+ }
+
+ return p;
+}
+
+function tryParse(str) {
+ try {
+ return JSON.parse(str);
+ } catch (e) {
+ return false;
+ }
+}
+
+/**
+ * Deallocates a parser's resources
+ *
+ * @api public
+ */
+
+Decoder.prototype.destroy = function () {
+ if (this.reconstructor) {
+ this.reconstructor.finishedReconstruction();
+ }
+};
+
+function error(msg) {
+ return {
+ type: ERROR,
+ data: "parser error: " + msg,
+ };
+}
+
+module.exports = Decoder;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js
new file mode 100644
index 0000000000..cdbad14abc
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js
@@ -0,0 +1,40 @@
+/*
+ * A socket.io encoder and decoder written in JavaScript complying with version 4
+ * of socket.io-protocol. Used by socket.io and socket.io-client.
+ *
+ * Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/socketio/socket.io-parser
+ */
+
+/* eslint-disable no-undef */
+
+"use strict";
+
+var withNativeBuffer =
+ typeof Buffer === "function" && typeof Buffer.isBuffer === "function";
+var withNativeArrayBuffer = typeof ArrayBuffer === "function";
+
+var isView = function (obj) {
+ return typeof ArrayBuffer.isView === "function"
+ ? ArrayBuffer.isView(obj)
+ : obj.buffer instanceof ArrayBuffer;
+};
+
+/**
+ * Returns true if obj is a buffer or an arraybuffer.
+ *
+ * @api private
+ */
+
+function isBuf(obj) {
+ return (
+ (withNativeBuffer && Buffer.isBuffer(obj)) ||
+ (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)))
+ );
+}
+
+module.exports = isBuf;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build
new file mode 100644
index 0000000000..d38ca19dd6
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build
@@ -0,0 +1,10 @@
+# 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/.
+
+DevToolsModules(
+ "binary.js",
+ "component-emitter.js",
+ "index.js",
+ "is-buffer.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js
new file mode 100644
index 0000000000..b688b84b36
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js
@@ -0,0 +1,56 @@
+/*
+ * SockJS is a browser JavaScript library that provides a WebSocket-like object.
+ * SockJS gives you a coherent, cross-browser, Javascript API which creates a low latency,
+ * full duplex, cross-domain communication channel between the browser and the web server.
+ *
+ * Copyright (c) 2011-2018 The sockjs-client Authors.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/sockjs/sockjs-client
+ */
+
+"use strict";
+
+function parseSockJS(msg) {
+ const type = msg.slice(0, 1);
+ const content = msg.slice(1);
+
+ // first check for messages that don't need a payload
+ switch (type) {
+ case "o":
+ return { type: "open" };
+ case "h":
+ return { type: "heartbeat" };
+ }
+
+ let payload;
+ if (content) {
+ try {
+ payload = JSON.parse(content);
+ } catch (e) {
+ return null;
+ }
+ }
+
+ if (typeof payload === "undefined") {
+ return null;
+ }
+
+ switch (type) {
+ case "a":
+ return { type: "message", data: payload };
+ case "m":
+ return { type: "message", data: payload };
+ case "c":
+ const [code, message] = payload;
+ return { type: "close", code, message };
+ default:
+ return null;
+ }
+}
+
+module.exports = {
+ parseSockJS,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build
new file mode 100644
index 0000000000..e1ca52aa96
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build
@@ -0,0 +1,7 @@
+# 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/.
+
+DevToolsModules(
+ "index.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js
new file mode 100644
index 0000000000..a55d5bff7a
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/byte.ts
+ */
+
+"use strict";
+
+const BYTE = {
+ // LINEFEED byte (octet 10)
+ LF: "\x0A",
+ // NULL byte (octet 0)
+ NULL: "\x00",
+};
+
+module.exports = { BYTE };
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js
new file mode 100644
index 0000000000..679b1140b4
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js
@@ -0,0 +1,204 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/frame.ts
+ */
+
+"use strict";
+
+const {
+ BYTE,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js");
+
+/**
+ * Frame class represents a STOMP frame.
+ *
+ * @internal
+ */
+class FrameImpl {
+ /**
+ * Frame constructor. `command`, `headers` and `body` are available as properties.
+ *
+ * @internal
+ */
+ constructor(params) {
+ const {
+ command,
+ headers,
+ body,
+ binaryBody,
+ escapeHeaderValues,
+ skipContentLengthHeader,
+ } = params;
+ this.command = command;
+ this.headers = Object.assign({}, headers || {});
+ if (binaryBody) {
+ this._binaryBody = binaryBody;
+ this.isBinaryBody = true;
+ } else {
+ this._body = body || "";
+ this.isBinaryBody = false;
+ }
+ this.escapeHeaderValues = escapeHeaderValues || false;
+ this.skipContentLengthHeader = skipContentLengthHeader || false;
+ }
+ /**
+ * body of the frame
+ */
+ get body() {
+ if (!this._body && this.isBinaryBody) {
+ this._body = new TextDecoder().decode(this._binaryBody);
+ }
+ return this._body;
+ }
+ /**
+ * body as Uint8Array
+ */
+ get binaryBody() {
+ if (!this._binaryBody && !this.isBinaryBody) {
+ this._binaryBody = new TextEncoder().encode(this._body);
+ }
+ return this._binaryBody;
+ }
+ /**
+ * deserialize a STOMP Frame from raw data.
+ *
+ * @internal
+ */
+ static fromRawFrame(rawFrame, escapeHeaderValues) {
+ const headers = {};
+ const trim = str => str.replace(/^\s+|\s+$/g, "");
+ // In case of repeated headers, as per standards, first value need to be used
+ for (const header of rawFrame.headers.reverse()) {
+ const key = trim(header[0]);
+ let value = trim(header[1]);
+ if (
+ escapeHeaderValues &&
+ rawFrame.command !== "CONNECT" &&
+ rawFrame.command !== "CONNECTED"
+ ) {
+ value = FrameImpl.hdrValueUnEscape(value);
+ }
+ headers[key] = value;
+ }
+ return new FrameImpl({
+ command: rawFrame.command,
+ headers,
+ binaryBody: rawFrame.binaryBody,
+ escapeHeaderValues,
+ });
+ }
+ /**
+ * @internal
+ */
+ toString() {
+ return this.serializeCmdAndHeaders();
+ }
+ /**
+ * serialize this Frame in a format suitable to be passed to WebSocket.
+ * If the body is string the output will be string.
+ * If the body is binary (i.e. of type Unit8Array) it will be serialized to ArrayBuffer.
+ *
+ * @internal
+ */
+ serialize() {
+ const cmdAndHeaders = this.serializeCmdAndHeaders();
+ if (this.isBinaryBody) {
+ return FrameImpl.toUnit8Array(cmdAndHeaders, this._binaryBody).buffer;
+ }
+ return cmdAndHeaders + this._body + BYTE.NULL;
+ }
+ serializeCmdAndHeaders() {
+ const lines = [this.command];
+ if (this.skipContentLengthHeader) {
+ delete this.headers["content-length"];
+ }
+ for (const name of Object.keys(this.headers || {})) {
+ const value = this.headers[name];
+ if (
+ this.escapeHeaderValues &&
+ this.command !== "CONNECT" &&
+ this.command !== "CONNECTED"
+ ) {
+ lines.push(`${name}:${FrameImpl.hdrValueEscape(`${value}`)}`);
+ } else {
+ lines.push(`${name}:${value}`);
+ }
+ }
+ if (
+ this.isBinaryBody ||
+ (!this.isBodyEmpty() && !this.skipContentLengthHeader)
+ ) {
+ lines.push(`content-length:${this.bodyLength()}`);
+ }
+ return lines.join(BYTE.LF) + BYTE.LF + BYTE.LF;
+ }
+ isBodyEmpty() {
+ return this.bodyLength() === 0;
+ }
+ bodyLength() {
+ const binaryBody = this.binaryBody;
+ return binaryBody ? binaryBody.length : 0;
+ }
+ /**
+ * Compute the size of a UTF-8 string by counting its number of bytes
+ * (and not the number of characters composing the string)
+ */
+ static sizeOfUTF8(s) {
+ return s ? new TextEncoder().encode(s).length : 0;
+ }
+ static toUnit8Array(cmdAndHeaders, binaryBody) {
+ const uint8CmdAndHeaders = new TextEncoder().encode(cmdAndHeaders);
+ const nullTerminator = new Uint8Array([0]);
+ const uint8Frame = new Uint8Array(
+ uint8CmdAndHeaders.length + binaryBody.length + nullTerminator.length
+ );
+ uint8Frame.set(uint8CmdAndHeaders);
+ uint8Frame.set(binaryBody, uint8CmdAndHeaders.length);
+ uint8Frame.set(
+ nullTerminator,
+ uint8CmdAndHeaders.length + binaryBody.length
+ );
+ return uint8Frame;
+ }
+ /**
+ * Serialize a STOMP frame as per STOMP standards, suitable to be sent to the STOMP broker.
+ *
+ * @internal
+ */
+ static marshall(params) {
+ const frame = new FrameImpl(params);
+ return frame.serialize();
+ }
+ /**
+ * Escape header values
+ */
+ static hdrValueEscape(str) {
+ return str
+ .replace(/\\/g, "\\\\")
+ .replace(/\r/g, "\\r")
+ .replace(/\n/g, "\\n")
+ .replace(/:/g, "\\c");
+ }
+ /**
+ * UnEscape header values
+ */
+ static hdrValueUnEscape(str) {
+ return str
+ .replace(/\\r/g, "\r")
+ .replace(/\\n/g, "\n")
+ .replace(/\\c/g, ":")
+ .replace(/\\\\/g, "\\");
+ }
+}
+
+module.exports = { Frame: FrameImpl };
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js
new file mode 100644
index 0000000000..d5d441c543
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js
@@ -0,0 +1,40 @@
+/* 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 frameModule = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js");
+const {
+ Parser,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js");
+const {
+ parseJSON,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const { Frame } = frameModule;
+
+function parseStompJs(message) {
+ let output;
+
+ function onFrame(rawFrame) {
+ const frame = Frame.fromRawFrame(rawFrame);
+ const { error, json } = parseJSON(frame.body);
+
+ output = {
+ command: frame.command,
+ headers: frame.headers,
+ body: error ? frame.body : json,
+ };
+ }
+ const onIncomingPing = () => {};
+ const parser = new Parser(onFrame, onIncomingPing);
+
+ parser.parseChunk(message);
+
+ return output;
+}
+
+module.exports = {
+ parseStompJs,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build
new file mode 100644
index 0000000000..420c7479db
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build
@@ -0,0 +1,10 @@
+# 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/.
+
+DevToolsModules(
+ "byte.js",
+ "frame.js",
+ "index.js",
+ "parser.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js
new file mode 100644
index 0000000000..a7116627d3
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js
@@ -0,0 +1,230 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/parser.ts
+ */
+
+"use strict";
+
+/**
+ * @internal
+ */
+const NULL = 0;
+/**
+ * @internal
+ */
+const LF = 10;
+/**
+ * @internal
+ */
+const CR = 13;
+/**
+ * @internal
+ */
+const COLON = 58;
+/**
+ * This is an evented, rec descent parser.
+ * A stream of Octets can be passed and whenever it recognizes
+ * a complete Frame or an incoming ping it will invoke the registered callbacks.
+ *
+ * All incoming Octets are fed into _onByte function.
+ * Depending on current state the _onByte function keeps changing.
+ * Depending on the state it keeps accumulating into _token and _results.
+ * State is indicated by current value of _onByte, all states are named as _collect.
+ *
+ * STOMP standards https://stomp.github.io/stomp-specification-1.2.html
+ * imply that all lengths are considered in bytes (instead of string lengths).
+ * So, before actual parsing, if the incoming data is String it is converted to Octets.
+ * This allows faithful implementation of the protocol and allows NULL Octets to be present in the body.
+ *
+ * There is no peek function on the incoming data.
+ * When a state change occurs based on an Octet without consuming the Octet,
+ * the Octet, after state change, is fed again (_reinjectByte).
+ * This became possible as the state change can be determined by inspecting just one Octet.
+ *
+ * There are two modes to collect the body, if content-length header is there then it by counting Octets
+ * otherwise it is determined by NULL terminator.
+ *
+ * Following the standards, the command and headers are converted to Strings
+ * and the body is returned as Octets.
+ * Headers are returned as an array and not as Hash - to allow multiple occurrence of an header.
+ *
+ * This parser does not use Regular Expressions as that can only operate on Strings.
+ *
+ * It handles if multiple STOMP frames are given as one chunk, a frame is split into multiple chunks, or
+ * any combination there of. The parser remembers its state (any partial frame) and continues when a new chunk
+ * is pushed.
+ *
+ * Typically the higher level function will convert headers to Hash, handle unescaping of header values
+ * (which is protocol version specific), and convert body to text.
+ *
+ * Check the parser.spec.js to understand cases that this parser is supposed to handle.
+ *
+ * Part of `@stomp/stompjs`.
+ *
+ * @internal
+ */
+class Parser {
+ constructor(onFrame, onIncomingPing) {
+ this.onFrame = onFrame;
+ this.onIncomingPing = onIncomingPing;
+ this._encoder = new TextEncoder();
+ this._decoder = new TextDecoder();
+ this._token = [];
+ this._initState();
+ }
+ parseChunk(segment, appendMissingNULLonIncoming = false) {
+ let chunk;
+ if (segment instanceof ArrayBuffer) {
+ chunk = new Uint8Array(segment);
+ } else {
+ chunk = this._encoder.encode(segment);
+ }
+ // See https://github.com/stomp-js/stompjs/issues/89
+ // Remove when underlying issue is fixed.
+ //
+ // Send a NULL byte, if the last byte of a Text frame was not NULL.F
+ if (appendMissingNULLonIncoming && chunk[chunk.length - 1] !== 0) {
+ const chunkWithNull = new Uint8Array(chunk.length + 1);
+ chunkWithNull.set(chunk, 0);
+ chunkWithNull[chunk.length] = 0;
+ chunk = chunkWithNull;
+ }
+ // tslint:disable-next-line:prefer-for-of
+ for (let i = 0; i < chunk.length; i++) {
+ const byte = chunk[i];
+ this._onByte(byte);
+ }
+ }
+ // The following implements a simple Rec Descent Parser.
+ // The grammar is simple and just one byte tells what should be the next state
+ _collectFrame(byte) {
+ if (byte === NULL) {
+ // Ignore
+ return;
+ }
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ // Incoming Ping
+ this.onIncomingPing();
+ return;
+ }
+ this._onByte = this._collectCommand;
+ this._reinjectByte(byte);
+ }
+ _collectCommand(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._results.command = this._consumeTokenAsUTF8();
+ this._onByte = this._collectHeaders;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectHeaders(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._setupCollectBody();
+ return;
+ }
+ this._onByte = this._collectHeaderKey;
+ this._reinjectByte(byte);
+ }
+ _reinjectByte(byte) {
+ this._onByte(byte);
+ }
+ _collectHeaderKey(byte) {
+ if (byte === COLON) {
+ this._headerKey = this._consumeTokenAsUTF8();
+ this._onByte = this._collectHeaderValue;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectHeaderValue(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._results.headers.push([this._headerKey, this._consumeTokenAsUTF8()]);
+ this._headerKey = undefined;
+ this._onByte = this._collectHeaders;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _setupCollectBody() {
+ const contentLengthHeader = this._results.headers.filter(header => {
+ return header[0] === "content-length";
+ })[0];
+ if (contentLengthHeader) {
+ this._bodyBytesRemaining = parseInt(contentLengthHeader[1], 10);
+ this._onByte = this._collectBodyFixedSize;
+ } else {
+ this._onByte = this._collectBodyNullTerminated;
+ }
+ }
+ _collectBodyNullTerminated(byte) {
+ if (byte === NULL) {
+ this._retrievedBody();
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectBodyFixedSize(byte) {
+ // It is post decrement, so that we discard the trailing NULL octet
+ if (this._bodyBytesRemaining-- === 0) {
+ this._retrievedBody();
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _retrievedBody() {
+ this._results.binaryBody = this._consumeTokenAsRaw();
+ this.onFrame(this._results);
+ this._initState();
+ }
+ // Rec Descent Parser helpers
+ _consumeByte(byte) {
+ this._token.push(byte);
+ }
+ _consumeTokenAsUTF8() {
+ return this._decoder.decode(this._consumeTokenAsRaw());
+ }
+ _consumeTokenAsRaw() {
+ const rawResult = new Uint8Array(this._token);
+ this._token = [];
+ return rawResult;
+ }
+ _initState() {
+ this._results = {
+ command: undefined,
+ headers: [],
+ binaryBody: undefined,
+ };
+ this._token = [];
+ this._headerKey = undefined;
+ this._onByte = this._collectFrame;
+ }
+}
+
+module.exports = { Parser };
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js b/devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js
new file mode 100644
index 0000000000..de73a7986c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js
@@ -0,0 +1,274 @@
+/* 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";
+
+// An implementation for WAMP messages parsing https://wamp-proto.org/
+var WampMessageType;
+(function (wampMessageTypeEnum) {
+ wampMessageTypeEnum[(wampMessageTypeEnum.Hello = 1)] = "Hello";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Welcome = 2)] = "Welcome";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Abort = 3)] = "Abort";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Challenge = 4)] = "Challenge";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Authenticate = 5)] = "Authenticate";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Goodbye = 6)] = "Goodbye";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Error = 8)] = "Error";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Publish = 16)] = "Publish";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Published = 17)] = "Published";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Subscribe = 32)] = "Subscribe";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Subscribed = 33)] = "Subscribed";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unsubscribe = 34)] = "Unsubscribe";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unsubscribed = 35)] = "Unsubscribed";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Event = 36)] = "Event";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Call = 48)] = "Call";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Cancel = 49)] = "Cancel";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Result = 50)] = "Result";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Register = 64)] = "Register";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Registered = 65)] = "Registered";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unregister = 66)] = "Unregister";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unregistered = 67)] = "Unregistered";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Invocation = 68)] = "Invocation";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Interrupt = 69)] = "Interrupt";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Yield = 70)] = "Yield";
+})(WampMessageType || (WampMessageType = {}));
+
+// The WAMP protocol consists of many messages, disable complexity for one time
+// eslint-disable-next-line complexity
+function parseWampArray(messageArray) {
+ const [messageType, ...args] = messageArray;
+ switch (messageType) {
+ case WampMessageType.Hello:
+ return new HelloMessage(args);
+ case WampMessageType.Welcome:
+ return new WelcomeMessage(args);
+ case WampMessageType.Abort:
+ return new AbortMessage(args);
+ case WampMessageType.Challenge:
+ return new ChallengeMessage(args);
+ case WampMessageType.Authenticate:
+ return new AuthenticateMessage(args);
+ case WampMessageType.Goodbye:
+ return new GoodbyeMessage(args);
+ case WampMessageType.Error:
+ return new ErrorMessage(args);
+ case WampMessageType.Publish:
+ return new PublishMessage(args);
+ case WampMessageType.Published:
+ return new PublishedMessage(args);
+ case WampMessageType.Subscribe:
+ return new SubscribeMessage(args);
+ case WampMessageType.Subscribed:
+ return new SubscribedMessage(args);
+ case WampMessageType.Unsubscribe:
+ return new UnsubscribeMessage(args);
+ case WampMessageType.Unsubscribed:
+ return new UnsubscribedMessage(args);
+ case WampMessageType.Event:
+ return new EventMessage(args);
+ case WampMessageType.Call:
+ return new CallMessage(args);
+ case WampMessageType.Cancel:
+ return new CancelMessage(args);
+ case WampMessageType.Result:
+ return new ResultMessage(args);
+ case WampMessageType.Register:
+ return new RegisterMessage(args);
+ case WampMessageType.Registered:
+ return new RegisteredMessage(args);
+ case WampMessageType.Unregister:
+ return new UnregisterMessage(args);
+ case WampMessageType.Unregistered:
+ return new UnregisteredMessage(args);
+ case WampMessageType.Invocation:
+ return new InvocationMessage(args);
+ case WampMessageType.Interrupt:
+ return new InterruptMessage(args);
+ case WampMessageType.Yield:
+ return new YieldMessage(args);
+ default:
+ return null;
+ }
+}
+class WampMessage {
+ constructor(code) {
+ this.messageCode = code;
+ this.messageName = WampMessageType[code].toUpperCase();
+ }
+}
+class HelloMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Hello);
+ [this.realm, this.details] = messageArgs;
+ }
+}
+class WelcomeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Welcome);
+ [this.session, this.details] = messageArgs;
+ }
+}
+class AbortMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Abort);
+ [this.details, this.reason] = messageArgs;
+ }
+}
+class ChallengeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Challenge);
+ [this.authMethod, this.extra] = messageArgs;
+ }
+}
+class AuthenticateMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Authenticate);
+ [this.signature, this.extra] = messageArgs;
+ }
+}
+class GoodbyeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Goodbye);
+ [this.details, this.reason] = messageArgs;
+ }
+}
+class ErrorMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Error);
+ [
+ this.type,
+ this.request,
+ this.details,
+ this.error,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class PublishMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Publish);
+ [this.request, this.options, this.topic, this.arguments, this.argumentsKw] =
+ messageArgs;
+ }
+}
+class PublishedMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Published);
+ [this.request, this.publication] = messageArgs;
+ }
+}
+class SubscribeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Subscribe);
+ [this.request, this.options, this.topic] = messageArgs;
+ }
+}
+class SubscribedMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Subscribed);
+ [this.request, this.subscription] = messageArgs;
+ }
+}
+class UnsubscribeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unsubscribe);
+ [this.request, this.subscription] = messageArgs;
+ }
+}
+class UnsubscribedMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unsubscribed);
+ [this.request] = messageArgs;
+ }
+}
+class EventMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Event);
+ [
+ this.subscription,
+ this.publication,
+ this.details,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class CallMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Call);
+ [
+ this.request,
+ this.options,
+ this.procedure,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class CancelMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Cancel);
+ [this.request, this.options] = messageArgs;
+ }
+}
+class ResultMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Result);
+ [this.request, this.details, this.arguments, this.argumentsKw] =
+ messageArgs;
+ }
+}
+class RegisterMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Register);
+ [this.request, this.options, this.procedure] = messageArgs;
+ }
+}
+class RegisteredMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Registered);
+ [this.request, this.registration] = messageArgs;
+ }
+}
+class UnregisterMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unregister);
+ [this.request, this.registration] = messageArgs;
+ }
+}
+class UnregisteredMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unregistered);
+ [this.request] = messageArgs;
+ }
+}
+class InvocationMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Invocation);
+ [
+ this.request,
+ this.registration,
+ this.details,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class InterruptMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Interrupt);
+ [this.request, this.options] = messageArgs;
+ }
+}
+class YieldMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Yield);
+ [this.request, this.options, this.arguments, this.argumentsKw] =
+ messageArgs;
+ }
+}
+
+module.exports = {
+ parseWampArray,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build
new file mode 100644
index 0000000000..b6b7c91036
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build
@@ -0,0 +1,8 @@
+# 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/.
+
+DevToolsModules(
+ "arrayParser.js",
+ "serializers.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js b/devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js
new file mode 100644
index 0000000000..c2139d320c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js
@@ -0,0 +1,73 @@
+/* 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 {
+ parseWampArray,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js");
+const msgpack = require("resource://devtools/client/netmonitor/src/components/messages/msgpack.js");
+const cbor = require("resource://devtools/client/netmonitor/src/components/messages/cbor.js");
+
+class WampSerializer {
+ deserializeMessage(payload) {
+ const array = this.deserializeToArray(payload);
+ const result = parseWampArray(array);
+ return result;
+ }
+
+ stringToBinary(str) {
+ const result = new Uint8Array(str.length);
+ for (let i = 0; i < str.length; i++) {
+ result[i] = str[i].charCodeAt(0);
+ }
+ return result;
+ }
+}
+
+class JsonSerializer extends WampSerializer {
+ constructor() {
+ super(...arguments);
+ this.subProtocol = "wamp.2.json";
+ this.description = "WAMP JSON";
+ }
+ deserializeToArray(payload) {
+ return JSON.parse(payload);
+ }
+}
+
+class MessagePackSerializer extends WampSerializer {
+ constructor() {
+ super(...arguments);
+ this.subProtocol = "wamp.2.msgpack";
+ this.description = "WAMP MessagePack";
+ }
+ deserializeToArray(payload) {
+ const binary = this.stringToBinary(payload);
+ return msgpack.deserialize(binary);
+ }
+}
+
+class CBORSerializer extends WampSerializer {
+ constructor() {
+ super(...arguments);
+ this.subProtocol = "wamp.2.cbor";
+ this.description = "WAMP CBOR";
+ }
+ deserializeToArray(payload) {
+ const binaryBuffer = this.stringToBinary(payload).buffer;
+ return cbor.decode(binaryBuffer);
+ }
+}
+
+const serializers = {};
+for (var serializer of [
+ new JsonSerializer(),
+ new MessagePackSerializer(),
+ new CBORSerializer(),
+]) {
+ serializers[serializer.subProtocol] = serializer;
+}
+
+module.exports = { wampSerializers: serializers };